diff --git a/docs/02_concepts/09_logging.mdx b/docs/02_concepts/09_logging.mdx index 80712da2..c360fe2a 100644 --- a/docs/02_concepts/09_logging.mdx +++ b/docs/02_concepts/09_logging.mdx @@ -98,6 +98,8 @@ Typical use case for log redirection is to call another Actor using the +The `Actor.call_task` method has the same `logger` argument, with the same default. + Each default redirect logger log entry will have a specific format. After the timestamp, it will contain cyan colored text that will contain the redirect information: the other Actor's name and the run ID. The rest of the log message will be printed in the same manner as the parent Actor's logger is configured. The log redirection can be deep, meaning that if the other Actor also starts another Actor and is redirecting logs from it, then in the top-level Actor, you can see it as well. See the following example screenshot of the Apify log console when one Actor recursively starts itself (there are 2 levels of recursion in the example). diff --git a/src/apify/_actor.py b/src/apify/_actor.py index 3e650c05..14315749 100644 --- a/src/apify/_actor.py +++ b/src/apify/_actor.py @@ -183,6 +183,9 @@ def __init__( self._child_run_registry = ChildRunRegistry(self.open_key_value_store) + self._runs_with_redirected_log: set[str | None] = set() + """IDs of the runs whose log a call of this Actor redirects right now.""" + self._internal_listeners = ExitStack() """Removes the listeners the Actor registered on the event manager, when the Actor leaves its context.""" @@ -1477,20 +1480,47 @@ async def _wait_for_child_run( if run.status == 'SUCCEEDED': return run - if not logger: - finished_run = await run_client.wait_for_finish(wait_duration=wait) - else: - to_logger = None if logger == 'default' else logger - status_redirector = await run_client.get_status_message_watcher(to_logger=to_logger) - streamed_log = await run_client.get_streamed_log(to_logger=to_logger, from_start=from_start) - - async with status_redirector, streamed_log: - finished_run = await run_client.wait_for_finish(wait_duration=wait) + finished_run = await self._wait_for_run(run_client, wait=wait, logger=logger, from_start=from_start) if finished_run is not None: await self._child_run_registry.update(name, finished_run) return finished_run + async def _wait_for_run( + self, + run_client: RunClientAsync, + *, + wait: timedelta | None, + logger: logging.Logger | Literal['default'] | None, + from_start: bool, + ) -> Run | None: + """Wait for a run to finish, and redirect its log and status messages to `logger` meanwhile.""" + run_id = run_client.resource_id + # A second redirect of the same run, e.g. from a concurrent call under the same `run_name`, would repeat + # each line of its log. + if not logger or run_id in self._runs_with_redirected_log: + return await run_client.wait_for_finish(wait_duration=wait) + + self._runs_with_redirected_log.add(run_id) + try: + to_logger = None if logger == 'default' else logger + try: + status_redirector = await run_client.get_status_message_watcher(to_logger=to_logger) + streamed_log = await run_client.get_streamed_log(to_logger=to_logger, from_start=from_start) + except Exception: + # The run is already started, so a failed redirect must not hide it from the caller. + self.log.warning( + 'Failed to redirect the log of the run, waiting for the run without it', + exc_info=True, + extra={'run_id': run_id}, + ) + return await run_client.wait_for_finish(wait_duration=wait) + + async with status_redirector, streamed_log: + return await run_client.wait_for_finish(wait_duration=wait) + finally: + self._runs_with_redirected_log.discard(run_id) + @_ensure_context async def start_task( self, @@ -1608,6 +1638,7 @@ async def call_task( timeout: timedelta | Literal['inherit'] | None = None, webhooks: list[Webhook] | None = None, wait: timedelta | None = None, + logger: logging.Logger | Literal['default'] | None = 'default', token: str | None = None, run_name: str | None = None, abort_with_parent: bool = False, @@ -1640,6 +1671,11 @@ async def call_task( be used to receive a notification, e.g. when the Actor finished or failed. If you already have a webhook set up for the Actor, you do not have to add it again here. wait: The maximum time the server waits for the run to finish. If not provided, waits indefinitely. + logger: Logger used to redirect logs from the Actor run. Using "default" literal means that a predefined + default logger will be used. Setting `None` will disable any log propagation. Passing custom logger + will redirect logs to the provided logger. With a logger, the method returns about 6 seconds after + the run finishes or `wait` runs out, since the redirect waits that long for the last status message + of the run. run_name: Optional name of the child run, unique within this Actor run. A named run is recorded in the default key-value store, so after a migration or resurrection of this Actor the same call reattaches to the recorded run. A `SUCCEEDED` run is returned as is, an `ABORTED` or `TIMED-OUT` one is @@ -1670,7 +1706,8 @@ async def call_task( task_client = client.task(task_id) if run_name is None: - run = await task_client.call( + # The client's `call` cannot redirect the log of the run, so the run is started and waited for here. + started_run = await task_client.start( task_input=task_input, build=build, max_items=max_items, @@ -1679,10 +1716,12 @@ async def call_task( memory_mbytes=memory_mbytes, run_timeout=self._resolve_run_timeout(timeout), webhooks=to_client_representations(webhooks), - wait_duration=wait, + # A request that times out is retried, and a retried start request can start a second run. + timeout='no_timeout', ) + run = await self._wait_for_run(client.run(started_run.id), wait=wait, logger=logger, from_start=True) else: - started_run, _ = await self._find_or_start_child_run( + started_run, is_new = await self._find_or_start_child_run( run_name, task_id=task_id, run_input=task_input, @@ -1706,8 +1745,9 @@ async def call_task( timeout=timeout, abort_with_parent=abort_with_parent, ) + # The earlier attempt of this call already streamed the log of a reattached or resurrected run. run = await self._wait_for_child_run( - run_name, client.run(started_run.id), started_run, wait=wait, logger=None, from_start=False + run_name, client.run(started_run.id), started_run, wait=wait, logger=logger, from_start=is_new ) if run is None: diff --git a/tests/unit/actor/test_actor_child_runs.py b/tests/unit/actor/test_actor_child_runs.py index 48fe1842..ffe87649 100644 --- a/tests/unit/actor/test_actor_child_runs.py +++ b/tests/unit/actor/test_actor_child_runs.py @@ -413,7 +413,7 @@ async def test_named_call_task_records_run_in_kvs(apify_client_async_patcher: Ap apify_client_async_patcher.patch('run', 'wait_for_finish', return_value=make_run('new-run', 'SUCCEEDED')) async with Actor: - run = await Actor.call_task('some-task', run_name='scrape-eu') + run = await Actor.call_task('some-task', run_name='scrape-eu', logger=None) kvs = await Actor.open_key_value_store() stored = await kvs.get_value(CHILD_RUNS_KEY) @@ -430,13 +430,74 @@ async def test_named_call_task_waits_for_reattached_run(apify_client_async_patch async with Actor: await record_child_run('scrape-eu', 'old-run', actor_id=None, task_id='some-task') - run = await Actor.call_task('some-task', run_name='scrape-eu') + run = await Actor.call_task('some-task', run_name='scrape-eu', logger=None) assert run.id == 'old-run' assert run.status == 'SUCCEEDED' assert apify_client_async_patcher.calls['task']['start'] == [] +@pytest.mark.parametrize( + ('is_recorded', 'from_start'), + [ + pytest.param(False, True, id='new run'), + pytest.param(True, False, id='reattached run'), + ], +) +async def test_named_call_task_streams_run_log( + apify_client_async_patcher: ApifyClientAsyncPatcher, *, is_recorded: bool, from_start: bool +) -> None: + """A named task call streams the log of a new run from the start, and only the new lines of a reattached run.""" + streamed_log = MagicMock() + get_streamed_log = Mock(return_value=streamed_log) + apify_client_async_patcher.patch('task', 'start', return_value=make_run('some-run', 'READY')) + apify_client_async_patcher.patch('run', 'get', return_value=make_run('some-run', 'RUNNING')) + apify_client_async_patcher.patch('run', 'wait_for_finish', return_value=make_run('some-run', 'SUCCEEDED')) + apify_client_async_patcher.patch('run', 'get_status_message_watcher', return_value=MagicMock()) + apify_client_async_patcher.patch('run', 'get_streamed_log', replacement_method=get_streamed_log) + + async with Actor: + if is_recorded: + await record_child_run('scrape-eu', 'some-run', actor_id=None, task_id='some-task') + run = await Actor.call_task('some-task', run_name='scrape-eu') + + assert run.status == 'SUCCEEDED' + assert get_streamed_log.call_args.kwargs['from_start'] is from_start + streamed_log.__aenter__.assert_awaited_once() + + +@pytest.mark.parametrize( + ('method', 'resource'), + [ + pytest.param('call', 'actor', id='call'), + pytest.param('call_task', 'task', id='call task'), + ], +) +async def test_concurrent_named_calls_redirect_the_run_log_once( + apify_client_async_patcher: ApifyClientAsyncPatcher, method: str, resource: str +) -> None: + """Concurrent calls under one name share one run, and only one of them redirects its log.""" + get_streamed_log = Mock(return_value=MagicMock()) + + async def wait_for_finish(*_args: Any, **_kwargs: Any) -> Run: + await asyncio.sleep(0.05) + return make_run('new-run', 'SUCCEEDED') + + apify_client_async_patcher.patch(resource, 'start', return_value=make_run('new-run', 'READY')) + apify_client_async_patcher.patch('run', 'get', return_value=make_run('new-run', 'RUNNING')) + apify_client_async_patcher.patch('run', 'wait_for_finish', replacement_method=wait_for_finish) + apify_client_async_patcher.patch('run', 'get_status_message_watcher', return_value=MagicMock()) + apify_client_async_patcher.patch('run', 'get_streamed_log', replacement_method=get_streamed_log) + + async with Actor: + calls = [getattr(Actor, method)('some-id', run_name='scrape-eu') for _ in range(3)] + runs = await asyncio.gather(*calls) + + assert {run.status for run in runs} == {'SUCCEEDED'} + assert len(apify_client_async_patcher.calls[resource]['start']) == 1 + assert get_streamed_log.call_count == 1 + + async def test_named_call_task_resurrects_recorded_run(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: """A named task call resurrects an aborted run with its own options.""" apify_client_async_patcher.patch('task', 'start', return_value=make_run('new-run', 'READY')) @@ -446,7 +507,7 @@ async def test_named_call_task_resurrects_recorded_run(apify_client_async_patche async with Actor: await record_child_run('scrape-eu', 'old-run', actor_id=None, task_id='some-task') - run = await Actor.call_task('some-task', run_name='scrape-eu', memory_mbytes=2048) + run = await Actor.call_task('some-task', run_name='scrape-eu', memory_mbytes=2048, logger=None) assert run.id == 'old-run' assert apify_client_async_patcher.calls['task']['start'] == [] @@ -464,7 +525,7 @@ async def test_named_call_task_rejects_name_recorded_for_actor( async with Actor: await record_child_run('scrape-eu', 'old-run') with pytest.raises(ValueError, match='already used for a different Actor, task or input'): - await Actor.call_task('some-task', run_name='scrape-eu') + await Actor.call_task('some-task', run_name='scrape-eu', logger=None) assert apify_client_async_patcher.calls['task']['start'] == [] @@ -478,7 +539,7 @@ async def test_named_runs_forward_max_items_to_start(apify_client_async_patcher: async with Actor: await Actor.start('some-actor', run_name='started', max_items=10) await Actor.call('some-actor', run_name='called', max_items=20, logger=None) - await Actor.call_task('some-task', run_name='task-called', max_items=30) + await Actor.call_task('some-task', run_name='task-called', max_items=30, logger=None) assert [kwargs['max_items'] for _, kwargs in apify_client_async_patcher.calls['actor']['start']] == [10, 20] [(_, task_kwargs)] = apify_client_async_patcher.calls['task']['start'] @@ -807,7 +868,7 @@ async def test_abort_with_parent_requires_run_name( """`abort_with_parent` without a `run_name` raises before any run is started.""" for resource in ('actor', 'task'): apify_client_async_patcher.patch(resource, 'start', return_value=make_run('new-run', 'READY')) - apify_client_async_patcher.patch(resource, 'call', return_value=make_run('new-run', 'SUCCEEDED')) + apify_client_async_patcher.patch('actor', 'call', return_value=make_run('new-run', 'SUCCEEDED')) async with Actor: with pytest.raises(ValueError, match='requires `run_name`'): @@ -815,7 +876,7 @@ async def test_abort_with_parent_requires_run_name( for resource in ('actor', 'task'): assert apify_client_async_patcher.calls[resource]['start'] == [] - assert apify_client_async_patcher.calls[resource]['call'] == [] + assert apify_client_async_patcher.calls['actor']['call'] == [] async def test_named_start_records_abort_with_parent(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: @@ -838,7 +899,7 @@ async def test_named_call_task_records_abort_with_parent( apify_client_async_patcher.patch('run', 'wait_for_finish', return_value=make_run('new-run', 'SUCCEEDED')) async with Actor: - await Actor.call_task('some-task', run_name='scrape-eu', abort_with_parent=True) + await Actor.call_task('some-task', run_name='scrape-eu', abort_with_parent=True, logger=None) kvs = await Actor.open_key_value_store() stored = await kvs.get_value(CHILD_RUNS_KEY) @@ -1198,7 +1259,7 @@ async def test_named_run_warns_experimental( async with Actor: method = getattr(Actor, method_name) target = 'some-task' if method_name.endswith('_task') else 'some-actor' - kwargs = {'logger': None} if method_name == 'call' else {} + kwargs = {'logger': None} if method_name in {'call', 'call_task'} else {} with pytest.warns(UserWarning, match='experimental') as warnings: await method(target, run_name='scrape-eu', **kwargs) diff --git a/tests/unit/actor/test_actor_helpers.py b/tests/unit/actor/test_actor_helpers.py index 2d740e4b..a6d6460d 100644 --- a/tests/unit/actor/test_actor_helpers.py +++ b/tests/unit/actor/test_actor_helpers.py @@ -5,8 +5,9 @@ import warnings from datetime import UTC, datetime, timedelta from decimal import Decimal +from types import SimpleNamespace from typing import TYPE_CHECKING -from unittest.mock import AsyncMock, Mock, patch +from unittest.mock import AsyncMock, MagicMock, Mock, patch import pytest @@ -68,6 +69,27 @@ def fake_actor_run() -> Run: ) +@pytest.fixture(autouse=True) +async def run_waiting(apify_client_async_patcher: ApifyClientAsyncPatcher, fake_actor_run: Run) -> SimpleNamespace: + """Make waiting for a run and redirecting its log work without the API, as `Actor.call_task` does both. + + The fixture is async, since the patcher needs the running event loop to build the awaitable return values. + Returns the run that the wait ends with, and the mocks that stand in for `RunClientAsync.get_streamed_log` and + `get_status_message_watcher`. + """ + mocks = SimpleNamespace( + finished_run=fake_actor_run.model_copy(update={'status': 'SUCCEEDED'}), + get_streamed_log=Mock(return_value=MagicMock()), + get_status_message_watcher=Mock(return_value=MagicMock()), + ) + apify_client_async_patcher.patch('run', 'wait_for_finish', return_value=mocks.finished_run) + apify_client_async_patcher.patch('run', 'get_streamed_log', replacement_method=mocks.get_streamed_log) + apify_client_async_patcher.patch( + 'run', 'get_status_message_watcher', replacement_method=mocks.get_status_message_watcher + ) + return mocks + + async def test_new_client_config_creation(monkeypatch: pytest.MonkeyPatch) -> None: token = 'my-token' monkeypatch.setenv(ApifyEnvVars.TOKEN, token) @@ -117,15 +139,85 @@ async def test_call_actor(apify_client_async_patcher: ApifyClientAsyncPatcher, f assert apify_client_async_patcher.calls['actor']['call'][0][0][0].resource_id == actor_id -async def test_call_actor_task(apify_client_async_patcher: ApifyClientAsyncPatcher, fake_actor_run: Run) -> None: - apify_client_async_patcher.patch('task', 'call', return_value=fake_actor_run) +async def test_call_actor_task( + apify_client_async_patcher: ApifyClientAsyncPatcher, fake_actor_run: Run, run_waiting: SimpleNamespace +) -> None: + apify_client_async_patcher.patch('task', 'start', return_value=fake_actor_run) task_id = 'some-task-id' async with Actor: - await Actor.call_task(task_id) + run = await Actor.call_task(task_id) + + assert run is run_waiting.finished_run + [(start_args, start_kwargs)] = apify_client_async_patcher.calls['task']['start'] + assert start_args[0].resource_id == task_id + assert start_kwargs['timeout'] == 'no_timeout' + assert len(apify_client_async_patcher.calls['run']['wait_for_finish']) == 1 + + +async def test_call_actor_task_streams_run_log_by_default( + apify_client_async_patcher: ApifyClientAsyncPatcher, fake_actor_run: Run, run_waiting: SimpleNamespace +) -> None: + """`Actor.call_task` redirects the log and the status messages of the run to the default logger.""" + apify_client_async_patcher.patch('task', 'start', return_value=fake_actor_run) + + async with Actor: + await Actor.call_task('some-task-id') + + assert run_waiting.get_streamed_log.call_args.kwargs == {'to_logger': None, 'from_start': True} + assert run_waiting.get_status_message_watcher.call_args.kwargs == {'to_logger': None} + run_waiting.get_streamed_log.return_value.__aenter__.assert_awaited_once() + run_waiting.get_status_message_watcher.return_value.__aenter__.assert_awaited_once() + [(args, _)] = apify_client_async_patcher.calls['run']['wait_for_finish'] + assert args[0].resource_id == fake_actor_run.id + + +async def test_call_actor_task_streams_run_log_to_custom_logger( + apify_client_async_patcher: ApifyClientAsyncPatcher, fake_actor_run: Run, run_waiting: SimpleNamespace +) -> None: + """`Actor.call_task` redirects the log of the run to the logger it is given.""" + custom_logger = logging.getLogger('custom') + apify_client_async_patcher.patch('task', 'start', return_value=fake_actor_run) + + async with Actor: + await Actor.call_task('some-task-id', logger=custom_logger) + + assert run_waiting.get_streamed_log.call_args.kwargs['to_logger'] is custom_logger + assert run_waiting.get_status_message_watcher.call_args.kwargs['to_logger'] is custom_logger + + +async def test_call_actor_task_without_logger_only_waits( + apify_client_async_patcher: ApifyClientAsyncPatcher, fake_actor_run: Run, run_waiting: SimpleNamespace +) -> None: + """`Actor.call_task` with `logger=None` waits for the run without redirecting its log or status messages.""" + apify_client_async_patcher.patch('task', 'start', return_value=fake_actor_run) + + async with Actor: + run = await Actor.call_task('some-task-id', wait=timedelta(seconds=5), logger=None) + + assert run is run_waiting.finished_run + run_waiting.get_streamed_log.assert_not_called() + run_waiting.get_status_message_watcher.assert_not_called() + [(_, kwargs)] = apify_client_async_patcher.calls['run']['wait_for_finish'] + assert kwargs == {'wait_duration': timedelta(seconds=5)} + + +async def test_call_actor_task_waits_for_the_run_when_the_log_redirect_fails( + apify_client_async_patcher: ApifyClientAsyncPatcher, + fake_actor_run: Run, + run_waiting: SimpleNamespace, + caplog: pytest.LogCaptureFixture, +) -> None: + """`Actor.call_task` still waits for the started run when the redirect of its log cannot be set up.""" + run_waiting.get_streamed_log.side_effect = RuntimeError('API is down') + apify_client_async_patcher.patch('task', 'start', return_value=fake_actor_run) + + async with Actor: + run = await Actor.call_task('some-task-id') - assert len(apify_client_async_patcher.calls['task']['call']) == 1 - assert apify_client_async_patcher.calls['task']['call'][0][0][0].resource_id == task_id + assert run is run_waiting.finished_run + assert len(apify_client_async_patcher.calls['run']['wait_for_finish']) == 1 + assert 'Failed to redirect the log of the run' in caplog.text async def test_start_actor_task(apify_client_async_patcher: ApifyClientAsyncPatcher, fake_actor_run: Run) -> None: @@ -160,7 +252,7 @@ async def test_start_actor(apify_client_async_patcher: ApifyClientAsyncPatcher, pytest.param('actor', 'start', 'start', id='start'), pytest.param('actor', 'call', 'call', id='call'), pytest.param('task', 'start', 'start_task', id='start_task'), - pytest.param('task', 'call', 'call_task', id='call_task'), + pytest.param('task', 'start', 'call_task', id='call_task'), ], ) async def test_max_items_forwarded_to_client( @@ -186,7 +278,7 @@ async def test_max_items_forwarded_to_client( pytest.param('actor', 'start', 'start', id='start'), pytest.param('actor', 'call', 'call', id='call'), pytest.param('task', 'start', 'start_task', id='start_task'), - pytest.param('task', 'call', 'call_task', id='call_task'), + pytest.param('task', 'start', 'call_task', id='call_task'), pytest.param('run', 'resurrect', 'resurrect', id='resurrect'), ], ) @@ -214,7 +306,7 @@ async def test_max_items_warns_deprecated( pytest.param('actor', 'start', 'start', id='start'), pytest.param('actor', 'call', 'call', id='call'), pytest.param('task', 'start', 'start_task', id='start_task'), - pytest.param('task', 'call', 'call_task', id='call_task'), + pytest.param('task', 'start', 'call_task', id='call_task'), pytest.param('run', 'resurrect', 'resurrect', id='resurrect'), ], ) @@ -240,7 +332,7 @@ async def test_no_max_items_warning_without_max_items( pytest.param('actor', 'start', 'start', id='start'), pytest.param('actor', 'call', 'call', id='call'), pytest.param('task', 'start', 'start_task', id='start_task'), - pytest.param('task', 'call', 'call_task', id='call_task'), + pytest.param('task', 'start', 'call_task', id='call_task'), ], ) async def test_max_total_charge_usd_forwarded_to_client( @@ -499,7 +591,7 @@ async def listener(_data: object) -> None: pytest.param('actor', 'start', 'start', 'some-actor-id', id='start'), pytest.param('actor', 'call', 'call', 'some-actor-id', id='call'), pytest.param('task', 'start', 'start_task', 'some-task-id', id='start_task'), - pytest.param('task', 'call', 'call_task', 'some-task-id', id='call_task'), + pytest.param('task', 'start', 'call_task', 'some-task-id', id='call_task'), ] @@ -640,7 +732,7 @@ async def test_actor_start_and_call_skipped_when_no_inherited_time_remains( ('client_method', 'actor_method_name'), [ pytest.param('start', 'start_task', id='start_task'), - pytest.param('call', 'call_task', id='call_task'), + pytest.param('start', 'call_task', id='call_task'), ], ) async def test_actor_task_methods_skipped_when_no_inherited_time_remains(