Skip to content
This repository has been archived by the owner on Apr 29, 2024. It is now read-only.

Commit

Permalink
Added logging (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
spietras authored May 20, 2022
1 parent e81d29b commit c959843
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 1 deletion.
30 changes: 30 additions & 0 deletions theatre/src/theatre/log.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import logging
from logging.config import dictConfig

from pydantic import BaseModel


class LogConfig(BaseModel):
version = 1
disable_existing_loggers = False
formatters = {
"default": {
"()": "uvicorn.logging.DefaultFormatter",
"fmt": "%(levelprefix)s | %(asctime)s | %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S",
},
}
handlers = {
"default": {
"formatter": "default",
"class": "logging.StreamHandler",
"stream": "ext://sys.stderr",
},
}
loggers = {
"theatre": {"handlers": ["default"], "level": "DEBUG"},
}


dictConfig(LogConfig().dict())
logger = logging.getLogger("theatre")
3 changes: 3 additions & 0 deletions theatre/src/theatre/models/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ class Session(FrozenModel):
class Emoji(FrozenModel):
id: str

def __str__(self) -> str:
return chr(int(self.id, 16))


class CodeEntry(FrozenModel):
emoji: Emoji
Expand Down
28 changes: 28 additions & 0 deletions theatre/src/theatre/server/room.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import logging
import random
import uuid
from asyncio import AbstractEventLoop
from dataclasses import dataclass
from typing import Dict, Optional, Set, Union

from pydantic import ValidationError
from pyee.asyncio import AsyncIOEventEmitter

from theatre.constants import AVAILABLE_AVATAR_EMOJI_IDS
from theatre.log import logger
from theatre.models.data import (
Avatar,
Code,
Emoji,
IncomingUserMessage,
OutgoingServerMessage,
Expand All @@ -23,16 +27,32 @@ class NotEnoughResourcesError(Exception):
pass


class RoomLoggerAdapter(logging.LoggerAdapter):
def __init__(self, base_logger, code: Code) -> None:
super().__init__(base_logger, {})
self.code = code

def process(self, msg, kwargs):
prefix = " ".join([str(entry.emoji) for entry in self.code.entries])
return f"[ {prefix} ] {msg}", kwargs


@dataclass
class UserInfo:
data: User
connection: Connection


class Room(AsyncIOEventEmitter):
_code: Code
_users: Dict[str, UserInfo] = {}
_connected_users: Set[str] = set()

def __init__(self, code: Code, loop: Optional[AbstractEventLoop] = None):
super().__init__(loop)
self._code = code
self._logger = RoomLoggerAdapter(logger, code=code)

@property
def users(self) -> Set[User]:
users = set()
Expand Down Expand Up @@ -102,6 +122,8 @@ def handle_connect(self, user_id: str) -> None:
self.broadcast(user_id, data)

def add(self, connection: Connection) -> User:
self._logger.info("New connection.")

user = self.create_user()

def cleanup() -> None:
Expand All @@ -112,23 +134,29 @@ def cleanup() -> None:

async def timeout() -> None:
if user.id not in self._connected_users:
self._logger.info(
f"User {user.avatar.emoji} didn't connect on time."
)
cleanup()

timer = Timer(60, timeout)

@connection.on("connected")
def on_connected() -> None:
self._logger.info(f"User {user.avatar.emoji} connected.")
timer.cancel()
self._connected_users.add(user.id)
self.handle_connect(user.id)

@connection.on("disconnected")
def on_disconnected() -> None:
self._logger.info(f"User {user.avatar.emoji} disconnected.")
self.handle_disconnect(user.id)
cleanup()

@connection.on("data")
def on_data(message: Union[bytes, str]) -> None:
self._logger.info(f"User {user.avatar.emoji} sent message.")
self.handle_data(user.id, message)

self._users[user.id] = UserInfo(data=user, connection=connection)
Expand Down
5 changes: 4 additions & 1 deletion theatre/src/theatre/server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ class InternalCode(FrozenModel):
def new(cls, code: Code) -> "InternalCode":
return cls(entries=tuple(code.entries))

def code(self) -> Code:
return Code(entries=list(self.entries))


class Server:
rooms: Dict[InternalCode, Room] = {}
Expand All @@ -22,7 +25,7 @@ async def cleanup(self) -> None:
await room.close()

def create_room(self, code: InternalCode) -> Room:
room = Room()
room = Room(code.code())

async def close() -> None:
await room.close()
Expand Down

0 comments on commit c959843

Please sign in to comment.