Skip to content

Commit

Permalink
fix: bugs in various spots
Browse files Browse the repository at this point in the history
Signed-off-by: Daniel Bluhm <[email protected]>
  • Loading branch information
dbluhm committed May 10, 2024
1 parent 883ae6d commit 8b90e44
Show file tree
Hide file tree
Showing 7 changed files with 43 additions and 33 deletions.
24 changes: 16 additions & 8 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -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

Expand Down
19 changes: 6 additions & 13 deletions demo/docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -1,23 +1,16 @@
version: '3'

services:
websocket-gateway:
socketdock:
build: ..
ports:
- "8765:8765"
volumes:
- ../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
3 changes: 2 additions & 1 deletion demo/socket_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@ async def hello():
print(f"< {response}", flush=True)


asyncio.run(hello())
if __name__ == "__main__":
asyncio.run(hello())
2 changes: 1 addition & 1 deletion socketdock/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
12 changes: 6 additions & 6 deletions socketdock/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand All @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions socketdock/httpbackend.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
12 changes: 10 additions & 2 deletions socketdock/testbackend.py
Original file line number Diff line number Diff line change
@@ -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."""
Expand All @@ -22,21 +25,26 @@ 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,
connection_id: str,
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)

0 comments on commit 8b90e44

Please sign in to comment.