diff options
| author | 2026-07-01 21:41:38 +0200 | |
|---|---|---|
| committer | 2026-07-01 21:41:38 +0200 | |
| commit | d8968acab83c7a91b01eee4b35828a2b05c8dd6b (patch) | |
| tree | 461fc01fcbeb8add7562c8fd48f13212a70577d5 | |
| parent | 12f2e24e2154113a6329d74aa556ae23506c34e1 (diff) | |
| download | server-d8968acab83c7a91b01eee4b35828a2b05c8dd6b.tar.gz server-d8968acab83c7a91b01eee4b35828a2b05c8dd6b.tar.bz2 server-d8968acab83c7a91b01eee4b35828a2b05c8dd6b.zip | |
Split each part into its own app
| -rw-r--r-- | proxy/__init__.py | 13 | ||||
| -rw-r--r-- | proxy/endpoints.py | 63 | ||||
| -rw-r--r-- | proxy/utils.py | 7 | ||||
| -rw-r--r-- | proxy/websockets.py | 112 | ||||
| -rw-r--r-- | ttun_server/__init__.py | 23 | ||||
| -rw-r--r-- | ttun_server/endpoints.py | 57 | ||||
| -rw-r--r-- | ttun_server/types.py | 1 | ||||
| -rw-r--r-- | ttun_server/websockets.py | 217 |
8 files changed, 268 insertions, 225 deletions
diff --git a/proxy/__init__.py b/proxy/__init__.py new file mode 100644 index 0000000..fcdb23b --- /dev/null +++ b/proxy/__init__.py | |||
| @@ -0,0 +1,13 @@ | |||
| 1 | from starlette.applications import Starlette | ||
| 2 | from starlette.routing import Route, WebSocketRoute | ||
| 3 | |||
| 4 | from proxy.endpoints import Proxy | ||
| 5 | from proxy.websockets import WebsocketProxy | ||
| 6 | |||
| 7 | app = Starlette( | ||
| 8 | debug=True, | ||
| 9 | routes=[ | ||
| 10 | Route('/{path:path}', Proxy), | ||
| 11 | WebSocketRoute('/{path:path}', WebsocketProxy), | ||
| 12 | ] | ||
| 13 | ) | ||
diff --git a/proxy/endpoints.py b/proxy/endpoints.py new file mode 100644 index 0000000..c287a88 --- /dev/null +++ b/proxy/endpoints.py | |||
| @@ -0,0 +1,63 @@ | |||
| 1 | import logging | ||
| 2 | from base64 import b64encode, b64decode | ||
| 3 | from uuid import uuid4 | ||
| 4 | |||
| 5 | from starlette.endpoints import HTTPEndpoint | ||
| 6 | from starlette.requests import Request | ||
| 7 | from starlette.responses import Response | ||
| 8 | |||
| 9 | from proxy.utils import get_path_with_query_string | ||
| 10 | from ttun_server.proxy_queue import ProxyQueue | ||
| 11 | from ttun_server.types import HttpMessage, HttpMessageType, HttpRequestData | ||
| 12 | |||
| 13 | logger = logging.getLogger(__name__) | ||
| 14 | |||
| 15 | |||
| 16 | class HeaderMapping: | ||
| 17 | def __init__(self, headers: list[tuple[str, str]]): | ||
| 18 | self._headers = headers | ||
| 19 | |||
| 20 | def items(self): | ||
| 21 | for header in self._headers: | ||
| 22 | yield header | ||
| 23 | |||
| 24 | |||
| 25 | class Proxy(HTTPEndpoint): | ||
| 26 | async def dispatch(self) -> None: | ||
| 27 | request = Request(self.scope, self.receive) | ||
| 28 | |||
| 29 | subdomain = request.path_params['subdomain'] | ||
| 30 | response = Response(content='Not Found', status_code=404) | ||
| 31 | |||
| 32 | identifier = str(uuid4()) | ||
| 33 | response_queue = await ProxyQueue.create_for_identifier(identifier) | ||
| 34 | |||
| 35 | try: | ||
| 36 | request_queue = await ProxyQueue.get_for_identifier(subdomain) | ||
| 37 | |||
| 38 | logger.debug('PROXY %s%s ', subdomain, request.url) | ||
| 39 | await request_queue.enqueue( | ||
| 40 | HttpMessage( | ||
| 41 | type=HttpMessageType.request.value, | ||
| 42 | identifier=identifier, | ||
| 43 | payload=HttpRequestData( | ||
| 44 | method=request.method, | ||
| 45 | path=get_path_with_query_string(request), | ||
| 46 | headers=list(request.headers.items()), | ||
| 47 | body=b64encode(await request.body()).decode() | ||
| 48 | ) | ||
| 49 | ) | ||
| 50 | ) | ||
| 51 | |||
| 52 | _response = await response_queue.dequeue() | ||
| 53 | payload = _response['payload'] | ||
| 54 | response = Response( | ||
| 55 | status_code=payload['status'], | ||
| 56 | headers=HeaderMapping(payload['headers']), | ||
| 57 | content=b64decode(payload['body'].encode()) | ||
| 58 | ) | ||
| 59 | except AssertionError: | ||
| 60 | pass | ||
| 61 | finally: | ||
| 62 | await response(self.scope, self.receive, self.send) | ||
| 63 | await response_queue.delete() | ||
diff --git a/proxy/utils.py b/proxy/utils.py new file mode 100644 index 0000000..2b80f43 --- /dev/null +++ b/proxy/utils.py | |||
| @@ -0,0 +1,7 @@ | |||
| 1 | from starlette.requests import HTTPConnection | ||
| 2 | |||
| 3 | |||
| 4 | def get_path_with_query_string(connection: HTTPConnection) -> str: | ||
| 5 | path = connection.url.path | ||
| 6 | query_string = '?' + connection.scope['query_string'].decode() if connection.scope['query_string'] else '' | ||
| 7 | return f"{path}{query_string}" | ||
diff --git a/proxy/websockets.py b/proxy/websockets.py new file mode 100644 index 0000000..ef80ec2 --- /dev/null +++ b/proxy/websockets.py | |||
| @@ -0,0 +1,112 @@ | |||
| 1 | import asyncio | ||
| 2 | import json | ||
| 3 | import logging | ||
| 4 | import typing | ||
| 5 | from base64 import b64decode, b64encode | ||
| 6 | from contextlib import asynccontextmanager | ||
| 7 | from uuid import uuid4 | ||
| 8 | |||
| 9 | from starlette.endpoints import WebSocketEndpoint | ||
| 10 | from starlette.websockets import WebSocket | ||
| 11 | |||
| 12 | from proxy.utils import get_path_with_query_string | ||
| 13 | from ttun_server.proxy_queue import ProxyQueue | ||
| 14 | from ttun_server.types import WebsocketMessage, WebsocketMessageType, WebsocketConnectData, WebsocketMessageData, \ | ||
| 15 | WebsocketDisconnectData | ||
| 16 | |||
| 17 | logger = logging.getLogger(__name__) | ||
| 18 | logger.setLevel('DEBUG') | ||
| 19 | |||
| 20 | |||
| 21 | class WebsocketProxy(WebSocketEndpoint): | ||
| 22 | encoding = 'json' | ||
| 23 | websocket_listen_task = None | ||
| 24 | |||
| 25 | def __init__(self, *args, **kwargs): | ||
| 26 | super().__init__(*args, **kwargs) | ||
| 27 | self.id = str(uuid4()) | ||
| 28 | |||
| 29 | @asynccontextmanager | ||
| 30 | async def proxy(self, websocket: WebSocket, message: WebsocketMessage): | ||
| 31 | [subdomain, *_] = websocket.url.hostname.split('.') | ||
| 32 | |||
| 33 | expect_ack = WebsocketMessageType(message['type']) == WebsocketMessageType.connect | ||
| 34 | |||
| 35 | try: | ||
| 36 | request_queue = await ProxyQueue.get_for_identifier(subdomain) | ||
| 37 | await request_queue.enqueue(message) | ||
| 38 | |||
| 39 | if expect_ack: | ||
| 40 | response_queue = await ProxyQueue.create_for_identifier(message["identifier"]) | ||
| 41 | yield await response_queue.dequeue() | ||
| 42 | await response_queue.delete() | ||
| 43 | else: | ||
| 44 | yield | ||
| 45 | except AssertionError: | ||
| 46 | yield None | ||
| 47 | |||
| 48 | async def listen_for_messages(self, websocket: WebSocket): | ||
| 49 | response_queue = await ProxyQueue.create_for_identifier(self.id) | ||
| 50 | |||
| 51 | while True: | ||
| 52 | message: WebsocketMessage = await response_queue.dequeue() | ||
| 53 | logger.debug(message) | ||
| 54 | await websocket.send_text(b64decode(message['payload']['body'].encode()).decode()) | ||
| 55 | |||
| 56 | async def on_connect(self, websocket: WebSocket) -> None: | ||
| 57 | message = WebsocketMessage( | ||
| 58 | type=WebsocketMessageType.connect.value, | ||
| 59 | identifier=self.id, | ||
| 60 | payload=WebsocketConnectData( | ||
| 61 | path=get_path_with_query_string(websocket), | ||
| 62 | headers=[ | ||
| 63 | (k.decode(), v.decode()) | ||
| 64 | for k, v | ||
| 65 | in websocket.scope['headers'] | ||
| 66 | ], | ||
| 67 | ) | ||
| 68 | ) | ||
| 69 | |||
| 70 | async with self.proxy(websocket, message) as m: | ||
| 71 | if m is not None and WebsocketMessageType(m['type']) == WebsocketMessageType.ack: | ||
| 72 | await super().on_connect(websocket) | ||
| 73 | |||
| 74 | self.websocket_listen_task = asyncio.create_task(self.listen_for_messages(websocket)) | ||
| 75 | |||
| 76 | def callback(*args, **kwargs): | ||
| 77 | self.websocket_listen_task = None | ||
| 78 | |||
| 79 | self.websocket_listen_task.add_done_callback(callback) | ||
| 80 | |||
| 81 | async def on_receive(self, websocket: WebSocket, data: typing.Any) -> None: | ||
| 82 | match data: | ||
| 83 | case dict(): | ||
| 84 | data_bytes = json.dumps(data).encode() | ||
| 85 | case bytes(): | ||
| 86 | data_bytes = data | ||
| 87 | case _: | ||
| 88 | data_bytes = data.encode() | ||
| 89 | |||
| 90 | message = WebsocketMessage( | ||
| 91 | type=WebsocketMessageType.message.value, | ||
| 92 | identifier=self.id, | ||
| 93 | payload=WebsocketMessageData( | ||
| 94 | body=b64encode(data_bytes).decode(), | ||
| 95 | ) | ||
| 96 | ) | ||
| 97 | |||
| 98 | async with self.proxy(websocket, message): | ||
| 99 | pass | ||
| 100 | |||
| 101 | async def on_disconnect(self, websocket: WebSocket, close_code: int) -> None: | ||
| 102 | message = WebsocketMessage( | ||
| 103 | type=WebsocketMessageType.disconnect.value, | ||
| 104 | identifier=self.id, | ||
| 105 | payload=WebsocketDisconnectData( | ||
| 106 | close_code=close_code, | ||
| 107 | ) | ||
| 108 | ) | ||
| 109 | |||
| 110 | async with self.proxy(websocket, message): | ||
| 111 | if self.websocket_listen_task is not None: | ||
| 112 | self.websocket_listen_task.cancel() | ||
diff --git a/ttun_server/__init__.py b/ttun_server/__init__.py index 6c77858..d54227a 100644 --- a/ttun_server/__init__.py +++ b/ttun_server/__init__.py | |||
| @@ -2,30 +2,23 @@ import logging | |||
| 2 | import os | 2 | import os |
| 3 | 3 | ||
| 4 | from fastapi import FastAPI | 4 | from fastapi import FastAPI |
| 5 | from starlette.routing import Host, Route, Router, WebSocketRoute | 5 | from starlette.routing import Host, Route, WebSocketRoute |
| 6 | 6 | ||
| 7 | from ttun_server.endpoints import health, proxy | 7 | from proxy import app as proxy_app |
| 8 | from .websockets import WebsocketProxy, Tunnel | 8 | from ttun_server.endpoints import health, base_endpoints |
| 9 | from ttun_server.websockets import tunnel | ||
| 9 | 10 | ||
| 10 | logging.basicConfig(level=getattr(logging, os.environ.get('LOG_LEVEL', 'INFO'))) | 11 | logging.basicConfig(level=getattr(logging, os.environ.get('LOG_LEVEL', 'INFO'))) |
| 11 | 12 | ||
| 12 | base_router = Router(routes=[ | 13 | app = FastAPI( |
| 13 | Route('/health/', health), | ||
| 14 | WebSocketRoute('/tunnel/', Tunnel) | ||
| 15 | ]) | ||
| 16 | |||
| 17 | server = FastAPI( | ||
| 18 | debug=True, | 14 | debug=True, |
| 19 | routes=[ | 15 | routes=[ |
| 20 | Host(os.environ['TUNNEL_DOMAIN'], base_router, 'base'), | 16 | |
