Skip to content

Commit 9f9b98a

Browse files
authored
feat: Allow passing X-Actor-Request-ID via charge() method (#1155)
Adds an optional `request_id` argument to `RunClient.charge()` and `RunClientAsync.charge()`. The client sends it as `requestId` in the charge request body. A multi-tenant Standby run passes the `X-Actor-Request-ID` header of the incoming request here, and the platform bills the event to the caller who made that request. - Needed by apify/apify-sdk-python#1193 - Counterpart of apify/apify-client-js#1162 *✍️ Drafted by Claude Code*
1 parent ce0a9e1 commit 9f9b98a

2 files changed

Lines changed: 78 additions & 12 deletions

File tree

‎src/apify_client/_resource_clients/run.py‎

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -390,6 +390,7 @@ def charge(
390390
*,
391391
count: int = 1,
392392
idempotency_key: str | None = None,
393+
request_id: str | None = None,
393394
timeout: Timeout = 'short',
394395
) -> None:
395396
"""Charge for an event of a Pay-Per-Event Actor run.
@@ -401,6 +402,9 @@ def charge(
401402
count: The number of events to charge.
402403
idempotency_key: A unique key to ensure idempotent charging. If not provided,
403404
one will be auto-generated.
405+
request_id: ID of the request served by a multi-tenant Actor Server run, taken from the `X-Actor-Request-ID`
406+
header of the incoming request. The charge then goes to the account of the caller who made that request,
407+
not the account that started the run.
404408
timeout: Timeout for the API HTTP request.
405409
406410
Raises:
@@ -414,19 +418,21 @@ def charge(
414418
timestamp_ms = int(time.time() * 1000)
415419
idempotency_key = f'{self._resource_id}-{event_name}-{timestamp_ms}-{random_suffix}'
416420

421+
body: dict[str, str | int] = {
422+
'eventName': event_name,
423+
'count': count,
424+
}
425+
if request_id is not None:
426+
body['requestId'] = request_id
427+
417428
self._http_client.call(
418429
url=self._build_url('charge'),
419430
method='POST',
420431
headers={
421432
'idempotency-key': idempotency_key,
422433
'content-type': 'application/json',
423434
},
424-
data=json.dumps(
425-
{
426-
'eventName': event_name,
427-
'count': count,
428-
}
429-
),
435+
data=json.dumps(body),
430436
timeout=timeout,
431437
)
432438

@@ -940,6 +946,7 @@ async def charge(
940946
*,
941947
count: int = 1,
942948
idempotency_key: str | None = None,
949+
request_id: str | None = None,
943950
timeout: Timeout = 'short',
944951
) -> None:
945952
"""Charge for an event of a Pay-Per-Event Actor run.
@@ -951,6 +958,9 @@ async def charge(
951958
count: The number of events to charge.
952959
idempotency_key: A unique key to ensure idempotent charging. If not provided,
953960
one will be auto-generated.
961+
request_id: ID of the request served by a multi-tenant Actor Server run, taken from the `X-Actor-Request-ID`
962+
header of the incoming request. The charge then goes to the account of the caller who made that request,
963+
not the account that started the run.
954964
timeout: Timeout for the API HTTP request.
955965
956966
Raises:
@@ -964,19 +974,21 @@ async def charge(
964974
timestamp_ms = int(time.time() * 1000)
965975
idempotency_key = f'{self._resource_id}-{event_name}-{timestamp_ms}-{random_suffix}'
966976

977+
body: dict[str, str | int] = {
978+
'eventName': event_name,
979+
'count': count,
980+
}
981+
if request_id is not None:
982+
body['requestId'] = request_id
983+
967984
await self._http_client.call(
968985
url=self._build_url('charge'),
969986
method='POST',
970987
headers={
971988
'idempotency-key': idempotency_key,
972989
'content-type': 'application/json',
973990
},
974-
data=json.dumps(
975-
{
976-
'eventName': event_name,
977-
'count': count,
978-
}
979-
),
991+
data=json.dumps(body),
980992
timeout=timeout,
981993
)
982994

‎tests/unit/test_run_charge.py‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,3 +71,57 @@ def capture_request(request: Request) -> Response:
7171
assert len(captured_requests) == 1
7272
body = json.loads(captured_requests[0].get_data())
7373
assert body['count'] == count
74+
75+
76+
@pytest.mark.parametrize(
77+
('request_id', 'expected_body'),
78+
[
79+
pytest.param(None, {'eventName': 'test-event', 'count': 1}, id='omitted'),
80+
pytest.param('req_123', {'eventName': 'test-event', 'count': 1, 'requestId': 'req_123'}, id='provided'),
81+
],
82+
)
83+
def test_run_charge_sends_request_id_sync(httpserver: HTTPServer, request_id: str | None, expected_body: dict) -> None:
84+
"""Ensure `request_id` is sent as `requestId` in the body, and left out when not provided."""
85+
captured_requests: list[Request] = []
86+
87+
def capture_request(request: Request) -> Response:
88+
captured_requests.append(request)
89+
return Response(status=200, mimetype='application/json')
90+
91+
httpserver.expect_request(_CHARGE_PATH, method='POST').respond_with_handler(capture_request)
92+
93+
api_url = httpserver.url_for('/').removesuffix('/')
94+
client = ApifyClient(token='test_token', api_url=api_url)
95+
96+
client.run(_MOCKED_RUN_ID).charge('test-event', request_id=request_id)
97+
98+
assert len(captured_requests) == 1
99+
assert json.loads(captured_requests[0].get_data()) == expected_body
100+
101+
102+
@pytest.mark.parametrize(
103+
('request_id', 'expected_body'),
104+
[
105+
pytest.param(None, {'eventName': 'test-event', 'count': 1}, id='omitted'),
106+
pytest.param('req_123', {'eventName': 'test-event', 'count': 1, 'requestId': 'req_123'}, id='provided'),
107+
],
108+
)
109+
async def test_run_charge_sends_request_id_async(
110+
httpserver: HTTPServer, request_id: str | None, expected_body: dict
111+
) -> None:
112+
"""Async variant of `test_run_charge_sends_request_id_sync`."""
113+
captured_requests: list[Request] = []
114+
115+
def capture_request(request: Request) -> Response:
116+
captured_requests.append(request)
117+
return Response(status=200, mimetype='application/json')
118+
119+
httpserver.expect_request(_CHARGE_PATH, method='POST').respond_with_handler(capture_request)
120+
121+
api_url = httpserver.url_for('/').removesuffix('/')
122+
client = ApifyClientAsync(token='test_token', api_url=api_url)
123+
124+
await client.run(_MOCKED_RUN_ID).charge('test-event', request_id=request_id)
125+
126+
assert len(captured_requests) == 1
127+
assert json.loads(captured_requests[0].get_data()) == expected_body

0 commit comments

Comments
 (0)