diff --git a/docs/02_concepts/06_logging.mdx b/docs/02_concepts/06_logging.mdx index acc20232..5da93e3e 100644 --- a/docs/02_concepts/06_logging.mdx +++ b/docs/02_concepts/06_logging.mdx @@ -14,6 +14,8 @@ import RedirectCallAsyncExample from '!!raw-loader!./code/06_redirect_call_async import RedirectCallSyncExample from '!!raw-loader!./code/06_redirect_call_sync.py'; import RedirectRunAsyncExample from '!!raw-loader!./code/06_redirect_run_async.py'; import RedirectRunSyncExample from '!!raw-loader!./code/06_redirect_run_sync.py'; +import RedirectResumeAsyncExample from '!!raw-loader!./code/06_redirect_resume_async.py'; +import RedirectResumeSyncExample from '!!raw-loader!./code/06_redirect_resume_sync.py'; import ApiLink from '@theme/ApiLink'; @@ -74,3 +76,22 @@ For a run started with `ActorClient.start` + +By default, the whole log of the run is redirected. To redirect only part of it, pass a `datetime` as `since`, and only the lines logged at that time or later are redirected. A naive `datetime` is treated as UTC. The deprecated `from_start` argument still works: `from_start=False` is the same as `since=datetime.now(tz=UTC)`. + +The platform cuts off a log stream that has carried no data for several minutes, even when the run is still going. When that happens, the client reopens the stream. The API can't continue a stream from a given point, so the reopened stream delivers the log from its start, and the client skips everything up to `StreamedLog.last_redirected_at`, the timestamp of the last redirected line. A stream that ends on its own has delivered the whole log of a finished run, and the client doesn't open it again. + +The same property lets you continue the redirection in another process, for example after the Actor that redirects the log reboots. Save `last_redirected_at` before the reboot, and afterwards pass it plus one millisecond as `since`. Log timestamps have millisecond precision, so this skips the last redirected line. It would also skip another line logged in that same millisecond and not yet redirected, which is rare. + + + + + {RedirectResumeAsyncExample} + + + + + {RedirectResumeSyncExample} + + + diff --git a/docs/02_concepts/code/06_redirect_resume_async.py b/docs/02_concepts/code/06_redirect_resume_async.py new file mode 100644 index 00000000..ecc175da --- /dev/null +++ b/docs/02_concepts/code/06_redirect_resume_async.py @@ -0,0 +1,28 @@ +from datetime import datetime, timedelta + +from apify_client import ApifyClientAsync + +TOKEN = 'MY-APIFY-TOKEN' +RECORD_KEY = 'LOG_REDIRECTED_UNTIL' + + +async def main() -> None: + apify_client = ApifyClientAsync(TOKEN) + run_client = apify_client.run('MY-RUN-ID') + store_client = apify_client.key_value_store('MY-STORE-ID') + + # After a reboot, continue after the last line redirected before it. + record = await store_client.get_record(RECORD_KEY) + since = None + if record: + since = datetime.fromisoformat(record['value']) + timedelta(milliseconds=1) + + streamed_log = await run_client.get_streamed_log(since=since) + async with streamed_log: + await run_client.wait_for_finish() + + # Before a reboot, save how far the redirection got. Here it is saved once the + # run finishes; save it on your own reboot or migration signal instead. + if streamed_log.last_redirected_at: + redirected_until = streamed_log.last_redirected_at.isoformat() + await store_client.set_record(RECORD_KEY, redirected_until) diff --git a/docs/02_concepts/code/06_redirect_resume_sync.py b/docs/02_concepts/code/06_redirect_resume_sync.py new file mode 100644 index 00000000..ef34ef48 --- /dev/null +++ b/docs/02_concepts/code/06_redirect_resume_sync.py @@ -0,0 +1,28 @@ +from datetime import datetime, timedelta + +from apify_client import ApifyClient + +TOKEN = 'MY-APIFY-TOKEN' +RECORD_KEY = 'LOG_REDIRECTED_UNTIL' + + +def main() -> None: + apify_client = ApifyClient(TOKEN) + run_client = apify_client.run('MY-RUN-ID') + store_client = apify_client.key_value_store('MY-STORE-ID') + + # After a reboot, continue after the last line redirected before it. + record = store_client.get_record(RECORD_KEY) + since = None + if record: + since = datetime.fromisoformat(record['value']) + timedelta(milliseconds=1) + + streamed_log = run_client.get_streamed_log(since=since) + with streamed_log: + run_client.wait_for_finish() + + # Before a reboot, save how far the redirection got. Here it is saved once the + # run finishes; save it on your own reboot or migration signal instead. + if streamed_log.last_redirected_at: + redirected_until = streamed_log.last_redirected_at.isoformat() + store_client.set_record(RECORD_KEY, redirected_until) diff --git a/docs/02_concepts/code/06_redirect_run_async.py b/docs/02_concepts/code/06_redirect_run_async.py index 333f733e..d55fce97 100644 --- a/docs/02_concepts/code/06_redirect_run_async.py +++ b/docs/02_concepts/code/06_redirect_run_async.py @@ -1,3 +1,5 @@ +from datetime import UTC, datetime + from apify_client import ApifyClientAsync TOKEN = 'MY-APIFY-TOKEN' @@ -20,8 +22,8 @@ async def main() -> None: actor_run = await actor_client.start() run_client = apify_client.run(actor_run.id) - # With `from_start=False`, only log lines written from now on are redirected. - streamed_log = await run_client.get_streamed_log(from_start=False) + # With `since`, only log lines written at that time or later are redirected. + streamed_log = await run_client.get_streamed_log(since=datetime.now(tz=UTC)) streamed_log.start() # Do other work while the run's log is redirected. await streamed_log.stop() diff --git a/docs/02_concepts/code/06_redirect_run_sync.py b/docs/02_concepts/code/06_redirect_run_sync.py index 4281c5fe..411e2c24 100644 --- a/docs/02_concepts/code/06_redirect_run_sync.py +++ b/docs/02_concepts/code/06_redirect_run_sync.py @@ -1,3 +1,5 @@ +from datetime import UTC, datetime + from apify_client import ApifyClient TOKEN = 'MY-APIFY-TOKEN' @@ -20,8 +22,8 @@ def main() -> None: actor_run = actor_client.start() run_client = apify_client.run(actor_run.id) - # With `from_start=False`, only log lines written from now on are redirected. - streamed_log = run_client.get_streamed_log(from_start=False) + # With `since`, only log lines written at that time or later are redirected. + streamed_log = run_client.get_streamed_log(since=datetime.now(tz=UTC)) streamed_log.start() # Do other work while the run's log is redirected. streamed_log.stop() diff --git a/src/apify_client/_resource_clients/run.py b/src/apify_client/_resource_clients/run.py index 22c44711..8947e81a 100644 --- a/src/apify_client/_resource_clients/run.py +++ b/src/apify_client/_resource_clients/run.py @@ -4,7 +4,7 @@ import random import string import time -from datetime import timedelta +from datetime import datetime, timedelta from typing import TYPE_CHECKING, Any, Literal from apify_client._docs import docs_group @@ -14,7 +14,7 @@ from apify_client._pagination import DEFAULT_CHUNK_SIZE from apify_client._resource_clients._resource_client import _TERMINAL_STATUSES, ResourceClient, ResourceClientAsync from apify_client._status_message_watcher import StatusMessageWatcher, StatusMessageWatcherAsync -from apify_client._streamed_log import StreamedLog, StreamedLogAsync +from apify_client._streamed_log import StreamedLog, StreamedLogAsync, resolve_since from apify_client._utils.encoding import encode_key_value_store_record_value from apify_client._utils.http import response_to_dict, to_safe_id from apify_client._utils.time import to_seconds @@ -350,23 +350,29 @@ def get_streamed_log( self, to_logger: logging.Logger | None = None, *, - from_start: bool = True, + since: datetime | None = None, + from_start: bool | None = None, timeout: Timeout = 'long', ) -> StreamedLog: """Get `StreamedLog` instance that can be used to redirect logs. - `StreamedLog` can be explicitly started and stopped or used as a context manager. + `StreamedLog` can be explicitly started and stopped or used as a context manager. When the platform closes + the log stream while the run is still going, for example after the run has logged nothing for several + minutes, the stream is reopened and the redirection resumes after the last redirected message. Args: to_logger: `Logger` used for logging the redirected messages. If not provided, a new logger is created - from_start: If `True`, all logs from the start of the Actor run will be redirected. If `False`, only newly - arrived logs will be redirected. This can be useful for redirecting only a small portion of relevant - logs for long-running Actors in stand-by. + since: Redirect only the log messages logged at this time or later. A naive datetime is treated as UTC. + If `None`, the whole log is redirected. Redirecting only the recent messages can be useful for + long-running Actors, such as Server Actors. + from_start: Deprecated, use `since` instead. `True` is the same as `since=None`, and `False` the same as + `since=datetime.now(tz=UTC)`. Will be removed in v4. timeout: Timeout for the API HTTP request. Returns: `StreamedLog` instance for redirected logs. """ + since = resolve_since(since=since, from_start=from_start) run_data = self.get(timeout=timeout) run_id = f'runId:{run_data.id}' if run_data and run_data.id else '' @@ -387,7 +393,7 @@ def get_streamed_log( name = ' '.join(part for part in (actor_name, run_id) if part) to_logger = create_redirect_logger(f'apify.{name}') - return StreamedLog(log_client=self.log(), to_logger=to_logger, from_start=from_start) + return StreamedLog(log_client=self.log(), to_logger=to_logger, since=since) def charge( self, @@ -943,23 +949,29 @@ async def get_streamed_log( self, to_logger: logging.Logger | None = None, *, - from_start: bool = True, + since: datetime | None = None, + from_start: bool | None = None, timeout: Timeout = 'long', ) -> StreamedLogAsync: """Get `StreamedLog` instance that can be used to redirect logs. - `StreamedLog` can be explicitly started and stopped or used as a context manager. + `StreamedLog` can be explicitly started and stopped or used as a context manager. When the platform closes + the log stream while the run is still going, for example after the run has logged nothing for several + minutes, the stream is reopened and the redirection resumes after the last redirected message. Args: to_logger: `Logger` used for logging the redirected messages. If not provided, a new logger is created - from_start: If `True`, all logs from the start of the Actor run will be redirected. If `False`, only newly - arrived logs will be redirected. This can be useful for redirecting only a small portion of relevant - logs for long-running Actors in stand-by. + since: Redirect only the log messages logged at this time or later. A naive datetime is treated as UTC. + If `None`, the whole log is redirected. Redirecting only the recent messages can be useful for + long-running Actors, such as Server Actors. + from_start: Deprecated, use `since` instead. `True` is the same as `since=None`, and `False` the same as + `since=datetime.now(tz=UTC)`. Will be removed in v4. timeout: Timeout for the API HTTP request. Returns: `StreamedLog` instance for redirected logs. """ + since = resolve_since(since=since, from_start=from_start) run_data = await self.get(timeout=timeout) run_id = f'runId:{run_data.id}' if run_data and run_data.id else '' @@ -980,7 +992,7 @@ async def get_streamed_log( name = ' '.join(part for part in (actor_name, run_id) if part) to_logger = create_redirect_logger(f'apify.{name}') - return StreamedLogAsync(log_client=self.log(), to_logger=to_logger, from_start=from_start) + return StreamedLogAsync(log_client=self.log(), to_logger=to_logger, since=since) async def charge( self, diff --git a/src/apify_client/_streamed_log.py b/src/apify_client/_streamed_log.py index 687a3215..fcc8f990 100644 --- a/src/apify_client/_streamed_log.py +++ b/src/apify_client/_streamed_log.py @@ -4,6 +4,7 @@ import logging import re import threading +import warnings from asyncio import Task from datetime import UTC, datetime from threading import Thread @@ -15,12 +16,43 @@ from types import TracebackType from apify_client._resource_clients import LogClient, LogClientAsync - from apify_client.http_clients import HttpResponse + from apify_client.http_clients import HttpClient, HttpClientAsync, HttpResponse from apify_client.types import Timeout _ANSI_CODE = re.compile(r'\x1b\[[0-9;]*m') _LEVEL_PATTERN = re.compile(r'\b(CRITICAL|FATAL|ERROR|WARNING|WARN|INFO|DEBUG)\b') +_NO_PROGRESS_MESSAGE = ( + 'Log redirection stopped: the reopened log stream broke off again before it reached the last redirected line: %r' +) + + +def _as_utc(value: datetime | None) -> datetime | None: + """Return `value` as an aware datetime, treating a naive one as UTC like the rest of the client does.""" + if value is None or value.tzinfo is not None: + return value + return value.replace(tzinfo=UTC) + + +def resolve_since(*, since: datetime | None, from_start: bool | None) -> datetime | None: + """Return the time to redirect the log from, given `since` and the deprecated `from_start` argument. + + A set `from_start` emits a `DeprecationWarning`. `from_start=True` means the whole log, `from_start=False` the log + from now on. + + Raises: + ValueError: If both `since` and `from_start` are set. + """ + if from_start is None: + return since + warnings.warn( + 'The `from_start` argument is deprecated and will be removed in v4. Use `since` instead.', + DeprecationWarning, + stacklevel=3, + ) + if since is not None: + raise ValueError('Pass only one of `since` and `from_start`.') + return None if from_start else datetime.now(tz=UTC) class StreamedLogBase: @@ -47,14 +79,28 @@ class StreamedLogBase: _empty_stream_max_retry_s: ClassVar[float] = 5 """Upper bound on the pause between reopens of an empty log stream.""" - def __init__(self, to_logger: logging.Logger, *, from_start: bool = True) -> None: + _reopen_pause_s: ClassVar[float] = 1 + """Pause before reopening a log stream that broke off before its end. + + The platform cuts off a log stream that has carried no data for several minutes, even though the run goes on. The + cut-off stream fails with a transport error, while the stream of a finished log ends without one. + """ + + def __init__(self, to_logger: logging.Logger, *, since: datetime | None = None) -> None: if self._force_propagate: to_logger.propagate = True self._to_logger = to_logger self._stream_buffer = list[bytes]() self._split_marker = re.compile(rb'(?:\n|^)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)') - self._relevancy_time_limit: datetime | None = None if from_start else datetime.now(tz=UTC) + self._since = _as_utc(since) self._received_data = False + self._last_redirected_at: datetime | None = None + # How many redirected messages carry `_last_redirected_at`. Several messages can share a millisecond. + self._redirected_at_last_timestamp = 0 + # What a reopened stream replays: the messages before `_replayed_until`, and the first `_replay_skip_count` + # messages at it. + self._replayed_until: datetime | None = None + self._replay_skip_count = 0 def _process_new_data(self, data: bytes) -> None: if data: @@ -85,13 +131,56 @@ def _log_buffer_content(self, *, include_last_part: bool = False) -> None: for marker, content in zip(message_markers, message_contents, strict=True): decoded_marker = marker.decode('utf-8') decoded_content = content.decode('utf-8') - if self._relevancy_time_limit: - log_time = datetime.fromisoformat(decoded_marker) - if log_time < self._relevancy_time_limit: - # Skip irrelevant logs - continue + log_time = datetime.fromisoformat(decoded_marker) + if self._is_replayed(log_time): + continue + if self._since is not None and log_time < self._since: + continue message = decoded_marker + decoded_content self._to_logger.log(level=self._guess_log_level_from_message(message), msg=message.strip()) + self._remember_redirected(log_time) + + def _is_replayed(self, log_time: datetime) -> bool: + """Return whether a message of a reopened stream was already redirected before the stream was reopened. + + Trimming of a long log removes only its oldest lines, so the replay keeps the last redirected messages in their + order, and counting the ones at the last timestamp finds where the redirection left off. + """ + if self._replayed_until is None: + return False + if log_time < self._replayed_until: + return True + if log_time == self._replayed_until and self._replay_skip_count > 0: + self._replay_skip_count -= 1 + return True + self._replayed_until = None + return False + + def _remember_redirected(self, log_time: datetime) -> None: + if log_time == self._last_redirected_at: + self._redirected_at_last_timestamp += 1 + else: + self._last_redirected_at = log_time + self._redirected_at_last_timestamp = 1 + + def _replay_caught_up(self) -> bool: + """Return whether the current stream got at least as far as the stream before it. + + A reopened stream that breaks off again before it replays the last redirected message makes no progress, and + reopening it again would most likely fail at the same point. + """ + return self._replayed_until is None or self._replay_skip_count == 0 + + def _prepare_reopen(self) -> None: + """Make the reopened stream redirect only the messages after the last redirected one. + + The API cannot continue a log stream from a given point, so the reopened stream replays the log from its start. + The unterminated last line of the stream that broke off is dropped, since the reopened stream delivers it in + full. + """ + self._stream_buffer = [] + self._replayed_until = self._last_redirected_at + self._replay_skip_count = self._redirected_at_last_timestamp def _process_whole_log(self, log: bytes | None) -> None: """Redirect a whole log read in one request, including its last part.""" @@ -99,6 +188,11 @@ def _process_whole_log(self, log: bytes | None) -> None: self._process_new_data(log) self._log_buffer_content(include_last_part=True) + @staticmethod + def _is_broken_read(http_client: HttpClient | HttpClientAsync, exc: Exception) -> bool: + """Return whether `exc`, raised while reading the stream, means the transport cut the stream off.""" + return http_client.is_retryable_transport_error(exc) and not http_client.is_timeout_error(exc) + @staticmethod def _guess_log_level_from_message(message: str) -> int: """Return the first whole-word level name found in the message, ignoring ANSI colors. Default to INFO.""" @@ -124,22 +218,40 @@ class StreamedLog(StreamedLogBase): without a bound `stop` would wait for the next chunk, which on a quiet run may be hours away. """ - def __init__(self, log_client: LogClient, *, to_logger: logging.Logger, from_start: bool = True) -> None: + def __init__( + self, + log_client: LogClient, + *, + to_logger: logging.Logger, + since: datetime | None = None, + from_start: bool | None = None, + ) -> None: """Initialize `StreamedLog`. Args: log_client: The log client used to stream raw log data from the Actor run. to_logger: The logger to which the log messages will be forwarded. - from_start: If `True`, all logs from the start of the Actor run will be streamed. If `False`, only newly - arrived logs will be streamed. This can be useful for long-running Actors in stand-by mode where only - recent logs are relevant. + since: Redirect only the log messages logged at this time or later. A naive datetime is treated as UTC. + If `None`, the whole log is redirected. + from_start: Deprecated, use `since` instead. `True` is the same as `since=None`, and `False` the same as + `since=datetime.now(tz=UTC)`. Will be removed in v4. """ - super().__init__(to_logger=to_logger, from_start=from_start) + since = resolve_since(since=since, from_start=from_start) + super().__init__(to_logger=to_logger, since=since) self._log_client = log_client self._streaming_thread: Thread | None = None self._log_stream: HttpResponse | None = None self._stop_event = threading.Event() + @property + def last_redirected_at(self) -> datetime | None: + """The timestamp of the last redirected log message, or `None` if nothing has been redirected yet. + + To continue the redirection later, for example after the Actor that redirects the log reboots, save it and + pass it plus one millisecond as `since` to `RunClient.get_streamed_log`. + """ + return self._last_redirected_at + def start(self) -> Thread: """Start the streaming thread. @@ -193,11 +305,14 @@ def __exit__( def _stream_log(self) -> None: try: - # An empty stream means the run has not logged anything yet, so reopen it until the first bytes arrive. retry_s = self._empty_stream_retry_s while not self._stop_event.is_set(): - if not self._stream_log_once() or self._received_data: + if not self._stream_log_once(): return + if self._received_data: + self._stop_event.wait(self._reopen_pause_s) + continue + # An empty stream means the run has not logged anything yet, so reopen it until the first bytes arrive. self._stop_event.wait(retry_s) retry_s = min(retry_s * 2, self._empty_stream_max_retry_s) except Exception as exc: @@ -208,12 +323,15 @@ def _stream_log(self) -> None: # The stream cannot continue, so warn and let the thread end instead of leaking a traceback. self._to_logger.warning('Log streaming stopped: the log stream request timed out.') return + else: # Any other failure in log redirection must not escape the background thread; log it instead. self._to_logger.exception('Log redirection stopped due to unexpected error:') return + if self._received_data: return + # Stopped before any stream delivered a byte, which a run that finishes quickly can cause. try: self._process_whole_log(self._log_client.get_as_bytes(raw=True)) @@ -221,22 +339,44 @@ def _stream_log(self) -> None: self._to_logger.exception('Log redirection stopped due to unexpected error:') def _stream_log_once(self) -> bool: - """Redirect one log stream until it ends or `stop` is called. Return `False` when the log does not exist.""" + """Redirect one log stream until it ends or `stop` is called. Return whether the stream has to be opened again. + + A stream is opened again when it was empty, or when it broke off after it had delivered data. A stream that + ends without an error after delivering data carried the whole log of a finished run. + """ with self._log_client.stream(raw=True, timeout=self._stream_timeout) as log_stream: if not log_stream: return False # Published so `stop` can close the response. self._log_stream = log_stream + broke_off = False try: - # `stop` may have run before the response existed for it to close. No earlier stream delivered - # anything, and one opened this late would end after its first chunk, so read the whole log in one - # request. + # `stop` may have run before the response existed for it to close. A stream opened this late would end + # after its first chunk, so leave the log to the earlier streams, or to the one-shot read when none of + # them delivered anything. if self._stop_event.is_set(): return True - for data in log_stream.iter_bytes(): - self._process_new_data(data) - if self._stop_event.is_set(): + chunks = iter(log_stream.iter_bytes()) + while not self._stop_event.is_set(): + # Only a failed read means the stream broke off. A failure to process the data would repeat on + # every replay, so it ends the redirection. + try: + data = next(chunks) + except StopIteration: break + except Exception as exc: + http_client = self._log_client._http_client # noqa: SLF001 + broken_read = self._received_data and self._is_broken_read(http_client, exc) + if not broken_read or self._stop_event.is_set(): + raise + if not self._replay_caught_up(): + self._to_logger.warning(_NO_PROGRESS_MESSAGE, exc) + break + self._to_logger.debug('Log stream broke off, reopening it: %r', exc) + self._prepare_reopen() + broke_off = True + break + self._process_new_data(data) finally: self._log_stream = None try: @@ -246,7 +386,7 @@ def _stream_log_once(self) -> bool: # A truncated stream leaves an undecodable tail, which is worth a traceback even while a stop is # in progress. self._to_logger.exception('Log redirection stopped due to unexpected error:') - return True + return broke_off or not self._received_data @docs_group('Other') @@ -263,20 +403,38 @@ class StreamedLogAsync(StreamedLogBase): _stop_timeout_s: ClassVar[float] = 1 """Grace period for in-flight log data before the streaming task is cancelled.""" - def __init__(self, log_client: LogClientAsync, *, to_logger: logging.Logger, from_start: bool = True) -> None: + def __init__( + self, + log_client: LogClientAsync, + *, + to_logger: logging.Logger, + since: datetime | None = None, + from_start: bool | None = None, + ) -> None: """Initialize `StreamedLogAsync`. Args: log_client: The async log client used to stream raw log data from the Actor run. to_logger: The logger to which the log messages will be forwarded. - from_start: If `True`, all logs from the start of the Actor run will be streamed. If `False`, only newly - arrived logs will be streamed. This can be useful for long-running Actors in stand-by mode where only - recent logs are relevant. + since: Redirect only the log messages logged at this time or later. A naive datetime is treated as UTC. + If `None`, the whole log is redirected. + from_start: Deprecated, use `since` instead. `True` is the same as `since=None`, and `False` the same as + `since=datetime.now(tz=UTC)`. Will be removed in v4. """ - super().__init__(to_logger=to_logger, from_start=from_start) + since = resolve_since(since=since, from_start=from_start) + super().__init__(to_logger=to_logger, since=since) self._log_client = log_client self._streaming_task: Task | None = None + @property + def last_redirected_at(self) -> datetime | None: + """The timestamp of the last redirected log message, or `None` if nothing has been redirected yet. + + To continue the redirection later, for example after the Actor that redirects the log reboots, save it and + pass it plus one millisecond as `since` to `RunClientAsync.get_streamed_log`. + """ + return self._last_redirected_at + def start(self) -> Task: """Start the streaming task. @@ -330,25 +488,12 @@ async def __aexit__( async def _stream_log(self) -> None: try: - # An empty stream means the run has not logged anything yet, so reopen it until the first bytes arrive. retry_s = self._empty_stream_retry_s - while True: - async with self._log_client.stream(raw=True, timeout=self._stream_timeout) as log_stream: - if not log_stream: - return - try: - async for data in log_stream.aiter_bytes(): - self._process_new_data(data) - finally: - try: - # Flush the last buffered part even if the task is cancelled by `stop()`. - self._log_buffer_content(include_last_part=True) - except Exception: - # A truncated stream leaves an undecodable tail. Keeping the failure here also keeps the - # cancellation `stop` raised propagating, so the task ends up cancelled as asyncio expects. - self._to_logger.exception('Log redirection stopped due to unexpected error:') + while await self._stream_log_once(): if self._received_data: - return + await asyncio.sleep(self._reopen_pause_s) + continue + # An empty stream means the run has not logged anything yet, so reopen it until the first bytes arrive. await asyncio.sleep(retry_s) retry_s = min(retry_s * 2, self._empty_stream_max_retry_s) except Exception as exc: @@ -358,3 +503,44 @@ async def _stream_log(self) -> None: else: # Exception in log redirection should not propagate further. self._to_logger.exception('Log redirection stopped due to unexpected error:') + + async def _stream_log_once(self) -> bool: + """Redirect one log stream until it ends. Return whether the stream has to be opened again. + + A stream is opened again when it was empty, or when it broke off after it had delivered data. A stream that + ends without an error after delivering data carried the whole log of a finished run. + """ + async with self._log_client.stream(raw=True, timeout=self._stream_timeout) as log_stream: + if not log_stream: + return False + broke_off = False + try: + chunks = aiter(log_stream.aiter_bytes()) + while True: + # Only a failed read means the stream broke off. A failure to process the data would repeat on + # every replay, so it ends the redirection. + try: + data = await anext(chunks) + except StopAsyncIteration: + break + except Exception as exc: + http_client = self._log_client._http_client # noqa: SLF001 + if not self._received_data or not self._is_broken_read(http_client, exc): + raise + if not self._replay_caught_up(): + self._to_logger.warning(_NO_PROGRESS_MESSAGE, exc) + break + self._to_logger.debug('Log stream broke off, reopening it: %r', exc) + self._prepare_reopen() + broke_off = True + break + self._process_new_data(data) + finally: + try: + # Flush the last buffered part even if the task is cancelled by `stop()`. + self._log_buffer_content(include_last_part=True) + except Exception: + # A truncated stream leaves an undecodable tail. Keeping the failure here also keeps the + # cancellation `stop` raised propagating, so the task ends up cancelled as asyncio expects. + self._to_logger.exception('Log redirection stopped due to unexpected error:') + return broke_off or not self._received_data diff --git a/tests/unit/test_logging.py b/tests/unit/test_logging.py index da7d23b4..7e2c6d06 100644 --- a/tests/unit/test_logging.py +++ b/tests/unit/test_logging.py @@ -10,7 +10,7 @@ from contextlib import asynccontextmanager, nullcontext from datetime import datetime, timedelta from typing import TYPE_CHECKING -from unittest.mock import AsyncMock, Mock, patch +from unittest.mock import AsyncMock, Mock import pytest from werkzeug import Request, Response @@ -60,6 +60,8 @@ b'2025-05-13T07:28:14.132Z [apify.redirect-logger runId:4U1oAnKau6jpzjUuA] -> 2025-05-13T07:27:14.132Z ACTOR:...\n', ) _EXISTING_LOGS_BEFORE_REDIRECT_ATTACH = 3 +_REDIRECT_ATTACH_TIME = datetime.fromisoformat('2025-05-13T07:24:14.132+00:00') +"""Later than the first `_EXISTING_LOGS_BEFORE_REDIRECT_ATTACH` messages of `_MOCKED_ACTOR_LOGS`.""" # Large enough that a real sleep is clearly detectable against `_FAST_EXIT_THRESHOLD_S`. _PATCHED_FINAL_SLEEP_S = 5 @@ -261,17 +263,21 @@ def reduce_final_timeout_for_status_message_redirector() -> None: @pytest.mark.parametrize( - ('log_from_start', 'expected_log_count'), + ('since', 'expected_log_count'), [ - (True, len(_EXPECTED_MESSAGES_AND_LEVELS)), - (False, len(_EXPECTED_MESSAGES_AND_LEVELS) - _EXISTING_LOGS_BEFORE_REDIRECT_ATTACH), + pytest.param(None, len(_EXPECTED_MESSAGES_AND_LEVELS), id='whole-log'), + pytest.param( + _REDIRECT_ATTACH_TIME, + len(_EXPECTED_MESSAGES_AND_LEVELS) - _EXISTING_LOGS_BEFORE_REDIRECT_ATTACH, + id='since-attach-time', + ), ], ) @pytest.mark.usefixtures('mock_api', 'propagate_stream_logs') async def test_redirected_logs_async( *, caplog: LogCaptureFixture, - log_from_start: bool, + since: datetime | None, expected_log_count: int, httpserver: HTTPServer, ) -> None: @@ -281,10 +287,7 @@ async def test_redirected_logs_async( run_client = ApifyClientAsync(token='mocked_token', api_url=api_url).run(run_id=_MOCKED_RUN_ID) - with patch('apify_client._streamed_log.datetime') as mocked_datetime: - # Mock `now()` so that it has timestamp bigger than the first 3 logs - mocked_datetime.now.return_value = datetime.fromisoformat('2025-05-13T07:24:14.132+00:00') - streamed_log = await run_client.get_streamed_log(from_start=log_from_start) + streamed_log = await run_client.get_streamed_log(since=since) # Set `propagate=True` during the tests, so that caplog can see the logs.. logger_name = f'apify.{_MOCKED_ACTOR_NAME}-{_MOCKED_RUN_ID}' @@ -301,17 +304,21 @@ async def test_redirected_logs_async( @pytest.mark.parametrize( - ('log_from_start', 'expected_log_count'), + ('since', 'expected_log_count'), [ - (True, len(_EXPECTED_MESSAGES_AND_LEVELS)), - (False, len(_EXPECTED_MESSAGES_AND_LEVELS) - _EXISTING_LOGS_BEFORE_REDIRECT_ATTACH), + pytest.param(None, len(_EXPECTED_MESSAGES_AND_LEVELS), id='whole-log'), + pytest.param( + _REDIRECT_ATTACH_TIME, + len(_EXPECTED_MESSAGES_AND_LEVELS) - _EXISTING_LOGS_BEFORE_REDIRECT_ATTACH, + id='since-attach-time', + ), ], ) @pytest.mark.usefixtures('mock_api', 'propagate_stream_logs') def test_redirected_logs_sync( *, caplog: LogCaptureFixture, - log_from_start: bool, + since: datetime | None, expected_log_count: int, httpserver: HTTPServer, ) -> None: @@ -321,10 +328,7 @@ def test_redirected_logs_sync( run_client = ApifyClient(token='mocked_token', api_url=api_url).run(run_id=_MOCKED_RUN_ID) - with patch('apify_client._streamed_log.datetime') as mocked_datetime: - # Mock `now()` so that it has timestamp bigger than the first 3 logs - mocked_datetime.now.return_value = datetime.fromisoformat('2025-05-13T07:24:14.132+00:00') - streamed_log = run_client.get_streamed_log(from_start=log_from_start) + streamed_log = run_client.get_streamed_log(since=since) # Set `propagate=True` during the tests, so that caplog can see the logs.. logger_name = f'apify.{_MOCKED_ACTOR_NAME}-{_MOCKED_RUN_ID}' @@ -1199,19 +1203,10 @@ def generate_logs() -> Iterator[bytes]: release_server.set() -@pytest.mark.usefixtures('propagate_stream_logs') -def test_streamed_log_sync_does_not_leak_exception_on_stream_timeout( - caplog: LogCaptureFixture, - httpserver: HTTPServer, - http_client_class: type[HttpClient], - monkeypatch: pytest.MonkeyPatch, -) -> None: - """The streaming thread ends quietly when either transport times out while reading the log stream.""" - monkeypatch.setattr(StreamedLog, '_stream_timeout', timedelta(seconds=1)) - - release_server = threading.Event() +def _register_timing_out_log_stream(httpserver: HTTPServer, release_server: threading.Event) -> None: + """Serve a log stream that stalls past the client-side stream timeout.""" - def _slow_handler(_request: Request) -> Response: + def handler(_request: Request) -> Response: def generate_logs() -> Iterator[bytes]: # Emit one complete line, then keep the connection open (as a running Actor would) past the # client-side stream timeout without sending anything more. @@ -1222,7 +1217,26 @@ def generate_logs() -> Iterator[bytes]: httpserver.expect_request( f'/v2/actor-runs/{_MOCKED_RUN_ID}/log', method='GET', query_string='stream=true&raw=true' - ).respond_with_handler(_slow_handler) + ).respond_with_handler(handler) + + +def _redirected_log_lines(caplog: LogCaptureFixture) -> list[str]: + """Return the redirected log lines `caplog` captured, without their timestamps.""" + return [record.message.split(' ', 1)[1] for record in caplog.records if record.message.startswith('2025-')] + + +@pytest.mark.usefixtures('propagate_stream_logs') +def test_streamed_log_sync_does_not_leak_exception_on_stream_timeout( + caplog: LogCaptureFixture, + httpserver: HTTPServer, + http_client_class: type[HttpClient], + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A stream timeout neither leaks nor logs an error, and ends the redirection without reopening the stream.""" + monkeypatch.setattr(StreamedLog, '_stream_timeout', timedelta(seconds=1)) + + release_server = threading.Event() + _register_timing_out_log_stream(httpserver, release_server) _register_run_and_actor_endpoints(httpserver) api_url = httpserver.url_for('/').removesuffix('/') @@ -1252,8 +1266,8 @@ def generate_logs() -> Iterator[bytes]: # The timeout is expected, so it must be swallowed quietly, not funnelled through the generic error handler. error_records = [r for r in caplog.records if r.levelno >= logging.ERROR and 'Log redirection stopped' in r.message] assert not error_records, f'sync thread logged an error on stream timeout: {[r.message for r in error_records]}' - # The line received before the timeout must still have been redirected. - assert any('ACTOR: still running' in record.message for record in caplog.records) + # The line received before the timeout is redirected once, so the timed-out stream was not reopened. + assert _redirected_log_lines(caplog) == ['ACTOR: still running'] @pytest.mark.usefixtures('propagate_stream_logs') @@ -1299,22 +1313,11 @@ async def test_streamed_log_async_does_not_error_on_stream_timeout( http_client_async_class: type[HttpClientAsync], monkeypatch: pytest.MonkeyPatch, ) -> None: - """The async streaming task treats either transport's stream timeout as an expected terminal condition.""" + """A stream timeout neither raises nor logs an error, and ends the redirection without reopening the stream.""" monkeypatch.setattr(StreamedLogAsync, '_stream_timeout', timedelta(seconds=1)) release_server = threading.Event() - - def _slow_handler(_request: Request) -> Response: - def generate_logs() -> Iterator[bytes]: - # Emit one complete line, then keep the connection open past the client-side stream timeout. - yield b'2025-05-13T07:24:12.588Z ACTOR: still running\n' - release_server.wait(timeout=30) - - return Response(response=generate_logs(), status=200, mimetype='application/octet-stream') - - httpserver.expect_request( - f'/v2/actor-runs/{_MOCKED_RUN_ID}/log', method='GET', query_string='stream=true&raw=true' - ).respond_with_handler(_slow_handler) + _register_timing_out_log_stream(httpserver, release_server) _register_run_and_actor_endpoints(httpserver) api_url = httpserver.url_for('/').removesuffix('/') @@ -1340,8 +1343,8 @@ def generate_logs() -> Iterator[bytes]: assert task.exception() is None, f'async streaming task raised on stream timeout: {task.exception()!r}' error_records = [r for r in caplog.records if r.levelno >= logging.ERROR and 'Log redirection stopped' in r.message] assert not error_records, f'async task logged an error on stream timeout: {[r.message for r in error_records]}' - # The line received before the timeout must still have been redirected. - assert any('ACTOR: still running' in record.message for record in caplog.records) + # The line received before the timeout is redirected once, so the timed-out stream was not reopened. + assert _redirected_log_lines(caplog) == ['ACTOR: still running'] _POLL_FAILURE_FINAL_SLEEP_S = 2 @@ -2014,6 +2017,490 @@ async def test_streamed_log_async_missing_log_is_neither_reopened_nor_read() -> log_client.get_as_bytes.assert_not_called() +@pytest.mark.parametrize( + ('from_start', 'expected_since'), + [ + pytest.param(True, None, id='from-start'), + pytest.param(False, _REDIRECT_ATTACH_TIME, id='from-now'), + ], +) +def test_streamed_log_from_start_is_deprecated_alias_of_since( + *, from_start: bool, expected_since: datetime | None, monkeypatch: pytest.MonkeyPatch +) -> None: + """`from_start` warns that it is deprecated, and maps to the whole log or to the log from now on.""" + mocked_datetime = Mock(wraps=datetime) + mocked_datetime.now.return_value = _REDIRECT_ATTACH_TIME + monkeypatch.setattr('apify_client._streamed_log.datetime', mocked_datetime) + + with pytest.warns(DeprecationWarning, match='`from_start` argument is deprecated') as warning_records: + streamed_log = StreamedLog(log_client=Mock(), to_logger=logging.getLogger('test'), from_start=from_start) + + assert streamed_log._since == expected_since + # The warning points at the code that passed the argument, so the default warning filters do not hide it. + assert warning_records[0].filename == __file__ + + +def test_streamed_log_rejects_both_since_and_from_start() -> None: + """Passing both `since` and the deprecated `from_start` is an error.""" + with ( + pytest.warns(DeprecationWarning, match='`from_start` argument is deprecated'), + pytest.raises(ValueError, match='Pass only one of'), + ): + StreamedLog( + log_client=Mock(), to_logger=logging.getLogger('test'), since=_REDIRECT_ATTACH_TIME, from_start=False + ) + + +def test_streamed_log_treats_naive_since_as_utc() -> None: + """A naive `since` is read as UTC, like the log timestamps.""" + naive_since = _REDIRECT_ATTACH_TIME.replace(tzinfo=None) + + streamed_log = StreamedLog(log_client=Mock(), to_logger=logging.getLogger('test'), since=naive_since) + + assert streamed_log._since == _REDIRECT_ATTACH_TIME + + +_LOG_BEFORE_DROP = ( + b'2025-05-13T07:24:12.588Z ACTOR: line 1\n' + b'2025-05-13T07:24:12.588Z ACTOR: line 2\n' + b'2025-05-13T07:24:13.000Z ACTOR: cut o' +) +"""What a log stream delivers before the platform cuts it off: two messages with the same timestamp, then a cut-off +message.""" + +_LOG_AFTER_DROP = ( + b'2025-05-13T07:24:12.588Z ACTOR: line 1\n' + b'2025-05-13T07:24:12.588Z ACTOR: line 2\n' + b'2025-05-13T07:24:13.000Z ACTOR: cut off before\n' + b'2025-05-13T07:34:13.000Z ACTOR: logged after a long silence\n' +) +"""What the reopened stream delivers: the whole log from its start, with the messages logged meanwhile.""" + +_LINES_AFTER_RESUME = [ + 'ACTOR: line 1', + 'ACTOR: line 2', + 'ACTOR: cut off before', + 'ACTOR: logged after a long silence', +] + +_LAST_LINE_TIME = datetime.fromisoformat('2025-05-13T07:34:13.000+00:00') + + +def _sync_streams(*chunk_lists: list[bytes] | Exception) -> list[nullcontext]: + """Return the log streams a mocked `LogClient.stream` opens, one per argument. + + An exception argument makes that stream deliver `_LOG_BEFORE_DROP` and then raise it. + """ + streams = [] + for chunk_list in chunk_lists: + log_stream = Mock() + if isinstance(chunk_list, Exception): + error = chunk_list + + def failing_iter(error: Exception = error) -> Iterator[bytes]: + yield _LOG_BEFORE_DROP + raise error + + log_stream.iter_bytes.side_effect = failing_iter + else: + log_stream.iter_bytes.return_value = chunk_list + streams.append(nullcontext(log_stream)) + return streams + + +def _async_streams(*chunk_lists: list[bytes] | Exception) -> list[nullcontext]: + """Return the log streams a mocked `LogClientAsync.stream` opens, one per argument. + + An exception argument makes that stream deliver `_LOG_BEFORE_DROP` and then raise it. + """ + streams = [] + for chunk_list in chunk_lists: + log_stream = Mock() + if isinstance(chunk_list, Exception): + error = chunk_list + + async def failing_aiter(error: Exception = error) -> AsyncIterator[bytes]: + yield _LOG_BEFORE_DROP + raise error + + log_stream.aiter_bytes.side_effect = failing_aiter + else: + log_stream.aiter_bytes.side_effect = lambda chunk_list=chunk_list: chunks(*chunk_list) + streams.append(nullcontext(log_stream)) + return streams + + +def test_streamed_log_sync_reopens_stream_that_broke_off( + caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """A stream that broke off is reopened, and only the messages not redirected yet are logged.""" + monkeypatch.setattr(StreamedLog, '_reopen_pause_s', 0) + log_client = Mock() + log_client.stream.side_effect = _sync_streams(ConnectionResetError('Simulated drop'), [_LOG_AFTER_DROP]) + log_client._http_client.is_timeout_error.return_value = False + log_client._http_client.is_retryable_transport_error.return_value = True + logger = logging.getLogger('apify_client.tests.broke_off_sync') + streamed_log = StreamedLog(log_client=log_client, to_logger=logger) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == _LINES_AFTER_RESUME + assert streamed_log.last_redirected_at == _LAST_LINE_TIME + assert log_client.stream.call_count == 2 + + +async def test_streamed_log_async_reopens_stream_that_broke_off( + caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """A stream that broke off is reopened, and only the messages not redirected yet are logged.""" + monkeypatch.setattr(StreamedLogAsync, '_reopen_pause_s', 0) + log_client = Mock() + log_client.stream.side_effect = _async_streams(ConnectionResetError('Simulated drop'), [_LOG_AFTER_DROP]) + log_client._http_client.is_timeout_error.return_value = False + log_client._http_client.is_retryable_transport_error.return_value = True + logger = logging.getLogger('apify_client.tests.broke_off_async') + streamed_log = StreamedLogAsync(log_client=log_client, to_logger=logger) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + await streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == _LINES_AFTER_RESUME + assert streamed_log.last_redirected_at == _LAST_LINE_TIME + assert log_client.stream.call_count == 2 + + +def test_streamed_log_sync_does_not_reopen_stream_after_non_transient_read_error(caplog: LogCaptureFixture) -> None: + """A read error the transport does not classify as transient ends the redirection with a logged error.""" + log_client = Mock() + log_client.stream.side_effect = _sync_streams(ValueError('Simulated permanent failure')) + log_client._http_client.is_timeout_error.return_value = False + log_client._http_client.is_retryable_transport_error.return_value = False + logger = logging.getLogger('apify_client.tests.non_transient_sync') + streamed_log = StreamedLog(log_client=log_client, to_logger=logger) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == ['ACTOR: line 1', 'ACTOR: line 2', 'ACTOR: cut o'] + assert 'Log redirection stopped due to unexpected error:' in caplog.text + log_client.stream.assert_called_once() + + +async def test_streamed_log_async_does_not_reopen_stream_after_non_transient_read_error( + caplog: LogCaptureFixture, +) -> None: + """A read error the transport does not classify as transient ends the redirection with a logged error.""" + log_client = Mock() + log_client.stream.side_effect = _async_streams(ValueError('Simulated permanent failure')) + log_client._http_client.is_timeout_error.return_value = False + log_client._http_client.is_retryable_transport_error.return_value = False + logger = logging.getLogger('apify_client.tests.non_transient_async') + streamed_log = StreamedLogAsync(log_client=log_client, to_logger=logger) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + await streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == ['ACTOR: line 1', 'ACTOR: line 2', 'ACTOR: cut o'] + assert 'Log redirection stopped due to unexpected error:' in caplog.text + log_client.stream.assert_called_once() + + +_LOG_WITH_INVALID_UTF8 = b'2025-05-13T07:24:12.588Z ACTOR: line 1\n2025-05-13T07:24:13.000Z ACTOR: bad \xff byte\n' + + +def test_streamed_log_sync_does_not_reopen_stream_with_unprocessable_line(caplog: LogCaptureFixture) -> None: + """A line that fails to be processed ends the redirection with a logged error, and the stream is not reopened.""" + log_client = Mock() + log_client.stream.side_effect = _sync_streams([_LOG_WITH_INVALID_UTF8]) + log_client._http_client.is_timeout_error.return_value = False + logger = logging.getLogger('apify_client.tests.unprocessable_sync') + streamed_log = StreamedLog(log_client=log_client, to_logger=logger) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == ['ACTOR: line 1'] + assert 'Log redirection stopped due to unexpected error:' in caplog.text + log_client.stream.assert_called_once() + + +async def test_streamed_log_async_does_not_reopen_stream_with_unprocessable_line(caplog: LogCaptureFixture) -> None: + """A line that fails to be processed ends the redirection with a logged error, and the stream is not reopened.""" + log_client = Mock() + log_client.stream.side_effect = _async_streams([_LOG_WITH_INVALID_UTF8]) + log_client._http_client.is_timeout_error.return_value = False + logger = logging.getLogger('apify_client.tests.unprocessable_async') + streamed_log = StreamedLogAsync(log_client=log_client, to_logger=logger) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + await streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == ['ACTOR: line 1'] + assert 'Log redirection stopped due to unexpected error:' in caplog.text + log_client.stream.assert_called_once() + + +def test_streamed_log_sync_does_not_reopen_stream_that_ended(caplog: LogCaptureFixture) -> None: + """A stream that ends without an error is not reopened, and its unterminated last line is redirected.""" + log_client = Mock() + log_client.stream.side_effect = _sync_streams([_LOG_BEFORE_DROP]) + logger = logging.getLogger('apify_client.tests.finished_sync') + streamed_log = StreamedLog(log_client=log_client, to_logger=logger) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == ['ACTOR: line 1', 'ACTOR: line 2', 'ACTOR: cut o'] + log_client.stream.assert_called_once() + + +async def test_streamed_log_async_does_not_reopen_stream_that_ended(caplog: LogCaptureFixture) -> None: + """A stream that ends without an error is not reopened, and its unterminated last line is redirected.""" + log_client = Mock() + log_client.stream.side_effect = _async_streams([_LOG_BEFORE_DROP]) + logger = logging.getLogger('apify_client.tests.finished_async') + streamed_log = StreamedLogAsync(log_client=log_client, to_logger=logger) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + await streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == ['ACTOR: line 1', 'ACTOR: line 2', 'ACTOR: cut o'] + log_client.stream.assert_called_once() + + +def _breaking_sync_stream(data: bytes) -> nullcontext: + """Return a mocked sync log stream that delivers `data` and then breaks off with a transport error.""" + + def iter_bytes() -> Iterator[bytes]: + yield data + raise ConnectionResetError('Simulated drop') + + log_stream = Mock() + log_stream.iter_bytes.side_effect = iter_bytes + return nullcontext(log_stream) + + +def _breaking_async_stream(data: bytes) -> nullcontext: + """Return a mocked async log stream that delivers `data` and then breaks off with a transport error.""" + + async def aiter_bytes() -> AsyncIterator[bytes]: + yield data + raise ConnectionResetError('Simulated drop') + + log_stream = Mock() + log_stream.aiter_bytes.side_effect = aiter_bytes + return nullcontext(log_stream) + + +def _mock_log_client_with_transient_errors() -> Mock: + log_client = Mock() + log_client._http_client.is_timeout_error.return_value = False + log_client._http_client.is_retryable_transport_error.return_value = True + return log_client + + +_TRACEBACK_BEFORE_DROP = ( + b'2025-05-13T07:24:12.588Z Traceback (most recent call last):\n' + b'2025-05-13T07:24:12.588Z File "main.py", line 1, in \n' + b'2025-05-13T07:24:12.588Z ValueEr' +) +"""A traceback whose lines share one millisecond, cut off in its last line.""" + +_TRACEBACK_REPLAY = ( + b'2025-05-13T07:24:12.588Z Traceback (most recent call last):\n' + b'2025-05-13T07:24:12.588Z File "main.py", line 1, in \n' + b'2025-05-13T07:24:12.588Z ValueError: boom\n' + b'2025-05-13T07:24:13.000Z ACTOR: Exiting\n' +) + +_TRACEBACK_LINES = [ + 'Traceback (most recent call last):', + ' File "main.py", line 1, in ', + 'ValueError: boom', + 'ACTOR: Exiting', +] + + +def test_streamed_log_sync_reopen_keeps_lines_sharing_the_last_timestamp( + caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """A stream that breaks off inside a group of lines with the same timestamp loses none of them on reopen.""" + monkeypatch.setattr(StreamedLog, '_reopen_pause_s', 0) + log_client = _mock_log_client_with_transient_errors() + log_client.stream.side_effect = [_breaking_sync_stream(_TRACEBACK_BEFORE_DROP), *_sync_streams([_TRACEBACK_REPLAY])] + logger = logging.getLogger('apify_client.tests.same_timestamp_sync') + streamed_log = StreamedLog(log_client=log_client, to_logger=logger) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == _TRACEBACK_LINES + + +async def test_streamed_log_async_reopen_keeps_lines_sharing_the_last_timestamp( + caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """A stream that breaks off inside a group of lines with the same timestamp loses none of them on reopen.""" + monkeypatch.setattr(StreamedLogAsync, '_reopen_pause_s', 0) + log_client = _mock_log_client_with_transient_errors() + log_client.stream.side_effect = [ + _breaking_async_stream(_TRACEBACK_BEFORE_DROP), + *_async_streams([_TRACEBACK_REPLAY]), + ] + logger = logging.getLogger('apify_client.tests.same_timestamp_async') + streamed_log = StreamedLogAsync(log_client=log_client, to_logger=logger) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + await streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == _TRACEBACK_LINES + + +_REPLAY_CUT_SHORT = b'2025-05-13T07:24:12.588Z ACTOR: line 1\n' +"""A replay of `_LOG_BEFORE_DROP` that breaks off before it reaches the last redirected line.""" + + +def test_streamed_log_sync_stops_when_reopened_stream_breaks_before_catching_up( + caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """A reopened stream that breaks off before it replays the last redirected line ends the redirection with a + warning instead of reopening again.""" + monkeypatch.setattr(StreamedLog, '_reopen_pause_s', 0) + log_client = _mock_log_client_with_transient_errors() + log_client.stream.side_effect = [ + _breaking_sync_stream(_LOG_BEFORE_DROP), + _breaking_sync_stream(_REPLAY_CUT_SHORT), + *_sync_streams([_LOG_AFTER_DROP]), + ] + logger = logging.getLogger('apify_client.tests.no_progress_sync') + streamed_log = StreamedLog(log_client=log_client, to_logger=logger) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == ['ACTOR: line 1', 'ACTOR: line 2'] + assert log_client.stream.call_count == 2 + assert any( + record.levelno == logging.WARNING and 'before it reached the last redirected line' in record.message + for record in caplog.records + ) + + +async def test_streamed_log_async_stops_when_reopened_stream_breaks_before_catching_up( + caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """A reopened stream that breaks off before it replays the last redirected line ends the redirection with a + warning instead of reopening again.""" + monkeypatch.setattr(StreamedLogAsync, '_reopen_pause_s', 0) + log_client = _mock_log_client_with_transient_errors() + log_client.stream.side_effect = [ + _breaking_async_stream(_LOG_BEFORE_DROP), + _breaking_async_stream(_REPLAY_CUT_SHORT), + *_async_streams([_LOG_AFTER_DROP]), + ] + logger = logging.getLogger('apify_client.tests.no_progress_async') + streamed_log = StreamedLogAsync(log_client=log_client, to_logger=logger) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + await streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == ['ACTOR: line 1', 'ACTOR: line 2'] + assert log_client.stream.call_count == 2 + assert any( + record.levelno == logging.WARNING and 'before it reached the last redirected line' in record.message + for record in caplog.records + ) + + +_SILENT_REPLAY = b'2025-05-13T07:24:12.588Z ACTOR: line 1\n2025-05-13T07:24:12.588Z ACTOR: line 2\n' +"""A replay of `_LOG_BEFORE_DROP` that reaches the last redirected line, after which the run logs nothing.""" + + +def test_streamed_log_sync_keeps_reopening_stream_of_silent_run( + caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """A silent run whose stream breaks off repeatedly keeps its redirection, because every replay catches up.""" + monkeypatch.setattr(StreamedLog, '_reopen_pause_s', 0) + log_client = _mock_log_client_with_transient_errors() + log_client.stream.side_effect = [ + _breaking_sync_stream(_LOG_BEFORE_DROP), + _breaking_sync_stream(_SILENT_REPLAY), + _breaking_sync_stream(_SILENT_REPLAY), + *_sync_streams([_LOG_AFTER_DROP]), + ] + logger = logging.getLogger('apify_client.tests.silent_run_sync') + streamed_log = StreamedLog(log_client=log_client, to_logger=logger) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == _LINES_AFTER_RESUME + assert log_client.stream.call_count == 4 + assert not any(record.levelno >= logging.WARNING for record in caplog.records) + + +async def test_streamed_log_async_keeps_reopening_stream_of_silent_run( + caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """A silent run whose stream breaks off repeatedly keeps its redirection, because every replay catches up.""" + monkeypatch.setattr(StreamedLogAsync, '_reopen_pause_s', 0) + log_client = _mock_log_client_with_transient_errors() + log_client.stream.side_effect = [ + _breaking_async_stream(_LOG_BEFORE_DROP), + _breaking_async_stream(_SILENT_REPLAY), + _breaking_async_stream(_SILENT_REPLAY), + *_async_streams([_LOG_AFTER_DROP]), + ] + logger = logging.getLogger('apify_client.tests.silent_run_async') + streamed_log = StreamedLogAsync(log_client=log_client, to_logger=logger) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + await streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == _LINES_AFTER_RESUME + assert log_client.stream.call_count == 4 + assert not any(record.levelno >= logging.WARNING for record in caplog.records) + + +def test_streamed_log_last_redirected_at_is_none_before_any_message() -> None: + """`last_redirected_at` is `None` until a message is redirected.""" + streamed_log = StreamedLog(log_client=Mock(), to_logger=logging.getLogger('test')) + + assert streamed_log.last_redirected_at is None + + +def test_streamed_log_last_redirected_at_ignores_skipped_messages() -> None: + """Messages skipped for being older than `since` do not move `last_redirected_at`.""" + log_stream = Mock() + log_stream.iter_bytes.return_value = [_LOG_AFTER_DROP] + log_client = Mock() + log_client.stream.return_value = nullcontext(log_stream) + streamed_log = StreamedLog( + log_client=log_client, to_logger=logging.getLogger('test'), since=_LAST_LINE_TIME + timedelta(seconds=1) + ) + + streamed_log._stream_log() + + assert streamed_log.last_redirected_at is None + + +def test_streamed_log_resumes_from_saved_last_redirected_at(caplog: LogCaptureFixture) -> None: + """A new streamed log started from a saved `last_redirected_at` plus one millisecond redirects only newer lines.""" + log_stream = Mock() + log_stream.iter_bytes.return_value = [_LOG_AFTER_DROP] + log_client = Mock() + log_client.stream.return_value = nullcontext(log_stream) + saved = datetime.fromisoformat('2025-05-13T07:24:12.588+00:00') + logger = logging.getLogger('apify_client.tests.resume_saved') + streamed_log = StreamedLog(log_client=log_client, to_logger=logger, since=saved + timedelta(milliseconds=1)) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == ['ACTOR: cut off before', 'ACTOR: logged after a long silence'] + + def test_logger_once_logs_the_first_call(caplog: LogCaptureFixture) -> None: """Test the first call with a given key is logged.""" logger = logging.getLogger('apify_client.tests.log_once_first')