Adopt async SQLAlchemy storage and verified Alembic migrations

Keep the message and idempotency receipt in one Core CTE statement with chat-first locking. Preserve rollback, bounded dependency failures, and domain ports.

Replace the SQL runner with Alembic. Adopt legacy databases only after validating their journal and PostgreSQL schema, retain all data, and verify migrations on fresh and populated databases.
This commit is contained in:
Artyom
2026-11-05 21:38:12 +03:00
parent c376882ce8
commit 71c643c6d1
29 changed files with 1542 additions and 409 deletions
+3
View File
@@ -36,6 +36,9 @@ COPY --from=builder --chown=root:root /opt/venv /opt/venv
WORKDIR /app
COPY --chown=root:root alembic.ini ./
COPY --chown=root:root alembic ./alembic
USER 10001:10001
EXPOSE 8080
+3 -3
View File
@@ -10,7 +10,7 @@ COMPOSE ?= docker compose
RATE ?= 100
FROM_REV ?=
SHIFT ?= 0
SCRIPTS_PY = scripts/probe.py scripts/limits.py scripts/scaling.py tools
SCRIPTS_PY = alembic scripts/probe.py scripts/limits.py scripts/scaling.py tools
TRACK1 = evidence/track1
SCALING = $(PYTHON) scripts/scaling.py --fresh-db
BEFORE_REV ?= edc091d
@@ -61,14 +61,14 @@ install:
lint:
$(VENV)/bin/ruff check src student-tests $(SCRIPTS_PY)
$(VENV)/bin/ruff format --check src student-tests $(SCRIPTS_PY)
$(VENV)/bin/ty check src student-tests
$(VENV)/bin/ty check src student-tests alembic
format:
$(VENV)/bin/ruff check --fix src student-tests $(SCRIPTS_PY)
$(VENV)/bin/ruff format src student-tests $(SCRIPTS_PY)
typecheck:
$(VENV)/bin/ty check src student-tests
$(VENV)/bin/ty check src student-tests alembic
student-test:
$(VENV)/bin/pytest $(PYTEST_ARGS)
+4
View File
@@ -0,0 +1,4 @@
[alembic]
script_location = %(here)s/alembic
prepend_sys_path = %(here)s/src %(here)s/alembic
path_separator = space
+81
View File
@@ -0,0 +1,81 @@
import asyncio
from alembic import context
from alembic.script import ScriptDirectory
from legacy import adopt_legacy
from sqlalchemy import Connection, func, make_url, pool, select
from sqlalchemy.ext.asyncio import create_async_engine
from messenger.identity.infrastructure.postgres import SessionRow, UserRow
from messenger.messaging.infrastructure.postgres import (
ChatMemberRow,
ChatRow,
IdempotencyKeyRow,
MessageRow,
)
from messenger.shared.config import PlatformSettings
LOCK_KEY = 20_260_002
MODELS = (UserRow, SessionRow, ChatRow, ChatMemberRow, MessageRow, IdempotencyKeyRow)
target_metadata = UserRow.metadata
config = context.config
def include_object(_obj, name, _type, _reflected, _compare_to):
return name != "schema_migrations"
def run_migrations(connection: Connection) -> None:
with connection.engine.connect() as lock:
lock.execute(select(func.pg_advisory_lock(LOCK_KEY)))
lock.commit()
try:
with connection.begin():
adopt_legacy(connection, ScriptDirectory.from_config(config))
context.configure(
connection=connection,
target_metadata=target_metadata,
transaction_per_migration=True,
compare_type=True,
include_object=include_object,
)
with context.begin_transaction():
context.run_migrations()
finally:
lock.execute(select(func.pg_advisory_unlock(LOCK_KEY)))
lock.commit()
async def run_async_migrations() -> None:
dsn = config.attributes.get("database_url")
if dsn is None:
dsn = PlatformSettings().database_url.get_secret_value()
engine = create_async_engine(
make_url(dsn).set(drivername="postgresql+asyncpg"),
poolclass=pool.NullPool,
hide_parameters=True,
connect_args={
"timeout": 10,
"server_settings": {"lock_timeout": "10000", "statement_timeout": "60000"},
},
)
try:
async with engine.connect() as connection:
await connection.run_sync(run_migrations)
finally:
await engine.dispose()
if context.is_offline_mode():
context.configure(
dialect_name="postgresql",
target_metadata=target_metadata,
literal_binds=True,
transaction_per_migration=True,
)
with context.begin_transaction():
context.run_migrations()
elif config.attributes.get("connection") is not None:
run_migrations(config.attributes["connection"])
else:
asyncio.run(run_async_migrations())
+86
View File
@@ -0,0 +1,86 @@
from uuid import uuid4
from alembic.migration import MigrationContext
from alembic.operations import Operations
from alembic.script import ScriptDirectory
from sqlalchemy import Connection, MetaData, Table, func, inspect, select, text
from sqlalchemy.schema import CreateSchema
LEGACY = {
"0001_init": "9a13618f078ae9056431391e2e5197a31b981ae1fff047a9b3421ac750d3fd0d",
"0002_idempotency_keys": "d9159a35553249a1e51af5f2e4e7c39b014e97593c49748e13f3799839063dd0",
}
SNAPSHOT = text("""
WITH relations AS (
SELECT c.* FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = :schema AND c.relkind IN ('r', 'p')
AND c.relname NOT IN ('schema_migrations', 'alembic_version')
)
SELECT 'table' AS kind, c.relname AS name,
concat_ws('|', c.relkind, c.relrowsecurity, c.relforcerowsecurity) AS definition
FROM relations c
UNION ALL
SELECT 'column', c.relname || '.' || a.attname,
concat_ws('|', a.attnum, format_type(a.atttypid, a.atttypmod), a.attnotnull,
a.attidentity, a.attgenerated, pg_get_expr(d.adbin, d.adrelid))
FROM relations c JOIN pg_attribute a ON a.attrelid = c.oid
LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = a.attnum
WHERE a.attnum > 0 AND NOT a.attisdropped
UNION ALL
SELECT 'constraint', c.relname || '.' || k.conname,
concat_ws('|', pg_get_constraintdef(k.oid), k.convalidated)
FROM relations c JOIN pg_constraint k ON k.conrelid = c.oid
UNION ALL
SELECT 'index', c.relname || '.' || x.relname,
concat_ws('|', pg_get_indexdef(i.indexrelid), i.indisvalid, i.indisready)
FROM relations c JOIN pg_index i ON i.indrelid = c.oid
JOIN pg_class x ON x.oid = i.indexrelid
UNION ALL
SELECT 'trigger', c.relname || '.' || t.tgname,
concat_ws('|', pg_get_triggerdef(t.oid), t.tgenabled)
FROM relations c JOIN pg_trigger t ON t.tgrelid = c.oid WHERE NOT t.tgisinternal
ORDER BY kind, name
""")
def snapshot(connection: Connection, schema: str) -> list[tuple[str, str, str]]:
return [
(kind, name, definition.replace(f"{schema}.", ""))
for kind, name, definition in connection.execute(SNAPSHOT, {"schema": schema})
]
def adopt_legacy(connection: Connection, scripts: ScriptDirectory) -> None:
migration = MigrationContext.configure(connection)
if migration.get_current_heads():
return
tables = set(inspect(connection).get_table_names(schema="public"))
if tables <= {"alembic_version"}:
return
if "schema_migrations" not in tables:
raise RuntimeError("Existing schema has no legacy migration journal")
journal = Table("schema_migrations", MetaData(), schema="public", autoload_with=connection)
applied = dict(connection.execute(select(journal.c.version, journal.c.checksum)).tuples().all())
expected = dict(list(LEGACY.items())[: len(applied)])
if applied != expected:
raise RuntimeError("Unknown or changed legacy migrations")
if not applied:
if tables - {"schema_migrations", "alembic_version"}:
raise RuntimeError("Existing schema has an empty migration journal")
return
revision = list(expected)[-1]
actual = snapshot(connection, "public")
reference = f"alembic_verify_{uuid4().hex}"
savepoint = connection.begin_nested()
try:
connection.execute(CreateSchema(reference))
connection.execute(select(func.set_config("search_path", reference, True)))
with Operations.context(MigrationContext.configure(connection)):
for script in reversed(list(scripts.walk_revisions(base="base", head=revision))):
script.module.upgrade()
wanted = snapshot(connection, reference)
finally:
savepoint.rollback()
if actual != wanted:
raise RuntimeError("Legacy schema differs from the recorded migrations")
migration.stamp(scripts, revision)
+16
View File
@@ -0,0 +1,16 @@
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}
+87
View File
@@ -0,0 +1,87 @@
import sqlalchemy as sa
from alembic import op
revision = "0001_init"
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"users",
sa.Column("id", sa.Uuid(), nullable=False),
sa.Column("username", sa.Text(), nullable=False),
sa.Column("display_name", sa.Text(), nullable=False),
sa.Column("password_hash", sa.Text(), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.CheckConstraint("password_hash LIKE '$argon2id$%'", name="users_password_hash_check"),
sa.CheckConstraint("username ~ '^[a-z0-9_]{3,32}$'", name="users_username_format"),
sa.CheckConstraint(
"char_length(display_name) BETWEEN 1 AND 100", name="users_display_name_check"
),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("username", name="users_username_key"),
)
op.create_table(
"sessions",
sa.Column("token_hash", sa.LargeBinary(), nullable=False),
sa.Column("user_id", sa.Uuid(), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("expires_at", sa.DateTime(timezone=True), nullable=False),
sa.CheckConstraint("expires_at > created_at", name="sessions_check"),
sa.CheckConstraint("octet_length(token_hash) = 32", name="sessions_token_hash_check"),
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
sa.PrimaryKeyConstraint("token_hash"),
)
op.create_index("sessions_user_idx", "sessions", ["user_id"], unique=False)
op.create_table(
"chats",
sa.Column("id", sa.Uuid(), nullable=False),
sa.Column("title", sa.Text(), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("last_message_at", sa.DateTime(timezone=True), nullable=True),
sa.CheckConstraint("char_length(title) BETWEEN 1 AND 100", name="chats_title_check"),
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.Column("position", sa.SmallInteger(), nullable=False),
sa.Column("chat_created_at", sa.DateTime(timezone=True), nullable=False),
sa.CheckConstraint("position BETWEEN 1 AND 100", name="chat_members_position_check"),
sa.ForeignKeyConstraint(["chat_id"], ["chats.id"], ondelete="CASCADE"),
sa.ForeignKeyConstraint(
["user_id"],
["users.id"],
),
sa.PrimaryKeyConstraint("chat_id", "user_id"),
)
op.create_index(
"chat_members_user_idx",
"chat_members",
["user_id", "chat_created_at", "chat_id"],
unique=False,
)
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.Text(), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.CheckConstraint("char_length(text) BETWEEN 1 AND 4000", name="messages_text_check"),
sa.ForeignKeyConstraint(
["chat_id", "sender_id"],
["chat_members.chat_id", "chat_members.user_id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(
"messages_history_idx", "messages", ["chat_id", "created_at", "id"], unique=False
)
def downgrade() -> None:
raise RuntimeError("Downgrade would delete application data")
+33
View File
@@ -0,0 +1,33 @@
import sqlalchemy as sa
from alembic import op
revision = "0002_idempotency_keys"
down_revision = "0001_init"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"idempotency_keys",
sa.Column("chat_id", sa.Uuid(), nullable=False),
sa.Column("user_id", sa.Uuid(), nullable=False),
sa.Column("key", sa.Text(), nullable=False),
sa.Column("fingerprint", sa.LargeBinary(), nullable=False),
sa.Column("message_id", sa.Uuid(), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.CheckConstraint("key ~ '^[A-Za-z0-9._:-]{1,128}$'", name="idempotency_keys_key_check"),
sa.CheckConstraint(
"octet_length(fingerprint) = 32", name="idempotency_keys_fingerprint_check"
),
sa.ForeignKeyConstraint(
["chat_id", "user_id"],
["chat_members.chat_id", "chat_members.user_id"],
),
sa.ForeignKeyConstraint(["message_id"], ["messages.id"], ondelete="CASCADE"),
sa.PrimaryKeyConstraint("chat_id", "user_id", "key"),
)
def downgrade() -> None:
raise RuntimeError("Downgrade would delete application data")
+1 -1
View File
@@ -74,7 +74,7 @@ services:
migrate:
<<: *app
pull_policy: never
command: ["python", "-m", "messenger.migrate"]
command: ["alembic", "upgrade", "head"]
environment:
DATABASE_URL_FILE: /run/secrets/database_url
LOG_LEVEL: ${LOG_LEVEL:-INFO}
+7 -2
View File
@@ -13,6 +13,8 @@ dependencies = [
"gunicorn>=26.2.0",
"orjson>=3.12.0",
"asyncpg>=0.32.0",
"sqlalchemy[asyncio]==2.0.45",
"alembic==1.16.5",
"argon2-cffi>=25.1.0",
"uvicorn-worker>=0.4.0",
"redis>=8.1.0",
@@ -87,7 +89,7 @@ ignore = [
"src/messenger/*/entrypoints/**" = ["TID251", "N818", "PLR0917", "S105"]
"src/messenger/shared/config.py" = ["ARG002", "ARG003"]
"src/messenger/main.py" = ["TID251"]
"src/messenger/migrate.py" = ["TID251"]
"alembic/**" = ["TID251"]
"src/messenger/gunicorn_conf.py" = ["TID251", "ARG002", "RUF012"]
[tool.ruff.lint.flake8-tidy-imports.banned-api]
@@ -99,7 +101,10 @@ ignore = [
known-first-party = ["messenger"]
[tool.ty.src]
include = ["src", "student-tests"]
include = ["src", "student-tests", "alembic"]
[tool.ty.environment]
extra-paths = ["alembic"]
[tool.ty.rules]
unresolved-import = "error"
+1 -1
View File
@@ -36,7 +36,7 @@ for r in csv.DictReader(sys.stdin.read().lstrip("# ").splitlines()):
echo "python in image: $(docker exec "$(docker compose ps -q api | head -1)" python -V)"
echo "haproxy: $(docker compose exec -T lb haproxy -v | head -1)"
echo "packages (uv.lock):"
for name in fastapi uvicorn uvicorn-worker gunicorn asyncpg argon2-cffi pydantic pydantic-settings dishka structlog redis; do
for name in fastapi uvicorn uvicorn-worker gunicorn sqlalchemy alembic asyncpg argon2-cffi pydantic pydantic-settings dishka structlog redis; do
printf ' %s %s\n' "$name" "$(sed -n "/^name = \"$name\"$/{n;s/version = \"\(.*\)\"/\1/p;}" uv.lock)"
done
echo "process users (service uid command):"
+4 -4
View File
@@ -3,17 +3,17 @@ set -eu
cd "$(dirname "$0")/.."
psql() { docker compose exec -T postgres psql -U messenger -d messenger -c "$1"; }
header() { echo "date: $(date -u +%FT%TZ) commit: $(git rev-parse --short HEAD)"; }
counts="SELECT (SELECT count(*) FROM users) users, (SELECT count(*) FROM sessions) sessions, (SELECT count(*) FROM chats) chats, (SELECT count(*) FROM chat_members) members, (SELECT count(*) FROM messages) messages, (SELECT count(*) FROM idempotency_keys) keys, (SELECT count(*) FROM schema_migrations) versions"
counts="SELECT (SELECT count(*) FROM users) users, (SELECT count(*) FROM sessions) sessions, (SELECT count(*) FROM chats) chats, (SELECT count(*) FROM chat_members) members, (SELECT count(*) FROM messages) messages, (SELECT count(*) FROM idempotency_keys) keys, (SELECT count(*) FROM alembic_version) versions"
kdf="SELECT substring(password_hash from '^[$]argon2id[$]v=[0-9]+[$]m=[0-9]+,t=[0-9]+,p=[0-9]+[$]') AS kdf_prefix, username = 'seed_author' AS seed_stub, count(*) AS users, min(length(password_hash)) AS min_length, max(length(password_hash)) AS max_length FROM users GROUP BY 1, 2 ORDER BY 2"
tokens="SELECT octet_length(token_hash) AS stored_bytes, count(*) AS sessions FROM sessions GROUP BY 1"
{
header
for table in users sessions chats chat_members messages idempotency_keys schema_migrations; do
for table in users sessions chats chat_members messages idempotency_keys alembic_version; do
echo "\$ psql -c '\\d+ $table'"
psql "\\d+ $table"
done
echo "\$ psql -c 'SELECT version, left(checksum, 12), applied_at FROM schema_migrations'"
psql "SELECT version, left(checksum, 12) AS checksum, applied_at FROM schema_migrations"
echo "\$ psql -c 'SELECT version_num FROM alembic_version'"
psql "SELECT version_num FROM alembic_version"
} > evidence/schema.txt
{
header
+121 -60
View File
@@ -1,85 +1,126 @@
from datetime import datetime
from uuid import UUID
from asyncpg import Record
from sqlalchemy import (
CheckConstraint,
DateTime,
ForeignKey,
Index,
LargeBinary,
UniqueConstraint,
delete,
literal,
select,
)
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.orm import Mapped, mapped_column
from messenger.identity.domain.errors import UsernameAlreadyTaken
from messenger.identity.domain.models import Session, User
from messenger.identity.domain.values import DisplayName, Username
from messenger.shared.infrastructure.postgres import Connection, Database, PostgresUnitOfWork
INSERT_USER = """
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (username) DO NOTHING
RETURNING true
"""
USER_BY_ID = """
SELECT id, username, display_name, password_hash, created_at FROM users WHERE id = $1
"""
USER_BY_USERNAME = """
SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1
"""
INSERT_SESSION = """
WITH expired AS (DELETE FROM sessions WHERE user_id = $2 AND expires_at <= $3)
INSERT INTO sessions (token_hash, user_id, created_at, expires_at) VALUES ($1, $2, $3, $4)
"""
DELETE_SESSION = "DELETE FROM sessions WHERE token_hash = $1"
ACTIVE_SESSION = """
SELECT token_hash, user_id, created_at, expires_at
FROM sessions
WHERE token_hash = $1 AND expires_at > $2
"""
from messenger.shared.infrastructure.postgres import (
Base,
Database,
DatabaseSession,
PostgresUnitOfWork,
)
def user_of(row: Record | None) -> User | None:
class UserRow(Base):
__tablename__ = "users"
__table_args__ = (
UniqueConstraint("username", name="users_username_key"),
CheckConstraint("username ~ '^[a-z0-9_]{3,32}$'", name="users_username_format"),
CheckConstraint(
"char_length(display_name) BETWEEN 1 AND 100", name="users_display_name_check"
),
CheckConstraint("password_hash LIKE '$argon2id$%'", name="users_password_hash_check"),
)
id: Mapped[UUID] = mapped_column(primary_key=True)
username: Mapped[str]
display_name: Mapped[str]
password_hash: Mapped[str]
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
class SessionRow(Base):
__tablename__ = "sessions"
__table_args__ = (
CheckConstraint("octet_length(token_hash) = 32", name="sessions_token_hash_check"),
CheckConstraint("expires_at > created_at", name="sessions_check"),
Index("sessions_user_idx", "user_id"),
)
token_hash: Mapped[bytes] = mapped_column(LargeBinary, primary_key=True)
user_id: Mapped[UUID] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
def user_of(row: UserRow | None) -> User | None:
if row is None:
return None
return User(
id=row["id"],
username=Username(row["username"]),
display_name=DisplayName(row["display_name"]),
created_at=row["created_at"],
password_hash=row["password_hash"],
id=row.id,
username=Username(row.username),
display_name=DisplayName(row.display_name),
created_at=row.created_at,
password_hash=row.password_hash,
)
class PostgresUserRepository:
__slots__ = ("_connection",)
__slots__ = ("_session",)
def __init__(self, connection: Connection) -> None:
self._connection = connection
def __init__(self, session: DatabaseSession) -> None:
self._session = session
async def add(self, user: User) -> None:
inserted = await self._connection.fetchval(
INSERT_USER,
user.id,
user.username.value,
user.display_name.value,
user.password_hash,
user.created_at,
statement = (
insert(UserRow)
.values(
id=user.id,
username=user.username.value,
display_name=user.display_name.value,
password_hash=user.password_hash,
created_at=user.created_at,
)
.on_conflict_do_nothing(index_elements=["username"])
.returning(literal(True))
)
inserted = (await self._session.execute(statement)).scalar_one_or_none()
if inserted is None:
raise UsernameAlreadyTaken("username уже занят")
class PostgresSessionRepository:
__slots__ = ("_connection",)
__slots__ = ("_session",)
def __init__(self, connection: Connection) -> None:
self._connection = connection
def __init__(self, session: DatabaseSession) -> None:
self._session = session
async def add(self, session: Session) -> None:
await self._connection.execute(
INSERT_SESSION,
session.token_hash,
session.user_id,
session.created_at,
session.expires_at,
expired = (
delete(SessionRow)
.where(
SessionRow.user_id == session.user_id, SessionRow.expires_at <= session.created_at
)
.cte("expired")
)
await self._session.execute(
insert(SessionRow)
.values(
token_hash=session.token_hash,
user_id=session.user_id,
created_at=session.created_at,
expires_at=session.expires_at,
)
.add_cte(expired)
)
async def remove(self, token_hash: bytes) -> None:
await self._connection.execute(DELETE_SESSION, token_hash)
await self._session.execute(delete(SessionRow).where(SessionRow.token_hash == token_hash))
class PostgresIdentityUnitOfWork(PostgresUnitOfWork):
@@ -87,11 +128,11 @@ class PostgresIdentityUnitOfWork(PostgresUnitOfWork):
@property
def users(self) -> PostgresUserRepository:
return PostgresUserRepository(self.connection)
return PostgresUserRepository(self.session)
@property
def sessions(self) -> PostgresSessionRepository:
return PostgresSessionRepository(self.connection)
return PostgresSessionRepository(self.session)
class PostgresUserDirectory:
@@ -101,12 +142,18 @@ class PostgresUserDirectory:
self._database = database
async def find(self, user_id: UUID) -> User | None:
async with self._database.connection() as connection:
return user_of(await connection.fetchrow(USER_BY_ID, user_id))
async with self._database.session() as session:
row = (
await session.execute(select(UserRow).where(UserRow.id == user_id))
).scalar_one_or_none()
return user_of(row)
async def find_by_username(self, username: str) -> User | None:
async with self._database.connection() as connection:
return user_of(await connection.fetchrow(USER_BY_USERNAME, username))
async with self._database.session() as session:
row = (
await session.execute(select(UserRow).where(UserRow.username == username))
).scalar_one_or_none()
return user_of(row)
class PostgresSessionDirectory:
@@ -116,6 +163,20 @@ class PostgresSessionDirectory:
self._database = database
async def find(self, token_hash: bytes, now: datetime) -> Session | None:
async with self._database.connection() as connection:
row = await connection.fetchrow(ACTIVE_SESSION, token_hash, now)
return None if row is None else Session(**dict(row))
async with self._database.session() as session:
row = (
await session.execute(
select(SessionRow).where(
SessionRow.token_hash == token_hash,
SessionRow.expires_at > now,
)
)
).scalar_one_or_none()
if row is None:
return None
return Session(
token_hash=row.token_hash,
user_id=row.user_id,
created_at=row.created_at,
expires_at=row.expires_at,
)
+284 -112
View File
@@ -1,9 +1,34 @@
from collections.abc import Sequence
from dataclasses import replace
from datetime import datetime
from datetime import datetime, timedelta
from typing import cast
from uuid import UUID
from asyncpg import ForeignKeyViolationError, Record
from sqlalchemy import (
CheckConstraint,
DateTime,
ForeignKey,
ForeignKeyConstraint,
Index,
LargeBinary,
RowMapping,
Select,
SmallInteger,
Table,
bindparam,
func,
insert,
literal,
select,
tuple_,
update,
)
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.dialects.postgresql import UUID as PGUUID
from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.sql.elements import Label
from messenger.messaging.domain.errors import InvalidChatData
from messenger.messaging.domain.keys import HistoryKey
@@ -11,86 +36,158 @@ from messenger.messaging.domain.models import Chat, Message, Receipt
from messenger.messaging.domain.values import ChatTitle, MessageText
from messenger.shared.application.errors import Unavailable
from messenger.shared.infrastructure.postgres import (
Connection,
Base,
Database,
DatabaseSession,
EventSource,
PostgresUnitOfWork,
)
INSERT_CHAT = "INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)"
INSERT_MEMBERS = """
INSERT INTO chat_members (chat_id, user_id, position, chat_created_at)
SELECT $1, member.user_id, member.position, $3
FROM unnest($2::uuid[]) WITH ORDINALITY AS member (user_id, position)
"""
POST_MESSAGE = """
WITH chat AS (
SELECT c.id, GREATEST($5::timestamptz, c.last_message_at + interval '1 microsecond') AS stamp
FROM chats c JOIN chat_members m ON m.chat_id = c.id AND m.user_id = $3
WHERE c.id = $2
FOR UPDATE OF c
), receipt AS (
INSERT INTO idempotency_keys (chat_id, user_id, key, fingerprint, message_id, created_at)
SELECT id, $3, $6, $7, $1, stamp FROM chat
ON CONFLICT (chat_id, user_id, key) DO UPDATE
SET fingerprint = EXCLUDED.fingerprint,
message_id = EXCLUDED.message_id,
created_at = EXCLUDED.created_at
WHERE idempotency_keys.created_at <= $8
RETURNING created_at
), message AS (
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT $1, $2, $3, $4, created_at FROM receipt
RETURNING created_at
), touched AS (
UPDATE chats SET last_message_at = message.created_at FROM message WHERE chats.id = $2
)
SELECT EXISTS (SELECT FROM chat) AS member, (SELECT created_at FROM message) AS created_at
"""
RECEIPT = """
SELECT k.fingerprint, m.id, m.chat_id, m.sender_id, m.text, m.created_at
FROM idempotency_keys k JOIN messages m ON m.id = k.message_id
WHERE k.chat_id = $1 AND k.user_id = $2 AND k.key = $3 AND k.created_at > $4
"""
CHAT_OF_MEMBER = """
SELECT c.id, c.title, c.created_at,
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY position) AS member_ids
FROM chat_members m JOIN chats c ON c.id = m.chat_id
WHERE m.chat_id = $1 AND m.user_id = $2
"""
CHATS_FIRST = """
SELECT c.id, c.title, c.created_at,
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY position) AS member_ids
FROM chat_members m JOIN chats c ON c.id = m.chat_id
WHERE m.user_id = $1
ORDER BY m.chat_created_at, m.chat_id
LIMIT $2
"""
CHATS_AFTER = """
SELECT c.id, c.title, c.created_at,
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY position) AS member_ids
FROM chat_members m JOIN chats c ON c.id = m.chat_id
WHERE m.user_id = $1 AND (m.chat_created_at, m.chat_id) > ($2, $3)
ORDER BY m.chat_created_at, m.chat_id
LIMIT $4
"""
HISTORY_FIRST = """
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = $1
ORDER BY created_at, id
LIMIT $2
"""
HISTORY_AFTER = """
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
ORDER BY created_at, id
LIMIT $4
"""
FOREIGN_KEY_VIOLATED = "23503"
def chat_of(row: Record) -> Chat:
class ChatRow(Base):
__tablename__ = "chats"
__table_args__ = (
CheckConstraint("char_length(title) BETWEEN 1 AND 100", name="chats_title_check"),
)
id: Mapped[UUID] = mapped_column(primary_key=True)
title: Mapped[str]
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
last_message_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
class ChatMemberRow(Base):
__tablename__ = "chat_members"
__table_args__ = (
CheckConstraint("position BETWEEN 1 AND 100", name="chat_members_position_check"),
Index("chat_members_user_idx", "user_id", "chat_created_at", "chat_id"),
)
chat_id: Mapped[UUID] = mapped_column(
ForeignKey("chats.id", ondelete="CASCADE"), primary_key=True
)
user_id: Mapped[UUID] = mapped_column(ForeignKey("users.id"), primary_key=True)
position: Mapped[int] = mapped_column(SmallInteger)
chat_created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
class MessageRow(Base):
__tablename__ = "messages"
__table_args__ = (
CheckConstraint("char_length(text) BETWEEN 1 AND 4000", name="messages_text_check"),
ForeignKeyConstraint(
["chat_id", "sender_id"], ["chat_members.chat_id", "chat_members.user_id"]
),
Index("messages_history_idx", "chat_id", "created_at", "id"),
)
id: Mapped[UUID] = mapped_column(primary_key=True)
chat_id: Mapped[UUID]
sender_id: Mapped[UUID]
text: Mapped[str]
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
class IdempotencyKeyRow(Base):
__tablename__ = "idempotency_keys"
__table_args__ = (
CheckConstraint("key ~ '^[A-Za-z0-9._:-]{1,128}$'", name="idempotency_keys_key_check"),
CheckConstraint(
"octet_length(fingerprint) = 32", name="idempotency_keys_fingerprint_check"
),
ForeignKeyConstraint(
["chat_id", "user_id"], ["chat_members.chat_id", "chat_members.user_id"]
),
)
chat_id: Mapped[UUID] = mapped_column(primary_key=True)
user_id: Mapped[UUID] = mapped_column(primary_key=True)
key: Mapped[str] = mapped_column(primary_key=True)
fingerprint: Mapped[bytes] = mapped_column(LargeBinary)
message_id: Mapped[UUID] = mapped_column(ForeignKey("messages.id", ondelete="CASCADE"))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
def post_message() -> Select:
chats, members = cast(Table, ChatRow.__table__), cast(Table, ChatMemberRow.__table__)
keys, messages = cast(Table, IdempotencyKeyRow.__table__), cast(Table, MessageRow.__table__)
sender = bindparam("sender_id", type_=PGUUID)
chat_id = bindparam("chat_id", type_=PGUUID)
message_id = bindparam("message_id", type_=PGUUID)
chat = (
select(
chats.c.id,
func.greatest(
bindparam("stamp", type_=DateTime(timezone=True)),
chats.c.last_message_at + timedelta(microseconds=1),
).label("stamp"),
)
.join(members, (members.c.chat_id == chats.c.id) & (members.c.user_id == sender))
.where(chats.c.id == chat_id)
.with_for_update(of=chats)
.cte("chat")
)
receipt_insert = pg_insert(keys).from_select(
["chat_id", "user_id", "key", "fingerprint", "message_id", "created_at"],
select(
chat.c.id,
sender,
bindparam("key"),
bindparam("fingerprint", type_=LargeBinary),
message_id,
chat.c.stamp,
),
)
receipt = (
receipt_insert.on_conflict_do_update(
index_elements=[keys.c.chat_id, keys.c.user_id, keys.c.key],
set_={
name: receipt_insert.excluded[name]
for name in ("fingerprint", "message_id", "created_at")
},
where=keys.c.created_at <= bindparam("since", type_=DateTime(timezone=True)),
)
.returning(keys.c.created_at)
.cte("receipt")
)
message = (
insert(messages)
.from_select(
["id", "chat_id", "sender_id", "text", "created_at"],
select(message_id, chat_id, sender, bindparam("text"), receipt.c.created_at),
)
.returning(messages.c.chat_id, messages.c.created_at)
.cte("message")
)
touched = (
update(chats)
.where(chats.c.id == message.c.chat_id)
.values(last_message_at=message.c.created_at)
.cte("touched")
)
return select(
select(chat.c.id).exists().label("member"),
select(message.c.created_at).scalar_subquery().label("created_at"),
).add_cte(touched)
POST_MESSAGE = post_message()
def member_ids() -> Label[Sequence[UUID]]:
return func.array(
select(ChatMemberRow.user_id)
.where(ChatMemberRow.chat_id == ChatRow.id)
.order_by(ChatMemberRow.position)
.correlate(ChatRow)
.scalar_subquery(),
type_=ARRAY(PGUUID(as_uuid=True)),
).label("member_ids")
def chat_of(row: RowMapping) -> Chat:
return Chat(
chat_id=row["id"],
title=ChatTitle(row["title"]),
@@ -99,7 +196,7 @@ def chat_of(row: Record) -> Chat:
)
def message_of(row: Record) -> Message:
def message_of(row: RowMapping) -> Message:
return Message(
id=row["id"],
chat_id=row["chat_id"],
@@ -114,19 +211,32 @@ def page[ItemT](rows: Sequence[ItemT], limit: int) -> tuple[list[ItemT], bool]:
class PostgresChatRepository:
__slots__ = ("_connection", "_seen")
__slots__ = ("_seen", "_session")
def __init__(self, connection: Connection, seen: list[EventSource]) -> None:
self._connection = connection
def __init__(self, session: DatabaseSession, seen: list[EventSource]) -> None:
self._session = session
self._seen = seen
async def add(self, chat: Chat) -> None:
await self._connection.execute(INSERT_CHAT, chat.id, chat.title.value, chat.created_at)
await self._session.execute(
insert(ChatRow).values(id=chat.id, title=chat.title.value, created_at=chat.created_at)
)
try:
await self._connection.execute(
INSERT_MEMBERS, chat.id, list(chat.member_ids), chat.created_at
await self._session.execute(
insert(ChatMemberRow),
[
{
"chat_id": chat.id,
"user_id": member_id,
"position": position,
"chat_created_at": chat.created_at,
}
for position, member_id in enumerate(chat.member_ids, 1)
],
)
except ForeignKeyViolationError as error:
except IntegrityError as error:
if getattr(error.orig, "sqlstate", None) != FOREIGN_KEY_VIOLATED:
raise
raise InvalidChatData("поле member_ids содержит неизвестного пользователя") from error
self._seen.append(chat)
@@ -141,23 +251,54 @@ class PostgresMessageLog:
self, message: Message, key: str, fingerprint: bytes, since: datetime
) -> Receipt | None:
chat_id, sender_id = message.chat_id, message.sender_id
async with self._database.connection() as connection:
row = await connection.fetchrow(
POST_MESSAGE,
message.id,
chat_id,
sender_id,
message.text.value,
message.created_at,
key,
fingerprint,
since,
async with self._database.session() as session:
row = (
(
await session.execute(
POST_MESSAGE,
{
"message_id": message.id,
"chat_id": chat_id,
"sender_id": sender_id,
"text": message.text.value,
"stamp": message.created_at,
"key": key,
"fingerprint": fingerprint,
"since": since,
},
)
)
.mappings()
.first()
)
if row is None or not row["member"]:
return None
if row["created_at"] is not None:
await session.commit()
return Receipt(key, fingerprint, replace(message, created_at=row["created_at"]))
known = await connection.fetchrow(RECEIPT, chat_id, sender_id, key, since)
known = (
(
await session.execute(
select(
IdempotencyKeyRow.fingerprint,
MessageRow.id,
MessageRow.chat_id,
MessageRow.sender_id,
MessageRow.text,
MessageRow.created_at,
)
.join(MessageRow, MessageRow.id == IdempotencyKeyRow.message_id)
.where(
IdempotencyKeyRow.chat_id == chat_id,
IdempotencyKeyRow.user_id == sender_id,
IdempotencyKeyRow.key == key,
IdempotencyKeyRow.created_at > since,
)
)
)
.mappings()
.first()
)
if known is None:
raise Unavailable("ключ идемпотентности занят незавершённой записью")
return Receipt(key, known["fingerprint"], message_of(known))
@@ -168,7 +309,7 @@ class PostgresMessagingUnitOfWork(PostgresUnitOfWork):
@property
def chats(self) -> PostgresChatRepository:
return PostgresChatRepository(self.connection, self.seen)
return PostgresChatRepository(self.session, self.seen)
class PostgresChatDirectory:
@@ -178,30 +319,61 @@ class PostgresChatDirectory:
self._database = database
async def chat_for_member(self, chat_id: UUID, user_id: UUID) -> Chat | None:
async with self._database.connection() as connection:
row = await connection.fetchrow(CHAT_OF_MEMBER, chat_id, user_id)
async with self._database.session() as session:
row = (
(
await session.execute(
select(ChatRow.id, ChatRow.title, ChatRow.created_at, member_ids())
.select_from(ChatMemberRow)
.join(ChatRow, ChatRow.id == ChatMemberRow.chat_id)
.where(ChatMemberRow.chat_id == chat_id, ChatMemberRow.user_id == user_id)
)
)
.mappings()
.first()
)
return None if row is None else chat_of(row)
async def chats_of(
self, user_id: UUID, *, after: HistoryKey | None, limit: int
) -> tuple[list[Chat], bool]:
async with self._database.connection() as connection:
if after is None:
rows = await connection.fetch(CHATS_FIRST, user_id, limit + 1)
else:
rows = await connection.fetch(
CHATS_AFTER, user_id, after[0], UUID(int=after[1]), limit + 1
)
statement = (
select(ChatRow.id, ChatRow.title, ChatRow.created_at, member_ids())
.select_from(ChatMemberRow)
.join(ChatRow, ChatRow.id == ChatMemberRow.chat_id)
.where(ChatMemberRow.user_id == user_id)
.order_by(ChatMemberRow.chat_created_at, ChatMemberRow.chat_id)
.limit(limit + 1)
)
if after is not None:
statement = statement.where(
tuple_(ChatMemberRow.chat_created_at, ChatMemberRow.chat_id)
> tuple_(literal(after[0]), literal(UUID(int=after[1])))
)
async with self._database.session() as session:
rows = (await session.execute(statement)).mappings().all()
return page([chat_of(row) for row in rows], limit)
async def history(
self, chat_id: UUID, *, after: HistoryKey | None, limit: int
) -> tuple[list[Message], bool]:
async with self._database.connection() as connection:
if after is None:
rows = await connection.fetch(HISTORY_FIRST, chat_id, limit + 1)
else:
rows = await connection.fetch(
HISTORY_AFTER, chat_id, after[0], UUID(int=after[1]), limit + 1
)
statement = (
select(
MessageRow.id,
MessageRow.chat_id,
MessageRow.sender_id,
MessageRow.text,
MessageRow.created_at,
)
.where(MessageRow.chat_id == chat_id)
.order_by(MessageRow.created_at, MessageRow.id)
.limit(limit + 1)
)
if after is not None:
statement = statement.where(
tuple_(MessageRow.created_at, MessageRow.id)
> tuple_(literal(after[0]), literal(UUID(int=after[1])))
)
async with self._database.session() as session:
rows = (await session.execute(statement)).mappings().all()
return page([message_of(row) for row in rows], limit)
-70
View File
@@ -1,70 +0,0 @@
import asyncio
import hashlib
from importlib import resources
import asyncpg
from messenger.shared.config import PlatformSettings
from messenger.shared.infrastructure.logging import PLATFORM_FIELDS, StructlogLogger
LOCK_KEY = 20_260_002
JOURNAL = """
CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY,
checksum text NOT NULL,
applied_at timestamptz NOT NULL DEFAULT now()
)
"""
class MigrationChangedError(Exception):
pass
def migrations() -> list[tuple[str, str]]:
folder = resources.files("messenger") / "migrations"
found = (item for item in folder.iterdir() if item.name.endswith(".sql"))
return sorted((item.name.removesuffix(".sql"), item.read_text()) for item in found)
async def migrate(dsn: str) -> list[str]:
connection = await asyncpg.connect(dsn, timeout=10)
try:
await connection.execute("SELECT pg_advisory_lock($1)", LOCK_KEY)
await connection.execute(JOURNAL)
applied = dict(await connection.fetch("SELECT version, checksum FROM schema_migrations"))
done: list[str] = []
for version, sql in migrations():
checksum = hashlib.sha256(sql.encode()).hexdigest()
if version in applied:
if applied[version] != checksum:
raise MigrationChangedError(version)
continue
async with connection.transaction():
await connection.execute(sql)
await connection.execute(
"INSERT INTO schema_migrations (version, checksum) VALUES ($1, $2)",
version,
checksum,
)
done.append(version)
return done
finally:
await connection.close()
def main() -> None:
settings = PlatformSettings()
logger = StructlogLogger(level=settings.log_level, allowed_fields=PLATFORM_FIELDS | {"version"})
try:
done = asyncio.run(migrate(settings.database_url.get_secret_value()))
except MigrationChangedError as error:
logger.error("migration.changed", version=str(error))
raise SystemExit(1) from None
for version in done:
logger.info("migration.applied", version=version)
logger.info("migration.completed", reason="up to date" if not done else "applied")
if __name__ == "__main__":
main()
+64 -45
View File
@@ -1,32 +1,45 @@
import asyncio
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import Any, Protocol
from typing import ClassVar, Protocol
import asyncpg
from sqlalchemy import Text, make_url, select
from sqlalchemy.exc import DBAPIError, IntegrityError, InterfaceError, OperationalError
from sqlalchemy.exc import TimeoutError as PoolTimeout
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase
from messenger.shared.application.errors import Unavailable
from messenger.shared.domain.events import DomainEvent
FAILURES = (
OSError,
asyncpg.InterfaceError,
asyncpg.PostgresConnectionError,
asyncpg.exceptions.OperatorInterventionError,
asyncpg.exceptions.InsufficientResourcesError,
asyncpg.exceptions.LockNotAvailableError,
)
FAILURES = (OSError, InterfaceError, OperationalError, PoolTimeout, TimeoutError)
PING_TIMEOUT_SECONDS = 0.4
type Connection = asyncpg.Connection
type DatabaseSession = AsyncSession
class EventSource(Protocol):
def collect_events(self) -> list[DomainEvent]: ...
class Base(DeclarativeBase):
type_annotation_map: ClassVar = {str: Text}
def unavailable(error: BaseException) -> bool:
if isinstance(error, IntegrityError):
return False
if isinstance(error, FAILURES):
return True
if isinstance(error, DBAPIError) and error.connection_invalidated:
return True
state = getattr(error.orig if isinstance(error, DBAPIError) else error, "sqlstate", None)
return isinstance(state, str) and (state.startswith(("08", "53", "57")) or state == "55P03")
class Database:
__slots__ = ("_acquire_timeout", "_pool")
__slots__ = ("_engine", "_sessions")
def __init__(
self,
@@ -37,75 +50,81 @@ class Database:
acquire_timeout: float,
command_timeout: float,
) -> None:
self._acquire_timeout = acquire_timeout
self._pool = asyncpg.create_pool(
dsn,
min_size=0,
max_size=max_size,
timeout=connect_timeout,
command_timeout=command_timeout,
max_inactive_connection_lifetime=60,
server_settings={
"statement_timeout": str(int(command_timeout * 1000)),
"lock_timeout": str(int(command_timeout * 1000)),
"idle_in_transaction_session_timeout": "10000",
self._engine = create_async_engine(
make_url(dsn).set(drivername="postgresql+asyncpg"),
pool_size=max_size,
max_overflow=0,
pool_timeout=acquire_timeout,
pool_recycle=60,
hide_parameters=True,
connect_args={
"timeout": connect_timeout,
"command_timeout": command_timeout,
"server_settings": {
"statement_timeout": str(int(command_timeout * 1000)),
"lock_timeout": str(int(command_timeout * 1000)),
"idle_in_transaction_session_timeout": "10000",
},
},
)
self._sessions = async_sessionmaker(self._engine, expire_on_commit=False)
async def open(self) -> None:
await self._pool
pass
async def close(self) -> None:
await self._pool.close()
await self._engine.dispose()
@asynccontextmanager
async def connection(self, wait: float | None = None) -> AsyncIterator[Connection]:
async def session(self) -> AsyncIterator[DatabaseSession]:
try:
async with self._pool.acquire(timeout=wait or self._acquire_timeout) as connection:
yield connection
except FAILURES as error:
async with self._sessions() as session:
yield session
except Exception as error:
if not unavailable(error):
raise
raise Unavailable("PostgreSQL недоступен") from error
async def ping(self) -> None:
async with self.connection(PING_TIMEOUT_SECONDS) as connection:
await connection.fetchval("SELECT 1", timeout=PING_TIMEOUT_SECONDS)
try:
async with asyncio.timeout(PING_TIMEOUT_SECONDS):
async with self.session() as session:
await session.execute(select(1))
except TimeoutError as error:
raise Unavailable("PostgreSQL недоступен") from error
class PostgresUnitOfWork:
__slots__ = ("_committed", "_connection", "_database", "_events", "_transaction", "seen")
__slots__ = ("_committed", "_database", "_events", "_session", "seen")
def __init__(self, database: Database) -> None:
self._database = database
self._connection: Connection | None = None
self._transaction: Any = None
self._session: DatabaseSession | None = None
self._committed = False
self._events: list[DomainEvent] = []
self.seen: list[EventSource] = []
@property
def connection(self) -> Connection:
if self._connection is None:
def session(self) -> DatabaseSession:
if self._session is None:
raise RuntimeError("репозиторий используется вне транзакции")
return self._connection
return self._session
@asynccontextmanager
async def transaction(self) -> AsyncIterator[None]:
async with self._database.connection() as connection:
self._connection = connection
self._transaction = connection.transaction()
await self._transaction.start()
async with self._database.session() as session:
self._session = session
self._committed = False
try:
yield
finally:
if not self._committed:
self._events.clear()
await self._transaction.rollback()
self.seen.clear()
self._connection = None
self._session = None
async def commit(self) -> None:
await self._transaction.commit()
await self.session.commit()
self._committed = True
for source in self.seen:
self._events.extend(source.collect_events())
+13 -14
View File
@@ -1,10 +1,11 @@
import time
from uuid import uuid4
from uuid import UUID, uuid4
import asyncpg
from httpx import AsyncClient
from sqlalchemy import select
from conftest import DATABASE, actor, keyed, make_chat, register
from conftest import actor, keyed, make_chat, register, sql_connection
from messenger.messaging.infrastructure.postgres import ChatRow
async def test_outsider_gets_404_on_chat(client: AsyncClient) -> None:
@@ -106,16 +107,14 @@ async def test_outsider_does_not_wait_for_members_lock(client: AsyncClient) -> N
alice = await register(client, "alice")
eve = await register(client, "eve")
chat = await make_chat(client, alice)
holder = await asyncpg.connect(DATABASE["url"])
try:
async with holder.transaction():
await holder.execute("SELECT 1 FROM chats WHERE id = $1 FOR UPDATE", chat["id"])
started = time.perf_counter()
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages", json={"text": "чужое"}, headers=keyed(eve)
)
elapsed = time.perf_counter() - started
finally:
await holder.close()
async with sql_connection() as holder:
await holder.execute(
select(ChatRow.id).where(ChatRow.id == UUID(chat["id"])).with_for_update()
)
started = time.perf_counter()
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages", json={"text": "чужое"}, headers=keyed(eve)
)
elapsed = time.perf_counter() - started
assert response.status_code == 404
assert elapsed < 0.5
@@ -211,6 +211,16 @@ def sql_tables(zone: str, tables: tuple[str, ...]) -> set[str]:
for node in ast.walk(tree):
if isinstance(node, ast.Constant) and isinstance(node.value, str):
words.update(re.findall(r"\b(?:FROM|JOIN|INTO|UPDATE)\s+(\w+)", node.value))
if (
isinstance(node, ast.Assign)
and any(
isinstance(target, ast.Name) and target.id == "__tablename__"
for target in node.targets
)
and isinstance(node.value, ast.Constant)
and isinstance(node.value.value, str)
):
words.add(node.value.value)
return words & set(tables)
@@ -227,3 +237,11 @@ def test_messaging_does_not_import_identity_at_all() -> None:
for path in modules_under("messaging")
}
assert not {key: value for key, value in borrowed.items() if value}
def test_sqlalchemy_stays_in_infrastructure_and_asyncpg_is_only_a_driver() -> None:
for path in SOURCE.rglob("*.py"):
modules = {module.split(".")[0] for module in imports_of(path)}
assert "asyncpg" not in modules
if "infrastructure" not in path.parts:
assert "sqlalchemy" not in modules
+6 -3
View File
@@ -2,14 +2,16 @@ import asyncio
import time
from datetime import datetime
from hashlib import sha256
from uuid import UUID
import pytest
from redis.asyncio import Redis
from sqlalchemy import select
from conftest import actor, bearer, keyed, make_chat, register, resolve, running_app, scalar
from messenger.identity.application.ports import SessionDirectory
from messenger.identity.domain.models import Session
from messenger.identity.infrastructure.postgres import PostgresSessionRepository
from messenger.identity.infrastructure.postgres import PostgresSessionRepository, SessionRow
from messenger.identity.infrastructure.valkey import CachedSessionDirectory
from messenger.shared.application.errors import Unavailable
@@ -34,8 +36,9 @@ async def test_second_check_is_served_from_cache(valkey: dict[str, str]) -> None
assert (await cache.info("stats"))["keyspace_hits"] == hits + 1
key = key_of(token_of(alice))
stored = str(await cache.get(key))
sql = "SELECT expires_at FROM sessions WHERE user_id = $1::uuid"
expires_at: datetime = await scalar(sql, alice["id"])
expires_at: datetime = await scalar(
select(SessionRow.expires_at).where(SessionRow.user_id == UUID(alice["id"]))
)
assert alice["id"] in stored and token_of(alice) not in stored
assert await cache.pexpiretime(key) <= int(expires_at.timestamp() * 1000)
await cache.aclose()
+15 -6
View File
@@ -1,10 +1,13 @@
import asyncio
from urllib.parse import quote
from uuid import uuid4
from uuid import UUID, uuid4
from httpx import AsyncClient
from sqlalchemy import func, select
from conftest import PASSWORD, actor, keyed, make_chat, new_user, register, running_app, scalar
from messenger.identity.infrastructure.postgres import UserRow
from messenger.messaging.infrastructure.postgres import ChatMemberRow, ChatRow
REGISTRATIONS = 25
@@ -65,8 +68,8 @@ async def test_rejected_registration_leaves_no_trace() -> None:
"/api/v1/users", json={"username": "AB", "display_name": "", "password": PASSWORD}
)
assert invalid.status_code == 400
sql = "SELECT count(*) FROM users WHERE username = $1"
assert await scalar(sql, alice["username"]) == 1
sql = select(func.count()).select_from(UserRow).where(UserRow.username == alice["username"])
assert await scalar(sql) == 1
async def test_failed_chat_creation_rolls_back_both_tables() -> None:
@@ -83,9 +86,15 @@ async def test_failed_chat_creation_rolls_back_both_tables() -> None:
assert rejected.json()["error"]["code"] == "invalid_request"
after = (await client.get("/api/v1/chats?limit=100", headers=actor(alice))).json()
assert after["items"] == before["items"]
assert await scalar("SELECT count(*) FROM chats WHERE title = $1", title) == 0
members = "SELECT count(*) FROM chat_members WHERE user_id = $1::uuid"
assert await scalar(members, alice["id"]) == 0
assert (
await scalar(select(func.count()).select_from(ChatRow).where(ChatRow.title == title)) == 0
)
members = (
select(func.count())
.select_from(ChatMemberRow)
.where(ChatMemberRow.user_id == UUID(alice["id"]))
)
assert await scalar(members) == 0
async def test_rejected_message_does_not_enter_history() -> None:
+11 -12
View File
@@ -5,6 +5,7 @@ import socket
import subprocess
import sys
import time
from pathlib import Path
import httpx
@@ -36,15 +37,9 @@ async def test_draining_replica_is_not_ready_but_alive(client: httpx.AsyncClient
assert (await client.get("/health/ready")).status_code == 200
def free_port() -> int:
with socket.socket() as probe:
probe.bind(("127.0.0.1", 0))
return probe.getsockname()[1]
def status(port: int, path: str) -> int:
try:
return httpx.get(f"http://127.0.0.1:{port}{path}", timeout=1).status_code
return httpx.get(f"http://127.0.0.1:{port}{path}", timeout=1, trust_env=False).status_code
except httpx.TransportError:
return 0
@@ -71,8 +66,8 @@ def begin_registration(port: int) -> tuple[socket.socket, bytes]:
return connection, body[8:]
def test_sigterm_leaves_rotation_then_closes_and_cancels_stuck_requests() -> None:
port = free_port()
def test_sigterm_leaves_rotation_then_closes_and_cancels_stuck_requests(tmp_path: Path) -> None:
port = 18083
settings = {
"HOST": "127.0.0.1",
"PORT": str(port),
@@ -83,16 +78,18 @@ def test_sigterm_leaves_rotation_then_closes_and_cancels_stuck_requests() -> Non
"DRAIN_SECONDS": str(DRAIN),
"SHUTDOWN_TIMEOUT_SECONDS": str(SHUTDOWN),
}
log_path = tmp_path / "gunicorn.log"
log = log_path.open("w")
server = subprocess.Popen(
[sys.executable, *GUNICORN],
env={**os.environ, **settings},
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
stdout=log,
stderr=log,
)
try:
deadline = time.monotonic() + 30
while status(port, "/health/ready") != 200:
assert time.monotonic() < deadline, "gunicorn не стал готов"
assert server.poll() is None and time.monotonic() < deadline, log_path.read_text()
time.sleep(0.2)
pending, rest = begin_registration(port)
stuck, _ = begin_registration(port)
@@ -112,6 +109,8 @@ def test_sigterm_leaves_rotation_then_closes_and_cancels_stuck_requests() -> Non
finally:
if server.poll() is None:
server.kill()
server.wait(timeout=5)
log.close()
print(f"окно: ready/live {during}, порт закрыт через {closed:.2f} с, выход {exited:.2f} с")
print(f"запрос, принятый до SIGTERM и дописанный после закрытия порта: {answer}")
print(f"запрос, тело которого так и не пришло: {cancelled or 'соединение закрыто без ответа'}")
+8 -1
View File
@@ -4,8 +4,10 @@ from uuid import uuid4
import pytest
from httpx import AsyncClient, Response
from sqlalchemy import func, select
from conftest import actor, keyed, make_chat, register, running_app, scalar
from messenger.messaging.infrastructure.postgres import IdempotencyKeyRow
INVALID_KEYS = ["", "k" * 129, "два слова", "a b", "a/b", "ключ"]
@@ -142,4 +144,9 @@ async def test_concurrent_retries_through_two_replicas_store_one_message() -> No
}
assert all(response.json() == responses[0].json() for response in responses)
assert [item["text"] for item in await history(second, chat, alice)] == [text]
assert await scalar("SELECT count(*) FROM idempotency_keys WHERE key = $1", key) == 1
assert (
await scalar(
select(func.count()).select_from(IdempotencyKeyRow).where(IdempotencyKeyRow.key == key)
)
== 1
)
+312 -51
View File
@@ -1,77 +1,338 @@
import asyncpg
import asyncio
import hashlib
import os
import shutil
import sys
from collections.abc import AsyncIterator
from datetime import UTC, datetime, timedelta
from pathlib import Path
from uuid import uuid4
import pytest
from alembic import command
from alembic.autogenerate import compare_metadata
from alembic.migration import MigrationContext
from alembic.script import ScriptDirectory
from alembic.util import CommandError
from sqlalchemy import MetaData, Table, func, insert, inspect, make_url, select, text
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.pool import NullPool
from conftest import DATABASE, scalar
from messenger.migrate import MigrationChangedError, migrate, migrations
from conftest import DATABASE, ROOT, migration_config, sql_connection, upgrade
from messenger.identity.infrastructure.postgres import SessionRow, UserRow
from messenger.messaging.infrastructure.postgres import (
ChatMemberRow,
ChatRow,
IdempotencyKeyRow,
MessageRow,
)
from messenger.shared.infrastructure.postgres import Base
COUNTS = """
SELECT (SELECT count(*) FROM users), (SELECT count(*) FROM sessions),
(SELECT count(*) FROM chats), (SELECT count(*) FROM chat_members),
(SELECT count(*) FROM messages), (SELECT count(*) FROM idempotency_keys)
"""
VERSIONS = ["0001_init", "0002_idempotency_keys"]
TABLES = [UserRow, SessionRow, ChatRow, ChatMemberRow, MessageRow, IdempotencyKeyRow]
async def counts() -> list[int]:
connection = await asyncpg.connect(DATABASE["url"])
@pytest.fixture
async def empty_database(database: str) -> AsyncIterator[str]:
name = f"migration_test_{uuid4().hex}"
url = make_url(database).set(drivername="postgresql+asyncpg")
engine = create_async_engine(url, isolation_level="AUTOCOMMIT", poolclass=NullPool)
try:
return list(await connection.fetchrow(COUNTS))
async with engine.connect() as connection:
await connection.exec_driver_sql(f"CREATE DATABASE {name}")
yield url.set(database=name).render_as_string(hide_password=False)
finally:
await connection.close()
async with engine.connect() as connection:
await connection.exec_driver_sql(f"DROP DATABASE {name} WITH (FORCE)")
await engine.dispose()
async def legacy(dsn: str, versions: int = 2) -> None:
async with sql_connection(dsn) as connection:
await connection.execute(
text(
"CREATE TABLE schema_migrations (version text PRIMARY KEY, checksum text NOT NULL, "
"applied_at timestamptz NOT NULL DEFAULT now())"
)
)
journal = await connection.run_sync(
lambda sync: Table("schema_migrations", MetaData(), autoload_with=sync)
)
for version in VERSIONS[:versions]:
sql = (ROOT / "student-tests" / "fixtures" / "legacy" / f"{version}.sql").read_text()
for statement in sql.split(";"):
if statement.strip():
await connection.execute(text(statement))
await connection.execute(
insert(journal).values(
version=version, checksum=hashlib.sha256(sql.encode()).hexdigest()
)
)
async def seed(dsn: str, versions: int = 2) -> None:
user, chat, message = uuid4(), uuid4(), uuid4()
stamp = datetime.now(UTC)
rows = [
(
UserRow,
{
"id": user,
"username": "legacy_user",
"display_name": "Старые данные",
"password_hash": "$argon2id$legacy",
"created_at": stamp,
},
),
(
SessionRow,
{
"token_hash": b"s" * 32,
"user_id": user,
"created_at": stamp,
"expires_at": stamp + timedelta(days=1),
},
),
(
ChatRow,
{
"id": chat,
"title": "Существующий чат",
"created_at": stamp,
"last_message_at": stamp,
},
),
(
ChatMemberRow,
{"chat_id": chat, "user_id": user, "position": 1, "chat_created_at": stamp},
),
(
MessageRow,
{
"id": message,
"chat_id": chat,
"sender_id": user,
"text": "Сохранить",
"created_at": stamp,
},
),
(
IdempotencyKeyRow,
{
"chat_id": chat,
"user_id": user,
"key": "legacy-key",
"fingerprint": b"f" * 32,
"message_id": message,
"created_at": stamp,
},
),
]
async with sql_connection(dsn) as connection:
for model, row in rows[: 5 if versions == 1 else 6]:
await connection.execute(insert(model).values(**row))
async def contents(dsn: str) -> dict:
async with sql_connection(dsn) as connection:
tables = await connection.run_sync(lambda sync: inspect(sync).get_table_names())
return {
model.__tablename__: (
await connection.execute(
select(model.__table__).order_by(*model.__table__.primary_key)
)
).all()
for model in TABLES
if model.__tablename__ in tables
}
async def revision(dsn: str) -> str | None:
async with sql_connection(dsn) as connection:
return await connection.run_sync(
lambda sync: MigrationContext.configure(sync).get_current_revision()
)
async def test_migrations_are_ordered_and_versioned() -> None:
versions = [version for version, _ in migrations()]
assert versions == sorted(versions)
assert versions[:2] == ["0001_init", "0002_idempotency_keys"]
applied = await scalar("SELECT array_agg(version ORDER BY version) FROM schema_migrations")
assert applied == versions
scripts = ScriptDirectory.from_config(migration_config(DATABASE["url"]))
assert [script.revision for script in reversed(list(scripts.walk_revisions()))] == VERSIONS
assert await revision(DATABASE["url"]) == VERSIONS[-1]
async def test_rerun_changes_nothing() -> None:
before = await counts()
assert await migrate(DATABASE["url"]) == []
assert await counts() == before
async def test_fresh_schema_matches_models(empty_database: str) -> None:
await upgrade(empty_database)
async with sql_connection(empty_database) as connection:
assert (
await connection.run_sync(
lambda sync: compare_metadata(MigrationContext.configure(sync), Base.metadata)
)
== []
)
await asyncio.to_thread(command.check, migration_config(empty_database))
async def test_changed_migration_is_refused() -> None:
connection = await asyncpg.connect(DATABASE["url"])
async def test_rerun_changes_nothing(empty_database: str) -> None:
await upgrade(empty_database)
await seed(empty_database)
before = await contents(empty_database)
await upgrade(empty_database)
assert await contents(empty_database) == before
assert await revision(empty_database) == VERSIONS[-1]
@pytest.mark.parametrize("versions", [1, 2])
async def test_legacy_upgrade_preserves_every_row(empty_database: str, versions: int) -> None:
await legacy(empty_database, versions)
await seed(empty_database, versions)
before = await contents(empty_database)
async with sql_connection(empty_database) as connection:
journal = (
await connection.execute(text("SELECT * FROM schema_migrations ORDER BY version"))
).all()
await upgrade(empty_database)
after = await contents(empty_database)
assert {name: after[name] for name in before} == before
assert await revision(empty_database) == VERSIONS[-1]
async with sql_connection(empty_database) as connection:
assert (
await connection.execute(text("SELECT * FROM schema_migrations ORDER BY version"))
).all() == journal
assert (
await connection.scalar(
text("SELECT count(*) FROM pg_namespace WHERE nspname LIKE 'alembic_verify_%'")
)
== 0
)
await upgrade(empty_database)
assert await contents(empty_database) == after
@pytest.mark.parametrize(
"damage",
[
"DROP INDEX messages_history_idx",
"ALTER TABLE messages DROP CONSTRAINT messages_chat_id_sender_id_fkey",
"ALTER TABLE users DROP CONSTRAINT users_username_format",
"ALTER TABLE users ALTER COLUMN display_name TYPE varchar",
"ALTER TABLE sessions ALTER COLUMN expires_at DROP NOT NULL",
"UPDATE schema_migrations SET checksum = 'tampered' WHERE version = '0001_init'",
"DELETE FROM schema_migrations WHERE version = '0001_init'",
"UPDATE schema_migrations SET version = 'unknown' WHERE version = '0002_idempotency_keys'",
"DROP TABLE schema_migrations",
],
)
async def test_legacy_drift_is_refused_without_stamping(empty_database: str, damage: str) -> None:
await legacy(empty_database)
await seed(empty_database)
before = await contents(empty_database)
async with sql_connection(empty_database) as connection:
await connection.execute(text(damage))
with pytest.raises(RuntimeError, match=r"[Ll]egacy|[Ee]xisting|Unknown"):
await upgrade(empty_database)
assert await revision(empty_database) is None
assert await contents(empty_database) == before
async def test_unknown_revision_is_refused(empty_database: str) -> None:
await upgrade(empty_database)
await seed(empty_database)
before = await contents(empty_database)
async with sql_connection(empty_database) as connection:
await connection.execute(text("UPDATE alembic_version SET version_num = 'unknown'"))
with pytest.raises(CommandError, match="unknown"):
await upgrade(empty_database)
assert await contents(empty_database) == before
assert await revision(empty_database) == "unknown"
@pytest.mark.parametrize("existing", [False, True])
async def test_simultaneous_migration_processes_serialize(
empty_database: str, existing: bool
) -> None:
if existing:
await legacy(empty_database)
await seed(empty_database)
before = await contents(empty_database)
processes = []
try:
original = await connection.fetchval(
"SELECT checksum FROM schema_migrations WHERE version = '0001_init'"
)
await connection.execute(
"UPDATE schema_migrations SET checksum = 'tampered' WHERE version = '0001_init'"
)
with pytest.raises(MigrationChangedError):
await migrate(DATABASE["url"])
await connection.execute(
"UPDATE schema_migrations SET checksum = $1 WHERE version = '0001_init'", original
)
for _ in range(2):
processes.append(
await asyncio.create_subprocess_exec(
sys.executable,
"-m",
"alembic",
"upgrade",
"head",
cwd=ROOT,
env={**os.environ, "DATABASE_URL": empty_database},
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
)
async with asyncio.timeout(30):
output = await asyncio.gather(*(process.communicate() for process in processes))
assert [process.returncode for process in processes] == [0, 0], output
finally:
await connection.close()
for process in processes:
if process.returncode is None:
process.kill()
await process.wait()
after = await contents(empty_database)
assert {name: after[name] for name in before} == before
assert await revision(empty_database) == VERSIONS[-1]
async def test_sender_must_be_member_even_bypassing_api() -> None:
connection = await asyncpg.connect(DATABASE["url"])
try:
with pytest.raises(asyncpg.ForeignKeyViolationError):
with pytest.raises(IntegrityError) as failure:
async with sql_connection() as connection:
await connection.execute(
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) "
"VALUES (gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), 'x', now())"
insert(MessageRow).values(
id=uuid4(), chat_id=uuid4(), sender_id=uuid4(), text="x", created_at=func.now()
)
)
finally:
await connection.close()
assert getattr(failure.value.orig, "sqlstate", None) == "23503"
async def test_key_needs_a_member_and_a_message() -> None:
connection = await asyncpg.connect(DATABASE["url"])
try:
with pytest.raises(asyncpg.ForeignKeyViolationError):
with pytest.raises(IntegrityError) as failure:
async with sql_connection() as connection:
await connection.execute(
"INSERT INTO idempotency_keys "
"(chat_id, user_id, key, fingerprint, message_id, created_at) "
"VALUES (gen_random_uuid(), gen_random_uuid(), 'k-1', "
"sha256('x'), gen_random_uuid(), now())"
insert(IdempotencyKeyRow).values(
chat_id=uuid4(),
user_id=uuid4(),
key="k-1",
fingerprint=b"x" * 32,
message_id=uuid4(),
created_at=func.now(),
)
)
finally:
await connection.close()
assert getattr(failure.value.orig, "sqlstate", None) == "23503"
async def test_failed_revision_rolls_back_ddl_and_version(
empty_database: str, tmp_path: Path
) -> None:
await upgrade(empty_database)
await seed(empty_database)
before = await contents(empty_database)
scripts = tmp_path / "alembic"
shutil.copytree(ROOT / "alembic", scripts, ignore=shutil.ignore_patterns("__pycache__"))
(scripts / "versions" / "0003_failure.py").write_text(
"from alembic import op\n"
"import sqlalchemy as sa\n"
"revision = '0003_failure'\n"
"down_revision = '0002_idempotency_keys'\n"
"def upgrade():\n"
" op.create_table('must_rollback', sa.Column('id', sa.Integer, primary_key=True))\n"
" raise RuntimeError('migration failed')\n"
)
config = migration_config(empty_database)
config.set_main_option("script_location", str(scripts))
with pytest.raises(RuntimeError, match="migration failed"):
await asyncio.to_thread(command.upgrade, config, "head")
assert await revision(empty_database) == VERSIONS[-1]
assert await contents(empty_database) == before
async with sql_connection(empty_database) as connection:
assert not await connection.run_sync(lambda sync: inspect(sync).has_table("must_rollback"))
+177 -5
View File
@@ -1,6 +1,27 @@
import time
from dataclasses import replace
from datetime import UTC, datetime, timedelta
from uuid import UUID, uuid4
from conftest import actor, register, resolve, running_app
import pytest
from sqlalchemy import func, select
from sqlalchemy.exc import DBAPIError, IntegrityError
from conftest import actor, keyed, make_chat, register, resolve, running_app
from messenger.identity.domain.models import Session
from messenger.identity.infrastructure.postgres import (
PostgresIdentityUnitOfWork,
PostgresSessionDirectory,
)
from messenger.messaging.domain.models import Message
from messenger.messaging.domain.values import MessageText
from messenger.messaging.infrastructure.postgres import (
ChatRow,
IdempotencyKeyRow,
PostgresMessageLog,
)
from messenger.shared.application.errors import Unavailable
from messenger.shared.domain.events import DomainEvent
from messenger.shared.infrastructure.postgres import Database
@@ -8,7 +29,8 @@ async def test_exhausted_pool_answers_503_in_bounded_time() -> None:
async with running_app(db_pool_max_size=1, db_acquire_timeout_seconds=0.3) as http:
alice = await register(http, "alice")
database = await resolve(http, Database)
async with database.connection():
async with database.session() as session:
await session.execute(select(1))
started = time.perf_counter()
starved = await http.get("/api/v1/users/me", headers=actor(alice))
elapsed = time.perf_counter() - started
@@ -22,6 +44,156 @@ async def test_exhausted_pool_answers_503_in_bounded_time() -> None:
async def test_statement_timeout_is_set_on_connections() -> None:
async with running_app(db_command_timeout_seconds=1.5) as http:
database = await resolve(http, Database)
async with database.connection() as connection:
assert await connection.fetchval("SHOW statement_timeout") == "1500ms"
assert await connection.fetchval("SHOW lock_timeout") == "1500ms"
async with database.session() as session:
statement_timeout = await session.scalar(
select(func.current_setting("statement_timeout"))
)
lock_timeout = await session.scalar(select(func.current_setting("lock_timeout")))
idle_timeout = await session.scalar(
select(func.current_setting("idle_in_transaction_session_timeout"))
)
assert statement_timeout == "1500ms"
assert lock_timeout == "1500ms"
assert idle_timeout == "10s"
async def test_idle_session_does_not_acquire_connection() -> None:
async with running_app(db_pool_max_size=1) as http:
database = await resolve(http, Database)
async with database.session(), database.session() as active:
assert await active.scalar(select(1)) == 1
await database.ping()
async def test_readiness_timeout_releases_waiter() -> None:
async with running_app(db_pool_max_size=1, db_acquire_timeout_seconds=2) as http:
database = await resolve(http, Database)
async with database.session() as session:
await session.execute(select(1))
started = time.perf_counter()
response = await http.get("/health/ready")
elapsed = time.perf_counter() - started
assert response.status_code == 503
assert response.json()["error"]["code"] == "unavailable"
assert 0.3 < elapsed < 1
assert (await http.get("/health/ready")).status_code == 200
async def test_server_statement_timeout_returns_connection() -> None:
async with running_app(db_pool_max_size=1, db_command_timeout_seconds=1.5) as http:
database = await resolve(http, Database)
with pytest.raises(Unavailable) as failure:
async with database.session() as session:
await session.execute(select(func.set_config("statement_timeout", "100ms", True)))
await session.execute(select(func.pg_sleep(2)))
assert isinstance(failure.value.__cause__, DBAPIError)
assert getattr(failure.value.__cause__.orig, "sqlstate", None) == "57014"
await database.ping()
@pytest.mark.parametrize("commit", [False, True])
async def test_unit_of_work_persists_sessions_and_events_only_on_commit(commit: bool) -> None:
async with running_app(db_pool_max_size=1) as http:
alice = await register(http, "alice")
database = await resolve(http, Database)
uow = PostgresIdentityUnitOfWork(database)
now = datetime.now(UTC)
_, session = Session.issue(user_id=UUID(alice["id"]), issued_at=now, ttl=timedelta(hours=1))
event = DomainEvent()
async with uow.transaction():
await uow.sessions.add(session)
uow.record(event)
if commit:
await uow.commit()
stored = await PostgresSessionDirectory(database).find(session.token_hash, now)
assert stored == (session if commit else None)
assert uow.collect_new_events() == ([event] if commit else [])
assert uow.collect_new_events() == []
with pytest.raises(RuntimeError, match="вне транзакции"):
_ = uow.session
async def test_integrity_failure_rolls_back_and_keeps_pool_usable() -> None:
async with running_app(db_pool_max_size=1) as http:
database = await resolve(http, Database)
uow = PostgresIdentityUnitOfWork(database)
_, session = Session.issue(
user_id=uuid4(), issued_at=datetime.now(UTC), ttl=timedelta(hours=1)
)
with pytest.raises(IntegrityError) as failure:
async with uow.transaction():
uow.record(DomainEvent())
await uow.sessions.add(session)
await uow.commit()
assert getattr(failure.value.orig, "sqlstate", None) == "23503"
assert uow.collect_new_events() == []
assert uow.seen == []
await database.ping()
@pytest.mark.parametrize(
("command_timeout", "request_timeout"), [(0.15, 5), (1.5, 0.3)], ids=["database", "request"]
)
async def test_blocked_message_times_out_without_taking_key(
command_timeout: float, request_timeout: float
) -> None:
async with running_app(
db_command_timeout_seconds=command_timeout, request_timeout_seconds=request_timeout
) as http:
alice = await register(http, "alice")
chat = await make_chat(http, alice)
database = await resolve(http, Database)
headers = keyed(alice)
path = f"/api/v1/chats/{chat['id']}/messages"
async with database.session() as session:
await session.execute(
select(ChatRow.id).where(ChatRow.id == UUID(chat["id"])).with_for_update()
)
started = time.perf_counter()
blocked = await http.post(path, json={"text": "повтор"}, headers=headers)
assert time.perf_counter() - started < 2
assert blocked.status_code == 503
assert blocked.json()["error"]["code"] == "unavailable"
recovered = await http.post(path, json={"text": "повтор"}, headers=headers)
replay = await http.post(path, json={"text": "повтор"}, headers=headers)
history = await http.get(path, headers=actor(alice))
assert recovered.status_code == replay.status_code == 201
assert replay.json() == recovered.json()
assert history.json()["items"] == [recovered.json()]
async def test_message_integrity_failure_rolls_back_receipt_and_timestamp() -> None:
async with running_app() as http:
alice = await register(http, "alice")
chat = await make_chat(http, alice)
database = await resolve(http, Database)
log = PostgresMessageLog(database)
now = datetime.now(UTC)
since = now - timedelta(days=1)
message = Message(uuid4(), UUID(chat["id"]), UUID(alice["id"]), MessageText("текст"), now)
fingerprint = b"x" * 32
first = await log.post(message, "first", fingerprint, since)
assert first is not None
with pytest.raises(IntegrityError):
await log.post(message, "retry", fingerprint, since)
async with database.session() as session:
assert (
await session.scalar(
select(ChatRow.last_message_at).where(ChatRow.id == message.chat_id)
)
== first.message.created_at
)
assert (
await session.scalar(
select(func.count())
.select_from(IdempotencyKeyRow)
.where(
IdempotencyKeyRow.chat_id == message.chat_id,
IdempotencyKeyRow.key == "retry",
)
)
== 0
)
retry = await log.post(replace(message, id=uuid4()), "retry", fingerprint, since)
assert retry is not None
assert retry.message.created_at > first.message.created_at
+10 -7
View File
@@ -1,8 +1,11 @@
import asyncio
from datetime import datetime, timedelta
from hashlib import sha256
from uuid import UUID
import pytest
from httpx import AsyncClient
from sqlalchemy import func, select
from conftest import (
PASSWORD,
@@ -16,6 +19,7 @@ from conftest import (
running_app,
scalar,
)
from messenger.identity.infrastructure.postgres import SessionRow, UserRow
BASIC = 'Basic realm="messenger", charset="UTF-8"'
BEARER = 'Bearer realm="messenger"'
@@ -52,7 +56,7 @@ async def test_registration_response_hides_password(client: AsyncClient) -> None
async def test_password_is_stored_as_argon2id(client: AsyncClient) -> None:
alice = await register(client, "alice")
stored = await scalar("SELECT password_hash FROM users WHERE id = $1::uuid", alice["id"])
stored = await scalar(select(UserRow.password_hash).where(UserRow.id == UUID(alice["id"])))
assert stored.startswith("$argon2id$v=19$m=19456,t=2,p=1$")
assert PASSWORD not in stored
@@ -60,10 +64,9 @@ async def test_password_is_stored_as_argon2id(client: AsyncClient) -> None:
async def test_session_stores_only_token_digest(client: AsyncClient) -> None:
alice = await register(client, "alice")
token = actor(alice)["Authorization"].split()[1]
sql = "SELECT count(*) FROM sessions WHERE token_hash = sha256(convert_to($1, 'UTF8'))"
assert await scalar(sql, token) == 1
raw = "SELECT count(*) FROM sessions WHERE encode(token_hash, 'escape') = $1"
assert await scalar(raw, token) == 0
rows = select(func.count()).select_from(SessionRow)
assert await scalar(rows.where(SessionRow.token_hash == sha256(token.encode()).digest())) == 1
assert await scalar(rows.where(SessionRow.token_hash == token.encode())) == 0
async def test_wrong_password_and_unknown_user_look_the_same(client: AsyncClient) -> None:
@@ -154,8 +157,8 @@ async def test_expired_sessions_are_purged_on_next_login() -> None:
await login(client, body["username"])
await asyncio.sleep(1.2)
await login(client, body["username"])
sql = "SELECT count(*) FROM sessions WHERE user_id = $1::uuid"
assert await scalar(sql, user["id"]) == 1
sql = select(func.count()).select_from(SessionRow).where(SessionRow.user_id == UUID(user["id"]))
assert await scalar(sql) == 1
async def test_chat_routes_require_bearer(client: AsyncClient) -> None:
+51 -12
View File
@@ -1,5 +1,6 @@
import asyncio
import re
import socket
import subprocess
import time
from base64 import b64encode
@@ -9,15 +10,19 @@ from pathlib import Path
from typing import Any
from uuid import uuid4
import asyncpg
import pytest
from alembic import command
from alembic.config import Config
from fastapi import FastAPI
from httpx import ASGITransport, AsyncClient
from sqlalchemy import make_url
from sqlalchemy.exc import DBAPIError
from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine
from sqlalchemy.pool import NullPool
from messenger.identity.config import IdentitySettings
from messenger.main import create_app
from messenger.messaging.config import MessagingSettings
from messenger.migrate import migrate
from messenger.shared.config import PlatformSettings
from messenger.shared.entrypoints.config import TransportSettings
@@ -36,18 +41,53 @@ def docker(*args: str) -> str:
return done.stdout.strip()
def migration_config(dsn: str) -> Config:
config = Config(str(ROOT / "alembic.ini"))
config.attributes["database_url"] = dsn
return config
async def upgrade(dsn: str, revision: str = "head") -> None:
await asyncio.to_thread(command.upgrade, migration_config(dsn), revision)
async def migrated(dsn: str) -> None:
deadline = time.monotonic() + STARTUP_SECONDS
while True:
try:
await migrate(dsn)
await upgrade(dsn)
return
except OSError, asyncpg.PostgresError, asyncpg.InterfaceError:
except OSError, DBAPIError:
if time.monotonic() > deadline:
raise
await asyncio.sleep(0.5)
@asynccontextmanager
async def sql_connection(dsn: str | None = None) -> AsyncIterator[AsyncConnection]:
engine = create_async_engine(
make_url(dsn or DATABASE["url"]).set(drivername="postgresql+asyncpg"),
poolclass=NullPool,
hide_parameters=True,
)
try:
async with engine.begin() as connection:
yield connection
finally:
await engine.dispose()
def free_port() -> int:
for port in range(23000, 24000):
with socket.socket() as probe:
try:
probe.bind(("127.0.0.1", port))
return port
except OSError:
continue
raise RuntimeError("No free test port in 23000–23999")
@pytest.fixture(autouse=True)
def database_for_api(request: pytest.FixtureRequest) -> None:
if "api" in request.node.path.parts:
@@ -76,7 +116,7 @@ def answering(name: str, *probe: str) -> bool:
@pytest.fixture(scope="session")
def valkey() -> Iterator[dict[str, str]]:
name = f"mtusi-lab3-test-valkey-{uuid4().hex[:8]}"
container(name, "-p", "127.0.0.1::6379", image(VALKEY_IMAGE))
container(name, "-p", f"127.0.0.1:{free_port()}:6379", image(VALKEY_IMAGE))
try:
deadline = time.monotonic() + STARTUP_SECONDS
while not answering(name, "valkey-cli", "ping"):
@@ -92,7 +132,9 @@ def database() -> Iterator[str]:
name = f"mtusi-lab3-test-{uuid4().hex[:8]}"
tuning = ["-c", "fsync=off", "-c", "synchronous_commit=off", "-c", "full_page_writes=off"]
environment = ["-e", "POSTGRES_PASSWORD=test", "-e", "POSTGRES_DB=messenger"]
container(name, *environment, "-p", "127.0.0.1::5432", image(POSTGRES_IMAGE), *tuning)
container(
name, *environment, "-p", f"127.0.0.1:{free_port()}:5432", image(POSTGRES_IMAGE), *tuning
)
try:
dsn = f"postgresql://postgres:test@127.0.0.1:{published(name, 5432)}/messenger"
asyncio.run(migrated(dsn))
@@ -147,12 +189,9 @@ async def client() -> AsyncIterator[AsyncClient]:
yield http
async def scalar(sql: str, *args: Any) -> Any:
connection = await asyncpg.connect(DATABASE["url"])
try:
return await connection.fetchval(sql, *args)
finally:
await connection.close()
async def scalar(statement: Any) -> Any:
async with sql_connection() as connection:
return await connection.scalar(statement)
def basic(username: str, password: str) -> dict[str, str]:
Generated
+126
View File
@@ -2,6 +2,20 @@ version = 1
revision = 5
requires-python = "==3.14.*"
[[package]]
name = "alembic"
version = "1.16.5"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "mako" },
{ name = "sqlalchemy" },
{ name = "typing-extensions" },
]
sdist = { url = "https://files.pythonhosted.org/packages/9a/ca/4dc52902cf3491892d464f5265a81e9dff094692c8a049a3ed6a05fe7ee8/alembic-1.16.5.tar.gz", hash = "sha256:a88bb7f6e513bd4301ecf4c7f2206fe93f9913f9b48dac3b78babde2d6fe765e", size = 1969868, upload-time = "2025-08-27T18:02:05.668Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/39/4a/4c61d4c84cfd9befb6fa08a702535b27b21fff08c946bc2f6139decbf7f7/alembic-1.16.5-py3-none-any.whl", hash = "sha256:e845dfe090c5ffa7b92593ae6687c5cb1a101e91fa53868497dbd79847f9dbe3", size = 247355, upload-time = "2025-08-27T18:02:07.37Z" },
]
[[package]]
name = "annotated-doc"
version = "0.0.5"
@@ -261,6 +275,33 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/cb/03/10388a42375ee7e4ac9b94eb2c5c569c8b5795e377e701c9ac3ad63de890/fastapi-0.141.1-py3-none-any.whl", hash = "sha256:bfb91aa2d334c61cb35ba9a116fc123b3d3df31640b801cf57a7a78ec3f603b3", size = 131954, upload-time = "2026-07-29T17:18:04.364Z" },
]
[[package]]
name = "greenlet"
version = "3.5.6"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/3e/6e/0091f175ccd02b02bc8811bbcbcc6ac2e980be116e3b2f7a736ca322bf84/greenlet-3.5.6.tar.gz", hash = "sha256:8e67c43bdfc88d5fee6db0d3e40175b362fc95fb85f0412d233b9b203c53a575", size = 207653, upload-time = "2026-09-14T15:42:51.806Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/66/c0/d254544ae2b8bdd311aef000fafc02828c2771b17d994b3075620ea7cc6e/greenlet-3.5.6-cp314-cp314-macosx_11_0_universal2.whl", hash = "sha256:8cddea1b8339451c2fb3388e138347b6126744f33b611bdb55b7357361cfef46", size = 295221, upload-time = "2026-09-14T14:25:11.583Z" },
{ url = "https://files.pythonhosted.org/packages/18/18/eb54be16b9cc3971e09ca5b73334e1b8c804a4630d9addaaf218a4fe300f/greenlet-3.5.6-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c59acfa8eb73a1e0d484392dc002bdf001fd4ce73394e0132df3d1ab6093d7cb", size = 660992, upload-time = "2026-09-14T15:12:04.876Z" },
{ url = "https://files.pythonhosted.org/packages/8f/b4/e193efe65671dcf294bc51fcc59efb52d154adf8612c4ea016da0d2c486c/greenlet-3.5.6-cp314-cp314-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a3b4a01c6da07ef9f80d4fe8933b994bc99747bcea3eab0330a9c34d3c12655b", size = 673428, upload-time = "2026-09-14T15:20:45.756Z" },
{ url = "https://files.pythonhosted.org/packages/fd/21/631bb45fafde1dca782152377c0676d182ec924820064047f533a3627b28/greenlet-3.5.6-cp314-cp314-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:dd0b83bed3405b586a3133629f1d1a5bc7bfd64822a3b7ab342bdc68e6dbc61b", size = 677688, upload-time = "2026-09-14T15:25:09.279Z" },
{ url = "https://files.pythonhosted.org/packages/45/ac/28fa7a9e50f2859466214c4ac584d776db52c1604ad4dd158960a5af2a1f/greenlet-3.5.6-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9a09d59bef1db94f384b5bcc2d523694d338f3df6b757aeeaf7baca5d0c0be88", size = 670773, upload-time = "2026-09-14T14:36:02.577Z" },
{ url = "https://files.pythonhosted.org/packages/40/30/2b0a73e68e1e18e30b601d0d183cfdfc2beca4de5a6843c630f0fc9fb90c/greenlet-3.5.6-cp314-cp314-manylinux_2_39_riscv64.whl", hash = "sha256:fdacf26402389bdd89857ad3c045a26fe8f3314f9a8b28226f82f88463a65b77", size = 480475, upload-time = "2026-09-14T15:28:40.741Z" },
{ url = "https://files.pythonhosted.org/packages/c3/cd/fb7d6cdd86ff3427c1494854f0e35437eba05142be91f530f6da75e09e19/greenlet-3.5.6-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:8b7c73d1cef3d9ae963e9ff03f6222df43efbb9054ffd2f1969c935b7fc84c02", size = 1631900, upload-time = "2026-09-14T15:10:09.745Z" },
{ url = "https://files.pythonhosted.org/packages/f6/40/143bdbb20a516628cb15074ae52ed17d850b450292609c7a6fccac6dbece/greenlet-3.5.6-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:8b27df301f56e3b3d2298095c8f7d6b68f2521f6b1693e901fa039bdbae34424", size = 1693740, upload-time = "2026-09-14T14:35:52.959Z" },
{ url = "https://files.pythonhosted.org/packages/c9/9e/019642432e6ae283301df1361227d47610709d2dc69a38f95edef266d713/greenlet-3.5.6-cp314-cp314-win_amd64.whl", hash = "sha256:f8f0bd690e1a41294ac87905e8121c81a3761ec2583c768f13467428606c8c7a", size = 327473, upload-time = "2026-09-14T14:28:12.948Z" },
{ url = "https://files.pythonhosted.org/packages/e9/7f/8aafc7bf70c948786dba7221d0dc0838e5329bebc6d434ef2208b4f0e760/greenlet-3.5.6-cp314-cp314-win_arm64.whl", hash = "sha256:8cda13494d86a4f12429641117cb6ac4bbbc9c30a33f711f7d3a2e5fbe4b0b7e", size = 311095, upload-time = "2026-09-14T14:28:00.7Z" },
{ url = "https://files.pythonhosted.org/packages/14/7e/7a205688a5b3074933b18a906608d46d106e9a79d776bdab5a4abf4b4feb/greenlet-3.5.6-cp314-cp314t-macosx_11_0_universal2.whl", hash = "sha256:97c5a53e8c1754df58e73f047a99e287d4da1bdfe64b0072fb25c87000897951", size = 305352, upload-time = "2026-09-14T14:21:31.962Z" },
{ url = "https://files.pythonhosted.org/packages/78/cb/9c4a57a9d9dd0256e20b8f7f4f06554c2c92badebf0ab73ce344321b78b9/greenlet-3.5.6-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fea4427d1ffdb3b523d7daa6712038428a4c16c450b9777bdd1221cfee0eab49", size = 672671, upload-time = "2026-09-14T15:12:06.347Z" },
{ url = "https://files.pythonhosted.org/packages/97/52/c6729681ebbd298f4decd28746815acc8a0b0a0fde21d2df33776fd4d042/greenlet-3.5.6-cp314-cp314t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:73a29b5ba642e35433166a03a3e02935e7238c4b3467fbd77523b99edea23e5b", size = 679489, upload-time = "2026-09-14T15:20:47.291Z" },
{ url = "https://files.pythonhosted.org/packages/71/76/3c11c21e0716b1f1dc7c1a4b3d690abb1d3b448c69a9d32049fecb64010a/greenlet-3.5.6-cp314-cp314t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:61a61b4a95a4f97922c3a6f5606d3e360851584bd47e500a5161373c53810e3d", size = 681303, upload-time = "2026-09-14T15:25:11.088Z" },
{ url = "https://files.pythonhosted.org/packages/58/c5/2b6c721ba8b8963da42d5a0f57f25b8aaeb1fe9bdd156875e57f3be648a2/greenlet-3.5.6-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:460e70b033aba8ed47e2ac9b5d0d2157b05a34fbfa30a241400aef4118902cdc", size = 676608, upload-time = "2026-09-14T14:36:03.959Z" },
{ url = "https://files.pythonhosted.org/packages/3f/26/3ae402202452cd5941bbbd483e5a74297e2397e7aa3182c2a5e3ab7d5666/greenlet-3.5.6-cp314-cp314t-manylinux_2_39_riscv64.whl", hash = "sha256:fe3170a69fe039b18ad18171e66faa9a75f6fe9d78f968fd9b54e09fbd714d81", size = 510112, upload-time = "2026-09-14T15:28:42.112Z" },
{ url = "https://files.pythonhosted.org/packages/b2/04/0d018e0d05bcdde19a0fcb907834155f1fc853a9bedd3f3f5e6acadcae19/greenlet-3.5.6-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ca80a49b53ed1d22f7282da7255f7bb2fd1935fd0f623d8613fda38745f18961", size = 1641479, upload-time = "2026-09-14T15:10:11.216Z" },
{ url = "https://files.pythonhosted.org/packages/59/bb/f02ef9073919158f6403fe3701d4ed4403d646720e7201dfc6e9d264bac3/greenlet-3.5.6-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:916f92f2a8db10508f739d0b5e00b83defe5d1115a997c54532a6d7cf8c95404", size = 1698758, upload-time = "2026-09-14T14:35:54.336Z" },
{ url = "https://files.pythonhosted.org/packages/08/a5/1f48fe647473a2dcccfd1839b2ff2c78eb57009be776b4da071e901c9bff/greenlet-3.5.6-cp314-cp314t-win_amd64.whl", hash = "sha256:886bcf1870af74c32bc310fd00a6b803445e17e51b7d5a107c7b35c0f362cc16", size = 331574, upload-time = "2026-09-14T14:27:18.451Z" },
]
[[package]]
name = "gunicorn"
version = "26.2.0"
@@ -415,11 +456,67 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/4a/df/c1ff843fd9c4978d9a50ef2bceda3897d71645d4127ec1413aa15204cb64/lazy_object_proxy-1.13.0-cp314-cp314t-win_arm64.whl", hash = "sha256:de295ae25e5c1fd712088547f251c4b2976d2f60df28057b6c416e771a99842b", size = 25297, upload-time = "2026-10-17T16:37:52.088Z" },
]
[[package]]
name = "mako"
version = "1.4.3"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "markupsafe" },
]
sdist = { url = "https://files.pythonhosted.org/packages/5a/09/e07c4b5579a79f4b16f8d4f29f6c54514ac787c4ad506b8c4f28a0e6b0bf/mako-1.4.3.tar.gz", hash = "sha256:cd6537fe88d5fec315c55c2f8529bc4ce7a9a352ad7db3eeaa6a66e2dd4ec37a", size = 412799, upload-time = "2026-09-22T20:54:31.509Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/6d/a0/053d6af3e8f871e0073b4a36732d9e65be77a72e5434c31b94f6af78a6bb/mako-1.4.3-py3-none-any.whl", hash = "sha256:723296007c870bfd6b3f0c3230dba7198096e5269297ebf5e4eff9e7ffa39d4f", size = 80164, upload-time = "2026-09-22T20:54:33.128Z" },
]
[[package]]
name = "markupsafe"
version = "3.0.4"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/38/9b/e422a865e1d5d57d0e509b4e0bf1c1a70a7f6382c29a5aa428df994c8bc8/markupsafe-3.0.4.tar.gz", hash = "sha256:2e9ad7dd851bf45fab9f75cbff4cb493fee9979e8d8c7c9c3ee119022518edd6", size = 153777, upload-time = "2026-10-02T23:07:22.29Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/5c/c3/a944f3b0df22bd129e96915b9f4e98d2eeca6516687d7618304a966c3c74/markupsafe-3.0.4-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:4ed644d75aa94a2baf7ec3a96eaa160ea58c742eb9d27c6506053c5c40fc84ed", size = 12787, upload-time = "2026-10-02T23:05:30.971Z" },
{ url = "https://files.pythonhosted.org/packages/d4/d6/a44863f69d88b6c7e27889108f70d47aed259edf89d5df3c5fca1eac87d6/markupsafe-3.0.4-cp314-cp314-android_24_x86_64.whl", hash = "sha256:6d2a9efe686f9de00d0d1ea32a4a5a86d558a2277501bd78d964214eab625e59", size = 12525, upload-time = "2026-10-02T23:05:32.263Z" },
{ url = "https://files.pythonhosted.org/packages/17/8f/168ba80e532dd6a93f96f8f706f1ad41d7990b6e1aeedc1cc0d211a33497/markupsafe-3.0.4-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:8781a792a070cf2bd1b86d3aa943894115faaba6e88122a7bf32d62072742453", size = 11589, upload-time = "2026-10-02T23:05:33.251Z" },
{ url = "https://files.pythonhosted.org/packages/32/b3/aa2c95a574d3af39403a469b295886eb9b6d448da568cbebb5a2cbfdc2e5/markupsafe-3.0.4-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:971a3bbb75d97ae4e2e8f7d4834236f86f85f0c85e04ab2e191db1123b04f80b", size = 11801, upload-time = "2026-10-02T23:05:34.315Z" },
{ url = "https://files.pythonhosted.org/packages/60/d0/34b810107d83840e768bf485de795893ebbae35b26ab061b487adfa0a692/markupsafe-3.0.4-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:8909c2f1c6dd65e054ac4b573a91c8384d1492281e55d82d159d653f7a13adf6", size = 11447, upload-time = "2026-10-02T23:05:35.302Z" },
{ url = "https://files.pythonhosted.org/packages/6c/ab/2f8488f0f817a39fca068d2b17daf446bf5cdb3eae28c3720af534d873b4/markupsafe-3.0.4-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:4cf3468d5ec187ffffcaca8e61929a37448f215dafc1386a12c750a72fe53634", size = 11722, upload-time = "2026-10-02T23:05:36.363Z" },
{ url = "https://files.pythonhosted.org/packages/ad/40/e2d117b048d47282ade906fbfd92814cbee5647afc13fda88a3406039372/markupsafe-3.0.4-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:52704c5d36eb6dda8866493decd61111fff86244c9b1ad225ca01b9e91e5970f", size = 12061, upload-time = "2026-10-02T23:05:37.397Z" },
{ url = "https://files.pythonhosted.org/packages/9a/a8/73a81135e85ba66217f5af7facb03bbb386807e1a729ab64532e4c802652/markupsafe-3.0.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1caa2fa5a6184fb233153b35f654e6687bd555476f6170f29d8ee9be1a8b0af9", size = 24434, upload-time = "2026-10-02T23:05:38.407Z" },
{ url = "https://files.pythonhosted.org/packages/ac/ca/fa9216dd01efee2dfdacafe7df32b4d0170fbac694b0c258a193d6e53999/markupsafe-3.0.4-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:387d8cd30e69b3f0a72877b9ae717033396404e19095b17fe89753a981fda44f", size = 27183, upload-time = "2026-10-02T23:05:39.581Z" },
{ url = "https://files.pythonhosted.org/packages/fa/4e/a469509e538d37af51103b17b073126973f2b1cbf197ff32c7ddf025cfe5/markupsafe-3.0.4-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:051417f74bcaaefa316276e0ff723f541616ca51043d070da00249d9bddd3e3c", size = 24813, upload-time = "2026-10-02T23:05:40.671Z" },
{ url = "https://files.pythonhosted.org/packages/8f/db/d7282caf7ab03af44d5d6fdbaa019b35c7d7f1c90588b839c07cba640d6a/markupsafe-3.0.4-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a8e9f292fcda89b324f2f5c91d13f1424a153e40fc2756f38ee23b15835ff300", size = 23049, upload-time = "2026-10-02T23:05:41.864Z" },
{ url = "https://files.pythonhosted.org/packages/30/f3/b6a425206e6964efda6acee544d0eb01d1501784d0b8e2dcc74986f33b17/markupsafe-3.0.4-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:df1ae86ff54725a01fa1a0510b914ca53a161b7050be74f6204e24aded5971d0", size = 22088, upload-time = "2026-10-02T23:05:43.014Z" },
{ url = "https://files.pythonhosted.org/packages/ea/8a/84d3582fc1f0d5bd466cdf2eebf175e172158a6e70701aacec1de1b35430/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:8965520ac587c94a4ac48b729be3d8b8de00af39699b17585dfb599babe77977", size = 23846, upload-time = "2026-10-02T23:05:44.098Z" },
{ url = "https://files.pythonhosted.org/packages/1c/65/db101cce51b7ba4864ac491a9859d297dd1adf0e55b103fee9db9c47c527/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:340cbb1957ba99929cbf19a75626d36ba1ae21d1730b287d1cf7f824a20c4fc7", size = 22674, upload-time = "2026-10-02T23:05:45.23Z" },
{ url = "https://files.pythonhosted.org/packages/e0/49/ddee9813d71db0c7a5c9d97c832125e6758a0c844777f1cf076569bb0e22/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:3a93d9616ddecfb393727a0041a562cf0b15a244e20f2bd25efc7949be4c4f17", size = 24104, upload-time = "2026-10-02T23:05:46.398Z" },
{ url = "https://files.pythonhosted.org/packages/aa/0e/7d8518d726726870a2399d69fd30d0fa36c5e57a2132c336b58d7c491073/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:d2e56fd3b00222722abfb3f5f0759ddbae4b90811b5ad4343c64030ad1bde70c", size = 21637, upload-time = "2026-10-02T23:05:47.48Z" },
{ url = "https://files.pythonhosted.org/packages/b4/b0/b505e8a361ba557dbf3b3aa7331ea39b00d2022a26e925ff8463b9714bb3/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:0d9c47709875fdb321452056622e930c52afbc07a7d780762fbb8b4d91ce6fa4", size = 23081, upload-time = "2026-10-02T23:05:48.611Z" },
{ url = "https://files.pythonhosted.org/packages/1c/ea/9cc3cea873f980c75cbdb6f4277ce30ee955de38be0b3d02f14c108e0698/markupsafe-3.0.4-cp314-cp314-win32.whl", hash = "sha256:38fc55594dab834470b6733dead2ee9e3f657fb0608c769dcafa0ba5ab52f45c", size = 14272, upload-time = "2026-10-02T23:05:49.707Z" },
{ url = "https://files.pythonhosted.org/packages/80/f0/5792ff768a410f93ee3f84fc19345295ffc352d2c936b424cb37e514714c/markupsafe-3.0.4-cp314-cp314-win_amd64.whl", hash = "sha256:c1bc67752d5f21013cfe430df4062441714eab79f65a6a05e01505957e9c35fe", size = 14501, upload-time = "2026-10-02T23:05:50.788Z" },
{ url = "https://files.pythonhosted.org/packages/5f/cf/3d074a8edffcc6899355232ff2543ae8d929733239596423b7db79698bc9/markupsafe-3.0.4-cp314-cp314-win_arm64.whl", hash = "sha256:7e1636da3d8dfc220b6dd10264db5f2b165e4888c4518594898fbe381049af8a", size = 14364, upload-time = "2026-10-02T23:05:51.857Z" },
{ url = "https://files.pythonhosted.org/packages/d9/31/87ce42159aae2163cf3bbbd0c44bc87780510eecab1ea3859099aed95dcb/markupsafe-3.0.4-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:805c8b84534fa10891890f0e4be39f3a99e94615d93e8836bf9fa1fdca2feeb2", size = 11759, upload-time = "2026-10-02T23:05:52.951Z" },
{ url = "https://files.pythonhosted.org/packages/5f/53/b047207eeb7752e960aca3eb1df5fb7eefa7dd4c62ac49bb156456c8a702/markupsafe-3.0.4-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:fa95848c929b6a75f6848d3c9793e59db365ee436776e57db835cdbfa79ba977", size = 12096, upload-time = "2026-10-02T23:05:54.066Z" },
{ url = "https://files.pythonhosted.org/packages/ee/51/4326c88a13c7b755657d44b4bb986f8c3d9843ecba7e22d98661d87f9a57/markupsafe-3.0.4-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e916035e3e9930cbdfdd10abf48861340221857f45509565898e012263f7b289", size = 25699, upload-time = "2026-10-02T23:05:55.15Z" },
{ url = "https://files.pythonhosted.org/packages/f2/bb/990581b7474bfcf2cf34bed6ba5ea23bd87adb9d671213d68e88620e7a6b/markupsafe-3.0.4-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:b4d12837e0203bbace818ff4a7461afdcd78bcd782351cea148139180d7bcffe", size = 27804, upload-time = "2026-10-02T23:05:56.29Z" },
{ url = "https://files.pythonhosted.org/packages/6b/89/89491878c28e8291f5aa2fffe2c2d57230d10ae366d55dd810b840513d78/markupsafe-3.0.4-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5086f9975abb1ab531ee6afca1761e4b59a19b446f3f6522ed776963228cfe5a", size = 25912, upload-time = "2026-10-02T23:05:57.416Z" },
{ url = "https://files.pythonhosted.org/packages/30/77/680998b54efdea06fc114565cd739b6d059f826a0279219b218dfa750d29/markupsafe-3.0.4-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b4a635a0487774f841cb1fb62e907e7195cc95bc761e053184b8acc3ceb20733", size = 23623, upload-time = "2026-10-02T23:05:58.557Z" },
{ url = "https://files.pythonhosted.org/packages/ae/75/2709f5ac5de9467b40b10e2bb8f89cc63dfb74582e09aa734b1124a217de/markupsafe-3.0.4-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:cb96e6e088d6cf71c1ea977510948320234824cf226e32f6f6e044f7a9c82b34", size = 23301, upload-time = "2026-10-02T23:05:59.94Z" },
{ url = "https://files.pythonhosted.org/packages/a0/c8/39eadc6c5b14c9c7679bfb98f4d4c6a97863b5beb91839aca4d2d6e16e55/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8b5d563170ff8ba3181caa967c99a3c804d1dedb702c7cb93a6a7c32247da978", size = 24950, upload-time = "2026-10-02T23:06:01.289Z" },
{ url = "https://files.pythonhosted.org/packages/1a/5e/01037f8a43e8ccb0bffb4fbdc5212db05bf080fdd7286cd392332d58128a/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:396ec4e65cc889f69786b3b89478b471cee5a3bcf468b9d9bb03e1a30fb291fc", size = 23330, upload-time = "2026-10-02T23:06:02.441Z" },
{ url = "https://files.pythonhosted.org/packages/d4/f4/23e83ce0596bb0cbe670502d31df8f757bbd01a392aa486fa3b40d1ed399/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:15ba9e28640feef770374b116a6f019c21f52404aeabe516aa7f800587b98cfc", size = 25239, upload-time = "2026-10-02T23:06:03.579Z" },
{ url = "https://files.pythonhosted.org/packages/88/5b/3708897368073cc683d524750474f41a77d2986152c380dcc55b20fdf340/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:d920abdfa61279ba1a2ef9484aab07bf03331f8c08a10120fa332353d06e6932", size = 22767, upload-time = "2026-10-02T23:06:04.699Z" },
{ url = "https://files.pythonhosted.org/packages/c6/61/ebda1307864b409e6b3115757a3d4a09cca46cfb6cc65191b5de226b424b/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:a9f54054101545a9a9cccefddf54316aa6e4491611fcbef9e91b3b6bebec04f6", size = 23668, upload-time = "2026-10-02T23:06:05.9Z" },
{ url = "https://files.pythonhosted.org/packages/09/15/98075cceac3b5ba0dbb8e4762a847be967d2befc349a2cf2d0ac77f62c9d/markupsafe-3.0.4-cp314-cp314t-win32.whl", hash = "sha256:12a606a492de952afcb43b59a14aaaaad120e708d3663dd0fdf2d738d427a691", size = 14301, upload-time = "2026-10-02T23:06:07.109Z" },
{ url = "https://files.pythonhosted.org/packages/0b/a3/768b560fcc4156685cb563d922b217810cfa7bc135773367f62f1f9d2078/markupsafe-3.0.4-cp314-cp314t-win_amd64.whl", hash = "sha256:a18f38cafc329bac5e3c2b96c765b4c96d3d103421ed22ab7988c1e3fce27464", size = 14526, upload-time = "2026-10-02T23:06:08.276Z" },
{ url = "https://files.pythonhosted.org/packages/93/63/da554b4c97a6b0ea3229ca7fe8cbfb620be81613d517f482e85958550537/markupsafe-3.0.4-cp314-cp314t-win_arm64.whl", hash = "sha256:eba154571c16e032112afac0dc2dfe9e63c2ceb7aedd07bb7eecf2ce26d4dd4c", size = 14421, upload-time = "2026-10-02T23:06:09.402Z" },
]
[[package]]
name = "mtusi-messenger"
version = "1.3.0"
source = { editable = "." }
dependencies = [
{ name = "alembic" },
{ name = "argon2-cffi" },
{ name = "asyncpg" },
{ name = "dishka" },
@@ -429,6 +526,7 @@ dependencies = [
{ name = "pydantic" },
{ name = "pydantic-settings" },
{ name = "redis" },
{ name = "sqlalchemy", extra = ["asyncio"] },
{ name = "structlog" },
{ name = "uvicorn", extra = ["standard"] },
{ name = "uvicorn-worker" },
@@ -446,6 +544,7 @@ dev = [
[package.metadata]
requires-dist = [
{ name = "alembic", specifier = "==1.16.5" },
{ name = "argon2-cffi", specifier = ">=25.1.0" },
{ name = "asyncpg", specifier = ">=0.32.0" },
{ name = "dishka", specifier = ">=1.7.0" },
@@ -455,6 +554,7 @@ requires-dist = [
{ name = "pydantic", specifier = ">=2.11.0" },
{ name = "pydantic-settings", specifier = ">=2.11.0" },
{ name = "redis", specifier = ">=8.1.0" },
{ name = "sqlalchemy", extras = ["asyncio"], specifier = "==2.0.45" },
{ name = "structlog", specifier = ">=26.1.0" },
{ name = "uvicorn", extras = ["standard"], specifier = ">=0.37.0" },
{ name = "uvicorn-worker", specifier = ">=0.4.0" },
@@ -816,6 +916,32 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" },
]
[[package]]
name = "sqlalchemy"
version = "2.0.45"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "greenlet", marker = "platform_machine == 'AMD64' or platform_machine == 'WIN32' or platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'ppc64le' or platform_machine == 'win32' or platform_machine == 'x86_64'" },
{ name = "typing-extensions" },
]
sdist = { url = "https://files.pythonhosted.org/packages/be/f9/5e4491e5ccf42f5d9cfc663741d261b3e6e1683ae7812114e7636409fcc6/sqlalchemy-2.0.45.tar.gz", hash = "sha256:1632a4bda8d2d25703fdad6363058d882541bdaaee0e5e3ddfa0cd3229efce88", size = 9869912, upload-time = "2025-12-09T21:05:16.737Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/cc/64/4e1913772646b060b025d3fc52ce91a58967fe58957df32b455de5a12b4f/sqlalchemy-2.0.45-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7f46ec744e7f51275582e6a24326e10c49fbdd3fc99103e01376841213028774", size = 3272404, upload-time = "2025-12-09T22:11:09.662Z" },
{ url = "https://files.pythonhosted.org/packages/b3/27/caf606ee924282fe4747ee4fd454b335a72a6e018f97eab5ff7f28199e16/sqlalchemy-2.0.45-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:883c600c345123c033c2f6caca18def08f1f7f4c3ebeb591a63b6fceffc95cce", size = 3277057, upload-time = "2025-12-09T22:13:56.213Z" },
{ url = "https://files.pythonhosted.org/packages/85/d0/3d64218c9724e91f3d1574d12eb7ff8f19f937643815d8daf792046d88ab/sqlalchemy-2.0.45-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:2c0b74aa79e2deade948fe8593654c8ef4228c44ba862bb7c9585c8e0db90f33", size = 3222279, upload-time = "2025-12-09T22:11:11.1Z" },
{ url = "https://files.pythonhosted.org/packages/24/10/dd7688a81c5bc7690c2a3764d55a238c524cd1a5a19487928844cb247695/sqlalchemy-2.0.45-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:8a420169cef179d4c9064365f42d779f1e5895ad26ca0c8b4c0233920973db74", size = 3244508, upload-time = "2025-12-09T22:13:57.932Z" },
{ url = "https://files.pythonhosted.org/packages/aa/41/db75756ca49f777e029968d9c9fee338c7907c563267740c6d310a8e3f60/sqlalchemy-2.0.45-cp314-cp314-win32.whl", hash = "sha256:e50dcb81a5dfe4b7b4a4aa8f338116d127cb209559124f3694c70d6cd072b68f", size = 2113204, upload-time = "2025-12-09T21:39:38.365Z" },
{ url = "https://files.pythonhosted.org/packages/89/a2/0e1590e9adb292b1d576dbcf67ff7df8cf55e56e78d2c927686d01080f4b/sqlalchemy-2.0.45-cp314-cp314-win_amd64.whl", hash = "sha256:4748601c8ea959e37e03d13dcda4a44837afcd1b21338e637f7c935b8da06177", size = 2138785, upload-time = "2025-12-09T21:39:39.503Z" },
{ url = "https://files.pythonhosted.org/packages/42/39/f05f0ed54d451156bbed0e23eb0516bcad7cbb9f18b3bf219c786371b3f0/sqlalchemy-2.0.45-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cd337d3526ec5298f67d6a30bbbe4ed7e5e68862f0bf6dd21d289f8d37b7d60b", size = 3522029, upload-time = "2025-12-09T22:13:32.09Z" },
{ url = "https://files.pythonhosted.org/packages/54/0f/d15398b98b65c2bce288d5ee3f7d0a81f77ab89d9456994d5c7cc8b2a9db/sqlalchemy-2.0.45-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:9a62b446b7d86a3909abbcd1cd3cc550a832f99c2bc37c5b22e1925438b9367b", size = 3475142, upload-time = "2025-12-09T22:13:33.739Z" },
{ url = "https://files.pythonhosted.org/packages/bf/e1/3ccb13c643399d22289c6a9786c1a91e3dcbb68bce4beb44926ac2c557bf/sqlalchemy-2.0.45-py3-none-any.whl", hash = "sha256:5225a288e4c8cc2308dbdd874edad6e7d0fd38eac1e9e5f23503425c8eee20d0", size = 1936672, upload-time = "2025-12-09T21:54:52.608Z" },
]
[package.optional-dependencies]
asyncio = [
{ name = "greenlet" },
]
[[package]]
name = "starlette"
version = "1.7.0"