"""Where a frontend is reachable from outside, as seen by one request.""" from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from starlette.requests import Request from beaver_gateway.frontends.base import Frontend, GatewayRuntime def request_origin(request: Request, runtime: GatewayRuntime) -> str: """``Gateway.public_url`` if configured, else the request's own origin.""" if runtime.public_url: return runtime.public_url host = request.headers.get("host") if not host: return f"http://{request.url.hostname}:{request.url.port}" scheme = request.headers.get("x-forwarded-proto") or request.url.scheme return f"{scheme}://{host}" def external_base(request: Request, runtime: GatewayRuntime) -> str: """Origin plus the mount path of the app handling ``request``.""" return request_origin(request, runtime) + str(request.scope.get("root_path", "")) def frontend_url(request: Request, runtime: GatewayRuntime, fe: Frontend) -> str | None: return request_origin(request, runtime) + fe.path if fe.path else None