feat-(move2lab2, postgres settings, repo base and other)

This commit is contained in:
2026-11-03 04:24:22 +03:00
parent 65003b6119
commit 273519109e
34 changed files with 1396 additions and 0 deletions
View File
+45
View File
@@ -0,0 +1,45 @@
from datetime import datetime, timezone
from fastapi import Request, HTTPException, Depends
from fastapi.responses import JSONResponse
from typing import Annotated
from sqlalchemy.ext.asyncio import AsyncSession
from src.database import get_db
import uuid
def get_now_iso():
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def get_current_user(request:Request) -> str:
path = request.url.path
method = request.method
if path in ["/health/ready", "/health/live"]:
return None
if path == "/api/v1/users" and method == "POST":
return None
user_id = request.headers.get("X-User-Id")
if not user_id:
raise HTTPException(status_code=401, detail="missing X-User-Id")
try:
user_id = uuid.UUID(user_id)
except ValueError:
raise HTTPException(status_code=401, detail="non-valid X-User-Id")
return str(user_id) ##repo.users.user_db.get(user_id)
def generate_id() -> str:
return str(uuid.uuid4())
def create_error_response(message: str, code: str, status_code: int, request_id: str) -> JSONResponse:
body = {"error": {"code": code, "message": message, "request_id": request_id}}
return JSONResponse(status_code=status_code, content=body, headers={"X-Request-Id": request_id})
type DbSession = Annotated[AsyncSession, Depends(get_db)] ##Dependency Injection
type CurrentUser = Annotated[str, Depends(get_current_user)]
+129
View File
@@ -0,0 +1,129 @@
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.engine import Result
from typing import List, Optional, Any, Type, TypeVar
from sqlalchemy.exc import IntegrityError
import logging
logger = logging.getLogger(__name__)
ModelType = TypeVar("ModelType")
class DatabaseManager:
def __init__(self, session: AsyncSession, model: Type[ModelType]):
self.session = session
self.model = model
async def execute_query(self, query) -> Result:
return await self.session.execute(query)
async def get_all(self) -> List[ModelType]:
result = await self.session.execute(select(self.model))
return result.scalars().all()
async def get_by_id(self, record_id: int) -> Optional[ModelType]:
result = await self.session.execute(select(self.model).where(self.model.id == record_id))
return result.scalar_one_or_none()
async def create(self, **data) -> ModelType:
try:
instance = self.model(**data)
self.session.add(instance)
except Exception as e:
await self.session.rollback()
logger.error(f"Error creating record in {self.model.__name__}: {e}")
raise
try:
await self.session.commit()
await self.session.refresh(instance)
return instance
except IntegrityError:
await self.session.rollback()
logger.error(f"Error: field value already exist")
raise
async def bulk_create(self, data_list: List[dict]) -> List[ModelType]:
try:
instances = [self.model(**data) for data in data_list]
self.session.add_all(instances)
await self.session.commit()
for instance in instances:
await self.session.refresh(instance)
return instances
except Exception as e:
await self.session.rollback()
logger.error(f"Error bulk creating records in {self.model.__name__}: {e}")
raise
async def update_by_id(self, record_id: int, **data) -> Optional[ModelType]:
try:
instance = await self.get_by_id(self.model, record_id)
if instance:
for key, value in data.items():
setattr(instance, key, value)
await self.session.commit()
await self.session.refresh(instance)
return instance
except Exception as e:
await self.session.rollback()
logger.error(f"Error updating record in {self.model.__name__}: {e}")
raise
async def delete_by_id(self, record_id: int) -> bool:
try:
instance = await self.get_by_id(self.model, record_id)
if instance:
await self.session.delete(instance)
await self.session.commit()
return True
return False
except Exception as e:
await self.session.rollback()
logger.error(f"Error deleting record in {self.model.__name__}: {e}")
raise
async def get_by_field(self, field_name: str, value: Any) -> Optional[ModelType]:
result = await self.session.execute(select(self.model).where(getattr(self.model, field_name) == value))
return result.scalar_one_or_none()
async def delete_by_field(self, field_name: str, value: Any) -> bool:
try:
instance = await self.get_by_field(field_name, value)
if instance:
await self.session.delete(instance)
await self.session.commit()
return True
return False
except Exception as e:
await self.session.rollback()
logger.error(f"Error deleting record in {self.model.__name__}: {e}")
raise
async def update_by_field(self, field_name: str, value: Any, **data) -> Optional[ModelType]:
try:
instance = await self.get_by_field(field_name, value)
if instance:
for key, value in data.items():
setattr(instance, key, value)
await self.session.commit()
await self.session.refresh(instance)
return instance
except Exception as e:
self.session.rollback()
logger.error(f"Error in updating record in {self.model.__name__}: {e}")
raise
async def get_many_by_field(self, field_name: str, value: Any) -> List[ModelType]:
result = await self.session.execute(select(self.model).where(getattr(self.model, field_name) == value))
return result.scalars().all()
async def exists(self, record_id: int) -> bool:
instance = await self.get_by_id(self.model, record_id)
return instance is not None
async def count(self) -> int:
result = await self.session.execute(select(self.model))
return len(result.scalars().all())
+9
View File
@@ -0,0 +1,9 @@
from src.api.repositories.user_repo import UserRepo
from src.api.repositories.session_repo import SessionRepo
from sqlalchemy.ext.asyncio import AsyncSession
class Repository():
def __init__(self, session: AsyncSession):
self.users = UserRepo(session)
self.sessions = SessionRepo(session)
+22
View File
@@ -0,0 +1,22 @@
from sqlalchemy.ext.asyncio import AsyncSession
import uuid
from datetime import datetime
from typing import Optional
from src.models.sessions import Session
from src.api.repositories.core import DatabaseManager
class SessionRepo(DatabaseManager):
def __init__(self, session: AsyncSession, model: Session):
super().__init__(session, model)
async def create(self, token_hash: str, user_id: uuid.UUID, expires_at: datetime) -> Optional[Session]:
result = await super().create(token_hash=token_hash, user_id=user_id, expires_at=expires_at)
return result
async def get_by_token_hash(self, token_hash: str) -> Optional[Session]:
result = await super().get_by_field("token_hash", token_hash)
return result
async def delete_by_token_hash(self, token_hash: str) -> bool:
result = await super().delete_by_field("token_hash", token_hash)
return result
+25
View File
@@ -0,0 +1,25 @@
import uuid
from datetime import datetime
from typing import Optional
from sqlalchemy.ext.asyncio import AsyncSession
from src.models.users import User
from src.api.repositories.core import DatabaseManager
from src.api.dependencies import generate_id
class UserRepo(DatabaseManager):
def __init__(self, session: AsyncSession, model: User):
super().__init__(session, model)
async def get_by_username(self, username: str) -> Optional[User]:
result = await super().get_by_field("username", username.lower())
return result
async def get_by_id(self, user_id: uuid.UUID) -> Optional[User]:
result = await super().get_by_id(user_id)
return result
async def create(self, username: str, display_name: str, password_hash: str) -> Optional[User]:
result = await super().create(id=generate_id(), username=username.lower(), display_name=display_name, password_hash=password_hash)
return result
+57
View File
@@ -0,0 +1,57 @@
from fastapi import HTTPException, APIRouter, Query
from typing import Optional
from uuid import UUID
from src.pydantic_valid.chat import CreateChat, Chat
from src.pydantic_valid.page_response import PageResponse
from src.api.dependencies import CurrentUser, Repo, generate_id, get_now_iso
router = APIRouter()
@router.post("/v1/chats", response_model=Chat, status_code=201)
async def chat(current_user_id: CurrentUser, repo: Repo, chat_in:CreateChat) -> Chat:
if current_user_id not in chat_in.member_ids:
raise HTTPException(statuc_code=400, detail="Creator of chat should be in chat member list")
for usr in chat_in.member_ids:
if usr not in repo.users.users_db:
raise HTTPException(status_code=400, detail="Unexisting user_id in chat member list")
chat_data = Chat(
id = generate_id(),
title = chat_in.title,
member_ids = chat_in.member_ids,
created_at = get_now_iso()
)
await repo.create_chat(chat_data)
return chat_data
@router.get("/v1/chats", response_model=PageResponse)
async def list_chats(current_user_id: CurrentUser, repo: Repo, limit: int = Query(default=50, ge=1, le=100), cursor: Optional[str] = Query(default=None, min_length=1)) -> PageResponse:
accessible_chats = [c for c in repo.chats.chats_db.values()
if current_user_id in c["member_ids"]]
accessible_chats.sort(key=lambda x: (x["created_at"], x["id"]))
start_idx = 0
if cursor:
try:
start_idx = int(cursor)
except ValueError:
raise HTTPException(status_code=400, detail="Invalid cursor")
page_items = accessible_chats[start_idx: start_idx + limit]
next_cursor = None
if start_idx + limit < len(accessible_chats):
next_cursor = str(start_idx + limit)
return PageResponse(items=page_items, next_cursor=next_cursor)
@router.get("/v1/chats/{chat_id}", response_model=Chat)
async def get_chat(current_user_id: CurrentUser, repo: Repo, chat_id: UUID) -> Chat:
chat = repo.chats.chats_db.get(str(chat_id))
if not chat:
raise HTTPException(status_code=404, detail="Chat not found")
if current_user_id not in chat["member_ids"]:
raise HTTPException(status_code=404, detail="Chat not found")
return chat
+15
View File
@@ -0,0 +1,15 @@
from fastapi import APIRouter
from src.pydantic_valid.errors import Health
router = APIRouter()
@router.get("/live", response_model=Health, status_code=200)
async def healh_live():
return {"status": "ok"}
@router.get("/ready", response_model=Health, status_code=200)
async def health_ready():
return {"status": "ok"}
+78
View File
@@ -0,0 +1,78 @@
import base64
from fastapi import HTTPException, APIRouter, Query
from typing import Optional
from uuid import UUID
from src.pydantic_valid.message import Message, CreateMessage
from src.pydantic_valid.page_response import PageResponse
from src.api.dependencies import Repo, CurrentUser, generate_id, get_now_iso
router = APIRouter()
def _encode_msg_cursor(chat_id: str, created_at: str, msg_id: str) -> str:
raw = f"m|{chat_id}|{created_at}|{msg_id}"
return base64.urlsafe_b64encode(raw.encode("utf-8")).decode("ascii").rstrip("=")
def _decode_msg_cursor(scope_chat_id: str, cursor: str) -> tuple[str, str]:
try:
padded = cursor + "=" * (-len(cursor) % 4)
raw = base64.urlsafe_b64decode(padded).decode("utf-8")
parts = raw.split("|", 3)
if len(parts) != 4 or parts[0] != "m":
raise ValueError("bad cursor structure")
chat_id, created_at, msg_id = parts[1], parts[2], parts[3]
except Exception as e:
raise HTTPException(status_code=400, detail="invalid cursor") from e
if scope_chat_id != chat_id:
raise HTTPException(status_code=400, detail="cursor from another chat")
return created_at, msg_id
@router.post("/v1/chats/{chat_id}/messages", response_model=Message, status_code=201)
async def send_message(chat_id: UUID, msg_in: CreateMessage, repo: Repo, crnt_usr_id: CurrentUser):
chat = repo.chats.chats_db.get(str(chat_id))
if not chat:
raise HTTPException(status_code=404, detail="Chat not found")
if crnt_usr_id not in chat["member_ids"]:
raise HTTPException(status_code=404, detail="Not found")
msg_data = Message(
id = generate_id(),
chat_id = str(chat_id),
sender_id = crnt_usr_id,
text = msg_in.text,
created_at = get_now_iso()
)
if await repo.create_message(msg_data):
return msg_data
else:
raise HTTPException(status_code=404, detail="Chat not found")
@router.get("/v1/chats/{chat_id}/messages", response_model=PageResponse, status_code=200)
async def list_messages(repo: Repo, crnt_usr_id: CurrentUser, chat_id: UUID, limit: int = Query(default=50, ge=1, le=100), cursor: Optional[str] = Query(default=None, min_length=1)):
chat = repo.chats.chats_db.get(str(chat_id))
if not chat:
raise HTTPException(status_code=404, detail="Chat not found")
if crnt_usr_id not in chat["member_ids"]:
raise HTTPException(status_code=404, detail="Not found")
# all_msgs = repo.messages.message_db.get(str(chat_id), [])
# all_msgs.sort(key=lambda x: (x["created_at"], x["id"]))
all_msgs = repo.messages.get_sorted_messages(str(chat_id))
if cursor:
cursor_created_at, cursor_message_id = _decode_msg_cursor(str(chat_id), cursor)
all_msgs = [m for m in all_msgs if (m["created_at"], m["id"]) > (cursor_created_at, cursor_message_id)]
page_items = all_msgs[:limit]
next_cursor = None
if len(all_msgs) > limit and page_items:
last = page_items[-1]
next_cursor = _encode_msg_cursor(str(chat_id), last["created_at"], last["id"])
return PageResponse(items=page_items, next_cursor=next_cursor)
+44
View File
@@ -0,0 +1,44 @@
from fastapi import APIRouter, HTTPException, status
from src.pydantic_valid.user import CreateUser, User as UserSchema
from src.models.users import User
from src.api.repositories.main_repo import Repository
from src.auth.password import hash_password
from src.api.dependencies import DbSession, CurrentUser, get_now_iso
router = APIRouter(prefix="/v1")
@router.post("/users", response_model=UserSchema, status_code=201)
async def register_user(body: CreateUser, session: DbSession) -> User:
repo = Repository(session)
existing_user = await repo.users.get_by_username(body.username)
if existing_user:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="username already exists")
password_hash = hash_password(body.password)
new_user = await repo.users.create(
username = body.username,
display_name = body.display_name,
password_hash = password_hash,
)
if not new_user:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="username already exists")
return UserSchema(
id=str(new_user.id),
username=new_user.username,
dispaly_name=new_user.display_name,
created_at=new_user.created_at.strftime("%Y-%m-%dT%H:%M:%SZ"),
)
@router.get("/users/me", response_model=UserSchema, status_code=200)
async def get_me(session: DbSession, current_user_id: CurrentUser) -> User:
repo = Repository(session)
user = await repo.get_user(current_user_id)
if not user:
raise HTTPException(status_code=401, detail="Unknown user")
return user
View File
+19
View File
@@ -0,0 +1,19 @@
import os
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
APP_NAME: str = "MTUSI Messenger"
APP_DEBUG: bool = False
DATABASE_URL: str = Field(..., description="Строка подключения к PostgreSQL")
SESSION_TTL_SECONDS: int = 3600
DB_POOL_SIZE: int = 5
DB_MAX_OVERFLOW: int = 10
model_config = SettingsConfigDict(env_file=".env", case_sensitive=False, extra="ignore")
settings = Settings()
+34
View File
@@ -0,0 +1,34 @@
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from src.config import settings
class Base(DeclarativeBase):
pass
engine = create_async_engine(
settings.DATABASE_URL,
echo=settings.APP_DEBUG,
pool_size=settings.DB_POOL_SIZE,
max_overflow=settings.DB_MAX_OVERFLOW,
pool_pre_ping=True,
)
AsyncSessionLocal = async_sessionmaker(
engine,
class_=AsyncSession, expire_on_commit=False, autoflush=False
)
async def get_db():
async with AsyncSessionLocal() as session:
try:
yield session
finally:
await session.close()
async def close_engine() -> None:
await engine.dispose()
+22
View File
@@ -0,0 +1,22 @@
from contextlib import asynccontextmanager
from src.migrations.runner import run_migrations
from src.database import engine
@asynccontextmanager
async def lifespan():
print(f"Startup: begin sql migratoins")
run_migrations()
print(f"startup: initializing db")
async with engine.connect as conn:
await conn.execute(
__import__("sqlalchemy").text("SELECT 1")
)
print(f"startup: database ready")
yield
print(f"shutdown: closing database connection")
await engine.dispose()
print(f"shutdown: complete")
+78
View File
@@ -0,0 +1,78 @@
from fastapi import FastAPI, Request, HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
import os
from src.api.dependencies import generate_id, create_error_response
from src.api.routes.health import health
from src.api.routes.users import user
from src.api.routes.chats import chat
from src.api.routes.messages import message
from src.lifespan import lifespan
application = FastAPI(title="MTUSI Messenger", version="1.0.0", lifespan=lifespan)
@application.middleware("http")
async def add_request_id(request: Request, call_next):
request_id = generate_id()
request.state.request_id = request_id
response = await call_next(request)
response.headers["X-Request-Id"] = request_id
return response
@application.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
messages = []
for err in exc.errors():
loc = '.'.join(str(p) for p in err["loc"] if p not in ('body',))
msg = err.get("msg", "invalid")
if msg.startswith("Value error, "):
msg = msg[len("Value error, "):]
messages.append(f"{loc}: {msg}" if loc else msg)
detail = "; ".join(messages) or "invalid request"
request_id = getattr(request.state, "request_id", "")
return JSONResponse(
status_code=400,
content={"error": {
"code": "invalid_request",
"message": detail,
"request_id": request_id
}
},
headers={"X-Request-Id": request_id},
)
@application.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
request_id = getattr(request.state, "request_id", None)
if request_id is None:
request_id = generate_id()
code_map = {
400: "invalid_request",
401: "unauthorized",
404: "not_found",
409: "conflict",
413: "payload_too_large",
415: "unsupported_media_type",
429: "rate_limited",
503: "unavailable"
}
code = code_map.get(exc.status_code, "internal_error")
return create_error_response(message=str(exc.detail), code=code, status_code=exc.status_code, request_id=request_id)
@application.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
request_id = getattr(request.state, "request_id", None)
if request_id is None:
request_id = generate_id()
print(f'Internal Error: {exc}')
return create_error_response(message="Internal Server Error", code="internal_error", status_code=500, request_id=request_id)
application.include_router(health.router, prefix="/health", tags=["Health"])
application.include_router(user.router, prefix="/api", tags=["Users"])
application.include_router(chat.router, prefix="/api", tags=["Chats"])
application.include_router(message.router, prefix="/api", tags=["Messages"])
+70
View File
@@ -0,0 +1,70 @@
BEGIN;
CREATE TABLE IF NOT EXISTS users(
id UUID PRIMARY_KEY
username VARCHAR(32) NOT NULL,
display_name VARCHAR(100) NOT NULL,
password_hash TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT users_username_unique UNIQUE(username),
CONSTRAINT users_username_pattern CHECK (username ~ '^[a-z0-9_]{3, 32}S')
CONSTRAINT users_display_name_length CHECK (
char_length(display_name) BETWEEN 1 AND 100
AND trim(display_name) <> ''
)
);
CREATE TABLE IF NOT EXISTS sessions(
token_hash CHAR(64) PRIMARY_KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
expires_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX IF NOT EXISTS sessions_user_id_idx
ON sessions(user_id);
CREATE INDEX IF NOT EXISTS sessions_created_at_idx
ON sessions(created_at);
CREATE TABLE IF NOT EXISTS chats(
id UUID PRIMARY_KEY,
title VARCHAR(100) NOT NULL,
created_at TIMESTAMPTZ DEFAULT now()
CONSTRAINT chats_title_length CHECK(
char_length(title) BETWEEN 1 AND 100
AND trim(title) <> ''
)
);
CREATE TABLE IF NOT EXISTS chat_members(
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
PRIMARY_KEY (chat_id, user_id)
);
CREATE INDEX IF NOT EXISTS chat_members_user_id_idx
ON chat_members(user_id);
CREATE TABLE IN NOT EXISTS messages(
id UUID PRIMARY_KEY,
chat_id NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
sender_id NOT NULL REFERENCES users(id) ON DELETE CASCADE,
text TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
CREATE CONSTRAINT messages_text_length CHECK(
char_length(text) BETWEEN 1 AND 4000
AND trim(text) <> ''
)
);
CREATE INDEX IF NOT EXISTS messages_chat_created_id_idx
ON messages(chat_id, created_at, id);
CREATE INDEX IF NOT EXISTS messages_chat_id_idx
ON messages(chat_id);
COMMIT;
+38
View File
@@ -0,0 +1,38 @@
import asyncio
import os
from pathlib import Path
import asyncpg
MIGRATIONS_DIR = Path(__file__).parent
async def run_migrations() -> None:
dsn = os.environ.get("DATABASE_URL")
if not dsn:
raise RuntimeError("DATABASE_URL environment is not set")
if dsn.startswith("postgresql+asyncpg://"):
dsn = dsn.replace("postgresql+asyncpg://", "postgresql://", 1)
print(f"Connecting to DB")
conn = await asyncpg.connect(dsn)
try:
sql_files = sorted(MIGRATIONS_DIR.glob("*.sql"))
if not sql_files:
print("no SQl files")
return
for sql_file in sql_files:
print(f"migration applying {sql_file.name}")
sql = sql_file.read_text(encding="utf-8")
await conn.execute(sql)
print(f"mighration applied succesful to {sql_file.name}")
print(f"All {len(sql_files)} migrations done")
finally:
await conn.close()
if __name__ == "__main__":
asyncio.run(run_migrations())
+70
View File
@@ -0,0 +1,70 @@
# #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
+48
View File
@@ -0,0 +1,48 @@
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy import String, DateTime, ForeignKey, text
import uuid
from datetime import datetime
from src.database import Base
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from src.models.users import User
class Chat(Base):
__tablename__ = "chats"
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True),
primary_key=True,
default=uuid.uuid4)
title: Mapped[str] = mapped_column(String(100), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True),
nullable=False,
server_dafault=text("now()"))
members: Mapped[list["Chat_Member"]] = relationship("Member_Chat",
cascade="True",
back_populates="")
def __repr__(self) -> str:
return f"<Chat(id={self.id}, title={self.title})>"
class Chat_Member(Base):
__tablename__ = "chat_members"
chat_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True),
ForeignKey("chats.id", ondelete="CASCADE"),
primary_key=True)
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True),
ForeignKey("users.id", ondelete="CASCADE"),
primary_key=True)
user: Mapped["User"] = relationship("User")
chat: Mapped["Chat"] = relationship("Chat", back_populates="members")
def __repr__(self) -> str:
return f"<Chat_Member(chat_id={self.chat_id}, user_id={self.user.id})>"
+56
View File
@@ -0,0 +1,56 @@
from sqlalchemy import String, DateTime, ForeignKey, Text, text
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.dialects.postgresql import UUID
from typing import TYPING_CHECKING
import uuid
from datetime import datetime
from src.database import Base
if TYPING_CHECKING:
from src.models.users import User
from src.models.chats import Chat
class Message(Base):
__tablename__ = "messages"
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True),
primary_key=True,
server_default=uuid.uuid4)
chat_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True),
ForeignKey("chats.id", ondelete="CASCADE"),
nullable=False,
index="True")
sender_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True),
ForeignKey("users.id", ondelete="RESTRICT"),
nullable=False)
text: Mapped[str] = mapped_column(Text,
nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True),
nullable=False,
server_default=text("now()"))
def __repr__(self):
return f"<Message(id={self.id}, chat_id={self.chat_id}, text={self.text[:20]})>"
# async def append_message(self, chat_id: str, msg: dict) -> bool:
# if chat_id not in self.message_db:
# return False
# else:
# self.message_db[chat_id].append(msg)
# self._cache_valid[chat_id] = False
# return True
# def get_sorted_messages(self, chat_id: str) -> list[dict]:
# if chat_id not in self.message_db:
# return []
# if self._cache_valid.get(chat_id, False) and chat_id in self._sorted_cache:
# return self._sorted_cache[chat_id]
# sorted_msg = sorted(self.message_db[chat_id], key=lambda x: (x["created_at"], x["id"]))
# self._sorted_cache[chat_id] = sorted_msg
# self._cache_valid[chat_id] = True
# return sorted_msg
+30
View File
@@ -0,0 +1,30 @@
import uuid
from datetime import datetime
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy import String, DateTime, ForeignKey, text
from src.database import Base
class Session(Base):
__tablename__ = "sessions"
token_hash: Mapped[str] = mapped_column(String(64), primary_key=True, comment="SHA-256 opaque token")
user_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
ForeignKey("user.id", ondelete="CASCADE",),
nullable=False,
index=True,
comment="Внешний ключ на идентификатор пользователя")
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True),
nullable=False,
index=True,
comment="время истечения сессии")
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True),
nullable=False,
server_default=text("now()"),
comment="время создания сессии")
def __repr__(self) -> str:
return f"<Session(token_hash={self.token_hash[:8]},... user_id={self.user_id})>"
+20
View File
@@ -0,0 +1,20 @@
from sqlalchemy import Column, String, DateTime, Text
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column
import uuid
from datetime import datetime
from src.database import Base
class User(Base):
__tablename__ = "users"
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4, comment="Первичный ключ как uui4, вероятность коллизии стремится к 0. В будущем лучше переходить к uuid7-время+рандом")
username: Mapped[str] = mapped_column(String(32), unique=True, nullable=False, index=True, comment="Логин пользователя")
display_name: Mapped[str] = mapped_column(String(100), nullable=False)
password_hash: Mapped[str] = mapped_column(String, nullable=False, comment="Argon2id hash пароля")
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
def __repr__(self) -> str:
return f"<User(id={self.id}, username={self.username})>"
+38
View File
@@ -0,0 +1,38 @@
import uuid
from pydantic import BaseModel, Field, field_validator, ConfigDict
class CreateChat(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str = Field(..., min_length=1, max_length=100)
member_ids: list[str] = Field(..., min_items=1, max_items=100)
@field_validator("title")
@classmethod
def title_validate(cls, v: str) -> str:
if not v.strip():
raise ValueError("title shouldn't have only whitespaces and cannot be blank")
return v
@field_validator("member_ids")
@classmethod
def validate_member_ids(cls, v: list[str]) -> list[str]:
if len(v) != len(set(v)):
raise ValueError("Dublicates are prohibitated")
for ids in v:
try:
uuid.UUID(ids)
except:
raise ValueError(f'invalid UUID format was detected for member_id: {ids}')
return v
class Chat(BaseModel):
id: str
title: str
member_ids: list[str]
created_at: str
+15
View File
@@ -0,0 +1,15 @@
from pydantic import BaseModel
class ErrorDetail(BaseModel):
code: str
message: str
request_id: str
class ErrorResponse(BaseModel):
detail: ErrorDetail
class Health(BaseModel):
status: str
+22
View File
@@ -0,0 +1,22 @@
from pydantic import BaseModel, Field, field_validator, ConfigDict
from uuid import UUID
class CreateMessage(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str = Field(..., min_length=1, max_length=4000)
@field_validator("text")
@classmethod
def validate_text(cls, v: str) -> str:
if not v.strip():
raise ValueError("Blank or text consisted only from whitespaces is prohibitated")
return v
class Message(BaseModel):
id: str
chat_id: str
sender_id: str
text: str
created_at: str
+7
View File
@@ -0,0 +1,7 @@
from pydantic import BaseModel
from typing import Any, Optional
class PageResponse(BaseModel):
items: list[Any]
next_cursor: Optional[str] = None
+22
View File
@@ -0,0 +1,22 @@
from pydantic import BaseModel, Field, field_validator, ConfigDict
class CreateUser(BaseModel):
model_config = ConfigDict(extra="forbid")
username: str = Field(..., pattern=r"^[a-z0-9_]{3,32}$")
display_name: str = Field(..., min_length=1, max_length=100)
@field_validator("display_name")
@classmethod
def validate_display_name(cls, v: str) -> str:
if not v.strip():
raise ValueError("Name cannot be whitespaces or none")
return v
class User(BaseModel):
id: str
username: str
display_name: str
created_at: str