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
20 changes: 19 additions & 1 deletion koyeb/sandbox/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

import os
import secrets
import string
import time
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Dict, List, Optional
Expand Down Expand Up @@ -353,6 +354,23 @@ def create_deployment_definition(
)


_BASE36 = string.digits + string.ascii_lowercase


def _app_name_suffix() -> str:
"""Base-36 seconds plus 4 random characters.

App names are unique per organization, so two same-name creates in the
same second must still differ. Until 2038 it is 10 characters, like the
decimal seconds it replaced, so every name that fit the 64-character app
name limit still fits."""
seconds, digits = int(time.time()), ""
while seconds:
seconds, digit = divmod(seconds, 36)
digits = _BASE36[digit] + digits
return digits + "".join(secrets.choice(_BASE36) for _ in range(4))


@dataclass
class SandboxSpec:
"""The single definition of a sandbox deployment.
Expand Down Expand Up @@ -413,7 +431,7 @@ def apply_sandbox_secret(self, sandbox_secret: Optional[str] = None) -> str:
def app_payload(self) -> Dict[str, Any]:
"""CreateApp payload for the app a create call owns."""
return {
"name": f"sandbox-app-{self.name}-{int(time.time())}",
"name": f"sandbox-app-{self.name}-{_app_name_suffix()}",
"life_cycle": {"delete_when_empty": True},
}

Expand Down
13 changes: 13 additions & 0 deletions koyeb/sandbox/test_spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
consumed by every create flow (sync and async, Sandbox and ServicePool)."""

import unittest
from unittest import mock

from koyeb.api.models.deployment_definition_type import DeploymentDefinitionType
from koyeb.api.models.deployment_mesh import DeploymentMesh
Expand Down Expand Up @@ -82,6 +83,18 @@ def test_app_payload_coerces_into_both_model_flavors(self):
self.assertTrue(app.life_cycle.delete_when_empty)
self.assertTrue(async_app.life_cycle.delete_when_empty)

def test_app_name_differs_for_same_name_creates_in_the_same_second(self):
# the longest name that fit with the 10-digit seconds suffix
spec = _spec(name="n" * 41)

with mock.patch("koyeb.sandbox.spec.time.time", return_value=1_794_916_800.0):
names = {spec.app_payload()["name"] for _ in range(20)}

self.assertEqual(len(names), 20)
for name in names:
self.assertLessEqual(len(name), 64)
self.assertRegex(name, r"^[a-z0-9]+([.-][a-z0-9]+)*$")

def test_full_snapshot_omits_definition(self):
payload = _spec(
snapshot_id="snap-1", snapshot_type=SnapshotType.FULL
Expand Down
Loading