добавлена постгря и начальная схема

This commit is contained in:
2026-10-07 21:44:56 +03:00
parent 65003b6119
commit 789bea2f1e
14 changed files with 904 additions and 0 deletions
+25
View File
@@ -0,0 +1,25 @@
FROM python:3.13.15-slim
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY alembic.ini .
COPY migrations ./migrations
COPY src ./src
RUN useradd --create-home --uid 10001 appuser
USER appuser
EXPOSE 8080
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2)" || exit 1
CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8080"]
+149
View File
@@ -0,0 +1,149 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts.
# this is typically a path given in POSIX (e.g. forward slashes)
# format, relative to the token %(here)s which refers to the location of this
# ini file
script_location = %(here)s/migrations
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# Or organize into date-based subdirectories (requires recursive_version_locations = true)
# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory. for multiple paths, the path separator
# is defined by "path_separator" below.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the tzdata library which can be installed by adding
# `alembic[tz]` to the pip requirements.
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =
# max length of characters to apply to the "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; This defaults
# to <script_location>/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "path_separator"
# below.
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
# path_separator; This indicates what character is used to split lists of file
# paths, including version_locations and prepend_sys_path within configparser
# files such as alembic.ini.
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
# to provide os-dependent path splitting.
#
# Note that in order to support legacy alembic.ini files, this default does NOT
# take place if path_separator is not present in alembic.ini. If this
# option is omitted entirely, fallback logic is as follows:
#
# 1. Parsing of the version_locations option falls back to using the legacy
# "version_path_separator" key, which if absent then falls back to the legacy
# behavior of splitting on spaces and/or commas.
# 2. Parsing of the prepend_sys_path option falls back to the legacy
# behavior of splitting on spaces, commas, or colons.
#
# Valid values for path_separator are:
#
# path_separator = :
# path_separator = ;
# path_separator = space
# path_separator = newline
#
# Use os.pathsep. Default configuration used for new projects.
path_separator = os
# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
# database URL. This is consumed by the user-maintained env.py script only.
# other means of configuring database URLs may be customized within the env.py
# file.
sqlalchemy.url =
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
# hooks = ruff
# ruff.type = module
# ruff.module = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Alternatively, use the exec runner to execute a binary found on your PATH
# hooks = ruff
# ruff.type = exec
# ruff.executable = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Logging configuration. This is also consumed by the user-maintained
# env.py script only.
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARNING
handlers = console
qualname =
[logger_sqlalchemy]
level = WARNING
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
+38
View File
@@ -0,0 +1,38 @@
services:
postgres:
image: postgres:17.6
environment:
POSTGRES_DB: messenger
POSTGRES_USER: lab2
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
secrets:
- postgres_password
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U lab2 -d messenger"]
interval: 5s
timeout: 3s
retries: 10
start_period: 5s
api:
build:
context: .
dockerfile: Dockerfile
secrets:
- database_url
depends_on:
postgres:
condition: service_healthy
ports:
- "8080:8080"
secrets:
postgres_password:
file: ./secrets/postgres_password
database_url:
file: ./secrets/database_url
volumes:
postgres_data:
+1
View File
@@ -0,0 +1 @@
Generic single-database configuration with an async dbapi.
+50
View File
@@ -0,0 +1,50 @@
import asyncio
from alembic import context
from sqlalchemy import pool
from sqlalchemy.ext.asyncio import async_engine_from_config
config = context.config
DATABASE_URL_FILE = "/run/secrets/database_url"
def read_database_url() -> str:
with open(DATABASE_URL_FILE, encoding="utf-8") as file:
return file.read().strip()
config.set_main_option("sqlalchemy.url", read_database_url())
target_metadata = None
def do_run_migrations(connection) -> None:
context.configure(
connection=connection,
target_metadata=target_metadata,
)
with context.begin_transaction():
context.run_migrations()
async def run_async_migrations() -> None:
connectable = async_engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
await connectable.dispose()
def run_migrations_online() -> None:
asyncio.run(run_async_migrations())
run_migrations_online()
+28
View File
@@ -0,0 +1,28 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
"""Upgrade schema."""
${upgrades if upgrades else "pass"}
def downgrade() -> None:
"""Downgrade schema."""
${downgrades if downgrades else "pass"}
@@ -0,0 +1,110 @@
"""initial schema
Revision ID: f7c51e1e945b
Revises:
Create Date: 2026-10-07 18:33:37.771593
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "f7c51e1e945b"
down_revision: Union[str, Sequence[str], None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.create_table(
"users",
sa.Column("id", sa.Uuid(), nullable=False),
sa.Column("username", sa.String(length=32), nullable=False),
sa.Column("display_name", sa.String(length=100), nullable=False),
sa.Column("password_hash", sa.Text(), nullable=False),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
server_default=sa.text("CURRENT_TIMESTAMP"),
nullable=False,
),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("username", name="uq_users_username"),
)
op.create_table(
"chats",
sa.Column("id", sa.Uuid(), nullable=False),
sa.Column("title", sa.String(length=100), nullable=False),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
server_default=sa.text("CURRENT_TIMESTAMP"),
nullable=False,
),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"chat_members",
sa.Column("chat_id", sa.Uuid(), nullable=False),
sa.Column("user_id", sa.Uuid(), nullable=False),
sa.ForeignKeyConstraint(
["chat_id"],
["chats.id"],
ondelete="CASCADE",
),
sa.ForeignKeyConstraint(
["user_id"],
["users.id"],
ondelete="CASCADE",
),
sa.PrimaryKeyConstraint("chat_id", "user_id"),
)
op.create_table(
"messages",
sa.Column("id", sa.Uuid(), nullable=False),
sa.Column("chat_id", sa.Uuid(), nullable=False),
sa.Column("sender_id", sa.Uuid(), nullable=False),
sa.Column("text", sa.String(length=4000), nullable=False),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
server_default=sa.text("CURRENT_TIMESTAMP"),
nullable=False,
),
sa.ForeignKeyConstraint(
["chat_id"],
["chats.id"],
ondelete="CASCADE",
),
sa.ForeignKeyConstraint(
["sender_id"],
["users.id"],
ondelete="RESTRICT",
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(
"ix_messages_chat_created_id",
"messages",
["chat_id", "created_at", "id"],
unique=False,
)
def downgrade() -> None:
op.drop_index(
"ix_messages_chat_created_id",
table_name="messages",
)
op.drop_table("messages")
op.drop_table("chat_members")
op.drop_table("chats")
op.drop_table("users")
+17
View File
@@ -0,0 +1,17 @@
annotated-doc==0.0.5
annotated-types==0.8.0
anyio==4.15.1
click==8.5.0
fastapi==0.141.1
h11==0.16.0
idna==3.20
pydantic==2.13.5
pydantic_core==2.46.5
starlette==1.7.0
typing-inspection==0.4.4
typing_extensions==4.16.0
uvicorn==0.53.0
SQLAlchemy==2.1.4
asyncpg==0.32.0
alembic==1.20.0
greenlet==3.5.6
View File
+60
View File
@@ -0,0 +1,60 @@
import base64
import binascii
import json
from datetime import datetime
from uuid import UUID
def encode_cursor(
chat_id: UUID,
created_at: datetime,
message_id: UUID,
) -> str:
data = {
"chat_id": str(chat_id),
"created_at": created_at.isoformat(),
"message_id": str(message_id),
}
raw = json.dumps(
data,
separators=(",", ":"),
).encode("utf-8")
return base64.urlsafe_b64encode(raw).decode("ascii")
def decode_cursor(cursor: str) -> tuple[UUID, datetime, UUID]:
try:
raw = base64.urlsafe_b64decode(cursor.encode("ascii"))
data = json.loads(raw.decode("utf-8"))
if not isinstance(data, dict):
raise ValueError("Invalid cursor")
if set(data.keys()) != {
"chat_id",
"created_at",
"message_id",
}:
raise ValueError("Invalid cursor")
chat_id = UUID(data["chat_id"])
created_at = datetime.fromisoformat(data["created_at"])
message_id = UUID(data["message_id"])
if created_at.tzinfo is None or created_at.utcoffset() is None:
raise ValueError("Invalid cursor")
return chat_id, created_at, message_id
except (
ValueError,
KeyError,
TypeError,
UnicodeError,
binascii.Error,
json.JSONDecodeError,
) as exc:
raise ValueError("Invalid cursor") from exc
+44
View File
@@ -0,0 +1,44 @@
from collections.abc import AsyncIterator
from sqlalchemy.ext.asyncio import (
AsyncSession,
async_sessionmaker,
create_async_engine,
)
DATABASE_URL_FILE = "/run/secrets/database_url"
POOL_SIZE = 5
MAX_OVERFLOW = 5
POOL_TIMEOUT_SECONDS = 5
DB_CONNECT_TIMEOUT_SECONDS = 5
def read_database_url() -> str:
with open(DATABASE_URL_FILE, encoding="utf-8") as file:
return file.read().strip()
database_url = read_database_url()
engine = create_async_engine(
database_url,
pool_size=POOL_SIZE,
max_overflow=MAX_OVERFLOW,
pool_timeout=POOL_TIMEOUT_SECONDS,
connect_args={
"timeout": DB_CONNECT_TIMEOUT_SECONDS,
},
pool_pre_ping=True,
)
SessionFactory = async_sessionmaker(
bind=engine,
expire_on_commit=False,
)
async def get_db_session() -> AsyncIterator[AsyncSession]:
async with SessionFactory() as session:
yield session
+5
View File
@@ -0,0 +1,5 @@
class APIError(Exception):
def __init__(self, status_code: int, code: str, message: str):
self.status_code = status_code
self.code = code
self.message = message
+271
View File
@@ -0,0 +1,271 @@
from uuid import UUID, uuid4
from fastapi import Depends, FastAPI, Header, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from src.errors import APIError
from src.models import Chat, ChatPage, CreateChat, CreateMessage, CreateUser, Message, MessagePage, User
from src.store import Store, UsernameAlreadyExistsError
app = FastAPI()
store = Store()
@app.middleware("http")
async def request_middleware(request: Request, call_next):
request_id = str(uuid4())
request.state.request_id = request_id
if request.method in {"POST", "PUT", "PATCH"}:
content_type = request.headers.get("content-type")
if content_type is not None:
media_type = content_type.split(";", 1)[0].strip().lower()
if media_type != "application/json":
return JSONResponse(
status_code=415,
content={
"error": {
"code": "unsupported_media_type",
"message": "Unsupported media type",
"request_id": request_id,
}
},
headers={
"X-Request-Id": request_id,
},
)
response = await call_next(request)
response.headers["X-Request-Id"] = request_id
return response
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(
request: Request,
exc: RequestValidationError,
):
request_id = request.state.request_id
return JSONResponse(
status_code=400,
content={
"error": {
"code": "invalid_request",
"message": "Invalid request",
"request_id": request_id,
}
},
)
@app.exception_handler(APIError)
async def api_error_handler(request: Request, exc: APIError):
request_id = request.state.request_id
return JSONResponse(
status_code=exc.status_code,
content={
"error": {
"code": exc.code,
"message": exc.message,
"request_id": request_id,
}
},
)
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(
request: Request,
exc: StarletteHTTPException,
):
request_id = request.state.request_id
if exc.status_code == 404:
code = "not_found"
message = "Not found"
else:
code = "invalid_request"
message = "Invalid request"
return JSONResponse(
status_code=exc.status_code,
content={
"error": {
"code": code,
"message": message,
"request_id": request_id,
}
},
headers=exc.headers,
)
@app.exception_handler(Exception)
async def unexpected_exception_handler(
request: Request,
exc: Exception,
):
request_id = request.state.request_id
return JSONResponse(
status_code=500,
content={
"error": {
"code": "internal_error",
"message": "Internal server error",
"request_id": request_id,
}
},
)
async def get_current_user(
x_user_id: str | None = Header(default=None),
) -> User:
if x_user_id is None:
raise APIError(
status_code=401,
code="unauthorized",
message="Unauthorized",
)
try:
user_id = UUID(x_user_id)
except ValueError:
raise APIError(
status_code=401,
code="unauthorized",
message="Unauthorized",
)
user = await store.get_user(user_id)
if user is None:
raise APIError(
status_code=401,
code="unauthorized",
message="Unauthorized",
)
return user
@app.get("/health/live")
async def health_live():
return {"status": "ok"}
@app.get("/health/ready")
async def health_ready():
return {"status": "ok"}
@app.post("/api/v1/users", response_model=User, status_code=201)
async def create_user(data: CreateUser):
try:
return await store.create_user(data)
except UsernameAlreadyExistsError:
raise APIError(
status_code=409,
code="conflict",
message="Username already exists",
)
@app.get("/api/v1/users/me", response_model=User)
async def get_me(
current_user: User = Depends(get_current_user),
):
return current_user
@app.post("/api/v1/chats", response_model=Chat, status_code=201)
async def create_chat(
data: CreateChat,
current_user: User = Depends(get_current_user),
):
return await store.create_chat(
data=data,
current_user_id=current_user.id,
)
@app.get("/api/v1/chats/{chat_id}", response_model=Chat)
async def get_chat(
chat_id: UUID,
current_user: User = Depends(get_current_user),
):
return await store.get_chat(
chat_id=chat_id,
current_user_id=current_user.id,
)
@app.get("/api/v1/chats", response_model=ChatPage)
async def get_chats(
limit: int = 50,
current_user: User = Depends(get_current_user),
):
if limit < 1 or limit > 100:
raise APIError(
status_code=400,
code="invalid_request",
message="Limit must be between 1 and 100",
)
return await store.get_chats(
current_user_id=current_user.id,
limit=limit,
)
@app.post(
"/api/v1/chats/{chat_id}/messages",
response_model=Message,
status_code=201,
)
async def create_message(
chat_id: UUID,
data: CreateMessage,
current_user: User = Depends(get_current_user),
):
return await store.create_message(
chat_id=chat_id,
current_user_id=current_user.id,
data=data,
)
@app.get(
"/api/v1/chats/{chat_id}/messages",
response_model=MessagePage,
)
async def get_messages(
chat_id: UUID,
limit: int = 50,
cursor: str | None = None,
current_user: User = Depends(get_current_user),
):
if limit < 1 or limit > 100:
raise APIError(
status_code=400,
code="invalid_request",
message="Limit must be between 1 and 100",
)
return await store.get_messages(
chat_id=chat_id,
current_user_id=current_user.id,
limit=limit,
cursor=cursor,
)
+106
View File
@@ -0,0 +1,106 @@
from datetime import datetime
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field, field_validator
class CreateUser(BaseModel):
model_config = ConfigDict(extra="forbid")
username: str = Field(
min_length=3,
max_length=32,
pattern=r"^[a-z0-9_]+$",
)
display_name: str = Field(
min_length=1,
max_length=100,
)
@field_validator("display_name")
@classmethod
def validate_display_name(cls, value: str) -> str:
if not value.strip():
raise ValueError("Display name must not be blank")
return value
class User(BaseModel):
id: UUID
username: str
display_name: str
created_at: datetime
class CreateChat(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str = Field(
min_length=1,
max_length=100,
)
member_ids: list[UUID] = Field(
min_length=1,
max_length=100,
)
@field_validator("title")
@classmethod
def validate_title(cls, value: str) -> str:
if not value.strip():
raise ValueError("Chat title must not be blank")
return value
@field_validator("member_ids")
@classmethod
def validate_member_ids(cls, value: list[UUID]) -> list[UUID]:
if len(value) != len(set(value)):
raise ValueError("Member IDs must be unique")
return value
class Chat(BaseModel):
id: UUID
title: str
member_ids: list[UUID]
created_at: datetime
class ChatPage(BaseModel):
items: list[Chat]
next_cursor: str | None
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, value: str) -> str:
if not value.strip():
raise ValueError("Message text must not be blank")
return value
class Message(BaseModel):
id: UUID
chat_id: UUID
sender_id: UUID
text: str
created_at: datetime
class MessagePage(BaseModel):
items: list[Message]
next_cursor: str | None