Skip to content

Secure, Fast, and Extensible Sandbox runtime for AI agents.

10.1 KB
Raw Blame
#
# Copyright 2025 The OpenSandbox Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
Connection configuration for OpenSandbox operations.
"""

import os
import ssl
from datetime import timedelta

import httpx  # type: ignore[reportMissingImports]
from pydantic import (  # type: ignore[reportMissingImports]
    BaseModel,
    ConfigDict,
    Field,
    PrivateAttr,
    field_validator,
)

from opensandbox._httpx import AsyncEventHook
from opensandbox.transport import RetryAsyncTransport, RetryPolicy


class ConnectionConfig(BaseModel):
    """
    Sandbox operations connection configuration.

    Transport lifecycle:
    - If `transport` is NOT provided, the SDK creates a default `httpx.AsyncHTTPTransport`
      per Sandbox/Manager instance. In this case, `Sandbox.close()` / `SandboxManager.close()`
      will close the transport.
    - If `transport` IS provided by the user, the SDK will NOT close it; the user owns it.

    Note:
    - Async transports are generally expected to be used within a single asyncio event loop.
      If your test runner creates multiple event loops (common in pytest-asyncio defaults),
      avoid sharing a single `ConnectionConfig(transport=...)` instance across loops.
    """

    model_config = ConfigDict(arbitrary_types_allowed=True)

    _owns_transport: bool = PrivateAttr(default=True)
    _ssl_context: ssl.SSLContext | None = PrivateAttr(default=None)

    api_key: str | None = Field(
        default=None, description="API key for authentication with sandbox service"
    )
    domain: str | None = Field(
        default=None, description="Base domain for the sandbox management API"
    )
    protocol: str = Field(default="http", description="Protocol to use (http/https)")
    request_timeout: timedelta = Field(
        default=timedelta(seconds=30),
        description="Timeout for HTTP requests to the management API",
    )
    debug: bool = Field(
        default=False, description="Enable debug logging for HTTP requests"
    )
    user_agent: str = Field(
        default="OpenSandbox-Python-SDK/1.2.0", description="User agent string"
    )
    headers: dict[str, str] = Field(
        default_factory=dict, description="User defined headers"
    )
    follow_redirects: bool = Field(
        default=False,
        description=(
            "Whether HTTP clients should follow redirects. Cross-origin redirects strip "
            "headers prefixed OPEN-SANDBOX- or OPENSANDBOX-, but other sensitive custom "
            "headers may still be forwarded."
        ),
    )
    event_hooks: dict[str, list[AsyncEventHook]] = Field(
        default_factory=dict,
        description=(
            "Additional httpx event hooks for SDK-created async clients. SDK security "
            "hooks run after configured request hooks."
        ),
    )
    transport: httpx.AsyncBaseTransport | None = Field(
        default=None,
        description=(
            "Shared httpx transport instance used by all HTTP clients within a "
            "Sandbox/Manager instance. When unset the SDK builds an "
            "AsyncHTTPTransport wrapped by RetryAsyncTransport honoring "
            "`retry_policy`. Pass a custom transport to override the whole "
            "stack (retry wrapping is then the caller's job)."
        ),
    )
    retry_policy: RetryPolicy = Field(
        default_factory=RetryPolicy,
        description=(
            "Retry policy applied to requests going through the shared "
            "transport. Streaming (SSE) requests only get its wake-timeout "
            "retry. Pass RetryPolicy.disabled() for fast-fail."
        ),
    )
    use_server_proxy: bool = Field(
        default=False,
        description=(
            "Using sandbox server as proxy for process execd requests"
            "It's useful when client sdk can't access the created sandbox directly"
        ),
    )
    endpoint_cache_ttl: timedelta = Field(
        default=timedelta(seconds=600),
        description="TTL for cached endpoint entries.",
    )
    endpoint_cache_size: int = Field(
        default=1024,
        description="Maximum number of cached endpoint entries. 0 means default (1024).",
    )
    endpoint_cache_disabled: bool = Field(
        default=False,
        description="Disable endpoint caching entirely.",
    )
    disable_metrics: bool = Field(
        default=False,
        description=(
            "Disable SDK telemetry (sandbox.create latency reports). "
            "Also honored via OPENSANDBOX_DISABLE_METRICS=1."
        ),
    )
    enable_tracing: bool = Field(
        default=False,
        description="Enable OpenTelemetry tracing for SDK operations.",
    )

    # Environment variable names
    _ENV_API_KEY = "OPEN_SANDBOX_API_KEY"
    _ENV_DOMAIN = "OPEN_SANDBOX_DOMAIN"
    _DEFAULT_DOMAIN = "localhost:8080"
    _API_VERSION = "v1"

    def model_post_init(self, __context: object) -> None:
        # If the user explicitly provided `transport`, the SDK must not close it.
        self._owns_transport = "transport" not in self.model_fields_set
        # Best-effort: attach the SDK host's own IP so the server can see the
        # client's self-reported address. Never overrides a user-supplied value
        # and is skipped silently when the IP cannot be determined.
        from opensandbox.config import client_ip

        client_ip.apply_client_ip(self.headers)

    @property
    def owns_transport(self) -> bool:
        """True when this config created (and may close) its transport."""
        return self._owns_transport

    def new_owned_transport(
        self,
        *,
        max_connections: int | None = 100,
        max_keepalive_connections: int = 20,
        keepalive_expiry: float = 30.0,
    ) -> httpx.AsyncBaseTransport:
        """
        Build a fresh transport stack owned by the caller.

        Same stack as `with_transport_if_missing` builds by default; the
        shared `transport` on this config is never touched. Callers that
        close what they build (e.g. adapter clients) can do so safely.
        """
        if self._ssl_context is None:
            self._ssl_context = httpx.create_ssl_context()
        inner = httpx.AsyncHTTPTransport(
            verify=self._ssl_context,
            limits=httpx.Limits(
                max_connections=max_connections,
                max_keepalive_connections=max_keepalive_connections,
                keepalive_expiry=keepalive_expiry,
            ),
        )
        if self.retry_policy.wraps_transport():
            return RetryAsyncTransport(inner, self.retry_policy, owns_inner=True)
        return inner

    def with_transport_if_missing(
        self,
        *,
        max_connections: int | None = 100,
        max_keepalive_connections: int = 20,
        keepalive_expiry: float = 30.0,
    ) -> "ConnectionConfig":
        """
        Ensure a transport exists for this SDK resource.

        When `transport` is missing, return a copy whose `transport` is
        a retry-wrapped AsyncHTTPTransport (unless the policy has no
        wrapper-only knobs, in which case the raw transport is used).
        When `transport` is present, return self unchanged; the caller
        owns retry wrapping.
        """
        if self.transport is not None:
            return self
        config = self.model_copy(
            update={
                "transport": self.new_owned_transport(
                    max_connections=max_connections,
                    max_keepalive_connections=max_keepalive_connections,
                    keepalive_expiry=keepalive_expiry,
                )
            }
        )
        config._owns_transport = True
        return config

    async def close_transport_if_owned(self) -> None:
        """Close the transport only if it was created by default_factory."""
        if self.transport is None or not self._owns_transport:
            return
        try:
            await self.transport.aclose()
        except Exception:
            # Avoid raising during cleanup paths.
            pass

    @field_validator("protocol")
    @classmethod
    def protocol_must_be_valid(cls, v: str) -> str:
        v = v.lower()
        if v not in ("http", "https"):
            raise ValueError("Protocol must be 'http' or 'https'")
        return v

    @field_validator("request_timeout")
    @classmethod
    def timeout_must_be_positive(cls, v: timedelta) -> timedelta:
        if v.total_seconds() <= 0:
            raise ValueError(f"Request timeout must be positive, got: {v}")
        return v

    def get_api_key(self) -> str:
        """
        Get API key from config or environment variable.
        Returns:
            API key string (may be empty if not configured)
        Note: An empty API key may cause authentication failures.
        Consider checking if the key is set before making API calls.
        """
        return self.api_key or os.getenv(self._ENV_API_KEY, "")

    def get_domain(self) -> str:
        """Get domain from config or environment variable."""
        return self.domain or os.getenv(self._ENV_DOMAIN, self._DEFAULT_DOMAIN)

    def get_base_url(self) -> str:
        """Get the full base URL for API requests."""
        # Ignore a trailing "/" or "/v1" like the other SDKs, so the version
        # prefix is never doubled ("//v1", "/v1/v1").
        domain = self.get_domain().rstrip("/")
        version_suffix = f"/{self._API_VERSION}"
        if domain.endswith(version_suffix):
            domain = domain[: -len(version_suffix)]
        # Allow domain to override protocol if it explicitly starts with a scheme
        if domain.startswith("http://") or domain.startswith("https://"):
            return f"{domain}/{self._API_VERSION}"
        return f"{self.protocol}://{domain}/{self._API_VERSION}"