droboticflow/scripts/lib/droboticflow_env.py
eust-w de98a46e6e
Some checks are pending
CI / verify (push) Waiting to run
CI / docker-build (push) Waiting to run
🛡️ Validate service endpoint URLs
2026-06-17 03:27:03 +08:00

63 lines
1.8 KiB
Python

from __future__ import annotations
import os
from collections.abc import Mapping, Sequence
from urllib.parse import urlparse
DEFAULT_API_BASE_URL = "http://127.0.0.1:3001"
DEFAULT_WORKER_BASE_URL = "http://127.0.0.1:3002"
def trim_trailing_slash(value: str | None) -> str:
return str(value or "").strip().rstrip("/")
def normalize_http_service_url(value: str | None, *, label: str = "service URL") -> str:
raw = str(value or "").strip()
if not raw:
return ""
normalized = trim_trailing_slash(raw)
if not normalized:
raise ValueError(f"{label} must be an absolute http(s) URL")
parsed = urlparse(normalized)
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
raise ValueError(f"{label} must be an absolute http(s) URL: {raw}")
return normalized
def first_non_empty(*values: str | None) -> str:
for value in values:
normalized = trim_trailing_slash(value)
if normalized:
return normalized
return ""
def first_service_url(*values: str | None) -> str:
for value in values:
normalized = normalize_http_service_url(value)
if normalized:
return normalized
return ""
def service_url_from_env(
names: Sequence[str],
*,
environ: Mapping[str, str] | None = None,
fallback: str = "",
) -> str:
source = environ if environ is not None else os.environ
return first_service_url(*(source.get(name, "") for name in names), fallback)
def api_base_url_from_env(
*,
environ: Mapping[str, str] | None = None,
include_base_url: bool = True,
fallback: str = DEFAULT_API_BASE_URL,
) -> str:
names = ("BASE_URL", "API_BASE_URL") if include_base_url else ("API_BASE_URL",)
return service_url_from_env(names, environ=environ, fallback=fallback)