diff --git a/src/apify/_actor.py b/src/apify/_actor.py index 654b1360..09f1888b 100644 --- a/src/apify/_actor.py +++ b/src/apify/_actor.py @@ -38,6 +38,7 @@ charge_lock_if_charging, ) from apify._child_runs import ( + RUN_NAME_PATTERN, TERMINAL_RUN_STATUSES, ChildRunRegistry, KeyValueStoreChildRunTracker, @@ -1220,8 +1221,9 @@ async def start( is in, and a new run is started only when nothing is recorded under the name, or the recorded run no longer exists. Using `run_name` for a different Actor, task, input, `build`, `force_permission_level` or `webhooks` raises a `ValueError`. An input that is not sent as JSON is not checked, and a warning is - logged. It raises a `ValueError` with child run tracking off. Named child runs are experimental, so - their behavior and interface may change in future versions. + logged. The name must have 1 to 63 letters, digits, hyphens or underscores, or it raises a `ValueError`. + It also raises a `ValueError` with child run tracking off. 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 receives the `ABORTING` event, or exits with a non-zero exit code (`Actor.fail()`, `Actor.exit()` with a non-zero code, or an exception that leaves `async with Actor`), also after a migration, reboot or resurrection. @@ -1432,8 +1434,9 @@ async def call( is in, and a new run is started only when nothing is recorded under the name, or the recorded run no longer exists. Using `run_name` for a different Actor, task, input, `build`, `force_permission_level` or `webhooks` raises a `ValueError`. An input that is not sent as JSON is not checked, and a warning is - logged. It raises a `ValueError` with child run tracking off. Named child runs are experimental, so - their behavior and interface may change in future versions. + logged. The name must have 1 to 63 letters, digits, hyphens or underscores, or it raises a `ValueError`. + It also raises a `ValueError` with child run tracking off. 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 receives the `ABORTING` event, or exits with a non-zero exit code (`Actor.fail()`, `Actor.exit()` with a non-zero code, or an exception that leaves `async with Actor`), also after a migration, reboot or resurrection. @@ -1507,9 +1510,11 @@ def _check_child_run_options( """Validate the child run options of `start`, `call`, `start_task` and `call_task`. Raises: - ValueError: If an option needs child run tracking and it is off, or `abort_with_parent` comes with a - `token`. + ValueError: If `run_name` has an invalid format, an option needs child run tracking and it is off, or + `abort_with_parent` comes with a `token`. """ + if run_name is not None and not RUN_NAME_PATTERN.fullmatch(run_name): + raise ValueError(f'`run_name` must have 1 to 63 letters, digits, hyphens or underscores, got {run_name!r}.') if not self._child_run_registry.is_enabled and (run_name is not None or abort_with_parent): raise ValueError( '`run_name` and `abort_with_parent` need child run tracking, which is turned off with ' @@ -1690,8 +1695,9 @@ async def start_task( is in, and a new run is started only when nothing is recorded under the name, or the recorded run no longer exists. Using `run_name` for a different Actor, task, input, `build`, `force_permission_level` or `webhooks` raises a `ValueError`. An input that is not sent as JSON is not checked, and a warning is - logged. It raises a `ValueError` with child run tracking off. Named child runs are experimental, so - their behavior and interface may change in future versions. + logged. The name must have 1 to 63 letters, digits, hyphens or underscores, or it raises a `ValueError`. + It also raises a `ValueError` with child run tracking off. 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 receives the `ABORTING` event, or exits with a non-zero exit code (`Actor.fail()`, `Actor.exit()` with a non-zero code, or an exception that leaves `async with Actor`), also after a migration, reboot or resurrection. @@ -1803,8 +1809,9 @@ async def call_task( is in, and a new run is started only when nothing is recorded under the name, or the recorded run no longer exists. Using `run_name` for a different Actor, task, input, `build`, `force_permission_level` or `webhooks` raises a `ValueError`. An input that is not sent as JSON is not checked, and a warning is - logged. It raises a `ValueError` with child run tracking off. Named child runs are experimental, so - their behavior and interface may change in future versions. + logged. The name must have 1 to 63 letters, digits, hyphens or underscores, or it raises a `ValueError`. + It also raises a `ValueError` with child run tracking off. 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 receives the `ABORTING` event, or exits with a non-zero exit code (`Actor.fail()`, `Actor.exit()` with a non-zero code, or an exception that leaves `async with Actor`), also after a migration, reboot or resurrection. diff --git a/src/apify/_child_runs.py b/src/apify/_child_runs.py index 9eb6a708..4d011c40 100644 --- a/src/apify/_child_runs.py +++ b/src/apify/_child_runs.py @@ -5,6 +5,7 @@ import itertools import json import math +import re from abc import ABC, abstractmethod from contextlib import asynccontextmanager, suppress from datetime import timedelta @@ -63,6 +64,9 @@ EXCESSIVE_CHILD_RUNS_THRESHOLD = 50 """Number of records above which the registry logs a warning about its size, once per process.""" +RUN_NAME_PATTERN = re.compile(r'[a-zA-Z0-9_-]{1,63}') +"""Format of a run name: characters and a length that the platform can use as a key if it stores run names.""" + def run_key(run_id: str) -> str: """Return the registry key of a child run started without a run name.""" diff --git a/tests/unit/actor/test_actor_child_runs.py b/tests/unit/actor/test_actor_child_runs.py index d1c97499..1fca66d0 100644 --- a/tests/unit/actor/test_actor_child_runs.py +++ b/tests/unit/actor/test_actor_child_runs.py @@ -1595,6 +1595,59 @@ async def test_tracking_off_starts_runs_without_recording_them( assert stored is None +@pytest.mark.parametrize( + 'run_name', + [ + pytest.param('', id='empty'), + pytest.param('a' * 64, id='too long'), + pytest.param('scrape.eu', id='dot'), + pytest.param('scrape eu', id='space'), + pytest.param('scrape/eu', id='slash'), + pytest.param('scrape:eu', id='colon'), + pytest.param('scrape-\u00e9u', id='non-ASCII letter'), + ], +) +@pytest.mark.parametrize( + ('method', 'resource'), + [ + pytest.param('start', 'actor', id='start'), + pytest.param('call', 'actor', id='call'), + pytest.param('start_task', 'task', id='start task'), + pytest.param('call_task', 'task', id='call task'), + ], +) +async def test_invalid_run_name_is_rejected( + apify_client_async_patcher: ApifyClientAsyncPatcher, method: str, resource: str, run_name: str +) -> None: + """A `run_name` outside 1 to 63 letters, digits, hyphens or underscores raises a `ValueError` and starts no run.""" + apify_client_async_patcher.patch(resource, 'start', return_value=make_run('new-run', 'READY')) + + async with Actor: + with pytest.raises(ValueError, match='`run_name` must have 1 to 63'): + await getattr(Actor, method)('some-id', run_name=run_name) + + assert apify_client_async_patcher.calls[resource]['start'] == [] + + +@pytest.mark.parametrize( + 'run_name', + [ + pytest.param('a', id='one character'), + pytest.param('a' * 63, id='63 characters'), + pytest.param('Scrape_EU-2', id='letters digits hyphen underscore'), + ], +) +async def test_valid_run_name_is_accepted(apify_client_async_patcher: ApifyClientAsyncPatcher, run_name: str) -> None: + """A `run_name` of 1 to 63 letters, digits, hyphens or underscores starts a run recorded under that name.""" + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) + + async with Actor: + await Actor.start('some-actor', run_name=run_name) + keys = [child_run.key for child_run in Actor.child_runs] + + assert keys == [name_key(run_name)] + + @pytest.mark.parametrize( 'kwargs', [