forked from mtusi2026/mtusi2026lab3
70 lines
2.8 KiB
Python
70 lines
2.8 KiB
Python
# #in_memory
|
|
# from src.models.users import UsersRepository
|
|
# from src.models.chats import ChatsRepository
|
|
# from src.models.messages import MessagesRepository
|
|
# import asyncio
|
|
# import uuid
|
|
# from src.pydantic_valid.user import User
|
|
# from src.pydantic_valid.chat import Chat
|
|
# from src.pydantic_valid.message import Message
|
|
|
|
|
|
# class Repository():
|
|
# def __init__(self):
|
|
# self.users = UsersRepository()
|
|
# self.chats = ChatsRepository()
|
|
# self.messages = MessagesRepository()
|
|
# self.username_index = UsernameIndexRepository()
|
|
# #self._lock = asyncio.Lock() #pessimistic locking против race condition
|
|
# self._user_lock = asyncio.Lock()
|
|
# self._chats_locks_guard = asyncio.Lock()
|
|
# self._chat_locks : dict[str, asyncio.Lock] = {}
|
|
|
|
|
|
# async def insert_user(self, user: User) -> bool:
|
|
# key = user.username.lower()
|
|
# async with self._user_lock: #избегания создания дубликатов данных юзера в self.users под разными индексами | в username_index 1 запись на все данные в то же время
|
|
# if key in self.username_index.username_index_db:
|
|
# return False
|
|
# self.username_index.username_index_db[key] = user.id
|
|
# self.users.users_db[user.id] = user
|
|
# return True
|
|
|
|
|
|
# async def get_user(self, uid: uuid.UUID) -> User:
|
|
# user_data = self.users.users_db.get(str(uid))
|
|
# if user_data:
|
|
# return user_data #"id": str(uid), for User model response else UserOut model
|
|
# return None
|
|
|
|
|
|
# async def _get_chat_lock(self, chat_id: str) -> asyncio.Lock:
|
|
# async with self._chats_locks_guard:
|
|
# if chat_id not in self._chat_locks:
|
|
# self._chat_locks[chat_id] = asyncio.Lock()
|
|
# return self._chat_locks[chat_id]
|
|
|
|
|
|
# async def create_chat(self, chat_data: Chat) -> bool:
|
|
# chat_id = chat_data.id
|
|
# lock = await self._get_chat_lock(chat_id)
|
|
# async with lock:
|
|
# if chat_id in self.chats.chats_db:
|
|
# return False
|
|
# else:
|
|
# self.chats.chats_db[chat_id] = chat_data.model_dump()
|
|
# self.messages.message_db[chat_id] = []
|
|
# return True
|
|
|
|
|
|
# async def create_message(self, message_data: Message) -> bool:
|
|
# chat_id = message_data.chat_id
|
|
# lock = await self._get_chat_lock(chat_id)
|
|
# async with lock:
|
|
# if chat_id in self.messages.message_db:
|
|
# # self.messages.message_db[chat_id].append(message_data.model_dump())
|
|
# await self.messages.append_message(chat_id, message_data.model_dump())
|
|
# return True
|
|
# else:
|
|
# return False
|
|
|