|
15 | 15 | from apify_client import ApifyClient, ApifyClientAsync |
16 | 16 | from apify_client._logging import RedirectLogFormatter |
17 | 17 | from apify_client._status_message_watcher import StatusMessageWatcherBase |
18 | | -from apify_client._streamed_log import StreamedLog, StreamedLogBase |
| 18 | +from apify_client._streamed_log import StreamedLog, StreamedLogAsync, StreamedLogBase |
19 | 19 |
|
20 | 20 | if TYPE_CHECKING: |
21 | 21 | from collections.abc import Iterator |
@@ -820,13 +820,13 @@ def generate_logs() -> Iterator[bytes]: |
820 | 820 | assert any(_TAIL_SECOND_MESSAGE in m for m in messages), f'Buffered tail dropped on async stop(). Got: {messages}' |
821 | 821 |
|
822 | 822 |
|
823 | | -def test_streamed_log_sync_stop_does_not_hang_on_silent_stream( |
| 823 | +def test_streamed_log_sync_stop_unblocks_on_finite_stream_timeout( |
824 | 824 | httpserver: HTTPServer, |
825 | 825 | monkeypatch: pytest.MonkeyPatch, |
826 | 826 | ) -> None: |
827 | | - """Verify `stop()` returns promptly even when the underlying stream is silent (no chunks).""" |
828 | | - # Shorten the read timeout so the test doesn't wait for the production default. |
829 | | - monkeypatch.setattr(StreamedLog, '_read_timeout', timedelta(seconds=1)) |
| 827 | + """A finite `_stream_timeout` bounds how long `stop()` waits on a silent stream, since the blocking read cannot |
| 828 | + otherwise be interrupted (the production default is `no_timeout`, so the test configures a short finite one).""" |
| 829 | + monkeypatch.setattr(StreamedLog, '_stream_timeout', timedelta(seconds=1)) |
830 | 830 |
|
831 | 831 | release_server = threading.Event() |
832 | 832 |
|
@@ -857,6 +857,143 @@ def generate_logs() -> Iterator[bytes]: |
857 | 857 | stop_thread = threading.Thread(target=streamed_log.stop) |
858 | 858 | stop_thread.start() |
859 | 859 | stop_thread.join(timeout=5) |
860 | | - assert not stop_thread.is_alive(), 'stop() hangs when the underlying stream is silent' |
| 860 | + assert not stop_thread.is_alive(), 'stop() did not unblock within the finite stream timeout' |
861 | 861 | finally: |
862 | 862 | release_server.set() |
| 863 | + |
| 864 | + |
| 865 | +@pytest.mark.usefixtures('propagate_stream_logs') |
| 866 | +def test_streamed_log_sync_does_not_leak_exception_on_stream_timeout( |
| 867 | + caplog: LogCaptureFixture, |
| 868 | + httpserver: HTTPServer, |
| 869 | + monkeypatch: pytest.MonkeyPatch, |
| 870 | +) -> None: |
| 871 | + """The streaming thread ends quietly when the log-stream request hits its total timeout (regression #1040).""" |
| 872 | + # impit enforces a whole-request timeout, so a still-running Actor whose run outlives the timeout makes |
| 873 | + # `iter_bytes()` raise `impit.TimeoutException`. Shorten the timeout to trigger this quickly. |
| 874 | + monkeypatch.setattr(StreamedLog, '_stream_timeout', timedelta(seconds=1)) |
| 875 | + |
| 876 | + release_server = threading.Event() |
| 877 | + |
| 878 | + def _slow_handler(_request: Request) -> Response: |
| 879 | + def generate_logs() -> Iterator[bytes]: |
| 880 | + # Emit one complete line, then keep the connection open (as a running Actor would) past the |
| 881 | + # client-side total timeout without sending anything more. |
| 882 | + yield b'2025-05-13T07:24:12.588Z ACTOR: still running\n' |
| 883 | + release_server.wait(timeout=30) |
| 884 | + |
| 885 | + return Response(response=generate_logs(), status=200, mimetype='application/octet-stream') |
| 886 | + |
| 887 | + httpserver.expect_request( |
| 888 | + f'/v2/actor-runs/{_MOCKED_RUN_ID}/log', method='GET', query_string='stream=true&raw=true' |
| 889 | + ).respond_with_handler(_slow_handler) |
| 890 | + _register_run_and_actor_endpoints(httpserver) |
| 891 | + |
| 892 | + api_url = httpserver.url_for('/').removesuffix('/') |
| 893 | + run_client = ApifyClient(token='mocked_token', api_url=api_url).run(run_id=_MOCKED_RUN_ID) |
| 894 | + streamed_log = run_client.get_streamed_log() |
| 895 | + logger_name = f'apify.{_MOCKED_ACTOR_NAME}-{_MOCKED_RUN_ID}' |
| 896 | + |
| 897 | + thread_exceptions: list[threading.ExceptHookArgs] = [] |
| 898 | + monkeypatch.setattr(threading, 'excepthook', thread_exceptions.append) |
| 899 | + |
| 900 | + try: |
| 901 | + with caplog.at_level(logging.DEBUG, logger=logger_name): |
| 902 | + thread = streamed_log.start() |
| 903 | + # Wait past the 1s total timeout so the streaming request fails inside the thread. |
| 904 | + thread.join(timeout=5) |
| 905 | + assert not thread.is_alive(), 'streaming thread did not end after the stream timed out' |
| 906 | + finally: |
| 907 | + release_server.set() |
| 908 | + streamed_log.stop() |
| 909 | + |
| 910 | + leaked = [args.exc_type.__name__ for args in thread_exceptions] |
| 911 | + assert not leaked, f'streaming thread leaked an uncaught exception: {leaked}' |
| 912 | + # The timeout is expected, so it must be swallowed quietly, not funnelled through the generic error handler. |
| 913 | + error_records = [r for r in caplog.records if r.levelno >= logging.ERROR and 'Log redirection stopped' in r.message] |
| 914 | + assert not error_records, f'sync thread logged an error on stream timeout: {[r.message for r in error_records]}' |
| 915 | + # The line received before the timeout must still have been redirected. |
| 916 | + assert any('ACTOR: still running' in record.message for record in caplog.records) |
| 917 | + |
| 918 | + |
| 919 | +@pytest.mark.usefixtures('propagate_stream_logs') |
| 920 | +def test_streamed_log_sync_requests_stream_with_no_timeout( |
| 921 | + httpserver: HTTPServer, |
| 922 | + monkeypatch: pytest.MonkeyPatch, |
| 923 | +) -> None: |
| 924 | + """The log stream is requested with `no_timeout`, so a long run is not truncated mid-stream (#1040).""" |
| 925 | + httpserver.expect_request( |
| 926 | + f'/v2/actor-runs/{_MOCKED_RUN_ID}/log', method='GET', query_string='stream=true&raw=true' |
| 927 | + ).respond_with_data(b'2025-05-13T07:24:12.588Z ACTOR: done\n', content_type='application/octet-stream') |
| 928 | + _register_run_and_actor_endpoints(httpserver) |
| 929 | + |
| 930 | + api_url = httpserver.url_for('/').removesuffix('/') |
| 931 | + run_client = ApifyClient(token='mocked_token', api_url=api_url).run(run_id=_MOCKED_RUN_ID) |
| 932 | + |
| 933 | + # Capture the timeout the log stream is requested with. impit applies it to the whole request (body included), |
| 934 | + # so anything but `no_timeout` would cut a long run off mid-stream, which is the root cause of #1040. |
| 935 | + log_stream_timeouts: list[object] = [] |
| 936 | + original_call = run_client._http_client.call |
| 937 | + |
| 938 | + def _recording_call(**kwargs: object) -> object: |
| 939 | + if str(kwargs.get('url', '')).endswith('/log'): |
| 940 | + log_stream_timeouts.append(kwargs.get('timeout')) |
| 941 | + return original_call(**kwargs) |
| 942 | + |
| 943 | + monkeypatch.setattr(run_client._http_client, 'call', _recording_call) |
| 944 | + |
| 945 | + streamed_log = run_client.get_streamed_log() |
| 946 | + thread = streamed_log.start() |
| 947 | + thread.join(timeout=5) |
| 948 | + streamed_log.stop() |
| 949 | + |
| 950 | + assert log_stream_timeouts == ['no_timeout'], ( |
| 951 | + f'log stream requested with timeout={log_stream_timeouts}, expected no_timeout so long runs are not truncated' |
| 952 | + ) |
| 953 | + |
| 954 | + |
| 955 | +@pytest.mark.usefixtures('propagate_stream_logs') |
| 956 | +async def test_streamed_log_async_does_not_error_on_stream_timeout( |
| 957 | + caplog: LogCaptureFixture, |
| 958 | + httpserver: HTTPServer, |
| 959 | + monkeypatch: pytest.MonkeyPatch, |
| 960 | +) -> None: |
| 961 | + """The async streaming task ends quietly on a stream-request timeout, matching the sync regression for #1040.""" |
| 962 | + monkeypatch.setattr(StreamedLogAsync, '_stream_timeout', timedelta(seconds=1)) |
| 963 | + |
| 964 | + release_server = threading.Event() |
| 965 | + |
| 966 | + def _slow_handler(_request: Request) -> Response: |
| 967 | + def generate_logs() -> Iterator[bytes]: |
| 968 | + # Emit one complete line, then keep the connection open past the client-side total timeout. |
| 969 | + yield b'2025-05-13T07:24:12.588Z ACTOR: still running\n' |
| 970 | + release_server.wait(timeout=30) |
| 971 | + |
| 972 | + return Response(response=generate_logs(), status=200, mimetype='application/octet-stream') |
| 973 | + |
| 974 | + httpserver.expect_request( |
| 975 | + f'/v2/actor-runs/{_MOCKED_RUN_ID}/log', method='GET', query_string='stream=true&raw=true' |
| 976 | + ).respond_with_handler(_slow_handler) |
| 977 | + _register_run_and_actor_endpoints(httpserver) |
| 978 | + |
| 979 | + api_url = httpserver.url_for('/').removesuffix('/') |
| 980 | + run_client = ApifyClientAsync(token='mocked_token', api_url=api_url).run(run_id=_MOCKED_RUN_ID) |
| 981 | + streamed_log = await run_client.get_streamed_log() |
| 982 | + logger_name = f'apify.{_MOCKED_ACTOR_NAME}-{_MOCKED_RUN_ID}' |
| 983 | + |
| 984 | + try: |
| 985 | + with caplog.at_level(logging.DEBUG, logger=logger_name): |
| 986 | + task = streamed_log.start() |
| 987 | + # The 1s total timeout fails the request inside the task; it must end on its own without our help. |
| 988 | + done, _pending = await asyncio.wait({task}, timeout=5) |
| 989 | + assert task in done, 'async streaming task did not end after the stream timed out' |
| 990 | + finally: |
| 991 | + release_server.set() |
| 992 | + await streamed_log.stop() |
| 993 | + |
| 994 | + assert not task.cancelled() |
| 995 | + assert task.exception() is None, f'async streaming task raised on stream timeout: {task.exception()!r}' |
| 996 | + error_records = [r for r in caplog.records if r.levelno >= logging.ERROR and 'Log redirection stopped' in r.message] |
| 997 | + assert not error_records, f'async task logged an error on stream timeout: {[r.message for r in error_records]}' |
| 998 | + # The line received before the timeout must still have been redirected. |
| 999 | + assert any('ACTOR: still running' in record.message for record in caplog.records) |
0 commit comments