diff --git a/src/apify/_actor.py b/src/apify/_actor.py index 14315749..c2876e5f 100644 --- a/src/apify/_actor.py +++ b/src/apify/_actor.py @@ -58,7 +58,7 @@ if TYPE_CHECKING: import logging - from collections.abc import Awaitable, Callable, MutableMapping + from collections.abc import Awaitable, Callable, Mapping, MutableMapping, Sequence from decimal import Decimal from types import TracebackType from typing import Self @@ -66,11 +66,20 @@ from apify_client._literals import ActorPermissionLevel from apify_client._models import Run from apify_client._resource_clients import RunClientAsync + from apify_client.types import StreamedBodySource from crawlee._types import JsonSerializable from crawlee.proxy_configuration import _NewUrlFunction from apify._webhook import Webhook + RunInput = Mapping[str, Any] | Sequence[Mapping[str, Any]] | bytes | bytearray | str | StreamedBodySource + """Type for the `run_input` parameter on `Actor.start`, `Actor.call`, and `Actor.metamorph`. + + A `dict`, or a list or tuple of `dict`s, is serialized to JSON when `content_type` is unset or JSON. Bytes and a + string are sent as they are, typically with a `content_type`, and a `StreamedBodySource` is streamed to the API in + chunks. An Actor with an input schema accepts only a JSON object. + """ + MainReturnType = TypeVar('MainReturnType') _ensure_context = ensure_context('_active') @@ -1100,7 +1109,7 @@ def get_env(self) -> dict: async def start( self, actor_id: str, - run_input: Any = None, + run_input: RunInput | None = None, *, token: str | None = None, content_type: str | None = None, @@ -1122,7 +1131,9 @@ async def start( Args: actor_id: The ID of the Actor to be run. - run_input: The input to pass to the Actor run. + run_input: The input to pass to the Actor run. A `dict`, or a list or tuple of `dict`s, is serialized to + JSON. Bytes, a string, and a stream such as an open file are sent as they are, typically with a + `content_type`. token: The Apify API token to use for this request (defaults to the `APIFY_TOKEN` environment variable). content_type: The content type of the input. build: Specifies the Actor build to run. It can be either a build tag or build number. By default, @@ -1144,12 +1155,12 @@ async def start( the Actor run which can 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 or task, you do not have to add it again here. 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 - resurrected, and a new run is started only when nothing is recorded under the name, or the recorded - run `FAILED` or no longer exists. Using `run_name` to attach to a run of a different Actor, task or - with a different input raises a `ValueError`. Named child runs are experimental, so their behavior - and interface may change in future versions. + 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 resurrected, + and a new run is started only when nothing is recorded under the name, or the recorded run `FAILED` or + no longer exists. Using `run_name` to attach to a run of a different Actor, task or with a different + input raises a `ValueError`. A streamed `run_input` is not compared. Named child runs are experimental, + so their behavior and interface may change in future versions. abort_with_parent: If true, the child run is gracefully aborted when this Actor run is gracefully aborted. It requires `run_name`, and the value is recorded under it, replacing the one from an earlier call. Once this Actor run is being gracefully aborted, a call with it raises a `RuntimeError` and @@ -1300,7 +1311,7 @@ async def resurrect( async def call( self, actor_id: str, - run_input: Any = None, + run_input: RunInput | None = None, *, token: str | None = None, content_type: str | None = None, @@ -1323,7 +1334,9 @@ async def call( Args: actor_id: The ID of the Actor to be run. - run_input: The input to pass to the Actor run. + run_input: The input to pass to the Actor run. A `dict`, or a list or tuple of `dict`s, is serialized to + JSON. Bytes, a string, and a stream such as an open file are sent as they are, typically with a + `content_type`. token: The Apify API token to use for this request (defaults to the `APIFY_TOKEN` environment variable). content_type: The content type of the input. build: Specifies the Actor build to run. It can be either a build tag or build number. By default, @@ -1349,12 +1362,12 @@ async def call( default logger will be used. Setting `None` will disable any log propagation. Passing custom logger will redirect logs to the provided logger. 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 - resurrected, and a new run is started only when nothing is recorded under the name, or the recorded - run `FAILED` or no longer exists. Using `run_name` to attach to a run of a different Actor, task or - with a different input raises a `ValueError`. Named child runs are experimental, so their behavior - and interface may change in future versions. + 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 resurrected, + and a new run is started only when nothing is recorded under the name, or the recorded run `FAILED` or + no longer exists. Using `run_name` to attach to a run of a different Actor, task or with a different + input raises a `ValueError`. A streamed `run_input` is not compared. Named child runs are experimental, + so their behavior and interface may change in future versions. abort_with_parent: If true, the child run is gracefully aborted when this Actor run is gracefully aborted. It requires `run_name`, and the value is recorded under it, replacing the one from an earlier call. Once this Actor run is being gracefully aborted, a call with it raises a `RuntimeError` and @@ -1759,7 +1772,7 @@ async def call_task( async def metamorph( self, target_actor_id: str, - run_input: Any = None, + run_input: RunInput | None = None, *, target_actor_build: str | None = None, content_type: str | None = None, @@ -1773,7 +1786,9 @@ async def metamorph( Args: target_actor_id: ID of the target Actor that the run should be transformed into - run_input: The input to pass to the new run. + run_input: The input to pass to the new run. A `dict`, or a list or tuple of `dict`s, is serialized to JSON. + Bytes, a string, and a stream such as an open file are sent as they are, typically with a + `content_type`. target_actor_build: The build of the target Actor. It can be either a build tag or build number. By default, the run uses the build specified in the default run configuration for the target Actor (typically the latest build). diff --git a/src/apify/_child_runs.py b/src/apify/_child_runs.py index 4b3bc52d..0e771e3f 100644 --- a/src/apify/_child_runs.py +++ b/src/apify/_child_runs.py @@ -12,6 +12,7 @@ from pydantic.alias_generators import to_camel from apify_client.errors import NotFoundError +from apify_client.http_clients import StreamedRequestBody if TYPE_CHECKING: from collections.abc import Awaitable, Callable @@ -69,11 +70,14 @@ class ChildRunRecord(ChildRunSnapshot): def checksum_request(*, actor_id: str | None, task_id: str | None, run_input: Any) -> str: - """Hash the Actor or task and the input of a named start, in the same JSON shape as the JS SDK.""" + """Hash the Actor or task and the input of a named start, in the same JSON shape as the JS SDK. + + A streamed input is left out, because its content is read only when it is sent. + """ request: dict[str, Any] = ( {'type': 'actor', 'id': actor_id} if actor_id is not None else {'type': 'task', 'id': task_id} ) - if run_input is not None: + if run_input is not None and not StreamedRequestBody.is_streamable(run_input): request['input'] = run_input serialized = json.dumps(request, sort_keys=True, separators=(',', ':'), ensure_ascii=False, default=str) return hashlib.sha256(serialized.encode()).hexdigest() @@ -140,7 +144,7 @@ async def find_or_start( actor_id: The Actor to start. task_id: The task to start, in place of `actor_id`. run_input: Input of the run. The recorded run is reused only if it was started with the same Actor or task - and input. + and input. A streamed input is not compared. client: Client used to look up the recorded run. start_run: Starts a new run of the Actor or task. resurrect_run: Resurrects the recorded run, given its ID. diff --git a/tests/unit/actor/test_actor_child_runs.py b/tests/unit/actor/test_actor_child_runs.py index ffe87649..52d4b5f7 100644 --- a/tests/unit/actor/test_actor_child_runs.py +++ b/tests/unit/actor/test_actor_child_runs.py @@ -1,6 +1,7 @@ from __future__ import annotations import asyncio +import io import warnings from datetime import timedelta from typing import TYPE_CHECKING, Any @@ -716,6 +717,19 @@ def test_checksum_matches_js_sdk(request_kwargs: dict[str, Any], expected: str) assert checksum_request(**request_kwargs) == expected +@pytest.mark.parametrize( + 'run_input', + [ + pytest.param(io.BytesIO(b'{"a": 1}'), id='file-like object'), + pytest.param(iter([b'{"a": ', b'1}']), id='iterator of chunks'), + ], +) +def test_checksum_leaves_out_streamed_input(run_input: Any) -> None: + """A streamed input does not change the checksum, so a reattach after a migration does not compare it.""" + without_input = checksum_request(actor_id='some-actor', task_id=None, run_input=None) + assert checksum_request(actor_id='some-actor', task_id=None, run_input=run_input) == without_input + + async def test_reattached_run_status_is_recorded(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: """Reattaching to a recorded run stores its current status.""" apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', 'SUCCEEDED'))