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
1 change: 0 additions & 1 deletion koyeb/api/docs/SandboxMetadata.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**public_url** | **str** | | [optional]
**routing_key** | **str** | | [optional]
**internal_url** | **str** | In-cluster url of the sandbox gateway, for clients running in the same k8s cluster | [optional]

## Example

Expand Down
9 changes: 2 additions & 7 deletions koyeb/api/models/sandbox_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@ class SandboxMetadata(BaseModel):

public_url: Optional[StrictStr] = None
routing_key: Optional[StrictStr] = None
internal_url: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["public_url", "routing_key", "internal_url"]
__properties: ClassVar[List[str]] = ["public_url", "routing_key"]

model_config = ConfigDict(
validate_by_name=True,
Expand Down Expand Up @@ -83,10 +82,6 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
return cls.model_validate(obj)

_obj = cls.model_validate(
{
"public_url": obj.get("public_url"),
"routing_key": obj.get("routing_key"),
"internal_url": obj.get("internal_url"),
}
{"public_url": obj.get("public_url"), "routing_key": obj.get("routing_key")}
)
return _obj
1 change: 0 additions & 1 deletion koyeb/api_async/docs/SandboxMetadata.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**public_url** | **str** | | [optional]
**routing_key** | **str** | | [optional]
**internal_url** | **str** | In-cluster url of the sandbox gateway, for clients running in the same k8s cluster | [optional]

## Example

Expand Down
9 changes: 2 additions & 7 deletions koyeb/api_async/models/sandbox_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@ class SandboxMetadata(BaseModel):

public_url: Optional[StrictStr] = None
routing_key: Optional[StrictStr] = None
internal_url: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["public_url", "routing_key", "internal_url"]
__properties: ClassVar[List[str]] = ["public_url", "routing_key"]

model_config = ConfigDict(
validate_by_name=True,
Expand Down Expand Up @@ -83,10 +82,6 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
return cls.model_validate(obj)

_obj = cls.model_validate(
{
"public_url": obj.get("public_url"),
"routing_key": obj.get("routing_key"),
"internal_url": obj.get("internal_url"),
}
{"public_url": obj.get("public_url"), "routing_key": obj.get("routing_key")}
)
return _obj
40 changes: 1 addition & 39 deletions koyeb/sandbox/control_plane.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,8 @@

from __future__ import annotations

import functools
import os
import socket
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urlparse

from koyeb.api.exceptions import ApiException, NotFoundException
from koyeb.api.models.create_app import CreateApp
Expand Down Expand Up @@ -74,40 +70,6 @@ class DeploymentInfo:
proxy_ports: List[Dict[str, Any]]


SANDBOX_URL_ENV = "KOYEB_SANDBOX_URL"


@functools.lru_cache(maxsize=None)
def _resolves(host: str) -> bool:
try:
socket.getaddrinfo(host, None)
return True
except (socket.gaierror, UnicodeError):
return False


def select_sandbox_url(sandbox_metadata: Any) -> Optional[str]:
"""Pick which sandbox gateway URL to call.

The API returns a public URL and, on self-hosted clusters, an in-cluster
one. The in-cluster URL is used when its host resolves (we run inside the
cluster); KOYEB_SANDBOX_URL=internal|public forces the choice.
"""
public_url = getattr(sandbox_metadata, "public_url", None)
internal_url = getattr(sandbox_metadata, "internal_url", None)
if not internal_url:
return public_url
mode = os.getenv(SANDBOX_URL_ENV, "").strip().lower()
if mode == "public":
return public_url
if mode == "internal" or not public_url:
return internal_url
host = urlparse(internal_url).hostname
if host and _resolves(host):
return internal_url
return public_url


def _deployment_info(deployment: Any) -> DeploymentInfo:
"""Model-flavor-agnostic conversion shared by both adapters."""
definition = deployment.definition
Expand All @@ -121,7 +83,7 @@ def _deployment_info(deployment: Any) -> DeploymentInfo:
metadata = getattr(deployment, "metadata", None)
if metadata is not None:
if metadata.sandbox is not None:
sandbox_url = select_sandbox_url(metadata.sandbox)
sandbox_url = metadata.sandbox.public_url
routing_key = metadata.sandbox.routing_key
for port in metadata.proxy_ports or []:
proxy_ports.append(
Expand Down
19 changes: 4 additions & 15 deletions koyeb/sandbox/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
DeploymentInfo,
ServiceInfo,
SyncControlPlane,
select_sandbox_url,
)
from .spec import SandboxSpec
from .clients import (
Expand Down Expand Up @@ -979,14 +978,9 @@ def delete(self) -> None:
# Caller-provided app: deleting it would destroy unrelated services.
cp.delete_service(self.service_id)

def _get_url_and_header_from_metadata(
self, prefer_internal: bool = True
) -> Optional[Tuple[str, str]]:
def _get_url_and_header_from_metadata(self) -> Optional[Tuple[str, str]]:
"""
Get the url of the sandbox and the routing key to use to reach it.

With prefer_internal=False, always returns the public URL: for URLs
handed to users, which must work from outside the cluster.
Get the public url of the sandbox and the routing key to use to reach it.
"""
try:
from koyeb.api.exceptions import ApiException
Expand All @@ -1001,12 +995,7 @@ def _get_url_and_header_from_metadata(
deployment = clients.deployments.get_deployment(deployment_id)
metadata = deployment.deployment.metadata
if metadata and metadata.sandbox:
url = (
select_sandbox_url(metadata.sandbox)
if prefer_internal
else metadata.sandbox.public_url
)
return url, metadata.sandbox.routing_key
return metadata.sandbox.public_url, metadata.sandbox.routing_key
return None

except (NotFoundException, ApiException, Exception):
Expand Down Expand Up @@ -1050,7 +1039,7 @@ def _get_url(self) -> Optional[str]:
Optional[str]: The full URL or None if unavailable
"""
if self._url is None:
url_data = self._get_url_and_header_from_metadata(prefer_internal=False)
url_data = self._get_url_and_header_from_metadata()
if url_data:
self._url = f"{url_data[0]}/r/{url_data[1]}/"
return self._url
Expand Down
48 changes: 0 additions & 48 deletions koyeb/sandbox/test_control_plane.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@
error mapping exactly where the orchestration contract demands it."""

import asyncio
import os
import unittest
from unittest import mock
from types import SimpleNamespace

from koyeb.api.exceptions import ApiException, NotFoundException
Expand All @@ -17,8 +15,6 @@
DeploymentInfo,
ServiceInfo,
SyncControlPlane,
_deployment_info,
select_sandbox_url,
)
from koyeb.sandbox.errors import SandboxError

Expand Down Expand Up @@ -294,49 +290,5 @@ async def update_service(id, service):
self.assertIsNotNone(sent[0].definition)


class TestSelectSandboxUrl(unittest.TestCase):
PUBLIC = "https://sandboxes.example.com"
INTERNAL = "http://sandbox-gateway.koyeb.svc.cluster.local"

def _meta(self, internal=INTERNAL):
return SimpleNamespace(public_url=self.PUBLIC, internal_url=internal)

def _select(self, meta, resolves, extra_env=None):
env = {k: v for k, v in os.environ.items() if k != "KOYEB_SANDBOX_URL"}
env.update(extra_env or {})
with mock.patch.dict(os.environ, env, clear=True), mock.patch(
"koyeb.sandbox.control_plane._resolves", return_value=resolves
):
return select_sandbox_url(meta)

def test_no_internal_url_uses_public(self):
self.assertEqual(self._select(self._meta(internal=None), True), self.PUBLIC)

def test_old_model_without_field_uses_public(self):
meta = SimpleNamespace(public_url=self.PUBLIC)
self.assertEqual(self._select(meta, True), self.PUBLIC)

def test_in_cluster_uses_internal(self):
self.assertEqual(self._select(self._meta(), True), self.INTERNAL)

def test_outside_cluster_uses_public(self):
self.assertEqual(self._select(self._meta(), False), self.PUBLIC)

def test_env_forces_public(self):
env = {"KOYEB_SANDBOX_URL": "public"}
self.assertEqual(self._select(self._meta(), True, env), self.PUBLIC)

def test_env_forces_internal(self):
env = {"KOYEB_SANDBOX_URL": "internal"}
self.assertEqual(self._select(self._meta(), False, env), self.INTERNAL)

def test_deployment_info_uses_selected_url(self):
deployment = _fake_deployment()
deployment.metadata.sandbox.internal_url = self.INTERNAL
with mock.patch("koyeb.sandbox.control_plane._resolves", return_value=True):
info = _deployment_info(deployment)
self.assertEqual(info.sandbox_url, self.INTERNAL)


if __name__ == "__main__":
unittest.main()
54 changes: 0 additions & 54 deletions koyeb/sandbox/test_sandbox_url_choice.py

This file was deleted.

4 changes: 0 additions & 4 deletions spec/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -19836,10 +19836,6 @@
},
"routing_key": {
"type": "string"
},
"internal_url": {
"type": "string",
"title": "In-cluster url of the sandbox gateway, for clients running in the same k8s cluster"
}
}
},
Expand Down
Loading