Repository navigation
feat: Implement charge() for multi-tenant Server Actors #1211
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
janbuchar
wants to merge
2
commits into
master
Choose a base branch
from
multi-tenant-charge
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| import asyncio | ||
| from typing import Annotated | ||
|
|
||
| import uvicorn | ||
| from fastapi import FastAPI, Header | ||
|
|
||
| from apify import Actor | ||
|
|
||
| app = FastAPI() | ||
|
|
||
|
|
||
| @app.get('/') | ||
| async def index( | ||
| x_actor_request_id: Annotated[str | None, Header()] = None, | ||
| ) -> str: | ||
| # The platform identifies the caller of each request with this header. | ||
| # Pass it along so the charge lands on the caller's account, not yours. | ||
| await Actor.charge(event_name='api-call', request_id=x_actor_request_id) | ||
| return 'done' | ||
|
|
||
|
|
||
| async def main() -> None: | ||
| async with Actor: | ||
| config = uvicorn.Config( | ||
| app, | ||
| host='0.0.0.0', # noqa: S104 | ||
| port=Actor.configuration.web_server_port, | ||
| ) | ||
| await uvicorn.Server(config).serve() | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| asyncio.run(main()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,9 +1,13 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import os | ||
| from decimal import Decimal | ||
| from functools import partial | ||
| from typing import TYPE_CHECKING | ||
| from urllib.parse import urlsplit | ||
|
|
||
| import impit | ||
| import pytest_asyncio | ||
|
|
||
| from .._utils import poll_until_condition | ||
|
|
@@ -226,3 +230,96 @@ async def test_actor_push_data_combined_budget_limit( | |
|
|
||
| assert run.status == 'SUCCEEDED' | ||
| assert run.charged_event_counts == expected_counts | ||
|
|
||
|
|
||
| async def test_actor_charge_in_multi_tenant_standby_run( | ||
| make_actor: MakeActorFunction, | ||
| apify_client_async: ApifyClientAsync, | ||
| apify_token: str, | ||
| ) -> None: | ||
| """Test that a multi-tenant Server Actor run charges with the request ID and rejects charges without it.""" | ||
|
|
||
| async def main() -> None: | ||
| import json | ||
|
|
||
| import uvicorn | ||
|
|
||
| async def app(scope, receive, send): # noqa: ANN001, ANN202, ARG001 | ||
| headers = dict(scope['headers']) | ||
| if b'x-apify-container-server-readiness-probe' in headers: | ||
| body = b'ready' | ||
| else: | ||
| request_id = headers.get(b'x-actor-request-id', b'').decode() or None | ||
| if scope['query_string'] == b'omit_request_id': | ||
| request_id = None | ||
| try: | ||
| result = await Actor.charge(event_name='api-call', request_id=request_id) | ||
| body = json.dumps({'charged_count': result.charged_count, 'request_id': request_id}).encode() | ||
| except ValueError as exc: | ||
| body = json.dumps({'error': str(exc)}).encode() | ||
| await send({'type': 'http.response.start', 'status': 200, 'headers': []}) | ||
| await send({'type': 'http.response.body', 'body': body}) | ||
|
|
||
| async with Actor: | ||
| config = uvicorn.Config(app, host='0.0.0.0', port=Actor.configuration.web_server_port) # noqa: S104 | ||
| await uvicorn.Server(config).serve() | ||
|
|
||
| actor_client = await make_actor('ppe-multi-tenant', main_func=main) | ||
| await actor_client.update( | ||
| pricing_infos=[ | ||
| { | ||
| 'pricingModel': 'PAY_PER_EVENT', | ||
| 'apifyMarginPercentage': 0.0, | ||
| 'createdAt': '2024-01-01T00:00:00.000Z', | ||
| 'startedAt': '2024-01-01T00:00:00.000Z', | ||
| 'pricingPerEvent': { | ||
| 'actorChargeEvents': { | ||
| 'api-call': { | ||
| 'eventTitle': 'API call', | ||
| 'eventPriceUsd': 0.01, | ||
| 'eventDescription': 'One API call', | ||
| }, | ||
| }, | ||
| }, | ||
| }, | ||
| ], | ||
| ) | ||
|
|
||
| actor = await actor_client.get() | ||
| assert actor is not None | ||
| auth = {'Authorization': f'Bearer {apify_token}'} | ||
|
|
||
| async with impit.AsyncClient(timeout=120) as http: | ||
| # `ActorClientAsync.update()` has no tenancy argument, so the field is set through the API directly. | ||
| api_url = os.getenv('APIFY_INTEGRATION_TESTS_API_URL', 'https://api.apify.com') | ||
| response = await http.put( | ||
| f'{api_url}/v2/acts/{actor.id}', | ||
| headers={**auth, 'Content-Type': 'application/json'}, | ||
| content=json.dumps({'actorStandby': {'isEnabled': True, 'tenancy': 'MULTI_TENANT'}}), | ||
| ) | ||
| assert response.status_code == 200, response.text | ||
|
Comment on lines
+295
to
+300
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This will be better after apify/apify-client-python#1169 |
||
|
|
||
| actor = await actor_client.get() | ||
| assert actor is not None | ||
| assert actor.standby_url is not None | ||
|
|
||
| # The `<username>--<actor-name>` label of `standby_url` exceeds the 63-char DNS label limit with generated | ||
| # Actor names, so the ID-based hostname is used instead. | ||
| standby_domain = urlsplit(actor.standby_url).netloc.split('.', 1)[1] | ||
| standby_url = f'https://{actor.id}.{standby_domain}' | ||
|
|
||
| try: | ||
| with_id = (await http.get(standby_url, headers=auth)).json() | ||
| without_id = (await http.get(f'{standby_url}?omit_request_id', headers=auth)).json() | ||
| finally: | ||
| runs = await actor_client.runs().list() | ||
| for run_item in runs.items: | ||
| await apify_client_async.run(run_item.id).abort() | ||
|
|
||
| assert with_id['charged_count'] == 1 | ||
| assert with_id['request_id'] | ||
| assert 'request_id' in without_id['error'] | ||
|
|
||
| run = await _get_run(apify_client_async, runs.items[0].id) | ||
| assert run.standby is not None | ||
| assert run.standby.deployment.startswith('MULTI_TENANT') | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
apify client 3.4.0 was released, so you can update it