From 6b6f20a032eb31d747366c8bc270ca81731eaf6a Mon Sep 17 00:00:00 2001 From: Tom van der Lee Date: Fri, 4 Sep 2026 17:09:24 +0200 Subject: Fixed pre-commit issues --- ttun_server/__init__.py | 19 ++++++++------- ttun_server/endpoints.py | 2 +- ttun_server/redis.py | 4 ++-- ttun_server/types.py | 32 ++++++++++++------------- ttun_server/websockets.py | 60 +++++++++++++++++++++++++---------------------- 5 files changed, 61 insertions(+), 56 deletions(-) (limited to 'ttun_server') diff --git a/ttun_server/__init__.py b/ttun_server/__init__.py index 388dd9e..6e1eabf 100644 --- a/ttun_server/__init__.py +++ b/ttun_server/__init__.py @@ -3,7 +3,7 @@ import os from fastapi import FastAPI from starlette.middleware.authentication import AuthenticationMiddleware -from starlette.routing import Host, Route, WebSocketRoute, Mount +from starlette.routing import Host, Mount, Route, WebSocketRoute from authentication.backend import BearerTokenAuthBackend from authentication.endpoints import authentication, oauth @@ -12,20 +12,20 @@ from proxy import app as proxy_app from ttun_server.endpoints import health from ttun_server.websockets import tunnel -logging.basicConfig(level=getattr(logging, os.environ.get('LOG_LEVEL', 'INFO'))) +logging.basicConfig(level=getattr(logging, os.environ.get("LOG_LEVEL", "INFO"))) app = FastAPI( debug=True, routes=[ - Mount('/management/', app=management), - Mount('/auth/', app=authentication), - Mount('/oauth/', app=oauth), + Mount("/management/", app=management), + Mount("/auth/", app=authentication), + Mount("/oauth/", app=oauth), WebSocketRoute( - '/tunnel/', + "/tunnel/", endpoint=tunnel, ), - Route('/health/', endpoint=health), - Host(f'{{subdomain}}.{os.environ['TUNNEL_DOMAIN']}', app=proxy_app) + Route("/health/", endpoint=health), + Host(f"{{subdomain}}.{os.environ['TUNNEL_DOMAIN']}", app=proxy_app), ], ) @@ -33,6 +33,7 @@ app.add_middleware(AuthenticationMiddleware, backend=BearerTokenAuthBackend()) try: from ._version import version + __version__ = version except ImportError: - __version__ = 'development' + __version__ = "development" diff --git a/ttun_server/endpoints.py b/ttun_server/endpoints.py index 61e3f21..e058009 100644 --- a/ttun_server/endpoints.py +++ b/ttun_server/endpoints.py @@ -1,2 +1,2 @@ async def health(): - return 'OK' + return "OK" diff --git a/ttun_server/redis.py b/ttun_server/redis.py index fb9ff81..dabe940 100644 --- a/ttun_server/redis.py +++ b/ttun_server/redis.py @@ -9,5 +9,5 @@ class RedisConnectionPool: @classmethod def get_connection(cls) -> Redis: if cls._pool is None: - cls._pool = ConnectionPool.from_url(os.environ.get('REDIS_URL')) - return Redis(connection_pool=cls._pool) \ No newline at end of file + cls._pool = ConnectionPool.from_url(os.environ.get("REDIS_URL")) + return Redis(connection_pool=cls._pool) diff --git a/ttun_server/types.py b/ttun_server/types.py index a0c22a3..33095ff 100644 --- a/ttun_server/types.py +++ b/ttun_server/types.py @@ -1,11 +1,11 @@ from asyncio import Queue from enum import Enum -from typing import TypedDict, Optional +from typing import TypedDict class HttpMessageType(Enum): - request = 'request' - response = 'response' + request = "request" + response = "response" class Config(TypedDict): @@ -18,13 +18,13 @@ class HttpRequestData(TypedDict): method: str path: str headers: list[tuple[str, str]] - body: Optional[str] + body: str | None class HttpResponseData(TypedDict): status: int headers: list[tuple[str, str]] - body: Optional[str] + body: str | None class HttpMessage(TypedDict): @@ -34,10 +34,10 @@ class HttpMessage(TypedDict): class WebsocketMessageType(Enum): - connect = 'connect' - disconnect = 'disconnect' - message = 'message' - ack = 'ack' + connect = "connect" + disconnect = "disconnect" + message = "message" + ack = "ack" class WebsocketConnectData(TypedDict): @@ -50,7 +50,7 @@ class WebsocketDisconnectData(TypedDict): class WebsocketMessageData(TypedDict): - body: Optional[str] + body: str | None class WebsocketMessage(TypedDict): @@ -60,13 +60,13 @@ class WebsocketMessage(TypedDict): class MessageType(Enum): - request = 'request' - response = 'response' + request = "request" + response = "response" - ws_connect = 'connect' - ws_disconnect = 'disconnect' - ws_message = 'message' - ws_ack = 'ack' + ws_connect = "connect" + ws_disconnect = "disconnect" + ws_message = "message" + ws_ack = "ack" Message = HttpMessage | WebsocketMessage diff --git a/ttun_server/websockets.py b/ttun_server/websockets.py index 88d6cac..a3cbc5f 100644 --- a/ttun_server/websockets.py +++ b/ttun_server/websockets.py @@ -16,24 +16,25 @@ from ttun_server.types import ( ) logger = logging.getLogger(__name__) -logger.setLevel('DEBUG') +logger.setLevel("DEBUG") + async def assert_compatible_version(websocket: WebSocket, config: Config) -> None: - client_version = config.get('version', '1.0.0') - logger.debug('client_version %s', client_version) + client_version = config.get("version", "1.0.0") + logger.debug("client_version %s", client_version) - if 'git' not in client_version and ttun_server.__version__ != 'development': - [client_major, *_] = [int(i) for i in client_version.split('.')[:3]] - [server_major, *_] = [int(i) for i in ttun_server.__version__.split('.')] + if "git" not in client_version and ttun_server.__version__ != "development": + [client_major, *_] = [int(i) for i in client_version.split(".")[:3]] + [server_major, *_] = [int(i) for i in ttun_server.__version__.split(".")] if client_major < server_major: - await websocket.close(4000, 'Your client is too old') + await websocket.close(4000, "Your client is too old") if client_major > server_major: - await websocket.close(4001, 'Your client is too new') + await websocket.close(4001, "Your client is too new") -@requires(['authenticated', 'token'] if conf.ENABLE_AUTH else []) +@requires(["authenticated", "token"] if conf.ENABLE_AUTH else []) async def tunnel(websocket: WebSocket) -> None: request_tasks: dict[str, asyncio.Task] = {} proxy_queues: dict[str, ProxyQueue] = {} @@ -43,36 +44,39 @@ async def tunnel(websocket: WebSocket) -> None: await assert_compatible_version(websocket, config) - if 'subdomains' not in config: - config['subdomains'] = [config['subdomain']] - elif config['subdomains'] is None: - config['subdomains'] = [None] + if "subdomains" not in config: + config["subdomains"] = [config["subdomain"]] + elif config["subdomains"] is None: + config["subdomains"] = [None] - for i, subdomain in enumerate(config['subdomains']): + for i, subdomain in enumerate(config["subdomains"]): if subdomain is None or await ProxyQueue.has_connection(subdomain): - config['subdomains'][i] = uuid4().hex + config["subdomains"][i] = uuid4().hex - for subdomain in config['subdomains']: + for subdomain in config["subdomains"]: proxy_queues[subdomain] = await ProxyQueue.create_for_identifier(subdomain) - hostname = os.environ.get('TUNNEL_DOMAIN') - protocol = 'https' if os.environ.get('SECURE', False) else 'http' + hostname = os.environ.get("TUNNEL_DOMAIN") + protocol = "https" if os.environ.get("SECURE") else "http" urls = [ - f'{protocol}://{subdomain}.{hostname}' - for subdomain in config['subdomains'] + f"{protocol}://{subdomain}.{hostname}" for subdomain in config["subdomains"] ] - await websocket.send_json({ - 'url': urls[0], - 'urls': urls, - }) + await websocket.send_json( + { + "url": urls[0], + "urls": urls, + } + ) async def handle_requests(subdomain: str) -> None: while request := await proxy_queues[subdomain].dequeue(): - asyncio.create_task(websocket.send_json(request), name=request['identifier']) + asyncio.create_task( + websocket.send_json(request), name=request["identifier"] + ) - for subdomain in config['subdomains']: + for subdomain in config["subdomains"]: request_tasks[subdomain] = asyncio.create_task( handle_requests(subdomain), name=subdomain ) @@ -81,8 +85,8 @@ async def tunnel(websocket: WebSocket) -> None: while True: data: Message = await websocket.receive_json() try: - data['type'] = MessageType(data['type']).value - response_queue = await ProxyQueue.get_for_identifier(data['identifier']) + data["type"] = MessageType(data["type"]).value + response_queue = await ProxyQueue.get_for_identifier(data["identifier"]) await response_queue.enqueue(data) except AssertionError: pass -- cgit v1.3