Repository navigation
Expand file tree
/
Copy pathtest_apify_request_queue_client.py
More file actions
959 lines (746 loc) · 40.7 KB
/
Copy pathtest_apify_request_queue_client.py
File metadata and controls
959 lines (746 loc) · 40.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
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
from __future__ import annotations
import asyncio
from datetime import UTC, datetime, timedelta
from itertools import chain, repeat
from types import SimpleNamespace
from typing import TYPE_CHECKING
from unittest.mock import AsyncMock
import pytest
from apify_client._models import (
AddedRequest,
BatchAddResult,
LockedRequestQueueHead,
LockedRequestQueueHeadItem,
RequestLockInfo,
RequestQueueHead,
RequestQueueHeadItem,
RequestQueueStats,
RequestRegistration,
UnprocessedRequest,
)
from apify_client._models import RequestResource as ClientRequest
from crawlee.storage_clients.models import AddRequestsResponse, ProcessedRequest, RequestQueueMetadata
from apify import Request
from apify.storage_clients._apify._models import ApifyRequestQueueMetadata
from apify.storage_clients._apify._request_queue_shared_client import ApifyRequestQueueSharedClient
from apify.storage_clients._apify._request_queue_single_client import ApifyRequestQueueSingleClient
from apify.storage_clients._apify._utils import unique_key_to_request_id
if TYPE_CHECKING:
from collections.abc import Callable, Sequence
def _make_metadata() -> RequestQueueMetadata:
now = datetime.now(tz=UTC)
return RequestQueueMetadata(
id='test-rq-id',
name='test-rq',
accessed_at=now,
created_at=now,
modified_at=now,
had_multiple_clients=False,
handled_request_count=0,
pending_request_count=0,
total_request_count=0,
)
def _batch_result(
*,
processed: Sequence[Request] = (),
unprocessed: Sequence[Request] = (),
) -> BatchAddResult:
"""Build a `batch_add_requests` response with explicit processed / unprocessed splits."""
return BatchAddResult.model_construct(
processed_requests=[
AddedRequest.model_construct(
request_id=unique_key_to_request_id(request.unique_key),
unique_key=request.unique_key,
was_already_present=False,
was_already_handled=False,
)
for request in processed
],
unprocessed_requests=[
UnprocessedRequest.model_construct(
unique_key=request.unique_key,
url=request.url,
method=request.method,
)
for request in unprocessed
],
)
def _batch_result_all_processed(requests: Sequence[Request]) -> BatchAddResult:
"""Build a `batch_add_requests` response marking every request as newly processed."""
return _batch_result(processed=requests)
def _make_single_client(
api_client: AsyncMock | None = None,
) -> tuple[ApifyRequestQueueSingleClient, AsyncMock]:
if api_client is None:
api_client = AsyncMock()
client = ApifyRequestQueueSingleClient(api_client=api_client, metadata=_make_metadata(), cache_size=100)
return client, api_client
def _make_shared_client(
api_client: AsyncMock | None = None,
) -> tuple[ApifyRequestQueueSharedClient, AsyncMock]:
if api_client is None:
api_client = AsyncMock()
metadata = _make_metadata()
client = ApifyRequestQueueSharedClient(
api_client=api_client,
metadata=metadata,
cache_size=100,
metadata_getter=AsyncMock(return_value=metadata),
)
return client, api_client
def _empty_locked_head(*, queue_has_locked_requests: bool = False) -> LockedRequestQueueHead:
"""Build an empty `list_and_lock_head` response, optionally reporting locked requests."""
return LockedRequestQueueHead(
limit=1,
queue_modified_at=datetime.now(tz=UTC),
queue_has_locked_requests=queue_has_locked_requests,
had_multiple_clients=True,
lock_secs=60,
items=[],
)
def _client_request(request: Request, *, handled_at: datetime | None) -> ClientRequest:
"""Build a `get_request` response for the given request in the given handled state."""
return ClientRequest.model_validate(
request.model_dump(by_alias=True)
| {'id': unique_key_to_request_id(request.unique_key), 'handledAt': handled_at}
)
def _request_registration(request: Request, *, was_already_handled: bool) -> RequestRegistration:
"""Build an `update_request` response reporting the given pre-update handled state."""
return RequestRegistration(
request_id=unique_key_to_request_id(request.unique_key),
was_already_present=True,
was_already_handled=was_already_handled,
)
def test_unique_key_to_request_id_length() -> None:
unique_key = 'exampleKey123'
request_id = unique_key_to_request_id(unique_key, request_id_length=15)
assert len(request_id) == 15, 'Request ID should have the correct length.'
def test_unique_key_to_request_id_consistency() -> None:
unique_key = 'consistentKey'
request_id_1 = unique_key_to_request_id(unique_key)
request_id_2 = unique_key_to_request_id(unique_key)
assert request_id_1 == request_id_2, 'The same unique key should generate consistent request IDs.'
@pytest.mark.parametrize(
('stats', 'expected_read_count'),
[(None, None), ({'readCount': 5}, 5)],
ids=['none_coerced_to_default', 'populated_passed_through'],
)
def test_metadata_stats_validation(stats: dict | None, expected_read_count: int | None) -> None:
"""A `stats: None` payload (as `open()` produces via `model_dump`) defaults; a populated one passes through."""
now = datetime.now(tz=UTC)
metadata = ApifyRequestQueueMetadata.model_validate(
{
'id': 'test-rq-id',
'name': None,
'accessedAt': now,
'createdAt': now,
'modifiedAt': now,
'hadMultipleClients': False,
'handledRequestCount': 0,
'pendingRequestCount': 0,
'totalRequestCount': 0,
'stats': stats,
}
)
assert isinstance(metadata.stats, RequestQueueStats)
assert metadata.stats.read_count == expected_read_count
@pytest.mark.parametrize(
('unique_key', 'expected_request_id'),
[
('abc', 'ungWv48BzpBQUDe'),
('uniqueKey', 'xiWPs083cree7mH'),
('', '47DEQpj8HBSaTIm'),
('测试中文', 'lKPdJkdvw8MXEUp'),
('test+/=', 'XZRQjhoG0yjfnYD'),
],
ids=[
'basic_abc',
'keyword_uniqueKey',
'empty_string',
'non_ascii_characters',
'url_unsafe_characters',
],
)
def test_unique_key_to_request_id_matches_known_values(unique_key: str, expected_request_id: str) -> None:
request_id = unique_key_to_request_id(unique_key)
assert request_id == expected_request_id, f'Unique key "{unique_key}" should produce the expected request ID.'
@pytest.mark.parametrize(
('in_progress_count', 'expected_limit'),
[
(0, 200),
(300, 500),
(900, ApifyRequestQueueSingleClient._MAX_HEAD_ITEMS),
],
ids=['no_in_progress', 'pads_by_in_progress', 'caps_at_max_head_items'],
)
async def test_list_head_limit(in_progress_count: int, expected_limit: int) -> None:
client, api_client = _make_single_client()
api_client.list_head = AsyncMock(
return_value=RequestQueueHead(
limit=expected_limit,
queue_modified_at=datetime.now(tz=UTC),
had_multiple_clients=False,
items=[],
)
)
client._requests_in_progress = {f'req_{i}' for i in range(in_progress_count)}
await client._list_head()
api_client.list_head.assert_awaited_once_with(limit=expected_limit)
# Adding a request through `batch_add_requests` must never poison the local dedup cache or report false
# success. A failed add leaves nothing cached, so a later add (sequential or concurrent) still reaches the
# platform; a concurrent producer of the same request deduplicates against the in-flight add instead of
# re-sending it, yet is only told the request is present once the platform actually accepts it.
@pytest.mark.parametrize('access', ['single', 'shared'])
async def test_failed_batch_add_does_not_poison_dedup_cache(access: str) -> None:
"""A failed `batch_add_requests` leaves no cached entry, so a retry still reaches the platform."""
client, api_client = _make_single_client() if access == 'single' else _make_shared_client()
# The single client lazily initializes its caches via `list_requests`; harmless for the shared client.
api_client.list_requests = AsyncMock(return_value=SimpleNamespace(items=[]))
request = Request.from_url('https://example.com/1')
request_id = unique_key_to_request_id(request.unique_key)
# First attempt: the platform call fails.
api_client.batch_add_requests = AsyncMock(side_effect=RuntimeError('network down'))
with pytest.raises(RuntimeError):
await client.add_batch_of_requests([request])
assert request_id not in client._requests_cache
# Retry: the platform call succeeds. The request must be sent again, not deduped away.
api_client.batch_add_requests = AsyncMock(return_value=_batch_result_all_processed([request]))
await client.add_batch_of_requests([request])
api_client.batch_add_requests.assert_awaited_once()
assert api_client.batch_add_requests.await_args is not None
assert len(api_client.batch_add_requests.await_args.kwargs['requests']) == 1
async def _start_first_then_concurrent_producer(
client: ApifyRequestQueueSingleClient | ApifyRequestQueueSharedClient,
request: Request,
*,
in_flight: asyncio.Event,
) -> tuple[asyncio.Task[AddRequestsResponse], asyncio.Task[AddRequestsResponse]]:
"""Start one producer, wait until its `batch_add_requests` is in flight, then start a concurrent producer
of the same request and let it park on the in-flight add. Returns the (first, second) tasks."""
if isinstance(client, ApifyRequestQueueSingleClient):
# Skip the lazy `list_requests` init so the concurrent producer's only suspension point is the
# in-flight future, which makes the scheduling below deterministic.
client._initialized_caches = True
first = asyncio.create_task(client.add_batch_of_requests([request]))
await in_flight.wait()
second = asyncio.create_task(client.add_batch_of_requests([request]))
await asyncio.sleep(0) # let the concurrent producer classify and park on the in-flight future
return first, second
@pytest.mark.parametrize('access', ['single', 'shared'])
async def test_concurrent_add_failure_does_not_falsely_dedupe(access: str) -> None:
"""While one producer's `batch_add_requests` is in flight and then fails, a concurrent producer of the same
request must not report false success: the request is returned unprocessed (so the caller retries it)."""
client, api_client = _make_single_client() if access == 'single' else _make_shared_client()
request = Request.from_url('https://example.com/1')
request_id = unique_key_to_request_id(request.unique_key)
in_flight = asyncio.Event()
release = asyncio.Event()
call_count = 0
async def batch_add(*, requests: list, forefront: bool = False) -> BatchAddResult: # noqa: ARG001
nonlocal call_count
call_count += 1
in_flight.set()
await release.wait()
raise RuntimeError('network down')
api_client.batch_add_requests = AsyncMock(side_effect=batch_add)
first, second = await _start_first_then_concurrent_producer(client, request, in_flight=in_flight)
# Nothing is committed while the first call is still in flight, so the concurrent producer cannot observe a
# false "already present" entry.
assert request_id not in client._requests_cache
# Let the first producer fail.
release.set()
with pytest.raises(RuntimeError):
await first
# The concurrent producer deduplicated against the in-flight add (no second API call), but because that add
# failed it must be told the request is unprocessed rather than receiving false success.
response = await second
assert call_count == 1
assert [unprocessed.unique_key for unprocessed in response.unprocessed_requests] == [request.unique_key]
assert all(processed.unique_key != request.unique_key for processed in response.processed_requests)
assert request_id not in client._requests_cache
@pytest.mark.parametrize('access', ['single', 'shared'])
async def test_concurrent_add_deduplicates_against_in_flight(access: str) -> None:
"""A concurrent producer of an in-flight request deduplicates against it: only one `batch_add_requests` call
is made, and once it succeeds the concurrent producer is told the request is already present."""
client, api_client = _make_single_client() if access == 'single' else _make_shared_client()
request = Request.from_url('https://example.com/1')
request_id = unique_key_to_request_id(request.unique_key)
in_flight = asyncio.Event()
release = asyncio.Event()
call_count = 0
async def batch_add(*, requests: list, forefront: bool = False) -> BatchAddResult: # noqa: ARG001
nonlocal call_count
call_count += 1
in_flight.set()
await release.wait()
return _batch_result_all_processed([request])
api_client.batch_add_requests = AsyncMock(side_effect=batch_add)
first, second = await _start_first_then_concurrent_producer(client, request, in_flight=in_flight)
# Let the first producer succeed.
release.set()
first_response = await first
second_response = await second
assert call_count == 1
assert request_id in client._requests_cache
# The first producer added the request, the concurrent one deduplicated against the in-flight add.
assert [processed.unique_key for processed in first_response.processed_requests] == [request.unique_key]
assert [processed.unique_key for processed in second_response.processed_requests] == [request.unique_key]
assert second_response.processed_requests[0].was_already_present is True
assert second_response.unprocessed_requests == []
@pytest.mark.parametrize('access', ['single', 'shared'])
async def test_partial_unprocessed_commits_only_accepted_requests(access: str) -> None:
"""When the platform accepts only part of a batch, only the accepted requests are cached. The rejected one
leaves no entry behind, so a later retry re-sends it while the accepted one is deduped locally."""
client, api_client = _make_single_client() if access == 'single' else _make_shared_client()
api_client.list_requests = AsyncMock(return_value=SimpleNamespace(items=[]))
accepted = Request.from_url('https://example.com/accepted')
rejected = Request.from_url('https://example.com/rejected')
accepted_id = unique_key_to_request_id(accepted.unique_key)
rejected_id = unique_key_to_request_id(rejected.unique_key)
api_client.batch_add_requests = AsyncMock(return_value=_batch_result(processed=[accepted], unprocessed=[rejected]))
response = await client.add_batch_of_requests([accepted, rejected])
# Only the accepted request is committed to the local cache; the rejected one is not.
assert accepted_id in client._requests_cache
assert rejected_id not in client._requests_cache
# The response mirrors the platform split, and no in-flight marker is left behind.
assert [processed.unique_key for processed in response.processed_requests] == [accepted.unique_key]
assert [unprocessed.unique_key for unprocessed in response.unprocessed_requests] == [rejected.unique_key]
assert client._requests_being_added == {}
# Retry both: the rejected request must reach the platform again (it was not poisoned), while the accepted one
# is deduped locally and never re-sent.
api_client.batch_add_requests = AsyncMock(return_value=_batch_result(processed=[rejected]))
await client.add_batch_of_requests([accepted, rejected])
api_client.batch_add_requests.assert_awaited_once()
assert api_client.batch_add_requests.await_args is not None
resent = api_client.batch_add_requests.await_args.kwargs['requests']
assert [request['uniqueKey'] for request in resent] == [rejected.unique_key]
@pytest.mark.parametrize(
'platform_request_visible',
[
pytest.param(True, id='still_pending'),
pytest.param(False, id='not_yet_visible'),
],
)
async def test_shared_is_finished_false_while_known_request_unhandled(*, platform_request_visible: bool) -> None:
"""An empty, lock-free head listing does not report the queue finished while a known request is unhandled:
the eventually consistent head can miss a just-added request, so its state is confirmed by fetching it."""
client, api_client = _make_shared_client()
request = Request.from_url('https://example.com/1')
request_id = unique_key_to_request_id(request.unique_key)
api_client.batch_add_requests = AsyncMock(return_value=_batch_result_all_processed([request]))
await client.add_batch_of_requests([request])
api_client.list_and_lock_head = AsyncMock(return_value=_empty_locked_head())
api_client.get_request = AsyncMock(
return_value=_client_request(request, handled_at=None) if platform_request_visible else None
)
assert await client.is_finished() is False
api_client.get_request.assert_awaited_once_with(request_id)
async def test_shared_is_finished_true_once_known_requests_confirmed_handled() -> None:
"""The queue reports finished once every known request is confirmed handled, and the confirmation is cached
so repeated `is_finished` calls do not re-fetch the request."""
client, api_client = _make_shared_client()
request = Request.from_url('https://example.com/1')
api_client.batch_add_requests = AsyncMock(return_value=_batch_result_all_processed([request]))
await client.add_batch_of_requests([request])
api_client.list_and_lock_head = AsyncMock(return_value=_empty_locked_head())
api_client.get_request = AsyncMock(return_value=_client_request(request, handled_at=datetime.now(tz=UTC)))
assert await client.is_finished() is True
assert await client.is_finished() is True
assert api_client.get_request.await_count == 1
async def test_shared_is_finished_false_when_head_reports_locked_requests() -> None:
"""Locked requests reported by the head listing mean the queue is not finished, without any per-request reads."""
client, api_client = _make_shared_client()
api_client.list_and_lock_head = AsyncMock(return_value=_empty_locked_head(queue_has_locked_requests=True))
api_client.get_request = AsyncMock()
assert await client.is_finished() is False
api_client.get_request.assert_not_awaited()
async def test_shared_is_finished_true_on_queue_with_no_known_requests() -> None:
"""An empty, lock-free queue with no locally known requests reports finished without per-request reads."""
client, api_client = _make_shared_client()
api_client.list_and_lock_head = AsyncMock(return_value=_empty_locked_head())
api_client.get_request = AsyncMock()
assert await client.is_finished() is True
api_client.get_request.assert_not_awaited()
async def test_shared_is_finished_true_after_this_client_marked_request_handled() -> None:
"""A request this client marked handled is trusted from the cache, so `is_finished` needs no per-request read."""
client, api_client = _make_shared_client()
request = Request.from_url('https://example.com/1')
api_client.batch_add_requests = AsyncMock(return_value=_batch_result_all_processed([request]))
await client.add_batch_of_requests([request])
# The platform reports the pre-update state, so a first-time handle comes back as not yet handled.
api_client.update_request = AsyncMock(return_value=_request_registration(request, was_already_handled=False))
assert await client.mark_request_as_handled(request) is not None
api_client.list_and_lock_head = AsyncMock(return_value=_empty_locked_head())
api_client.get_request = AsyncMock()
assert await client.is_finished() is True
api_client.get_request.assert_not_awaited()
async def test_shared_is_finished_false_after_failed_mark_request_as_handled() -> None:
"""A failed `mark_request_as_handled` leaves the request unconfirmed, so `is_finished` re-checks it."""
client, api_client = _make_shared_client()
request = Request.from_url('https://example.com/1')
request_id = unique_key_to_request_id(request.unique_key)
api_client.batch_add_requests = AsyncMock(return_value=_batch_result_all_processed([request]))
await client.add_batch_of_requests([request])
api_client.update_request = AsyncMock(side_effect=RuntimeError('network down'))
assert await client.mark_request_as_handled(request) is None
api_client.list_and_lock_head = AsyncMock(return_value=_empty_locked_head())
api_client.get_request = AsyncMock(return_value=_client_request(request, handled_at=None))
assert await client.is_finished() is False
api_client.get_request.assert_awaited_once_with(request_id)
async def test_shared_is_finished_false_after_reclaiming_handled_request() -> None:
"""A reclaimed previously-handled request is pending again, so `is_finished` re-checks it via the platform."""
client, api_client = _make_shared_client()
request = Request.from_url('https://example.com/1')
request_id = unique_key_to_request_id(request.unique_key)
api_client.batch_add_requests = AsyncMock(return_value=_batch_result_all_processed([request]))
await client.add_batch_of_requests([request])
api_client.update_request = AsyncMock(return_value=_request_registration(request, was_already_handled=False))
await client.mark_request_as_handled(request)
# Reclaim the handled request: the platform reports the pre-update (handled) state.
api_client.update_request = AsyncMock(return_value=_request_registration(request, was_already_handled=True))
assert await client.reclaim_request(request) is not None
api_client.list_and_lock_head = AsyncMock(return_value=_empty_locked_head())
api_client.get_request = AsyncMock(return_value=_client_request(request, handled_at=None))
assert await client.is_finished() is False
api_client.get_request.assert_awaited_once_with(request_id)
async def test_shared_is_finished_false_while_add_batch_in_flight() -> None:
"""The queue does not report finished while an `add_batch_of_requests` call is still in flight."""
client, api_client = _make_shared_client()
request = Request.from_url('https://example.com/1')
in_flight = asyncio.Event()
release = asyncio.Event()
async def batch_add(*, requests: list, forefront: bool = False) -> BatchAddResult: # noqa: ARG001
in_flight.set()
await release.wait()
return _batch_result_all_processed([request])
api_client.batch_add_requests = AsyncMock(side_effect=batch_add)
api_client.list_and_lock_head = AsyncMock(return_value=_empty_locked_head())
api_client.get_request = AsyncMock()
add_task = asyncio.create_task(client.add_batch_of_requests([request]))
await in_flight.wait()
assert await client.is_finished() is False
api_client.get_request.assert_not_awaited()
release.set()
await add_task
async def test_shared_is_finished_confirms_known_requests_in_bounded_parallel_batches() -> None:
"""`is_finished` confirms unhandled requests concurrently, in batches bounded by `_VERIFICATION_BATCH_SIZE`."""
client, api_client = _make_shared_client()
batch_size = ApifyRequestQueueSharedClient._VERIFICATION_BATCH_SIZE
requests = [Request.from_url(f'https://example.com/{i}') for i in range(batch_size * 2 + 5)]
requests_by_id = {unique_key_to_request_id(request.unique_key): request for request in requests}
api_client.batch_add_requests = AsyncMock(return_value=_batch_result_all_processed(requests))
await client.add_batch_of_requests(requests)
in_flight = 0
peak_in_flight = 0
async def get_request(request_id: str) -> ClientRequest:
nonlocal in_flight, peak_in_flight
in_flight += 1
peak_in_flight = max(peak_in_flight, in_flight)
# Yield to the loop so the whole batch is in flight before any of its calls completes.
await asyncio.sleep(0)
in_flight -= 1
return _client_request(requests_by_id[request_id], handled_at=datetime.now(tz=UTC))
api_client.list_and_lock_head = AsyncMock(return_value=_empty_locked_head())
api_client.get_request = AsyncMock(side_effect=get_request)
assert await client.is_finished() is True
assert api_client.get_request.await_count == len(requests)
assert peak_in_flight == batch_size
async def test_shared_is_finished_does_not_refetch_requests_confirmed_in_an_unfinished_batch() -> None:
"""Requests confirmed handled alongside an unhandled one are not fetched again by the next `is_finished`."""
client, api_client = _make_shared_client()
handled, straggler = (Request.from_url(f'https://example.com/{i}') for i in range(2))
straggler_id = unique_key_to_request_id(straggler.unique_key)
api_client.batch_add_requests = AsyncMock(return_value=_batch_result_all_processed([handled, straggler]))
await client.add_batch_of_requests([handled, straggler])
api_client.list_and_lock_head = AsyncMock(return_value=_empty_locked_head())
api_client.get_request = AsyncMock(
side_effect=lambda request_id: _client_request(
straggler if request_id == straggler_id else handled,
handled_at=None if request_id == straggler_id else datetime.now(tz=UTC),
)
)
assert await client.is_finished() is False
assert api_client.get_request.await_count == 2
api_client.get_request = AsyncMock(return_value=_client_request(straggler, handled_at=datetime.now(tz=UTC)))
assert await client.is_finished() is True
api_client.get_request.assert_awaited_once_with(straggler_id)
def _locked_item(request: Request, *, lock_expires_at: datetime) -> LockedRequestQueueHeadItem:
"""Build a single locked head entry for `request` with the given lock expiry."""
return LockedRequestQueueHeadItem(
id=unique_key_to_request_id(request.unique_key),
unique_key=request.unique_key,
url=request.url,
method=request.method,
retry_count=0,
lock_expires_at=lock_expires_at,
)
def _locked_head(
items: Sequence[LockedRequestQueueHeadItem],
*,
queue_has_locked_requests: bool = True,
) -> LockedRequestQueueHead:
"""Build a `list_and_lock_head` response wrapping the given locked entries."""
return LockedRequestQueueHead(
limit=25,
queue_modified_at=datetime.now(tz=UTC),
queue_has_locked_requests=queue_has_locked_requests,
had_multiple_clients=True,
lock_secs=180,
items=list(items),
)
def _processed(request: Request, *, was_already_handled: bool = False) -> ProcessedRequest:
"""Build the `update_request` result returned by the API for a handled or reclaimed request."""
return ProcessedRequest(
id=unique_key_to_request_id(request.unique_key),
unique_key=request.unique_key,
was_already_present=True,
was_already_handled=was_already_handled,
)
def _client_request_getter(requests: Sequence[Request]) -> Callable[[str], ClientRequest]:
"""Build a `get_request` side effect mapping request IDs back to their API client `Request`."""
by_id = {
unique_key_to_request_id(request.unique_key): _client_request(request, handled_at=None) for request in requests
}
return lambda request_id: by_id[request_id]
async def test_fetch_next_request_prolongs_expiring_lock() -> None:
"""A request whose lock is about to expire is prolonged, so a handler slower than the batch lock is still safe."""
client, api_client = _make_shared_client()
request = Request.from_url('https://example.com/1')
request_id = unique_key_to_request_id(request.unique_key)
now = datetime.now(tz=UTC)
api_client.list_and_lock_head = AsyncMock(
return_value=_locked_head([_locked_item(request, lock_expires_at=now + timedelta(seconds=30))])
)
api_client.get_request = AsyncMock(return_value=_client_request(request, handled_at=None))
api_client.prolong_request_lock = AsyncMock(
return_value=RequestLockInfo(lock_expires_at=now + timedelta(seconds=180))
)
fetched = await client.fetch_next_request()
assert fetched is not None
assert fetched.unique_key == request.unique_key
api_client.prolong_request_lock.assert_awaited_once()
assert api_client.prolong_request_lock.await_args is not None
assert api_client.prolong_request_lock.await_args.args[0] == request_id
async def test_fetch_next_request_keeps_fresh_lock() -> None:
"""A request still holding most of its batch lock is handed out as it is, without paying for a lock prolong."""
client, api_client = _make_shared_client()
request = Request.from_url('https://example.com/1')
future = datetime.now(tz=UTC) + timedelta(seconds=180)
api_client.list_and_lock_head = AsyncMock(
return_value=_locked_head([_locked_item(request, lock_expires_at=future)])
)
api_client.get_request = AsyncMock(return_value=_client_request(request, handled_at=None))
api_client.prolong_request_lock = AsyncMock(return_value=RequestLockInfo(lock_expires_at=future))
fetched = await client.fetch_next_request()
assert fetched is not None
assert fetched.unique_key == request.unique_key
api_client.prolong_request_lock.assert_not_awaited()
async def test_fetch_next_request_skips_expired_lock() -> None:
"""A queued head entry whose lock already lapsed is skipped in favour of the next entry with a live lock."""
client, api_client = _make_shared_client()
expired = Request.from_url('https://example.com/expired')
valid = Request.from_url('https://example.com/valid')
now = datetime.now(tz=UTC)
api_client.list_and_lock_head = AsyncMock(
return_value=_locked_head(
[
_locked_item(expired, lock_expires_at=now - timedelta(seconds=60)),
_locked_item(valid, lock_expires_at=now + timedelta(seconds=180)),
]
)
)
api_client.get_request = AsyncMock(side_effect=_client_request_getter([expired, valid]))
api_client.prolong_request_lock = AsyncMock(
return_value=RequestLockInfo(lock_expires_at=now + timedelta(seconds=180))
)
fetched = await client.fetch_next_request()
assert fetched is not None
assert fetched.unique_key == valid.unique_key
# The expired request is skipped rather than re-processed, and the live-lock one needs no prolong.
api_client.prolong_request_lock.assert_not_awaited()
async def test_fetch_next_request_does_not_rehand_in_progress() -> None:
"""A request already in progress is not handed out again even if the platform re-lists it after a lock lapse."""
client, api_client = _make_shared_client()
request = Request.from_url('https://example.com/1')
future = datetime.now(tz=UTC) + timedelta(seconds=180)
# The platform keeps returning the same locked request on every head listing.
api_client.list_and_lock_head = AsyncMock(
return_value=_locked_head([_locked_item(request, lock_expires_at=future)])
)
api_client.get_request = AsyncMock(return_value=_client_request(request, handled_at=None))
api_client.prolong_request_lock = AsyncMock(return_value=RequestLockInfo(lock_expires_at=future))
first = await client.fetch_next_request()
second = await client.fetch_next_request()
assert first is not None
assert first.unique_key == request.unique_key
assert second is None
async def test_fetch_next_request_skips_when_lock_prolong_fails() -> None:
"""A request whose lock cannot be prolonged is skipped and released, so a later fetch can still hand it out."""
client, api_client = _make_shared_client()
request = Request.from_url('https://example.com/1')
now = datetime.now(tz=UTC)
# The lock is about to expire, so every fetch of this request goes through a prolong.
api_client.list_and_lock_head = AsyncMock(
return_value=_locked_head([_locked_item(request, lock_expires_at=now + timedelta(seconds=30))])
)
api_client.get_request = AsyncMock(return_value=_client_request(request, handled_at=None))
api_client.prolong_request_lock = AsyncMock(
side_effect=[RuntimeError('lock lost'), RequestLockInfo(lock_expires_at=now + timedelta(seconds=180))]
)
first = await client.fetch_next_request()
second = await client.fetch_next_request()
assert first is None
assert second is not None
assert second.unique_key == request.unique_key
async def test_fetch_next_request_skips_when_lock_not_reacquired() -> None:
"""A `None` from `prolong_request_lock` (lock not re-acquired) is a skip, not a successful hand-out."""
client, api_client = _make_shared_client()
request = Request.from_url('https://example.com/1')
now = datetime.now(tz=UTC)
# The lock is about to expire, so every fetch of this request goes through a prolong.
api_client.list_and_lock_head = AsyncMock(
return_value=_locked_head([_locked_item(request, lock_expires_at=now + timedelta(seconds=30))])
)
api_client.get_request = AsyncMock(return_value=_client_request(request, handled_at=None))
# First fetch: lock not re-acquired (`None`); second: re-acquired.
api_client.prolong_request_lock = AsyncMock(
side_effect=[None, RequestLockInfo(lock_expires_at=now + timedelta(seconds=180))]
)
first = await client.fetch_next_request()
second = await client.fetch_next_request()
assert first is None
assert second is not None
assert second.unique_key == request.unique_key
async def test_is_finished_false_while_request_in_progress() -> None:
"""`is_finished` stays False while a fetched request is still in progress, even if the head lists empty."""
client, api_client = _make_shared_client()
request = Request.from_url('https://example.com/1')
future = datetime.now(tz=UTC) + timedelta(seconds=180)
api_client.list_and_lock_head = AsyncMock(
side_effect=[
_locked_head([_locked_item(request, lock_expires_at=future)]),
# In-progress request stays locked: head lists empty, no locked requests reported.
_locked_head([], queue_has_locked_requests=False),
]
)
api_client.get_request = AsyncMock(return_value=_client_request(request, handled_at=None))
api_client.prolong_request_lock = AsyncMock(return_value=RequestLockInfo(lock_expires_at=future))
fetched = await client.fetch_next_request()
assert fetched is not None
assert await client.is_finished() is False
async def test_mark_request_as_handled_clears_in_progress() -> None:
"""Marking a fetched request handled stops tracking it as in progress, so the queue can finish."""
client, api_client = _make_shared_client()
request = Request.from_url('https://example.com/1')
request_id = unique_key_to_request_id(request.unique_key)
future = datetime.now(tz=UTC) + timedelta(seconds=180)
api_client.list_and_lock_head = AsyncMock(
return_value=_locked_head([_locked_item(request, lock_expires_at=future)])
)
api_client.get_request = AsyncMock(return_value=_client_request(request, handled_at=None))
api_client.prolong_request_lock = AsyncMock(return_value=RequestLockInfo(lock_expires_at=future))
api_client.update_request = AsyncMock(return_value=_processed(request))
fetched = await client.fetch_next_request()
assert fetched is not None
assert request_id in client._requests_in_progress
await client.mark_request_as_handled(fetched)
assert request_id not in client._requests_in_progress
async def test_reclaim_request_frees_in_progress() -> None:
"""Reclaiming a fetched request stops tracking it as in progress so it can be handed out again."""
client, api_client = _make_shared_client()
request = Request.from_url('https://example.com/1')
request_id = unique_key_to_request_id(request.unique_key)
future = datetime.now(tz=UTC) + timedelta(seconds=180)
api_client.list_and_lock_head = AsyncMock(
return_value=_locked_head([_locked_item(request, lock_expires_at=future)])
)
api_client.get_request = AsyncMock(return_value=_client_request(request, handled_at=None))
api_client.prolong_request_lock = AsyncMock(return_value=RequestLockInfo(lock_expires_at=future))
api_client.update_request = AsyncMock(return_value=_processed(request))
first = await client.fetch_next_request()
assert first is not None
assert request_id in client._requests_in_progress
await client.reclaim_request(first)
assert request_id not in client._requests_in_progress
# After reclaim the same request is eligible to be handed out again.
second = await client.fetch_next_request()
assert second is not None
assert second.unique_key == request.unique_key
def _head_item(request: Request) -> RequestQueueHeadItem:
"""Build a `list_head` item for the given request."""
return RequestQueueHeadItem(
id=unique_key_to_request_id(request.unique_key),
unique_key=request.unique_key,
url=request.url,
method=request.method,
retry_count=0,
)
def _head(*items: RequestQueueHeadItem) -> RequestQueueHead:
"""Build a `list_head` response wrapping the given items."""
return RequestQueueHead(
limit=200,
queue_modified_at=datetime.now(tz=UTC),
had_multiple_clients=False,
items=list(items),
)
@pytest.mark.parametrize('forefront', [pytest.param(False, id='default'), pytest.param(True, id='forefront')])
async def test_single_reclaimed_request_kept_pending_while_head_lags(*, forefront: bool) -> None:
"""A reclaimed request stays locally pending in single mode while the platform head listing lags behind it."""
client, api_client = _make_single_client()
request = Request.from_url('https://example.com/1')
# The head serves the request once, then lags behind the reclaim and keeps listing empty.
api_client.list_head = AsyncMock(side_effect=chain([_head(_head_item(request))], repeat(_head())))
api_client.get_request = AsyncMock(return_value=_client_request(request, handled_at=None))
api_client.update_request = AsyncMock(return_value=_request_registration(request, was_already_handled=False))
fetched = await client.fetch_next_request()
assert fetched is not None
await client.reclaim_request(fetched, forefront=forefront)
# A True here would let `AutoscaledPool` end the run while the request is still pending on the platform.
assert await client.is_empty() is False
assert await client.is_finished() is False
refetched = await client.fetch_next_request()
assert refetched is not None
assert refetched.unique_key == request.unique_key
@pytest.mark.parametrize(
('forefront', 'expected_order'),
[
pytest.param(False, ['https://example.com/2', 'https://example.com/1'], id='default'),
pytest.param(True, ['https://example.com/1', 'https://example.com/2'], id='forefront'),
],
)
async def test_single_reclaimed_request_position_follows_forefront(
*,
forefront: bool,
expected_order: list[str],
) -> None:
"""A reclaimed request re-enters the local head estimate at the top with `forefront`, at the bottom without it."""
client, api_client = _make_single_client()
first = Request.from_url('https://example.com/1')
second = Request.from_url('https://example.com/2')
# The head serves both requests once, then lags behind the reclaim and keeps listing empty.
api_client.list_head = AsyncMock(side_effect=chain([_head(_head_item(first), _head_item(second))], repeat(_head())))
api_client.get_request = AsyncMock(side_effect=_client_request_getter([first, second]))
api_client.update_request = AsyncMock(return_value=_request_registration(first, was_already_handled=False))
fetched = await client.fetch_next_request()
assert fetched is not None
assert fetched.url == first.url
await client.reclaim_request(fetched, forefront=forefront)
first_served = await client.fetch_next_request()
second_served = await client.fetch_next_request()
assert first_served is not None
assert second_served is not None
assert [first_served.url, second_served.url] == expected_order
async def test_single_reclaimed_request_finishes_queue_once_handled() -> None:
"""The head entry a reclaim leaves behind is drained, so the queue still reports finished once handled."""
client, api_client = _make_single_client()
request = Request.from_url('https://example.com/1')
api_client.list_head = AsyncMock(side_effect=chain([_head(_head_item(request))], repeat(_head())))
api_client.get_request = AsyncMock(return_value=_client_request(request, handled_at=None))
api_client.update_request = AsyncMock(return_value=_request_registration(request, was_already_handled=False))
fetched = await client.fetch_next_request()
assert fetched is not None
await client.reclaim_request(fetched)
refetched = await client.fetch_next_request()
assert refetched is not None
await client.mark_request_as_handled(refetched)
assert await client.is_finished() is True