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
14 changes: 14 additions & 0 deletions hyperbrowser/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,26 @@
from .client.async_client import AsyncHyperbrowser
from .config import ClientConfig
from .customer_key import CustomerKey, create_customer_key, secret_envelope_digest
from .exceptions import HyperbrowserError
from .image_builds import (
DockerBuildContextChangedError,
DockerCommandError,
docker_build_context_fingerprint,
docker_image_digest,
image_build_name,
)

__all__ = [
"Hyperbrowser",
"AsyncHyperbrowser",
"ClientConfig",
"HyperbrowserError",
"CustomerKey",
"create_customer_key",
"secret_envelope_digest",
"docker_build_context_fingerprint",
"DockerBuildContextChangedError",
"image_build_name",
"docker_image_digest",
"DockerCommandError",
]
62 changes: 37 additions & 25 deletions hyperbrowser/client/managers/async_manager/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import time
from pathlib import Path
from typing import Dict, List, Optional, Union
from urllib.parse import quote

from ..._request import coerce_request, dump_request
from ....exceptions import HyperbrowserError
Expand Down Expand Up @@ -375,7 +376,16 @@ async def get_process(self, process_id: str) -> SandboxProcessHandle:
return await self.processes.get(process_id)

def _hydrate(self, detail: SandboxDetail) -> None:
if (
detail.startup_secrets is None
and getattr(self, "_detail", None) is not None
and self._detail.startup_secrets is not None
):
detail = detail.model_copy(
update={"startup_secrets": self._detail.startup_secrets}
)
self._detail = detail
self.startup_secrets = self._detail.startup_secrets
self._runtime_session = self._to_runtime_session(detail)

async def _resolve_runtime_connection(
Expand All @@ -396,18 +406,6 @@ async def _resolve_runtime_socket_info(self) -> RuntimeConnection:
token=session.token,
)

def _apply_runtime_session(self, session: SandboxRuntimeSession) -> None:
self._runtime_session = _copy_model(session)
self._detail = self._detail.model_copy(
update={
"status": session.status,
"region": session.region,
"runtime": session.runtime,
"token": session.token,
"token_expires_at": session.token_expires_at,
}
)

def _clear_runtime_session(self, status: Optional[str] = None) -> None:
self._runtime_session = None
self._detail = self._detail.model_copy(
Expand Down Expand Up @@ -492,7 +490,7 @@ async def list(
return SandboxListResponse(**payload)

async def delete_image(self, image: str) -> SandboxImageDeleteResult:
payload = await self._request("DELETE", f"/images/{image}")
payload = await self._request("DELETE", f"/images/{quote(str(image), safe='')}")
return SandboxImageDeleteResult(**payload)

async def list_images(
Expand Down Expand Up @@ -681,15 +679,21 @@ async def list_snapshots(
return SandboxSnapshotListResponse(**payload)

async def get_snapshot(self, snapshot: str) -> SandboxSnapshotSummary:
payload = await self._request("GET", f"/snapshots/{snapshot}")
payload = await self._request(
"GET", f"/snapshots/{quote(str(snapshot), safe='')}"
)
return SandboxSnapshotSummary(**payload["snapshot"])

async def delete_snapshot(self, snapshot: str) -> SandboxSnapshotDeleteResult:
payload = await self._request("DELETE", f"/snapshots/{snapshot}")
payload = await self._request(
"DELETE", f"/snapshots/{quote(str(snapshot), safe='')}"
)
return SandboxSnapshotDeleteResult(**payload)

async def stop(self, sandbox_id: str) -> BasicResponse:
payload = await self._request("PUT", f"/sandbox/{sandbox_id}/stop")
payload = await self._request(
"PUT", f"/sandbox/{quote(str(sandbox_id), safe='')}/stop"
)
return BasicResponse(**payload)

async def create_image_build(
Expand All @@ -707,7 +711,9 @@ async def create_image_build(
return SandboxImageBuildCreateResult(**payload)

async def get_image_build(self, build_id: str) -> SandboxImageBuild:
payload = await self._request("GET", f"/images/builds/{build_id}")
payload = await self._request(
"GET", f"/images/builds/{quote(str(build_id), safe='')}"
)
return SandboxImageBuild(**payload["build"])

async def reuse_docker_image(
Expand All @@ -734,13 +740,15 @@ async def complete_image_build(
) -> SandboxImageBuild:
payload = await self._request(
"POST",
f"/images/builds/{build_id}/complete",
f"/images/builds/{quote(str(build_id), safe='')}/complete",
data=dump_request(params, CompleteSandboxImageBuildParams),
)
return SandboxImageBuild(**payload["build"])

async def cancel_image_build(self, build_id: str) -> SandboxImageBuild:
payload = await self._request("POST", f"/images/builds/{build_id}/cancel")
payload = await self._request(
"POST", f"/images/builds/{quote(str(build_id), safe='')}/cancel"
)
return SandboxImageBuild(**payload["build"])

async def list_image_builds(
Expand Down Expand Up @@ -1104,7 +1112,9 @@ async def get_runtime_session(self, sandbox_id: str) -> SandboxRuntimeSession:
return session

async def get_detail(self, sandbox_id: str) -> SandboxDetail:
payload = await self._request("GET", f"/sandbox/{sandbox_id}")
payload = await self._request(
"GET", f"/sandbox/{quote(str(sandbox_id), safe='')}"
)
return SandboxDetail(**payload)

def attach(self, detail: SandboxDetail) -> SandboxHandle:
Expand All @@ -1119,7 +1129,7 @@ async def create_memory_snapshot(
) -> SandboxMemorySnapshotResult:
payload = await self._request(
"POST",
f"/sandbox/{sandbox_id}/snapshot",
f"/sandbox/{quote(str(sandbox_id), safe='')}/snapshot",
data=dump_request(
params if params is not None else {},
SandboxMemorySnapshotParams,
Expand All @@ -1134,7 +1144,7 @@ async def update_network(
) -> SandboxNetworkUpdateResult:
payload = await self._request(
"PUT",
f"/sandbox/{sandbox_id}/network",
f"/sandbox/{quote(str(sandbox_id), safe='')}/network",
data=dump_request(
policy,
SandboxNetworkPolicy,
Expand All @@ -1153,7 +1163,7 @@ async def expose(
) -> SandboxExposeResult:
payload = await self._request(
"POST",
f"/sandbox/{sandbox_id}/expose",
f"/sandbox/{quote(str(sandbox_id), safe='')}/expose",
data=dump_request(params, SandboxExposeParams),
)
target_runtime = runtime or (await self.get_detail(sandbox_id)).runtime
Expand All @@ -1164,7 +1174,7 @@ async def expose(
async def unexpose(self, sandbox_id: str, port: int) -> SandboxUnexposeResult:
payload = await self._request(
"POST",
f"/sandbox/{sandbox_id}/unexpose",
f"/sandbox/{quote(str(sandbox_id), safe='')}/unexpose",
data={"port": port},
)
return SandboxUnexposeResult(**payload)
Expand All @@ -1179,7 +1189,9 @@ async def start_secret_process(
"""
try:
response = await self._request(
"POST", f"/sandbox/{sandbox_id}/processes", data=payload
"POST",
f"/sandbox/{quote(str(sandbox_id), safe='')}/processes",
data=payload,
)
except HyperbrowserError as error:
raise secret_process_start_error(sandbox_id, error)
Expand Down
7 changes: 7 additions & 0 deletions hyperbrowser/client/managers/async_manager/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
CaptchaEvaluationResponse,
CreateSessionParams,
CreateSessionSnapshotResponse,
GetActiveSessionsCountResponse,
GetSessionDownloadsUrlResponse,
GetSessionRecordingUrlResponse,
GetSessionVideoRecordingUrlResponse,
Expand Down Expand Up @@ -139,6 +140,12 @@ async def list(
)
return SessionListResponse(**response.data)

async def get_active_sessions_count(self) -> GetActiveSessionsCountResponse:
response = await self._client.transport.get(
self._client._build_url("/sessions/active-count")
)
return GetActiveSessionsCountResponse(**response.data)

async def get_recording(self, id: str) -> List[SessionRecording]:
response = await self._client.transport.get(
self._client._build_url(f"/session/{id}/recording"), None, True
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
CREDENTIAL_FILL_REQUEST_TIMEOUT_SECONDS,
fill_credential_payload,
)
from hyperbrowser.exceptions import HyperbrowserError
from hyperbrowser.models.credential import CredentialFillResult, FillCredentialParams
from hyperbrowser.types.credential import (
FillCredentialParams as FillCredentialParamsDict,
Expand Down Expand Up @@ -42,10 +43,12 @@ async def fill(
``error.details["details"]["pages"]``; pass one's ``pageId`` as
``page_id``, or a URL prefix as ``page_url``.
"""
if not isinstance(session_id, str) or not session_id.strip():
raise HyperbrowserError("A session ID is required", code="invalid_request")
body = fill_credential_payload(params)
response = await self._client.transport.post(
self._client._build_url(
f"/session/{quote(session_id, safe='')}/credentials/fill"
f"/session/{quote(session_id.strip(), safe='')}/credentials/fill"
),
data=body,
timeout=max(self._client.timeout, CREDENTIAL_FILL_REQUEST_TIMEOUT_SECONDS),
Expand Down
30 changes: 19 additions & 11 deletions hyperbrowser/client/managers/sandboxes/image_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -1224,8 +1224,7 @@ def _follow_context_source_symlinks(
) from exc
if not target or "\x00" in target:
raise ValueError(
f'build context symlink "{current_relative}" has an '
"invalid target"
f'build context symlink "{current_relative}" has an invalid target'
)

remainder = parts[index + 1 :]
Expand Down Expand Up @@ -1634,6 +1633,10 @@ def _remove_docker_container(container_id: str) -> None:
pass


class DockerCommandError(RuntimeError):
"""Raised when a local Docker CLI command fails."""


def _run_command(args: Sequence[str]) -> None:
_run_command_result(args)

Expand All @@ -1643,16 +1646,21 @@ def _run_command_output(args: Sequence[str]) -> str:


def _run_command_result(args: Sequence[str]) -> subprocess.CompletedProcess:
result = subprocess.run(
list(args),
check=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
try:
result = subprocess.run(
list(args),
check=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
except FileNotFoundError as exc:
raise DockerCommandError(
"docker CLI is required for local Docker image operations"
) from exc
if result.returncode == 0:
return result
message = result.stderr.strip()
if message:
raise RuntimeError(f"{' '.join(args)}: {message}")
raise RuntimeError(f"{' '.join(args)} failed with code {result.returncode}")
raise DockerCommandError(f"{' '.join(args)}: {message}")
raise DockerCommandError(f"{' '.join(args)} failed with code {result.returncode}")
Loading