forked from mtusi2026/mtusi2026lab3
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:
@@ -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
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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 'соединение закрыто без ответа'}")
|
||||
|
||||
@@ -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
|
||||
)
|
||||
|
||||
@@ -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"))
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
@@ -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]:
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL CONSTRAINT users_username_key UNIQUE
|
||||
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||
password_hash text NOT NULL CHECK (password_hash LIKE '$argon2id$%'),
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
token_hash bytea PRIMARY KEY CHECK (octet_length(token_hash) = 32),
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
created_at timestamptz NOT NULL,
|
||||
expires_at timestamptz NOT NULL,
|
||||
CHECK (expires_at > created_at)
|
||||
);
|
||||
|
||||
CREATE INDEX sessions_user_idx ON sessions (user_id);
|
||||
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
|
||||
created_at timestamptz NOT NULL,
|
||||
last_message_at timestamptz
|
||||
);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
position smallint NOT NULL CHECK (position BETWEEN 1 AND 100),
|
||||
chat_created_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_created_at, chat_id);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL,
|
||||
sender_id uuid NOT NULL,
|
||||
text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||
created_at timestamptz NOT NULL,
|
||||
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id);
|
||||
@@ -0,0 +1,10 @@
|
||||
CREATE TABLE idempotency_keys (
|
||||
chat_id uuid NOT NULL,
|
||||
user_id uuid NOT NULL,
|
||||
key text NOT NULL CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'),
|
||||
fingerprint bytea NOT NULL CHECK (octet_length(fingerprint) = 32),
|
||||
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
|
||||
created_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (chat_id, user_id, key),
|
||||
FOREIGN KEY (chat_id, user_id) REFERENCES chat_members (chat_id, user_id)
|
||||
);
|
||||
Reference in New Issue
Block a user