Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions hyperbrowser/client/managers/sandboxes/shared.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import base64
import collections.abc
import inspect
import posixpath
import re
from datetime import datetime, timedelta, timezone
from typing import Dict, Optional, Union
from urllib.parse import urlencode, urlsplit, urlunsplit

from websockets.sync.client import connect as _sync_ws_connect

from ..._request import coerce_request, dump_request
from ....exceptions import HyperbrowserError
from ....models.sandbox import (
Expand Down Expand Up @@ -224,6 +227,15 @@ def _build_query_path(path: str, params: Optional[Dict[str, object]] = None) ->
return f"{path}?{urlencode(filtered)}"


# websockets 17.1 deprecates calling the synchronous connect() outside a with block unless it is
# passed legacy=True; earlier releases take no such argument.
SYNC_WEBSOCKET_CONNECT_OPTIONS: Dict[str, bool] = (
{"legacy": True}
if "legacy" in inspect.signature(_sync_ws_connect).parameters
else {}
)


def _normalize_websocket_error(error: BaseException) -> HyperbrowserError:
if isinstance(error, HyperbrowserError):
return error
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
SandboxFileWriteEntry as SandboxFileWriteEntryDict,
)
from ...sandboxes.shared import (
SYNC_WEBSOCKET_CONNECT_OPTIONS,
DEFAULT_WATCH_TIMEOUT_MS,
_encode_batch_write_entry,
_copy_model,
Expand Down Expand Up @@ -142,7 +143,7 @@ def events(
self._runtime_proxy_override,
)
headers = build_headers(connection.token, host_header=target.host_header)
connect_kwargs = {}
connect_kwargs: Dict[str, Any] = dict(SYNC_WEBSOCKET_CONNECT_OPTIONS)
if target.connect_host is not None and target.connect_port is not None:
connect_kwargs["sock"] = socket.create_connection(
(target.connect_host, target.connect_port),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import base64
import json
import socket
from typing import Dict, Optional, Union
from typing import Any, Dict, Optional, Union
from urllib.parse import urlencode

from websockets.exceptions import ConnectionClosed
Expand All @@ -20,6 +20,7 @@
SandboxTerminalCreateParams as SandboxTerminalCreateParamsDict,
)
from ...sandboxes.shared import (
SYNC_WEBSOCKET_CONNECT_OPTIONS,
_copy_model,
_normalize_terminal_output_chunk,
_normalize_terminal_status,
Expand Down Expand Up @@ -182,7 +183,7 @@ def attach(self, cursor: Optional[int] = None) -> SandboxTerminalConnection:
self._runtime_proxy_override,
)
headers = build_headers(connection.token, host_header=target.host_header)
connect_kwargs = {}
connect_kwargs: Dict[str, Any] = dict(SYNC_WEBSOCKET_CONNECT_OPTIONS)
if target.connect_host is not None and target.connect_port is not None:
connect_kwargs["sock"] = socket.create_connection(
(target.connect_host, target.connect_port),
Expand Down
2 changes: 1 addition & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "hyperbrowser"
version = "1.11.1"
version = "1.12.0"
description = "Python SDK for hyperbrowser"
authors = ["Nikhil Shahi <nshahi1998@gmail.com>"]
license = "MIT"
Expand All @@ -17,7 +17,7 @@ python = "^3.8"
pydantic = ">=2.0,<3"
httpx = ">=0.23.0,<1"
jsonref = ">=1.1.0"
websockets = ">=13,<16"
websockets = ">=13,<18"
typing-extensions = ">=4.0,<5"
cryptography = ">=41.0.0"

Expand Down
40 changes: 39 additions & 1 deletion tests/test_sandbox_wire_contract.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import inspect
import io
import threading
import warnings

import httpx
import pytest
from types import SimpleNamespace

from websockets.sync.client import connect as sync_ws_connect
from websockets.sync.server import serve as sync_ws_serve
import hyperbrowser.client.managers.async_manager.sandboxes.sandbox_terminal as async_terminal_module
import hyperbrowser.client.managers.sync_manager.sandboxes.sandbox_terminal as sync_terminal_module

Expand Down Expand Up @@ -33,7 +40,10 @@
from hyperbrowser.client.managers.sync_manager.sandboxes.sandbox_terminal import (
SandboxTerminalApi,
)
from hyperbrowser.client.managers.sandboxes.shared import _build_sandbox_exposed_url
from hyperbrowser.client.managers.sandboxes.shared import (
SYNC_WEBSOCKET_CONNECT_OPTIONS,
_build_sandbox_exposed_url,
)
from hyperbrowser.exceptions import HyperbrowserError
from hyperbrowser.models import (
CompleteSandboxImageBuildParams,
Expand Down Expand Up @@ -2230,6 +2240,7 @@ def fake_target(base_url, path, runtime_proxy_override):

def fake_connect(url, additional_headers=None, open_timeout=None, **kwargs):
captured["url"] = url
captured["kwargs"] = kwargs
return object()

monkeypatch.setattr(
Expand All @@ -2255,6 +2266,33 @@ def fake_connect(url, additional_headers=None, open_timeout=None, **kwargs):

assert "cursor=7" in captured["path"]
assert "cursor=7" in captured["url"]
assert captured["kwargs"].items() >= SYNC_WEBSOCKET_CONNECT_OPTIONS.items()


def test_sync_websocket_connect_options_connect_without_a_deprecation_warning():
supports_legacy = "legacy" in inspect.signature(sync_ws_connect).parameters
assert SYNC_WEBSOCKET_CONNECT_OPTIONS == (
{"legacy": True} if supports_legacy else {}
)

def echo(websocket):
for message in websocket:
websocket.send(message)

with sync_ws_serve(echo, "127.0.0.1", 0) as server:
threading.Thread(target=server.serve_forever, daemon=True).start()
port = server.socket.getsockname()[1]
with warnings.catch_warnings():
warnings.simplefilter("error", DeprecationWarning)
websocket = sync_ws_connect(
f"ws://127.0.0.1:{port}", **SYNC_WEBSOCKET_CONNECT_OPTIONS
)
try:
websocket.send("ping")
assert websocket.recv() == "ping"
finally:
websocket.close()
server.shutdown()


@pytest.mark.anyio
Expand Down