-
Notifications
You must be signed in to change notification settings - Fork 3
feat: add browser routing cache #93
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
Merged
Merged
Changes from 11 commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
7ca6887
feat: add browser-scoped session client
rgarcia b2c7aac
fix: reserve internal browser request query params
rgarcia cfff5b4
fix: type-check browser-scoped helpers
rgarcia fc34859
chore: fix browser-scoped test import order
rgarcia 8e8dde2
fix: satisfy browser-scoped lint checks
rgarcia 53b17c8
feat: generate browser-scoped resource bindings
rgarcia 0bdf85e
fix: quiet generator-script pyright noise
rgarcia b410245
fix: satisfy generated browser-scoped type checks
rgarcia a80716b
chore: keep browser-scoped generator lint clean
rgarcia ca5d188
docs: flesh out browser-scoped example
rgarcia dba503e
refactor: drop browser-scoped wrapper clients
rgarcia de0476f
refactor: simplify browser routing cache
rgarcia 3ae9dab
refactor: rename browser routing subresources config
rgarcia 622f844
refactor: clean up python browser routing diff
rgarcia 694907a
fix: finish python browser routing cleanup
rgarcia 9690923
fix: address python browser routing ci follow-ups
rgarcia 3ce80e7
fix: normalize python browser request string bodies
rgarcia 0647d5c
refactor: move python browser routing rollout to env
rgarcia f4c247b
fix: normalize browser route cache session IDs
rgarcia 563de7d
refactor: sniff browser routes in response hooks
rgarcia a873a18
fix: evict deleted browser routes
rgarcia 02a2f59
refactor: inline browser resource passthrough returns
rgarcia 5328730
fix: sniff browser pool route cache updates
rgarcia 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| """Example: direct-to-VM browser routing for process exec and raw HTTP.""" | ||
|
|
||
| from kernel import BrowserRoutingConfig, Kernel | ||
|
|
||
|
|
||
| def main() -> None: | ||
| with Kernel(browser_routing=BrowserRoutingConfig(enabled=True, direct_to_vm_subresources=("process",))) as client: | ||
| browser = client.browsers.create(headless=True) | ||
| try: | ||
| client.prime_browser_route_cache(browser) | ||
|
|
||
| client.browsers.process.exec(browser.session_id, command="uname", args=["-a"]) | ||
|
|
||
| response = client.browsers.request(browser.session_id, "GET", "https://example.com") | ||
| print("status", response.status_code) | ||
|
|
||
| with client.browsers.stream(browser.session_id, "GET", "https://example.com") as streamed: | ||
| print("streamed-bytes", len(streamed.read())) | ||
| finally: | ||
| client.browsers.delete_by_id(browser.session_id) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| __all__: list[str] = [] |
101 changes: 101 additions & 0 deletions
101
src/kernel/lib/browser_scoped/browser_session_kernel.py
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,101 @@ | ||
| """Internal Kernel clones for browser session HTTP (base_url + /browser/kernel paths).""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import Any, Mapping, cast | ||
| from typing_extensions import override | ||
|
|
||
| from ..._client import Kernel, AsyncKernel | ||
| from ..._compat import model_copy | ||
| from ..._models import FinalRequestOptions | ||
|
|
||
|
|
||
| class _BrowserSessionKernel(Kernel): | ||
| """Kernel clone whose HTTP base is the browser session; strips /browsers/{id} from paths.""" | ||
|
|
||
| _scoped_session_id: str | ||
|
|
||
| def __init__(self, *, browser_session_id: str, **kwargs: Any) -> None: | ||
| self._scoped_session_id = browser_session_id | ||
| super().__init__(**kwargs) | ||
|
|
||
| @override | ||
| def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions: | ||
| options = super()._prepare_options(options) | ||
| url = options.url | ||
| prefix = f"/browsers/{self._scoped_session_id}/" | ||
| if not url.startswith(prefix): | ||
| return options | ||
| suffix = url[len(prefix) :].lstrip("/") | ||
| new_url = f"/{suffix}" if suffix else "/" | ||
| out = model_copy(options) | ||
| out.url = new_url | ||
| return out | ||
|
|
||
|
|
||
| class _BrowserSessionAsyncKernel(AsyncKernel): | ||
| _scoped_session_id: str | ||
|
|
||
| def __init__(self, *, browser_session_id: str, **kwargs: Any) -> None: | ||
| self._scoped_session_id = browser_session_id | ||
| super().__init__(**kwargs) | ||
|
|
||
| @override | ||
| async def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions: | ||
| options = await super()._prepare_options(options) | ||
| url = options.url | ||
| prefix = f"/browsers/{self._scoped_session_id}/" | ||
| if not url.startswith(prefix): | ||
| return options | ||
| suffix = url[len(prefix) :].lstrip("/") | ||
| new_url = f"/{suffix}" if suffix else "/" | ||
| out = model_copy(options) | ||
| out.url = new_url | ||
| return out | ||
|
|
||
|
|
||
| def build_browser_session_kernel( | ||
| parent: Kernel, *, session_id: str, session_base_url: str, jwt: str | ||
| ) -> _BrowserSessionKernel: | ||
| """Build a sync client sharing the parent's httpx transport; requests use session_base_url.""" | ||
| base_q_raw = getattr(parent, "_custom_query", None) | ||
| if isinstance(base_q_raw, Mapping): | ||
| base_q = {str(k): v for k, v in cast(Mapping[str, object], base_q_raw).items()} | ||
| else: | ||
| base_q = {} | ||
| dq = dict(base_q) | ||
| dq["jwt"] = jwt | ||
| return _BrowserSessionKernel( | ||
| browser_session_id=session_id, | ||
| api_key=parent.api_key, | ||
| base_url=session_base_url, | ||
| timeout=parent.timeout, | ||
| max_retries=parent.max_retries, | ||
| http_client=parent._client, | ||
| default_headers=dict(parent._custom_headers), | ||
| default_query=dq, | ||
| _strict_response_validation=getattr(parent, "_strict_response_validation", False), | ||
| ) | ||
|
|
||
|
|
||
| def build_async_browser_session_kernel( | ||
| parent: AsyncKernel, *, session_id: str, session_base_url: str, jwt: str | ||
| ) -> _BrowserSessionAsyncKernel: | ||
| base_q_raw = getattr(parent, "_custom_query", None) | ||
| if isinstance(base_q_raw, Mapping): | ||
| base_q = {str(k): v for k, v in cast(Mapping[str, object], base_q_raw).items()} | ||
| else: | ||
| base_q = {} | ||
| dq = dict(base_q) | ||
| dq["jwt"] = jwt | ||
| return _BrowserSessionAsyncKernel( | ||
| browser_session_id=session_id, | ||
| api_key=parent.api_key, | ||
| base_url=session_base_url, | ||
| timeout=parent.timeout, | ||
| max_retries=parent.max_retries, | ||
| http_client=parent._client, | ||
| default_headers=dict(parent._custom_headers), | ||
| default_query=dq, | ||
| _strict_response_validation=getattr(parent, "_strict_response_validation", False), | ||
| ) | ||
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.
Uh oh!
There was an error while loading. Please reload this page.