From 8b90e44bf66a72f40f536ee8a3acb9ac8684440c Mon Sep 17 00:00:00 2001 From: Daniel Bluhm Date: Thu, 9 May 2024 22:05:46 -0400 Subject: [PATCH] fix: bugs in various spots Signed-off-by: Daniel Bluhm --- Dockerfile | 24 ++++++++++++++++-------- demo/docker-compose.yaml | 19 ++++++------------- demo/socket_client.py | 3 ++- socketdock/__main__.py | 2 +- socketdock/api.py | 12 ++++++------ socketdock/httpbackend.py | 4 ++-- socketdock/testbackend.py | 12 ++++++++++-- 7 files changed, 43 insertions(+), 33 deletions(-) diff --git a/Dockerfile b/Dockerfile index 8bacdf7..a63a59d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,14 +1,22 @@ -FROM python:3.9-slim-bullseye +FROM python:3.9-slim-bookworm as base WORKDIR /usr/src/app -ENV POETRY_VERSION=1.4.2 - RUN apt-get update && apt-get install -y curl && apt-get clean -RUN pip install "poetry==$POETRY_VERSION" -COPY poetry.lock pyproject.toml README.md ./ -RUN mkdir -p socketdock && touch socketdock/__init__.py -RUN poetry config virtualenvs.create false \ - && poetry install --without=dev --no-interaction --no-ansi +ENV POETRY_VERSION=1.5.1 +ENV POETRY_HOME=/opt/poetry +RUN curl -sSL https://install.python-poetry.org | python - + +ENV PATH="/opt/poetry/bin:$PATH" +RUN poetry config virtualenvs.in-project true + +# Setup project +COPY pyproject.toml poetry.lock ./ +RUN poetry install --without dev + +FROM python:3.9-slim-bookworm +WORKDIR /usr/src/app +COPY --from=base /usr/src/app/.venv /usr/src/app/.venv +ENV PATH="/usr/src/app/.venv/bin:$PATH" COPY socketdock socketdock diff --git a/demo/docker-compose.yaml b/demo/docker-compose.yaml index 557df8c..159d221 100644 --- a/demo/docker-compose.yaml +++ b/demo/docker-compose.yaml @@ -1,7 +1,7 @@ version: '3' services: - websocket-gateway: + socketdock: build: .. ports: - "8765:8765" @@ -9,15 +9,8 @@ services: - ../socketdock:/usr/src/app/socketdock:z command: > --bindip 0.0.0.0 - --backend http - --message-uri ${LAMBDA_ENDPOINT} - --disconnect-uri ${LAMBDA_DISCONNECT_ENDPOINT} - --endpoint ${EXTERNAL_ENDPOINT} - - # Socket Dock Parameters: - # parser.add_argument('--bindip', default='127.0.0.1') - # parser.add_argument('--bindport', default=8765) - # parser.add_argument('--externalhostandport', default="127.0.0.1:8765") - # parser.add_argument('--backend', default="loopback", choices=["loopback", "http"]) - # parser.add_argument('--message_uri') - # parser.add_argument('--disconnect_uri') + --backend loopback + --message-uri https://example.com + --disconnect-uri https://example.com + --endpoint http://socketdock:8765 + --log-level INFO diff --git a/demo/socket_client.py b/demo/socket_client.py index 57cd305..555ffba 100644 --- a/demo/socket_client.py +++ b/demo/socket_client.py @@ -14,4 +14,5 @@ async def hello(): print(f"< {response}", flush=True) -asyncio.run(hello()) +if __name__ == "__main__": + asyncio.run(hello()) diff --git a/socketdock/__main__.py b/socketdock/__main__.py index c8b0a0a..2292670 100644 --- a/socketdock/__main__.py +++ b/socketdock/__main__.py @@ -34,7 +34,7 @@ def main(): if args.backend == "loopback": from .testbackend import TestBackend - backend = TestBackend() + backend = TestBackend(args.endpoint) elif args.backend == "http": from .httpbackend import HTTPBackend diff --git a/socketdock/api.py b/socketdock/api.py index 083f6f6..4bdf6af 100644 --- a/socketdock/api.py +++ b/socketdock/api.py @@ -44,7 +44,7 @@ async def status_handler(request: Request): async def socket_send(request: Request, connectionid: str): """Send a message to a connected socket.""" LOGGER.info("Inbound message for %s", connectionid) - LOGGER.info("Existing connections: %s", active_connections.keys()) + LOGGER.debug("Existing connections: %s", active_connections.keys()) if connectionid not in active_connections: return text("FAIL", status=500) @@ -61,7 +61,7 @@ async def socket_send(request: Request, connectionid: str): async def socket_disconnect(request: Request, connectionid: str): """Disconnect a socket.""" LOGGER.info("Disconnect %s", connectionid) - LOGGER.info("Existing connections: %s", active_connections.keys()) + LOGGER.debug("Existing connections: %s", active_connections.keys()) if connectionid not in active_connections: return text("FAIL", status=500) @@ -80,12 +80,12 @@ async def socket_handler(request: Request, websocket: Websocket): try: # register user LOGGER.info("new client connected") - socket_id = websocket.connection.id.hex + socket_id = websocket.ws_proto.id.hex active_connections[socket_id] = websocket lifetime_connections += 1 - LOGGER.info("Existing connections: %s", active_connections.keys()) - LOGGER.info("Added connection: %s", socket_id) - LOGGER.info("Request headers: %s", dict(request.headers.items())) + LOGGER.debug("Existing connections: %s", active_connections.keys()) + LOGGER.debug("Added connection: %s", socket_id) + LOGGER.debug("Request headers: %s", dict(request.headers.items())) await backend.socket_connected( connection_id=socket_id, diff --git a/socketdock/httpbackend.py b/socketdock/httpbackend.py index c132ce2..6c2e705 100644 --- a/socketdock/httpbackend.py +++ b/socketdock/httpbackend.py @@ -29,11 +29,11 @@ def __init__( def send_callback(self, connection_id: str) -> str: """Return the callback URI for sending a message to a connected socket.""" - return f"{self.socket_base_uri}/{connection_id}/send" + return f"{self.socket_base_uri}/socket/{connection_id}/send" def disconnect_callback(self, connection_id: str) -> str: """Return the callback URI for disconnecting a connected socket.""" - return f"{self.socket_base_uri}/{connection_id}/disconnect" + return f"{self.socket_base_uri}/socket/{connection_id}/disconnect" def callback_uris(self, connection_id: str) -> Dict[str, str]: """Return labelled callback URIs.""" diff --git a/socketdock/testbackend.py b/socketdock/testbackend.py index ed43de3..4b8d3ec 100644 --- a/socketdock/testbackend.py +++ b/socketdock/testbackend.py @@ -1,10 +1,13 @@ """Test backend for SocketDock.""" +import logging from typing import Dict, Union import aiohttp from .backend import Backend +LOGGER = logging.getLogger(__name__) + class TestBackend(Backend): """Test backend for SocketDock.""" @@ -22,6 +25,7 @@ async def socket_connected( This test backend doesn't care, but can be useful to clean up state. """ + LOGGER.debug("Connected to test backend: %s", connection_id) async def inbound_socket_message( self, @@ -29,14 +33,18 @@ async def inbound_socket_message( message: Union[str, bytes], ): """Receive socket message.""" - send_uri = f"{self.base_uri}/{connection_id}/send" + LOGGER.debug("Recieved message [%s]: %s", connection_id, message) + send_uri = f"{self.base_uri}/socket/{connection_id}/send" async with aiohttp.ClientSession() as session: async with session.post(send_uri, data="Hello yourself") as resp: + if not resp.ok: + raise Exception(f"Failed to post to: {send_uri}") response = await resp.text() - print(response) + LOGGER.debug("Response: %s", response) async def socket_disconnected(self, connection_id: str): """Socket disconnected. This test backend doesn't care, but can be useful to clean up state. """ + LOGGER.debug("Disconnected from test backend: %s", connection_id)