@@ -0,0 +1,67 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Request, WebSocket
|
||||
from starlette.responses import Response
|
||||
|
||||
from devplacepy.services.containers import activity, api, forward, store
|
||||
from devplacepy.services.containers.workspace import naming, tunnels
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter()
|
||||
|
||||
METHODS = forward.METHODS
|
||||
|
||||
|
||||
def resolve(host: str):
|
||||
if not naming.is_tunnel_host(host):
|
||||
return None, None, None, None
|
||||
row = tunnels.by_hostname(host)
|
||||
if not row or row.get("status") not in tunnels.SERVING_STATUSES:
|
||||
return None, None, None, None
|
||||
instance = store.get_instance(row.get("instance_uid", ""))
|
||||
if not instance or instance.get("deleted_at"):
|
||||
return None, None, None, None
|
||||
if instance.get("suspended_at"):
|
||||
return row, instance, None, None
|
||||
if instance.get("status") != store.ST_RUNNING:
|
||||
return row, instance, None, None
|
||||
gateway, _ = api.proxy_target(instance)
|
||||
host_port = _published_host_port(instance, int(row.get("container_port") or 0))
|
||||
return row, instance, gateway, host_port
|
||||
|
||||
|
||||
def _published_host_port(instance: dict, container_port: int) -> int:
|
||||
import json
|
||||
|
||||
for mapping in json.loads(instance.get("ports_json") or "[]"):
|
||||
if int(mapping.get("container") or 0) == container_port:
|
||||
return int(mapping.get("host") or 0)
|
||||
return 0
|
||||
|
||||
|
||||
async def handle_http(request: Request, path: str) -> Response:
|
||||
host = request.headers.get("host", "")
|
||||
row, instance, gateway, port = resolve(host)
|
||||
if row is None:
|
||||
return Response("no tunnel is published at this address", status_code=404)
|
||||
if instance is not None and instance.get("suspended_at"):
|
||||
return Response("this workspace is suspended", status_code=403)
|
||||
if not gateway or not port:
|
||||
return Response("the tunnel has no reachable port", status_code=502)
|
||||
response = await forward.proxy_http(request, gateway, port, path)
|
||||
size = len(response.body) if hasattr(response, "body") and response.body else 0
|
||||
activity.touch(instance["uid"], egress_bytes=size)
|
||||
tunnels.record_hit(row["uid"], size)
|
||||
return response
|
||||
|
||||
|
||||
async def handle_ws(websocket: WebSocket, path: str) -> None:
|
||||
host = websocket.headers.get("host", "")
|
||||
row, instance, gateway, port = resolve(host)
|
||||
if row is None or instance is None or not gateway or not port:
|
||||
await websocket.close(code=1011)
|
||||
return
|
||||
activity.touch(instance["uid"])
|
||||
await forward.proxy_ws(websocket, gateway, port, path)
|
||||
Reference in New Issue
Block a user