ЛР 4 — БПИ2303 — Костылев — на 5 #162
@@ -57,7 +57,8 @@ make down # остановка без удаления д
|
|||||||
## Правила работы с репозиторием
|
## Правила работы с репозиторием
|
||||||
|
|
||||||
- Не менять и не ослаблять `contracts/`, `tests/`, `README.md`, `COURSE.md`, рубрику. Расхождение оформляется вопросом преподавателю.
|
- Не менять и не ослаблять `contracts/`, `tests/`, `README.md`, `COURSE.md`, рубрику. Расхождение оформляется вопросом преподавателю.
|
||||||
- Код — `src/messenger/`, миграции — `src/messenger/migrations/NNNN_*.sql`, конфигурация LB, нагрузки и S3 — `infra/`, хуки и обвязка стенда — `scripts/`, собственные тесты — `student-tests/`, обезличенные доказательства — `evidence/`.
|
- Код — `src/messenger/`, миграции — `alembic/versions/NNNN_*.py`, конфигурация LB, нагрузки и S3 — `infra/`, хуки и обвязка стенда — `scripts/`, собственные тесты — `student-tests/`, обезличенные доказательства — `evidence/`.
|
||||||
|
- PostgreSQL — SQLAlchemy 2 async с asyncpg как драйвером; ORM-модели внутри зон, Alembic принимает legacy-схему только после сверки журнала и каталога.
|
||||||
- Без комментариев в коде; отступы — пробелы (`[tool.ruff.format]`); Python 3.14 без `from __future__ import annotations` и `TYPE_CHECKING`.
|
- Без комментариев в коде; отступы — пробелы (`[tool.ruff.format]`); Python 3.14 без `from __future__ import annotations` и `TYPE_CHECKING`.
|
||||||
- Порты реплик API и S3 наружу не публикуются: только LB. Нет `container_name`, `hostname` и общего `INSTANCE_ID` у сервиса `api`. Root-ключи S3 есть только у `s3`, `s3-init` и `s3-cli`; API получает отдельный ключ только на объекты bucket (`Get/Put/DeleteObject`), сверка — свой ключ (`ListBucket`, `Get/DeleteObject`). `s3-init` и `s3-cli` работают от uid 65534, `migrate` и `reconciler` — с `init: true`.
|
- Порты реплик API и S3 наружу не публикуются: только LB. Нет `container_name`, `hostname` и общего `INSTANCE_ID` у сервиса `api`. Root-ключи S3 есть только у `s3`, `s3-init` и `s3-cli`; API получает отдельный ключ только на объекты bucket (`Get/Put/DeleteObject`), сверка — свой ключ (`ListBucket`, `Get/DeleteObject`). `s3-init` и `s3-cli` работают от uid 65534, `migrate` и `reconciler` — с `init: true`.
|
||||||
- `REPORT.md`: команды из чистого clone, архитектура, таблица «критерий → команда → наблюдение → файл», таблица отказов. PASS без команды не доказательство; для отказов — какой контейнер реально остановлен (`docker ps -a`).
|
- `REPORT.md`: команды из чистого clone, архитектура, таблица «критерий → команда → наблюдение → файл», таблица отказов. PASS без команды не доказательство; для отказов — какой контейнер реально остановлен (`docker ps -a`).
|
||||||
|
|||||||
@@ -36,6 +36,9 @@ COPY --from=builder --chown=root:root /opt/venv /opt/venv
|
|||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY --chown=root:root alembic.ini ./
|
||||||
|
COPY --chown=root:root alembic ./alembic
|
||||||
|
|
||||||
USER 10001:10001
|
USER 10001:10001
|
||||||
|
|
||||||
EXPOSE 8080
|
EXPOSE 8080
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ COMPOSE ?= docker compose
|
|||||||
RATE ?= 100
|
RATE ?= 100
|
||||||
FROM_REV ?=
|
FROM_REV ?=
|
||||||
SHIFT ?= 0
|
SHIFT ?= 0
|
||||||
SCRIPTS_PY = scripts/probe.py scripts/limits.py scripts/lab4_scenarios.py scripts/lab4_seed.py \
|
SCRIPTS_PY = alembic scripts/scaling.py tools scripts/probe.py scripts/limits.py scripts/lab4_scenarios.py scripts/lab4_seed.py \
|
||||||
scripts/upload_memory.py scripts/reconcile_check.py scripts/reconcile_track.py
|
scripts/upload_memory.py scripts/reconcile_check.py scripts/reconcile_track.py
|
||||||
SCENARIO ?= failover-upload
|
SCENARIO ?= failover-upload
|
||||||
PSQL = $(COMPOSE) exec -T postgres psql -U messenger -d messenger -X -q
|
PSQL = $(COMPOSE) exec -T postgres psql -U messenger -d messenger -X -q
|
||||||
@@ -24,6 +24,8 @@ PYTEST_ARGS ?=
|
|||||||
scenario s3-check attachments-evidence upload-faults upload-memory \
|
scenario s3-check attachments-evidence upload-faults upload-memory \
|
||||||
reconcile reconcile-demo reconcile-cost load-evidence clean-clone-evidence overload-leftovers
|
reconcile reconcile-demo reconcile-cost load-evidence clean-clone-evidence overload-leftovers
|
||||||
|
|
||||||
|
.NOTPARALLEL:
|
||||||
|
|
||||||
help:
|
help:
|
||||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||||
@echo "install/lint/typecheck/student-test: студенческий тулчейн"
|
@echo "install/lint/typecheck/student-test: студенческий тулчейн"
|
||||||
@@ -69,14 +71,14 @@ install:
|
|||||||
lint:
|
lint:
|
||||||
$(VENV)/bin/ruff check src student-tests $(SCRIPTS_PY)
|
$(VENV)/bin/ruff check src student-tests $(SCRIPTS_PY)
|
||||||
$(VENV)/bin/ruff format --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:
|
format:
|
||||||
$(VENV)/bin/ruff check --fix src student-tests $(SCRIPTS_PY)
|
$(VENV)/bin/ruff check --fix src student-tests $(SCRIPTS_PY)
|
||||||
$(VENV)/bin/ruff format src student-tests $(SCRIPTS_PY)
|
$(VENV)/bin/ruff format src student-tests $(SCRIPTS_PY)
|
||||||
|
|
||||||
typecheck:
|
typecheck:
|
||||||
$(VENV)/bin/ty check src student-tests
|
$(VENV)/bin/ty check src student-tests alembic
|
||||||
|
|
||||||
student-test:
|
student-test:
|
||||||
$(VENV)/bin/pytest $(PYTEST_ARGS)
|
$(VENV)/bin/pytest $(PYTEST_ARGS)
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
[alembic]
|
||||||
|
script_location = %(here)s/alembic
|
||||||
|
prepend_sys_path = %(here)s/src %(here)s/alembic
|
||||||
|
path_separator = space
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
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.attachments.infrastructure.postgres import AttachmentRow
|
||||||
|
from messenger.identity.infrastructure.postgres import SessionRow, UserRow
|
||||||
|
from messenger.messaging.infrastructure.postgres import (
|
||||||
|
ChatMemberRow,
|
||||||
|
ChatRow,
|
||||||
|
IdempotencyKeyRow,
|
||||||
|
MessageAttachmentRow,
|
||||||
|
MessageRow,
|
||||||
|
)
|
||||||
|
from messenger.shared.config import PlatformSettings
|
||||||
|
|
||||||
|
LOCK_KEY = 20_260_002
|
||||||
|
MODELS = (
|
||||||
|
UserRow,
|
||||||
|
SessionRow,
|
||||||
|
ChatRow,
|
||||||
|
ChatMemberRow,
|
||||||
|
MessageRow,
|
||||||
|
IdempotencyKeyRow,
|
||||||
|
AttachmentRow,
|
||||||
|
MessageAttachmentRow,
|
||||||
|
)
|
||||||
|
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())
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
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",
|
||||||
|
"0003_attachments": "c4417f560538a083efba1c67f660147dc94532fcbb2fa91f3f3e8258a0f01f2e",
|
||||||
|
"0004_attachment_quarantine": (
|
||||||
|
"541f5399d87fac3584c4102b4e0bf92c23cd372cc20a7d56dad03e771773202c"
|
||||||
|
),
|
||||||
|
}
|
||||||
|
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.relpersistence,
|
||||||
|
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, a.attcollation::regcollation,
|
||||||
|
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)
|
||||||
@@ -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"}
|
||||||
@@ -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")
|
||||||
@@ -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")
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision = "0003_attachments"
|
||||||
|
down_revision = "0002_idempotency_keys"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.drop_constraint("messages_text_check", "messages", type_="check")
|
||||||
|
op.create_check_constraint("messages_text_check", "messages", "char_length(text) <= 4000")
|
||||||
|
op.create_table(
|
||||||
|
"attachments",
|
||||||
|
sa.Column("id", sa.Uuid(), nullable=False),
|
||||||
|
sa.Column("chat_id", sa.Uuid(), nullable=False),
|
||||||
|
sa.Column("owner_id", sa.Uuid(), nullable=False),
|
||||||
|
sa.Column("filename", sa.Text(), nullable=False),
|
||||||
|
sa.Column("content_type", sa.Text(), nullable=False),
|
||||||
|
sa.Column("size_bytes", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("sha256", sa.Text(), nullable=False),
|
||||||
|
sa.Column("width", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("height", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("object_key", sa.Text(collation="C"), nullable=False),
|
||||||
|
sa.Column("status", sa.Text(), nullable=False),
|
||||||
|
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
sa.UniqueConstraint("object_key", name="attachments_object_key_key"),
|
||||||
|
sa.UniqueConstraint("id", "chat_id", name="attachments_chat_key"),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["chat_id", "owner_id"],
|
||||||
|
["chat_members.chat_id", "chat_members.user_id"],
|
||||||
|
name="attachments_owner_fkey",
|
||||||
|
),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"char_length(filename) BETWEEN 1 AND 255", name="attachments_filename_check"
|
||||||
|
),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"content_type IN ('image/png', 'image/jpeg')", name="attachments_content_type_check"
|
||||||
|
),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"size_bytes BETWEEN 1 AND 10485760", name="attachments_size_bytes_check"
|
||||||
|
),
|
||||||
|
sa.CheckConstraint("sha256 ~ '^[0-9a-f]{64}$'", name="attachments_sha256_check"),
|
||||||
|
sa.CheckConstraint("width > 0", name="attachments_width_check"),
|
||||||
|
sa.CheckConstraint("height > 0", name="attachments_height_check"),
|
||||||
|
sa.CheckConstraint("status IN ('pending', 'ready')", name="attachments_status_check"),
|
||||||
|
)
|
||||||
|
op.create_index(
|
||||||
|
"attachments_pending_idx",
|
||||||
|
"attachments",
|
||||||
|
["created_at"],
|
||||||
|
postgresql_where=sa.text("status = 'pending'"),
|
||||||
|
)
|
||||||
|
op.create_table(
|
||||||
|
"message_attachments",
|
||||||
|
sa.Column("message_id", sa.Uuid(), nullable=False),
|
||||||
|
sa.Column("position", sa.SmallInteger(), nullable=False),
|
||||||
|
sa.Column("chat_id", sa.Uuid(), nullable=False),
|
||||||
|
sa.Column("attachment_id", sa.Uuid(), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint("message_id", "position"),
|
||||||
|
sa.UniqueConstraint("message_id", "attachment_id"),
|
||||||
|
sa.CheckConstraint("position BETWEEN 0 AND 9", name="message_attachments_position_check"),
|
||||||
|
sa.ForeignKeyConstraint(["message_id"], ["messages.id"], ondelete="CASCADE"),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["attachment_id", "chat_id"],
|
||||||
|
["attachments.id", "attachments.chat_id"],
|
||||||
|
name="message_attachments_attachment_fkey",
|
||||||
|
ondelete="RESTRICT",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
op.create_index("message_attachments_attachment_idx", "message_attachments", ["attachment_id"])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
raise RuntimeError("Downgrade would delete application data")
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision = "0004_attachment_quarantine"
|
||||||
|
down_revision = "0003_attachments"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column("attachments", sa.Column("quarantine_reason", sa.Text(), nullable=True))
|
||||||
|
op.create_check_constraint(
|
||||||
|
"attachments_quarantine_reason_check",
|
||||||
|
"attachments",
|
||||||
|
"quarantine_reason IN ('missing', 'size_mismatch', 'sha_mismatch')",
|
||||||
|
)
|
||||||
|
op.add_column(
|
||||||
|
"attachments", sa.Column("quarantined_at", sa.DateTime(timezone=True), nullable=True)
|
||||||
|
)
|
||||||
|
op.create_check_constraint(
|
||||||
|
"attachments_quarantine_check",
|
||||||
|
"attachments",
|
||||||
|
"(quarantine_reason IS NULL) = (quarantined_at IS NULL)",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
raise RuntimeError("Downgrade would delete quarantine data")
|
||||||
+1
-1
@@ -123,7 +123,7 @@ services:
|
|||||||
<<: *app
|
<<: *app
|
||||||
pull_policy: never
|
pull_policy: never
|
||||||
init: true
|
init: true
|
||||||
command: ["python", "-m", "messenger.migrate"]
|
command: ["alembic", "upgrade", "head"]
|
||||||
environment:
|
environment:
|
||||||
DATABASE_URL_FILE: /run/secrets/database_url
|
DATABASE_URL_FILE: /run/secrets/database_url
|
||||||
LOG_LEVEL: ${LOG_LEVEL:-INFO}
|
LOG_LEVEL: ${LOG_LEVEL:-INFO}
|
||||||
|
|||||||
@@ -50,3 +50,11 @@
|
|||||||
без удаления постоянных volumes. Нормативные файлы и WIP проверяются по хешам.
|
без удаления постоянных volumes. Нормативные файлы и WIP проверяются по хешам.
|
||||||
|
|
||||||
Документация проверена через context7: SQLAlchemy rel_2_0_45 и Alembic rel_1_16_5.
|
Документация проверена через context7: SQLAlchemy rel_2_0_45 и Alembic rel_1_16_5.
|
||||||
|
|
||||||
|
## Слияние обвязки
|
||||||
|
|
||||||
|
Сохранены Makefile-цели ЛР4 и трека 2; цели старого трека масштабирования ЛР3 с его
|
||||||
|
жёсткими SHA не подменяют выбранный трек ЛР4. Обновлённые scripts/scaling.py и tools/plot_track1.py
|
||||||
|
перенесены вместе с нужными sampler-скриптами из того же snapshot. Исходные серии evidence
|
||||||
|
и архивы экспериментов ЛР3 не копируются как доказательства ЛР4. Исправления probe.py,
|
||||||
|
пула и новых проверок перенесены полностью; соответствующие требования оформлены дельтами.
|
||||||
|
|||||||
@@ -23,6 +23,8 @@
|
|||||||
|
|
||||||
- `lab2-persistent-storage`: весь PostgreSQL-доступ через SQLAlchemy, миграции Alembic,
|
- `lab2-persistent-storage`: весь PostgreSQL-доступ через SQLAlchemy, миграции Alembic,
|
||||||
безопасное принятие существующих схем ЛР4.
|
безопасное принятие существующих схем ЛР4.
|
||||||
|
- `lab2-dependency-failures`: восстановление чтения и записи после закрытия соединений.
|
||||||
|
- `lab3-failover-operations`: достоверность нагрузочного зонда и запуск Alembic.
|
||||||
|
|
||||||
## Impact
|
## Impact
|
||||||
|
|
||||||
|
|||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
## MODIFIED Requirements
|
||||||
|
|
||||||
|
### Requirement: Восстановление без рестарта API
|
||||||
|
|
||||||
|
После возвращения PostgreSQL API SHALL восстанавливать чтение и запись без перезапуска своего процесса за счёт переподключения пула. Закрытое сервером простаивающее соединение SHALL заменяться до выполнения новой операции; его повторная выдача SHALL NOT приводить к `503` при доступной БД. Уже начатые операции SHALL NOT автоматически повторяться. Требование сохраняет минимум lab2 и минимум ЛР3 (критерий 3.9 `README.md` ЛР4).
|
||||||
|
|
||||||
|
#### Scenario: PostgreSQL снова запущен
|
||||||
|
|
||||||
|
- **WHEN** сервис `postgres` запущен после остановки
|
||||||
|
- **THEN** в течение 30 с `/health/ready` отвечает `200`, а прежний токен читает свои данные
|
||||||
|
- **AND** после возвращения всех реплик в ротацию валидные новые `POST /api/v1/users` через LB возвращают `201`, без перезапуска API
|
||||||
|
|
||||||
|
#### Scenario: Сервер закрыл простаивающее соединение
|
||||||
|
|
||||||
|
- **WHEN** PostgreSQL доступен, но закрыл ранее возвращённое в пул соединение, и приходит валидный `POST /api/v1/users`
|
||||||
|
- **THEN** запрос возвращает `201` с `User`, `X-Request-Id` и `X-Instance-Id`; создаётся ровно один пользователь
|
||||||
|
|
||||||
|
#### Scenario: БД ещё недоступна
|
||||||
|
|
||||||
|
- **WHEN** соединение закрыто и PostgreSQL всё ещё недоступен
|
||||||
|
- **THEN** запрос получает ограниченную ошибку `503` с `error.code=unavailable`, `error.message`, `error.request_id`, `X-Request-Id` и `X-Instance-Id` согласно общему контракту
|
||||||
|
|
||||||
+47
@@ -0,0 +1,47 @@
|
|||||||
|
## MODIFIED Requirements
|
||||||
|
|
||||||
|
### Requirement: Поочерёдная замена под нагрузкой и однократные миграции
|
||||||
|
|
||||||
|
Оператор SHALL одной командой заменять реплики новой версией образа по одной: сначала миграции применяются один раз отдельным процессом, затем на каждую старую реплику запускается новая, и старая останавливается только после того, как балансировщик видит новую готовой. Число готовых реплик в балансировщике SHALL NOT опускаться ниже исходного. Миграции SHALL быть совместимы с работающей предыдущей версией (только добавление объектов схемы) либо ограничение SHALL быть описано в `REPORT.md`.
|
||||||
|
|
||||||
|
#### Scenario: Замена под нагрузкой
|
||||||
|
|
||||||
|
- **WHEN** выполняется `make rolling-update`
|
||||||
|
- **THEN** `evidence/rolling/result.json` показывает, что балансировщик ни разу не видел меньше исходного числа готовых реплик, доля ошибок нагрузки не больше 1 %, зонд не потерял записей, а после замены запросы обслуживают только новые контейнеры
|
||||||
|
|
||||||
|
#### Scenario: Обновление с прежней версии
|
||||||
|
|
||||||
|
- **WHEN** выполняется `make rolling-update FROM_REV=<коммит>`
|
||||||
|
- **THEN** стенд сначала поднимается на образе, собранном из этого коммита, а затем заменяется текущей версией с теми же гарантиями; журнал замены называет старый и новый образ каждой реплики
|
||||||
|
|
||||||
|
#### Scenario: Миграции один раз
|
||||||
|
|
||||||
|
- **WHEN** идёт поочерёдная замена
|
||||||
|
- **THEN** `migrate` запускается один раз до замены первой реплики, реплики схему не меняют, а повторный `alembic upgrade head` завершается кодом 0 без новых ревизий и изменения данных
|
||||||
|
|
||||||
|
|
||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: Достоверность нагрузочного доказательства
|
||||||
|
|
||||||
|
Для сохранённого минимума ЛР3 (строка 3.9 README ЛР4) нагрузочный зонд SHALL измерять восстановление по завершению
|
||||||
|
первого успешного POST после последней ошибки, а не по времени самой ошибки. Первый успешный
|
||||||
|
POST после начала действия SHALL завершиться не позже 10 с. Отсутствие успешного ответа после
|
||||||
|
ошибки SHALL приводить к неуспешной проверке. После нагрузки полная история отдельного чата зонда
|
||||||
|
SHALL совпадать с подтверждёнными телами Message, без пропусков и дублей. Нулевое число запросов,
|
||||||
|
пропущенные итерации нагрузки и отсутствие наблюдений LB SHALL NOT давать PASS.
|
||||||
|
|
||||||
|
#### Scenario: Ошибка не подтверждает восстановление
|
||||||
|
|
||||||
|
- **WHEN** последняя попытка записи завершилась ошибкой либо успешный ответ после неё пришёл позже 10 с от начала действия
|
||||||
|
- **THEN** проверка восстановления завершается неуспешно, даже если сама ошибка возникла раньше 10 с
|
||||||
|
|
||||||
|
#### Scenario: История после действия
|
||||||
|
|
||||||
|
- **WHEN** поочерёдный отказ или rolling update завершён под нагрузкой
|
||||||
|
- **THEN** зонд читает все страницы своего чата и сравнивает все поля с ответами 201; пропуск, дубль или изменение сообщения дают неуспех
|
||||||
|
|
||||||
|
#### Scenario: Неполная нагрузка или статистика
|
||||||
|
|
||||||
|
- **WHEN** генератор не выполнил запросов, пропустил итерации либо опрос LB не получил статистику
|
||||||
|
- **THEN** прогон не подтверждает сохранение нагрузки и ёмкости и завершается неуспешно
|
||||||
@@ -1,17 +1,38 @@
|
|||||||
## 1. Основа уровня «3»
|
## 1. Основа уровня «3»
|
||||||
|
|
||||||
- [ ] 1.1 Перенести diff immutable snapshot в платформу, зависимости, Dockerfile и обвязку с сохранением WIP.
|
- [x] 1.1 Перенести diff immutable snapshot в платформу, зависимости, Dockerfile и обвязку с сохранением WIP.
|
||||||
- [ ] 1.2 Перенести SQLAlchemy-адаптер identity и его тесты.
|
- [x] 1.2 Перенести SQLAlchemy-адаптер identity и его тесты.
|
||||||
- [ ] 1.3 Перенести messaging и сохранить атомарные ссылки на вложения и replay.
|
- [x] 1.3 Перенести messaging и сохранить атомарные ссылки на вложения и replay.
|
||||||
- [ ] 1.4 Перевести attachments на SQLAlchemy и добавить Alembic 0003/0004 с legacy adoption.
|
- [x] 1.4 Перевести attachments на SQLAlchemy и добавить Alembic 0003/0004 с legacy adoption.
|
||||||
- [ ] 1.5 Проверить миграции и API собственными тестами, выполнить make check и make lint.
|
- [x] 1.5 Проверить миграции и API собственными тестами, выполнить make check и make lint.
|
||||||
|
|
||||||
## 2. Сохранение уровня «4» и трека «5»
|
## 2. Сохранение уровня «4» и трека «5»
|
||||||
|
|
||||||
- [ ] 2.1 Сохранить компенсацию, SKIP LOCKED, keyset, single-run lock, карантин и аудит; адаптировать тесты и инструменты БД.
|
- [x] 2.1 Сохранить компенсацию, SKIP LOCKED, keyset, single-run lock, карантин и аудит; адаптировать тесты и инструменты БД.
|
||||||
- [ ] 2.2 Выполнить make student-test, включая загрузки, отказы и reconciler.
|
- [x] 2.2 Выполнить make student-test, включая загрузки, отказы и reconciler.
|
||||||
|
|
||||||
## 3. Стенд и завершение
|
## 3. Стенд и завершение
|
||||||
|
|
||||||
- [ ] 3.1 Выполнить smoke через собственный LB 18084, проверить Alembic и остановить стенд без удаления volumes.
|
- [x] 3.1 Выполнить smoke через собственный LB 18084, проверить Alembic и остановить стенд без удаления volumes.
|
||||||
- [ ] 3.2 Сверить WIP и нормативные файлы, синхронизировать OpenSpec, архивировать change и создать английские коммиты после make lint.
|
- [ ] 3.2 Сверить WIP и нормативные файлы, синхронизировать OpenSpec, архивировать change и создать английские коммиты после make lint.
|
||||||
|
|
||||||
|
## Проверки переноса
|
||||||
|
|
||||||
|
- `make check`, `make validate`, `make lint`: PASS.
|
||||||
|
- `NO_PROXY=localhost,127.0.0.1,::1 make student-test PYTEST_ARGS='-q -x'`:
|
||||||
|
404 passed, 19 deselected, 79.92 s. Первый запуск проверки S3 без NO_PROXY прервался
|
||||||
|
из-за системного прокси macOS; прямой HTTP-запрос вернул 200.
|
||||||
|
- `COMPOSE_PROJECT_NAME=hlpipe-lab4-forward-20261106 LB_HTTP_PORT=18084 LB_STATS_PORT=24844
|
||||||
|
COMPOSE_FILE=compose.yaml NO_PROXY=localhost,127.0.0.1,::1 make up`: все долгоживущие
|
||||||
|
сервисы healthy, migrate и s3-init завершены; обе реплики UP.
|
||||||
|
- В том же окружении `make test BASE_URL=http://127.0.0.1:18084`: PASS public API lab4.
|
||||||
|
- `make migrate`: повторный upgrade успешен; `SELECT version_num FROM alembic_version`
|
||||||
|
возвращает `0004_attachment_quarantine`.
|
||||||
|
- `make reconcile ARGS='--dry-run --deep'`: 1 объект, 1 строка, 111817 байт,
|
||||||
|
0 расхождений, 0 ошибок, 1 SQL-страница.
|
||||||
|
- `make down`: собственный стенд остановлен, постоянные volumes сохранены.
|
||||||
|
- Хеши REPORT, evidence/README и нормативных файлов совпадают с началом этапа.
|
||||||
|
|
||||||
|
Полные отказы стенда, грейды и нагрузочная матрица не выполняются в фазе forward:
|
||||||
|
это последующий этап runner по прямой инструкции пользователя. Старые evidence
|
||||||
|
не считаются результатами нового приложения и не перезаписывались.
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ context: |
|
|||||||
Python 3.14 (аннотации вычисляются лениво по PEP 649, `TYPE_CHECKING` и
|
Python 3.14 (аннотации вычисляются лениво по PEP 649, `TYPE_CHECKING` и
|
||||||
`from __future__ import annotations` не используются), FastAPI, gunicorn с несколькими
|
`from __future__ import annotations` не используются), FastAPI, gunicorn с несколькими
|
||||||
`UvicornWorker` (пакет `uvicorn-worker`), dishka (DI), pydantic v2 + pydantic-settings, structlog,
|
`UvicornWorker` (пакет `uvicorn-worker`), dishka (DI), pydantic v2 + pydantic-settings, structlog,
|
||||||
asyncpg (параметризованный SQL без ORM), redis-py (`redis.asyncio`) для Valkey, argon2-cffi,
|
SQLAlchemy 2 async (ORM/Core, asyncpg как драйвер), Alembic, redis-py (`redis.asyncio`) для Valkey, argon2-cffi,
|
||||||
aiobotocore (S3 path-style, SigV4, таймауты connect/read, checksum `when_required`), Pillow
|
aiobotocore (S3 path-style, SigV4, таймауты connect/read, checksum `when_required`), Pillow
|
||||||
(разбор заголовка и проверка изображения), pytest + pytest-asyncio + httpx. Зависимости — uv и
|
(разбор заголовка и проверка изображения), pytest + pytest-asyncio + httpx. Зависимости — uv и
|
||||||
`uv.lock`; ruff и ty обязательны на `src/`, `student-tests/` и Python-обвязке стенда;
|
`uv.lock`; ruff и ty обязательны на `src/`, `student-tests/` и Python-обвязке стенда;
|
||||||
@@ -56,14 +56,14 @@ context: |
|
|||||||
(`openspec/notes/architecture-patterns-python.md`), развёрнутый N одинаковыми репликами:
|
(`openspec/notes/architecture-patterns-python.md`), развёрнутый N одинаковыми репликами:
|
||||||
|
|
||||||
main.py сборка приложения: собирает вклады зон в один процесс, связывает зоны портами
|
main.py сборка приложения: собирает вклады зон в один процесс, связывает зоны портами
|
||||||
migrate.py одноразовая точка входа: применяет SQL-миграции под advisory lock
|
alembic/ одноразовые версионированные миграции под advisory lock, проверка legacy-схемы
|
||||||
gunicorn_conf.py конфигурация процесса: воркеры, окно вывода из ротации по SIGTERM
|
gunicorn_conf.py конфигурация процесса: воркеры, окно вывода из ротации по SIGTERM
|
||||||
(флаг вывода — shared/infrastructure/readiness)
|
(флаг вывода — shared/infrastructure/readiness)
|
||||||
identity/ пользователи, пароли и сессии
|
identity/ пользователи, пароли и сессии
|
||||||
messaging/ чаты, история и идемпотентная отправка, ссылки сообщения на вложения
|
messaging/ чаты, история и идемпотентная отправка, ссылки сообщения на вложения
|
||||||
attachments/ вложения: метаданные, проверка изображения, порт объектного хранилища и его
|
attachments/ вложения: метаданные, проверка изображения, порт объектного хранилища и его
|
||||||
адаптер S3, свой HTTP-слой upload, метаданных и скачивания
|
адаптер S3, свой HTTP-слой upload, метаданных и скачивания
|
||||||
shared/ только платформа: часы, id, журнал, пул PostgreSQL, UoW-база, готовность за
|
shared/ только платформа: часы, id, журнал, движок и сессии PostgreSQL, UoW-база, готовность за
|
||||||
портом Readiness, конвейер, health, ошибки, настройки, идентификатор реплики
|
портом Readiness, конвейер, health, ошибки, настройки, идентификатор реплики
|
||||||
|
|
||||||
Стрелки указывают внутрь: `domain/` не импортирует инфраструктуру, `application/` зависит только
|
Стрелки указывают внутрь: `domain/` не импортирует инфраструктуру, `application/` зависит только
|
||||||
@@ -146,7 +146,7 @@ operations:
|
|||||||
- "Логирование — только через порт `Logger`; второй логгер в приложении не заводится. Object key, ключи S3 и содержимое файлов в журнал не пишутся."
|
- "Логирование — только через порт `Logger`; второй логгер в приложении не заводится. Object key, ключи S3 и содержимое файлов в журнал не пишутся."
|
||||||
- "Код приложения — в `src/`, конфигурация LB, нагрузки и S3 — в `infra/`, собственные тесты — в `student-tests/`, обезличенные доказательства — в `evidence/`."
|
- "Код приложения — в `src/`, конфигурация LB, нагрузки и S3 — в `infra/`, собственные тесты — в `student-tests/`, обезличенные доказательства — в `evidence/`."
|
||||||
- "Перед коммитом прогоняй `make lint`, `make student-test` и `make check`."
|
- "Перед коммитом прогоняй `make lint`, `make student-test` и `make check`."
|
||||||
- "SQL только параметризованный (`$1`, `$2`); значения из запроса никогда не склеиваются в текст запроса."
|
- "SQL только через SQLAlchemy ORM/Core с параметрами; text() только для системного каталога и специальных операций; миграции Alembic."
|
||||||
- "Тело загрузки читается потоком со счётчиком до лимита; изображение не декодируется целиком до проверки размера по заголовку; тяжёлая проверка идёт в потоке под ограничением параллелизма."
|
- "Тело загрузки читается потоком со счётчиком до лимита; изображение не декодируется целиком до проверки размера по заголовку; тяжёлая проверка идёт в потоке под ограничением параллелизма."
|
||||||
- "Реплика не хранит в памяти процесса и на своём диске ничего, от чего зависит корректность ответа другой реплики: сессии, ключи идемпотентности, курсоры и файлы — через общее хранилище или общий секрет."
|
- "Реплика не хранит в памяти процесса и на своём диске ничего, от чего зависит корректность ответа другой реплики: сессии, ключи идемпотентности, курсоры и файлы — через общее хранилище или общий секрет."
|
||||||
- "Ошибка зависимости (PostgreSQL, Valkey, S3) превращается в `503 unavailable` за ограниченное время; отказ кэша обходится и никогда не превращается в анонимный доступ."
|
- "Ошибка зависимости (PostgreSQL, Valkey, S3) превращается в `503 unavailable` за ограниченное время; отказ кэша обходится и никогда не превращается в анонимный доступ."
|
||||||
|
|||||||
+8
-2
@@ -13,6 +13,8 @@ dependencies = [
|
|||||||
"gunicorn>=26.2.0",
|
"gunicorn>=26.2.0",
|
||||||
"orjson>=3.12.0",
|
"orjson>=3.12.0",
|
||||||
"asyncpg>=0.32.0",
|
"asyncpg>=0.32.0",
|
||||||
|
"sqlalchemy[asyncio]==2.0.45",
|
||||||
|
"alembic==1.16.5",
|
||||||
"argon2-cffi>=25.1.0",
|
"argon2-cffi>=25.1.0",
|
||||||
"uvicorn-worker>=0.4.0",
|
"uvicorn-worker>=0.4.0",
|
||||||
"redis>=8.1.0",
|
"redis>=8.1.0",
|
||||||
@@ -81,6 +83,7 @@ ignore = [
|
|||||||
|
|
||||||
[tool.ruff.lint.per-file-ignores]
|
[tool.ruff.lint.per-file-ignores]
|
||||||
"student-tests/**" = ["S101", "S105", "S106", "S603", "S607", "PLR2004", "ARG001", "T20", "TID251"]
|
"student-tests/**" = ["S101", "S105", "S106", "S603", "S607", "PLR2004", "ARG001", "T20", "TID251"]
|
||||||
|
"tools/*.py" = ["T20"]
|
||||||
"scripts/*.py" = ["T20", "S603", "S607", "S310", "PLR2004", "TID251"]
|
"scripts/*.py" = ["T20", "S603", "S607", "S310", "PLR2004", "TID251"]
|
||||||
"src/messenger/*/infrastructure/**" = ["TID251", "ARG002"]
|
"src/messenger/*/infrastructure/**" = ["TID251", "ARG002"]
|
||||||
"src/messenger/*/domain/errors.py" = ["N818"]
|
"src/messenger/*/domain/errors.py" = ["N818"]
|
||||||
@@ -88,7 +91,7 @@ ignore = [
|
|||||||
"src/messenger/*/entrypoints/**" = ["TID251", "N818", "PLR0917", "S105"]
|
"src/messenger/*/entrypoints/**" = ["TID251", "N818", "PLR0917", "S105"]
|
||||||
"src/messenger/shared/config.py" = ["ARG002", "ARG003"]
|
"src/messenger/shared/config.py" = ["ARG002", "ARG003"]
|
||||||
"src/messenger/main.py" = ["TID251"]
|
"src/messenger/main.py" = ["TID251"]
|
||||||
"src/messenger/migrate.py" = ["TID251"]
|
"alembic/**" = ["TID251"]
|
||||||
"src/messenger/gunicorn_conf.py" = ["TID251", "ARG002", "RUF012"]
|
"src/messenger/gunicorn_conf.py" = ["TID251", "ARG002", "RUF012"]
|
||||||
|
|
||||||
[tool.ruff.lint.flake8-tidy-imports.banned-api]
|
[tool.ruff.lint.flake8-tidy-imports.banned-api]
|
||||||
@@ -101,7 +104,10 @@ ignore = [
|
|||||||
known-first-party = ["messenger"]
|
known-first-party = ["messenger"]
|
||||||
|
|
||||||
[tool.ty.src]
|
[tool.ty.src]
|
||||||
include = ["src", "student-tests"]
|
include = ["src", "student-tests", "alembic"]
|
||||||
|
|
||||||
|
[tool.ty.environment]
|
||||||
|
extra-paths = ["alembic"]
|
||||||
|
|
||||||
[tool.ty.rules]
|
[tool.ty.rules]
|
||||||
unresolved-import = "error"
|
unresolved-import = "error"
|
||||||
|
|||||||
Executable
+15
@@ -0,0 +1,15 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
out=${1:?usage: docker-stats.sh <csv>}
|
||||||
|
vm=$(dirname "$out")/vm_stat.csv
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
project=$(docker compose config | sed -n 's/^name: //p')
|
||||||
|
echo 'ts,name,cpu_pct,mem_usage,mem_pct,net_io,block_io,pids' > "$out"
|
||||||
|
echo 'ts,busy,total,cpus' > "$vm"
|
||||||
|
while :; do
|
||||||
|
ts=$(date +%s)
|
||||||
|
docker compose exec -T valkey cat /proc/stat 2>/dev/null | awk -v ts="$ts" '/^cpu /{b=$2+$3+$4+$7+$8+$9; t=b+$5+$6} /^cpu[0-9]/{n++} END{if (t) print ts "," b "," t "," n}' >> "$vm" || true
|
||||||
|
ids=$(docker ps -q --filter "label=com.docker.compose.project=$project")
|
||||||
|
[ -z "$ids" ] || docker stats --no-stream --format "$ts,{{.Name}},{{.CPUPerc}},{{.MemUsage}},{{.MemPerc}},{{.NetIO}},{{.BlockIO}},{{.PIDs}}" $ids >> "$out" || true
|
||||||
|
sleep "${INTERVAL:-1}"
|
||||||
|
done
|
||||||
@@ -37,7 +37,7 @@ for r in csv.DictReader(sys.stdin.read().lstrip("# ").splitlines()):
|
|||||||
echo "haproxy: $(docker compose exec -T lb haproxy -v | head -1)"
|
echo "haproxy: $(docker compose exec -T lb haproxy -v | head -1)"
|
||||||
echo "rustfs: $(docker compose exec -T s3 rustfs --version 2>/dev/null | head -1)"
|
echo "rustfs: $(docker compose exec -T s3 rustfs --version 2>/dev/null | head -1)"
|
||||||
echo "packages (uv.lock):"
|
echo "packages (uv.lock):"
|
||||||
for name in fastapi uvicorn uvicorn-worker gunicorn asyncpg argon2-cffi pydantic pydantic-settings dishka structlog redis aiobotocore botocore aiohttp pillow; do
|
for name in fastapi uvicorn uvicorn-worker gunicorn sqlalchemy alembic asyncpg argon2-cffi pydantic pydantic-settings dishka structlog redis aiobotocore botocore aiohttp pillow; do
|
||||||
printf ' %s %s\n' "$name" "$(sed -n "/^name = \"$name\"$/{n;s/version = \"\(.*\)\"/\1/p;}" uv.lock)"
|
printf ' %s %s\n' "$name" "$(sed -n "/^name = \"$name\"$/{n;s/version = \"\(.*\)\"/\1/p;}" uv.lock)"
|
||||||
done
|
done
|
||||||
echo "process users (service uid command):"
|
echo "process users (service uid command):"
|
||||||
|
|||||||
@@ -3,17 +3,17 @@ set -eu
|
|||||||
cd "$(dirname "$0")/.."
|
cd "$(dirname "$0")/.."
|
||||||
psql() { docker compose exec -T postgres psql -U messenger -d messenger -c "$1"; }
|
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)"; }
|
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 attachments) attachments, (SELECT count(*) FROM message_attachments) links, (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 attachments) attachments, (SELECT count(*) FROM message_attachments) links, (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"
|
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"
|
tokens="SELECT octet_length(token_hash) AS stored_bytes, count(*) AS sessions FROM sessions GROUP BY 1"
|
||||||
{
|
{
|
||||||
header
|
header
|
||||||
for table in users sessions chats chat_members messages idempotency_keys attachments message_attachments schema_migrations; do
|
for table in users sessions chats chat_members messages idempotency_keys attachments message_attachments alembic_version; do
|
||||||
echo "\$ psql -c '\\d+ $table'"
|
echo "\$ psql -c '\\d+ $table'"
|
||||||
psql "\\d+ $table"
|
psql "\\d+ $table"
|
||||||
done
|
done
|
||||||
echo "\$ psql -c 'SELECT version, left(checksum, 12), applied_at FROM schema_migrations'"
|
echo "\$ psql -c 'SELECT version_num FROM alembic_version'"
|
||||||
psql "SELECT version, left(checksum, 12) AS checksum, applied_at FROM schema_migrations"
|
psql "SELECT version_num FROM alembic_version"
|
||||||
} > evidence/schema.txt
|
} > evidence/schema.txt
|
||||||
{
|
{
|
||||||
header
|
header
|
||||||
|
|||||||
Executable
+11
@@ -0,0 +1,11 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
out=${1:?usage: lb-stats.sh <csv>}
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
url=${LB_STATS_URL:-http://$(docker compose port lb 8404)/stats;csv}
|
||||||
|
curl -fsS "$url" | sed -n '1s/^# /ts,/p' > "$out"
|
||||||
|
while :; do
|
||||||
|
ts=$(date +%s)
|
||||||
|
curl -fsS "$url" | grep -E '^(public|api),' | sed "s/^/$ts,/" >> "$out" || true
|
||||||
|
sleep "${INTERVAL:-1}"
|
||||||
|
done
|
||||||
Executable
+30
@@ -0,0 +1,30 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
mode=${1:?usage: pg-stats.sh activity <csv> | statements <csv> | size | reset}
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
psql() {
|
||||||
|
docker compose exec -T postgres sh -c 'exec psql -X -q -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "${POSTGRES_DB:-$POSTGRES_USER}" "$@"' psql "$@"
|
||||||
|
}
|
||||||
|
case $mode in
|
||||||
|
reset)
|
||||||
|
psql -c 'set client_min_messages = warning' -c 'create extension if not exists pg_stat_statements' -c 'select pg_stat_statements_reset()' >/dev/null
|
||||||
|
;;
|
||||||
|
size)
|
||||||
|
psql -At -F, -c "select pg_database_size(current_database()), coalesce((select n_live_tup from pg_stat_user_tables where relname = 'messages'), 0)"
|
||||||
|
;;
|
||||||
|
statements)
|
||||||
|
psql -c "copy (select calls, round(total_exec_time::numeric, 3) as total_ms, round(mean_exec_time::numeric, 3) as mean_ms, rows, shared_blks_hit, shared_blks_read, left(regexp_replace(query, '\s+', ' ', 'g'), 200) as query from pg_stat_statements where dbid = (select oid from pg_database where datname = current_database()) and query not like '%pg_stat%' order by total_exec_time desc limit ${TOP:-20}) to stdout with csv header" > "${2:?csv}"
|
||||||
|
;;
|
||||||
|
activity)
|
||||||
|
echo 'ts,state,wait_event_type,wait_event,backends,max_connections' > "${2:?csv}"
|
||||||
|
while :; do
|
||||||
|
ts=$(date +%s)
|
||||||
|
psql -At -F, -c "select coalesce(state, ''), coalesce(wait_event_type, ''), coalesce(wait_event, ''), count(*), current_setting('max_connections') from pg_stat_activity where backend_type = 'client backend' and pid <> pg_backend_pid() group by 1, 2, 3" | sed "s/^/$ts,/" >> "$2" || true
|
||||||
|
sleep "${INTERVAL:-1}"
|
||||||
|
done
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "unknown mode $mode" >&2
|
||||||
|
exit 2
|
||||||
|
;;
|
||||||
|
esac
|
||||||
+59
-7
@@ -10,6 +10,7 @@ import sys
|
|||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
import urllib.error
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
import urllib.request
|
import urllib.request
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
@@ -306,15 +307,16 @@ def retry(args):
|
|||||||
|
|
||||||
|
|
||||||
def record(stop, alice, chat):
|
def record(stop, alice, chat):
|
||||||
probes, trace = [], []
|
probes, trace, confirmed = [], [], []
|
||||||
|
|
||||||
def prober():
|
def prober():
|
||||||
key = uuid.uuid4().hex
|
key = uuid.uuid4().hex
|
||||||
while not stop.is_set():
|
while not stop.is_set():
|
||||||
started = time.time()
|
started = time.time()
|
||||||
status, instance, _ = send(alice, chat, "probe " + key, key)
|
status, instance, body = send(alice, chat, "probe " + key, key)
|
||||||
probes.append((started, status, round(1000 * (time.time() - started), 1), instance))
|
probes.append((started, status, round(1000 * (time.time() - started), 1), instance))
|
||||||
if status == 201:
|
if status == 201:
|
||||||
|
confirmed.append(body)
|
||||||
key = uuid.uuid4().hex
|
key = uuid.uuid4().hex
|
||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
|
|
||||||
@@ -326,7 +328,38 @@ def record(stop, alice, chat):
|
|||||||
threads = [threading.Thread(target=t, daemon=True) for t in (prober, poller)]
|
threads = [threading.Thread(target=t, daemon=True) for t in (prober, poller)]
|
||||||
for thread in threads:
|
for thread in threads:
|
||||||
thread.start()
|
thread.start()
|
||||||
return probes, trace, threads
|
return probes, trace, threads, confirmed
|
||||||
|
|
||||||
|
|
||||||
|
def history_check(reader, chat, confirmed):
|
||||||
|
items, cursors = [], set()
|
||||||
|
cursor = None
|
||||||
|
for _ in range(len(confirmed) // 100 + 2):
|
||||||
|
path = f"/api/v1/chats/{chat}/messages?limit=100"
|
||||||
|
if cursor:
|
||||||
|
path += "&cursor=" + urllib.parse.quote(cursor, safe="")
|
||||||
|
status, _, page = call("GET", path, headers=reader["auth"])
|
||||||
|
if status != 200 or not isinstance(page, dict):
|
||||||
|
break
|
||||||
|
items.extend(page["items"])
|
||||||
|
cursor = page["next_cursor"]
|
||||||
|
if cursor is None:
|
||||||
|
same = sorted(items, key=lambda m: m["id"]) == sorted(confirmed, key=lambda m: m["id"])
|
||||||
|
return {
|
||||||
|
"confirmed": len(confirmed),
|
||||||
|
"stored": len(items),
|
||||||
|
"exact_match": bool(confirmed) and same,
|
||||||
|
"unique": len({m["id"] for m in items}) == len(items),
|
||||||
|
}
|
||||||
|
if cursor in cursors:
|
||||||
|
break
|
||||||
|
cursors.add(cursor)
|
||||||
|
return {
|
||||||
|
"confirmed": len(confirmed),
|
||||||
|
"stored": len(items),
|
||||||
|
"exact_match": False,
|
||||||
|
"unique": False,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def write_csv(path, header, rows):
|
def write_csv(path, header, rows):
|
||||||
@@ -339,6 +372,10 @@ def summarize(args, probes, trace, action, expected):
|
|||||||
t0, end = action["start"], action["end"]
|
t0, end = action["start"], action["end"]
|
||||||
label = args.label or os.environ.get("TARGET_INSTANCE_ID", "action")
|
label = args.label or os.environ.get("TARGET_INSTANCE_ID", "action")
|
||||||
failures = [t - t0 for t, s, _, _ in probes if s != 201 and t >= t0]
|
failures = [t - t0 for t, s, _, _ in probes if s != 201 and t >= t0]
|
||||||
|
successes = [(t, t + ms / 1000 - t0) for t, s, ms, _ in probes if s == 201 and t >= t0]
|
||||||
|
recovery = (
|
||||||
|
next((end for t, end in successes if t - t0 > failures[-1]), None) if failures else 0.0
|
||||||
|
)
|
||||||
down = [t for t, up in trace if t >= t0 and up is not None and up < expected]
|
down = [t for t, up in trace if t >= t0 and up is not None and up < expected]
|
||||||
back = [t for t, up in trace if down and t > down[0] and up is not None and up >= expected]
|
back = [t for t, up in trace if down and t > down[0] and up is not None and up >= expected]
|
||||||
outage = [t for t in down if not back or t < back[0]] or [end]
|
outage = [t for t in down if not back or t < back[0]] or [end]
|
||||||
@@ -354,13 +391,15 @@ def summarize(args, probes, trace, action, expected):
|
|||||||
"action_finished_before_load_end": end < action["load_end"],
|
"action_finished_before_load_end": end < action["load_end"],
|
||||||
"lb_up_before": expected,
|
"lb_up_before": expected,
|
||||||
"lb_up_min": min((up for _, up in trace if up is not None), default=None),
|
"lb_up_min": min((up for _, up in trace if up is not None), default=None),
|
||||||
|
"lb_samples_missing": sum(up is None for _, up in trace),
|
||||||
"detection_seconds": round(down[0] - t0, 3) if down else None,
|
"detection_seconds": round(down[0] - t0, 3) if down else None,
|
||||||
"rejoin_seconds": round(back[0] - t0, 3) if back else None,
|
"rejoin_seconds": round(back[0] - t0, 3) if back else None,
|
||||||
"probe": {
|
"probe": {
|
||||||
"attempts": len(probes),
|
"attempts": len(probes),
|
||||||
"failed_attempts": sum(1 for _, s, _, _ in probes if s != 201),
|
"failed_attempts": sum(1 for _, s, _, _ in probes if s != 201),
|
||||||
"first_failure_s": round(failures[0], 3) if failures else None,
|
"first_failure_s": round(failures[0], 3) if failures else None,
|
||||||
"recovery_s": round(failures[-1], 3) if failures else 0.0,
|
"first_success_s": round(successes[0][1], 3) if successes else None,
|
||||||
|
"recovery_s": round(recovery, 3) if recovery is not None else None,
|
||||||
"instances_before": dict(before),
|
"instances_before": dict(before),
|
||||||
"instances_during_outage": dict(during),
|
"instances_during_outage": dict(during),
|
||||||
"instances_after": dict(after),
|
"instances_after": dict(after),
|
||||||
@@ -373,7 +412,13 @@ def verdict(args, result):
|
|||||||
checks = {
|
checks = {
|
||||||
"action_ok": result["action_exit"] == 0 and result["action_finished_before_load_end"],
|
"action_ok": result["action_exit"] == 0 and result["action_finished_before_load_end"],
|
||||||
"load_errors_ok": k6["exit"] == 0 and k6["failed_ratio"] <= args.max_failed_ratio,
|
"load_errors_ok": k6["exit"] == 0 and k6["failed_ratio"] <= args.max_failed_ratio,
|
||||||
"write_recovery_ok": probe["recovery_s"] <= args.max_recovery,
|
"load_delivered": k6["requests"] > 0 and k6["dropped_iterations"] == 0,
|
||||||
|
"lb_observed": result["lb_up_before"] >= 2 and result["lb_samples_missing"] == 0,
|
||||||
|
"write_recovery_ok": all(
|
||||||
|
probe[k] is not None and probe[k] <= args.max_recovery
|
||||||
|
for k in ("first_success_s", "recovery_s")
|
||||||
|
),
|
||||||
|
"history_preserved": result["history"]["exact_match"] and result["history"]["unique"],
|
||||||
}
|
}
|
||||||
if args.expect == "dip":
|
if args.expect == "dip":
|
||||||
checks["detected"] = result["detection_seconds"] is not None
|
checks["detected"] = result["detection_seconds"] is not None
|
||||||
@@ -394,7 +439,8 @@ def load(args):
|
|||||||
expected = lb_up() or 0
|
expected = lb_up() or 0
|
||||||
alice, bob = actor("alice"), actor("bob")
|
alice, bob = actor("alice"), actor("bob")
|
||||||
stop, action = threading.Event(), {}
|
stop, action = threading.Event(), {}
|
||||||
probes, trace, threads = record(stop, alice, chat_of(alice, bob))
|
chat = chat_of(alice, bob)
|
||||||
|
probes, trace, threads, confirmed = record(stop, alice, chat)
|
||||||
|
|
||||||
def act():
|
def act():
|
||||||
time.sleep(args.warmup + args.lead)
|
time.sleep(args.warmup + args.lead)
|
||||||
@@ -425,6 +471,7 @@ def load(args):
|
|||||||
)
|
)
|
||||||
write_csv(out / "lb_up.csv", "t_rel_s,up", ((round(t - t0, 3), up) for t, up in trace))
|
write_csv(out / "lb_up.csv", "t_rel_s,up", ((round(t - t0, 3), up) for t, up in trace))
|
||||||
result = summarize(args, probes, trace, action, expected)
|
result = summarize(args, probes, trace, action, expected)
|
||||||
|
result["history"] = history_check(bob, chat, confirmed)
|
||||||
result["lb_counters"] = {k: v - counters[k] for k, v in lb_counters().items()}
|
result["lb_counters"] = {k: v - counters[k] for k, v in lb_counters().items()}
|
||||||
result["k6"] = dict(
|
result["k6"] = dict(
|
||||||
k6_metrics(out / "k6/summary.json", args.duration), exit=code, rate=args.rate
|
k6_metrics(out / "k6/summary.json", args.duration), exit=code, rate=args.rate
|
||||||
@@ -442,10 +489,13 @@ def detect(args):
|
|||||||
started = time.time()
|
started = time.time()
|
||||||
process = subprocess.Popen(args.command, cwd=str(ROOT))
|
process = subprocess.Popen(args.command, cwd=str(ROOT))
|
||||||
detected = acted = None
|
detected = acted = None
|
||||||
|
missing = 0
|
||||||
while time.time() - started < args.timeout and (detected is None or acted is None):
|
while time.time() - started < args.timeout and (detected is None or acted is None):
|
||||||
if acted is None and process.poll() is not None:
|
if acted is None and process.poll() is not None:
|
||||||
acted = time.time() - started
|
acted = time.time() - started
|
||||||
if detected is None and (lb_up() or 0) <= until:
|
up = lb_up()
|
||||||
|
missing += up is None
|
||||||
|
if detected is None and up is not None and up <= until:
|
||||||
detected = time.time() - started
|
detected = time.time() - started
|
||||||
time.sleep(0.05)
|
time.sleep(0.05)
|
||||||
code = process.wait()
|
code = process.wait()
|
||||||
@@ -460,6 +510,7 @@ def detect(args):
|
|||||||
restored = round(time.time() - begun, 3) if (lb_up() or 0) >= before else None
|
restored = round(time.time() - begun, 3) if (lb_up() or 0) >= before else None
|
||||||
checks = {
|
checks = {
|
||||||
"action_ok": code == 0,
|
"action_ok": code == 0,
|
||||||
|
"lb_observed": before >= 2 and missing == 0,
|
||||||
"detected_in_time": detected is not None and detected <= args.max + args.slack,
|
"detected_in_time": detected is not None and detected <= args.max + args.slack,
|
||||||
"lb_answer_ok": status == args.lb_status,
|
"lb_answer_ok": status == args.lb_status,
|
||||||
}
|
}
|
||||||
@@ -472,6 +523,7 @@ def detect(args):
|
|||||||
"action_exit": code,
|
"action_exit": code,
|
||||||
"action_seconds": round(acted, 3),
|
"action_seconds": round(acted, 3),
|
||||||
"lb_up_before": before,
|
"lb_up_before": before,
|
||||||
|
"lb_samples_missing": missing,
|
||||||
"lb_up_counted_as_detected": until,
|
"lb_up_counted_as_detected": until,
|
||||||
"detection_seconds": None if detected is None else round(detected, 3),
|
"detection_seconds": None if detected is None else round(detected, 3),
|
||||||
"declared_max_seconds": args.max,
|
"declared_max_seconds": args.max,
|
||||||
|
|||||||
Executable
+524
@@ -0,0 +1,524 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
import argparse
|
||||||
|
import collections
|
||||||
|
import contextlib
|
||||||
|
import csv
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import signal
|
||||||
|
import statistics
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from probe import ROOT, k6_metrics, lb_up, run_k6
|
||||||
|
|
||||||
|
SCRIPTS = ROOT / "scripts"
|
||||||
|
UNITS = {"B": 1, "KIB": 2**10, "MIB": 2**20, "GIB": 2**30, "KB": 10**3, "MB": 10**6, "GB": 10**9}
|
||||||
|
PINNED = {
|
||||||
|
"PG_CPUSET": "0-1",
|
||||||
|
"LB_CPUSET": "2",
|
||||||
|
"VALKEY_CPUSET": "3",
|
||||||
|
"K6_CPUSET": "4-6",
|
||||||
|
"K6_CPUS": "3",
|
||||||
|
"K6_MEMORY": "1g",
|
||||||
|
}
|
||||||
|
API_FIRST_CPU = 7
|
||||||
|
FIELDS = [
|
||||||
|
"raw_dir",
|
||||||
|
"variant",
|
||||||
|
"config",
|
||||||
|
"replicas",
|
||||||
|
"cpus",
|
||||||
|
"memory_mb",
|
||||||
|
"workers",
|
||||||
|
"pool",
|
||||||
|
"maxconn",
|
||||||
|
"api_cpuset",
|
||||||
|
"rate",
|
||||||
|
"repeat",
|
||||||
|
"started",
|
||||||
|
"db_mb",
|
||||||
|
"messages",
|
||||||
|
"k6_exit",
|
||||||
|
"saturated",
|
||||||
|
"requests",
|
||||||
|
"rps",
|
||||||
|
"ok_rps",
|
||||||
|
"failed_ratio",
|
||||||
|
"dropped_iterations",
|
||||||
|
"p50_ms",
|
||||||
|
"p95_ms",
|
||||||
|
"p99_ms",
|
||||||
|
"p95_post_ms",
|
||||||
|
"p95_get_ms",
|
||||||
|
"cpu_api",
|
||||||
|
"cpu_postgres",
|
||||||
|
"cpu_lb",
|
||||||
|
"cpu_valkey",
|
||||||
|
"cpu_k6",
|
||||||
|
"mem_api_mb",
|
||||||
|
"mem_postgres_mb",
|
||||||
|
"mem_k6_mb",
|
||||||
|
"pg_backends_max",
|
||||||
|
"pg_active_avg",
|
||||||
|
"pg_active_max",
|
||||||
|
"pg_idle_avg",
|
||||||
|
"pg_idle_tx_avg",
|
||||||
|
"pg_lock_avg",
|
||||||
|
"pg_lock_max",
|
||||||
|
"pg_lwlock_avg",
|
||||||
|
"pg_io_avg",
|
||||||
|
"lb_scur_max",
|
||||||
|
"lb_qcur_max",
|
||||||
|
"lb_qtime_max_ms",
|
||||||
|
"lb_rtime_avg_ms",
|
||||||
|
"cpu_vm",
|
||||||
|
"cpu_other",
|
||||||
|
"gap_s",
|
||||||
|
"wall_s",
|
||||||
|
"disturbed",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def compose(*args, env=None):
|
||||||
|
command = ["docker", "compose", *args]
|
||||||
|
return subprocess.run(
|
||||||
|
command, cwd=str(ROOT), env=env, check=True, capture_output=True, text=True
|
||||||
|
).stdout
|
||||||
|
|
||||||
|
|
||||||
|
def size(text):
|
||||||
|
match = re.match(r"([\d.]+)\s*([A-Za-z]+)", text.strip())
|
||||||
|
return float(match.group(1)) * UNITS.get(match.group(2).upper(), 1) if match else 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def rows(path, start, end):
|
||||||
|
with path.open() as handle:
|
||||||
|
return [r for r in csv.DictReader(handle) if r["ts"] and start <= float(r["ts"]) <= end]
|
||||||
|
|
||||||
|
|
||||||
|
def mean(values):
|
||||||
|
return round(statistics.mean(values), 2) if values else 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def docker_usage(path, project, start, end):
|
||||||
|
ticks = collections.defaultdict(collections.Counter)
|
||||||
|
memory = collections.Counter()
|
||||||
|
for r in rows(path, start, end):
|
||||||
|
name = re.sub(r"(-run-[0-9a-f]+|-\d+)$", "", r["name"][len(project) + 1 :])
|
||||||
|
ticks[r["ts"]][name] += float(r["cpu_pct"].rstrip("%") or 0)
|
||||||
|
memory[name] = max(memory[name], size(r["mem_usage"].split("/")[0]) / 2**20)
|
||||||
|
cpu = {
|
||||||
|
name: mean([t[name] for t in ticks.values() if name in t])
|
||||||
|
for name in ("api", "postgres", "lb", "valkey", "k6")
|
||||||
|
}
|
||||||
|
usage = {f"cpu_{name}": value for name, value in cpu.items()}
|
||||||
|
usage.update({f"mem_{name}_mb": round(memory[name], 1) for name in ("api", "postgres", "k6")})
|
||||||
|
return usage
|
||||||
|
|
||||||
|
|
||||||
|
def vm_usage(path, start, end):
|
||||||
|
samples = [(int(r["busy"]), int(r["total"]), int(r["cpus"])) for r in rows(path, start, end)]
|
||||||
|
if len(samples) < 2 or samples[-1][1] == samples[0][1]:
|
||||||
|
return 0.0
|
||||||
|
first, last = samples[0], samples[-1]
|
||||||
|
return round(100 * last[2] * (last[0] - first[0]) / (last[1] - first[1]), 1)
|
||||||
|
|
||||||
|
|
||||||
|
def gap(path, start, end):
|
||||||
|
ticks = sorted({float(r["ts"]) for r in rows(path, start - 5, end + 5)})
|
||||||
|
edges = [start, *[t for t in ticks if start <= t <= end], end]
|
||||||
|
return max(b - a for a, b in zip(edges, edges[1:]))
|
||||||
|
|
||||||
|
|
||||||
|
def vm_counters():
|
||||||
|
lines = compose("exec", "-T", "valkey", "cat", "/proc/stat").splitlines()
|
||||||
|
values = [int(v) for v in lines[0].split()[1:]]
|
||||||
|
cpus = sum(1 for line in lines if re.match(r"cpu\d", line))
|
||||||
|
return sum(values) - values[3] - values[4], sum(values), cpus
|
||||||
|
|
||||||
|
|
||||||
|
def wait_quiet(args):
|
||||||
|
deadline, calm = time.monotonic() + args.quiet_timeout, 0
|
||||||
|
while calm < 3 and time.monotonic() < deadline:
|
||||||
|
first = vm_counters()
|
||||||
|
time.sleep(5)
|
||||||
|
last = vm_counters()
|
||||||
|
busy = 100 * last[2] * (last[0] - first[0]) / max(1, last[1] - first[1])
|
||||||
|
calm = calm + 1 if busy < args.max_other else 0
|
||||||
|
print(json.dumps({"waiting_for_quiet_vm_cpu": round(busy, 1)}), flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
def pg_usage(path, start, end):
|
||||||
|
ticks = collections.defaultdict(collections.Counter)
|
||||||
|
for r in rows(path, start, end):
|
||||||
|
count, state, wait = int(r["backends"]), r["state"], r["wait_event_type"]
|
||||||
|
tick = ticks[r["ts"]]
|
||||||
|
tick["backends"] += count
|
||||||
|
tick["active"] += count * (state == "active")
|
||||||
|
tick["idle"] += count * (state == "idle")
|
||||||
|
tick["idle_tx"] += count * state.startswith("idle in transaction")
|
||||||
|
tick["lock"] += count * (wait == "Lock")
|
||||||
|
tick["lwlock"] += count * (wait == "LWLock")
|
||||||
|
tick["io"] += count * (wait == "IO")
|
||||||
|
series = list(ticks.values())
|
||||||
|
return {
|
||||||
|
"pg_backends_max": max((t["backends"] for t in series), default=0),
|
||||||
|
"pg_active_avg": mean([t["active"] for t in series]),
|
||||||
|
"pg_active_max": max((t["active"] for t in series), default=0),
|
||||||
|
"pg_idle_avg": mean([t["idle"] for t in series]),
|
||||||
|
"pg_idle_tx_avg": mean([t["idle_tx"] for t in series]),
|
||||||
|
"pg_lock_avg": mean([t["lock"] for t in series]),
|
||||||
|
"pg_lock_max": max((t["lock"] for t in series), default=0),
|
||||||
|
"pg_lwlock_avg": mean([t["lwlock"] for t in series]),
|
||||||
|
"pg_io_avg": mean([t["io"] for t in series]),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def lb_usage(path, start, end):
|
||||||
|
backend = [
|
||||||
|
r for r in rows(path, start, end) if r["pxname"] == "api" and r["svname"] == "BACKEND"
|
||||||
|
]
|
||||||
|
|
||||||
|
def numbers(field):
|
||||||
|
return [int(r[field] or 0) for r in backend]
|
||||||
|
|
||||||
|
return {
|
||||||
|
"lb_scur_max": max(numbers("scur"), default=0),
|
||||||
|
"lb_qcur_max": max(numbers("qcur"), default=0),
|
||||||
|
"lb_qtime_max_ms": max(numbers("qtime"), default=0),
|
||||||
|
"lb_rtime_avg_ms": mean(numbers("rtime")),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def trend(path, name):
|
||||||
|
metrics = json.loads(Path(path).read_text())["metrics"]
|
||||||
|
found = metrics.get(f"http_req_duration{{scenario:measure,name:{name}}}", {})
|
||||||
|
return round(found.get("values", {}).get("p(95)", 0.0), 2)
|
||||||
|
|
||||||
|
|
||||||
|
def sampler(*command):
|
||||||
|
return subprocess.Popen([str(SCRIPTS / command[0]), *command[1:]], start_new_session=True)
|
||||||
|
|
||||||
|
|
||||||
|
def stop(process):
|
||||||
|
try:
|
||||||
|
os.killpg(process.pid, signal.SIGTERM)
|
||||||
|
except ProcessLookupError:
|
||||||
|
return
|
||||||
|
process.wait()
|
||||||
|
|
||||||
|
|
||||||
|
def wait_lb(expected, timeout=120):
|
||||||
|
deadline, stable = time.monotonic() + timeout, 0
|
||||||
|
while stable < 4:
|
||||||
|
if time.monotonic() > deadline:
|
||||||
|
raise SystemExit(f"LB does not settle on {expected} UP servers (now {lb_up()})")
|
||||||
|
stable = stable + 1 if lb_up() == expected else 0
|
||||||
|
time.sleep(0.5)
|
||||||
|
|
||||||
|
|
||||||
|
def layout(config, args, variant):
|
||||||
|
name, _, extra = variant.partition(":")
|
||||||
|
replicas, cpus = (float(v) for v in config.split("x"))
|
||||||
|
replicas = int(replicas)
|
||||||
|
workers = args.workers or max(1, int(cpus))
|
||||||
|
width = max(1, math.ceil(replicas * cpus))
|
||||||
|
cpuset = str(API_FIRST_CPU) + (f"-{API_FIRST_CPU + width - 1}" if width > 1 else "")
|
||||||
|
memory = args.api_memory or args.api_memory_total // replicas
|
||||||
|
settings = {
|
||||||
|
"API_REPLICAS": str(replicas),
|
||||||
|
"API_CPUS": f"{cpus:g}",
|
||||||
|
"API_MEMORY": f"{memory}m",
|
||||||
|
"WEB_CONCURRENCY": str(workers),
|
||||||
|
"DB_POOL_MAX_SIZE": str(args.pool),
|
||||||
|
"API_SERVER_MAXCONN": str(args.conn_per_worker * workers),
|
||||||
|
"API_CPUSET": cpuset if args.pin else "",
|
||||||
|
}
|
||||||
|
settings.update(dict(kv.split("=", 1) for kv in [*args.env, *filter(None, extra.split(","))]))
|
||||||
|
base = {
|
||||||
|
"variant": name,
|
||||||
|
"config": config,
|
||||||
|
"replicas": replicas,
|
||||||
|
"cpus": cpus,
|
||||||
|
"memory_mb": memory,
|
||||||
|
"workers": int(settings["WEB_CONCURRENCY"]),
|
||||||
|
"pool": int(settings["DB_POOL_MAX_SIZE"]),
|
||||||
|
"maxconn": int(settings["API_SERVER_MAXCONN"]),
|
||||||
|
"api_cpuset": settings["API_CPUSET"],
|
||||||
|
}
|
||||||
|
return base, settings
|
||||||
|
|
||||||
|
|
||||||
|
def apply(base, settings, env, out):
|
||||||
|
env = dict(env, **settings)
|
||||||
|
for attempt in range(3):
|
||||||
|
try:
|
||||||
|
compose("up", "-d", "--wait", "--wait-timeout", "180", env=env)
|
||||||
|
break
|
||||||
|
except subprocess.CalledProcessError as error:
|
||||||
|
log = Path(out) / "compose-up-failed.txt"
|
||||||
|
with log.open("a") as handle:
|
||||||
|
stamp = time.strftime("%FT%TZ", time.gmtime())
|
||||||
|
commit = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip()
|
||||||
|
handle.write(f"date: {stamp} commit: {commit}\n")
|
||||||
|
handle.write(f"== {stamp} {base} attempt {attempt + 1}\n")
|
||||||
|
handle.write(error.stdout + error.stderr + "\n")
|
||||||
|
print(json.dumps({"compose_up_failed": attempt + 1, "log": str(log)}))
|
||||||
|
if attempt == 2:
|
||||||
|
raise
|
||||||
|
time.sleep(30)
|
||||||
|
wait_lb(base["replicas"])
|
||||||
|
return env
|
||||||
|
|
||||||
|
|
||||||
|
def deployment(env):
|
||||||
|
ids = compose("ps", "-q", env=env).split()
|
||||||
|
template = "{{json .Name}} {{json .Image}} {{json .HostConfig}}"
|
||||||
|
result = subprocess.run(
|
||||||
|
["docker", "inspect", "--format", template, *ids],
|
||||||
|
check=True,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
containers = []
|
||||||
|
for line in result.stdout.splitlines():
|
||||||
|
name, image, config = line.split(" ", 2)
|
||||||
|
limits = json.loads(config)
|
||||||
|
containers.append(
|
||||||
|
dict(
|
||||||
|
name=json.loads(name),
|
||||||
|
image=json.loads(image),
|
||||||
|
**{k: limits[k] for k in ("NanoCpus", "Memory", "CpusetCpus", "PortBindings")},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return containers
|
||||||
|
|
||||||
|
|
||||||
|
def provenance(folder, args, env):
|
||||||
|
stamp = time.strftime("%FT%TZ", time.gmtime())
|
||||||
|
metadata = {
|
||||||
|
"date": stamp,
|
||||||
|
"commit": args.commit,
|
||||||
|
"project": args.project,
|
||||||
|
"command": sys.argv,
|
||||||
|
"api_image": env.get("API_IMAGE", "compose default"),
|
||||||
|
"warmup_seconds": args.warmup,
|
||||||
|
"duration_seconds": args.duration,
|
||||||
|
"containers": args.deployment,
|
||||||
|
}
|
||||||
|
(folder / "metadata.json").write_text(json.dumps(metadata, ensure_ascii=False) + "\n")
|
||||||
|
for path in folder.rglob("*"):
|
||||||
|
if path.suffix in {".csv", ".txt"}:
|
||||||
|
path.write_text(f"# date: {stamp} commit: {args.commit}\n" + path.read_text())
|
||||||
|
elif path.name == "summary.json":
|
||||||
|
data = dict(date=stamp, commit=args.commit, **json.loads(path.read_text()))
|
||||||
|
path.write_text(json.dumps(data) + "\n")
|
||||||
|
|
||||||
|
|
||||||
|
def attempt_folder(out, base, rate, repeat):
|
||||||
|
name = f"{base['variant']}-{base['config']}_rate{rate}_rep{repeat}"
|
||||||
|
attempt = 1
|
||||||
|
while (Path(out) / f"{name}_attempt{attempt}").exists():
|
||||||
|
attempt += 1
|
||||||
|
folder = Path(out) / f"{name}_attempt{attempt}"
|
||||||
|
folder.mkdir(parents=True)
|
||||||
|
return folder
|
||||||
|
|
||||||
|
|
||||||
|
def measure(folder, args, rate, env):
|
||||||
|
subprocess.run([str(SCRIPTS / "pg-stats.sh"), "reset"], check=True)
|
||||||
|
database = subprocess.run(
|
||||||
|
[str(SCRIPTS / "pg-stats.sh"), "size"], check=True, capture_output=True, text=True
|
||||||
|
).stdout.split(",")
|
||||||
|
samplers = [
|
||||||
|
sampler("docker-stats.sh", str(folder / "docker_stats.csv")),
|
||||||
|
sampler("lb-stats.sh", str(folder / "lb_stats.csv")),
|
||||||
|
sampler("pg-stats.sh", "activity", str(folder / "pg_activity.csv")),
|
||||||
|
]
|
||||||
|
load = dict(env, RATE=str(rate), WARMUP=str(args.warmup), DURATION=str(args.duration))
|
||||||
|
began = time.time()
|
||||||
|
try:
|
||||||
|
code, started = run_k6(folder / "k6", load)
|
||||||
|
finally:
|
||||||
|
wall = time.time() - began
|
||||||
|
for process in samplers:
|
||||||
|
stop(process)
|
||||||
|
subprocess.run(
|
||||||
|
[str(SCRIPTS / "pg-stats.sh"), "statements", str(folder / "pg_statements.csv")], check=True
|
||||||
|
)
|
||||||
|
if started is None:
|
||||||
|
raise SystemExit(f"k6 failed in setup, see {folder / 'k6/k6.txt'}")
|
||||||
|
return code, started + args.warmup, database, wall
|
||||||
|
|
||||||
|
|
||||||
|
def step(base, rate, repeat, args, env):
|
||||||
|
folder = attempt_folder(args.out, base, rate, repeat)
|
||||||
|
code, start, database, wall = measure(folder, args, rate, env)
|
||||||
|
end = start + args.duration
|
||||||
|
summary = folder / "k6/summary.json"
|
||||||
|
metrics = k6_metrics(summary, args.duration)
|
||||||
|
saturated = (
|
||||||
|
metrics["failed_ratio"] > args.max_error_ratio
|
||||||
|
or metrics["dropped_iterations"] > args.max_error_ratio * rate * args.duration
|
||||||
|
or metrics["p95_ms"] > args.slo_p95_ms
|
||||||
|
)
|
||||||
|
row = dict(
|
||||||
|
base,
|
||||||
|
raw_dir=folder.name,
|
||||||
|
rate=rate,
|
||||||
|
repeat=repeat,
|
||||||
|
k6_exit=code,
|
||||||
|
saturated=saturated,
|
||||||
|
**metrics,
|
||||||
|
)
|
||||||
|
row["started"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(start))
|
||||||
|
row["db_mb"] = round(int(database[0]) / 2**20, 1)
|
||||||
|
row["messages"] = int(database[1])
|
||||||
|
row["p95_post_ms"] = trend(summary, "post_message")
|
||||||
|
row["p95_get_ms"] = trend(summary, "get_history")
|
||||||
|
row.update(docker_usage(folder / "docker_stats.csv", args.project, start, end))
|
||||||
|
row.update(pg_usage(folder / "pg_activity.csv", start, end))
|
||||||
|
row.update(lb_usage(folder / "lb_stats.csv", start, end))
|
||||||
|
row["cpu_vm"] = vm_usage(folder / "vm_stat.csv", start, end)
|
||||||
|
own = sum(row[f"cpu_{name}"] for name in ("api", "postgres", "lb", "valkey", "k6"))
|
||||||
|
row["cpu_other"] = round(row["cpu_vm"] - own, 1)
|
||||||
|
row["gap_s"] = round(gap(folder / "docker_stats.csv", start, end), 1)
|
||||||
|
row["wall_s"] = round(wall, 1)
|
||||||
|
row["disturbed"] = (
|
||||||
|
row["cpu_other"] > args.max_other
|
||||||
|
or row["gap_s"] > args.max_gap
|
||||||
|
or wall > args.warmup + args.duration + args.max_overhead
|
||||||
|
or row["cpu_k6"] >= 95 * float(env.get("K6_CPUS", "2"))
|
||||||
|
or any(row[f"cpu_{name}"] <= 0 for name in ("vm", "api", "postgres", "k6"))
|
||||||
|
or not rows(folder / "pg_activity.csv", start, end)
|
||||||
|
or not rows(folder / "lb_stats.csv", start, end)
|
||||||
|
)
|
||||||
|
provenance(folder, args, env)
|
||||||
|
if code or not metrics["requests"]:
|
||||||
|
raise SystemExit(f"invalid k6 run: {folder}")
|
||||||
|
print(json.dumps({k: row[k] for k in FIELDS}, ensure_ascii=False), flush=True)
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
def rates(args, base):
|
||||||
|
if args.rates:
|
||||||
|
return [int(r) for r in args.rates.split(",")]
|
||||||
|
factor, top = (float(v) for v in args.search.split(":"))
|
||||||
|
value, values = args.start_per_cpu * base["replicas"] * base["cpus"], []
|
||||||
|
while value <= top:
|
||||||
|
values.append(int(round(value, -1)))
|
||||||
|
value *= factor
|
||||||
|
return values
|
||||||
|
|
||||||
|
|
||||||
|
def arguments():
|
||||||
|
parser = argparse.ArgumentParser(description="Track 1: replicas against throughput")
|
||||||
|
parser.add_argument("--out", required=True)
|
||||||
|
parser.add_argument("--configs", default="1x4,2x2,4x1", help="replicas x cpus per replica")
|
||||||
|
parser.add_argument(
|
||||||
|
"--variant",
|
||||||
|
dest="variants",
|
||||||
|
action="append",
|
||||||
|
help="NAME[:KEY=VALUE,...]; several variants alternate per repeat",
|
||||||
|
)
|
||||||
|
parser.add_argument("--api-memory-total", type=int, default=2048, help="MiB for all replicas")
|
||||||
|
parser.add_argument("--api-memory", type=int, default=0, help="MiB per replica")
|
||||||
|
parser.add_argument("--workers", type=int, default=0, help="gunicorn workers, default = cpus")
|
||||||
|
parser.add_argument("--pool", type=int, default=8, help="DB pool per worker")
|
||||||
|
parser.add_argument("--conn-per-worker", type=int, default=32, help="LB maxconn per worker")
|
||||||
|
parser.add_argument("--env", action="append", default=[], help="extra compose KEY=VALUE")
|
||||||
|
parser.add_argument("--no-pin", dest="pin", action="store_false", help="do not pin CPUs")
|
||||||
|
parser.add_argument("--rates", help="comma separated offered rates, rps")
|
||||||
|
parser.add_argument("--search", default="1.5:8000", help="factor:max, from start-per-cpu")
|
||||||
|
parser.add_argument("--start-per-cpu", type=float, default=100.0)
|
||||||
|
parser.add_argument("--repeats", type=int, default=3)
|
||||||
|
parser.add_argument("--first-repeat", type=int, default=1, help="number of the first repeat")
|
||||||
|
parser.add_argument("--warmup", type=int, default=10)
|
||||||
|
parser.add_argument("--duration", type=int, default=30)
|
||||||
|
parser.add_argument("--pause", type=float, default=5.0)
|
||||||
|
parser.add_argument("--slo-p95-ms", type=float, default=500.0)
|
||||||
|
parser.add_argument("--max-error-ratio", type=float, default=0.01)
|
||||||
|
parser.add_argument("--keep", action="store_true", help="leave the last layout running")
|
||||||
|
parser.add_argument("--max-other", type=float, default=100.0, help="foreign VM CPU, %% core")
|
||||||
|
parser.add_argument("--max-gap", type=float, default=10.0, help="sampling gap, s")
|
||||||
|
parser.add_argument("--max-overhead", type=float, default=90.0, help="k6 run beyond load, s")
|
||||||
|
parser.add_argument("--retries", type=int, default=3, help="reruns of a disturbed step")
|
||||||
|
parser.add_argument("--quiet-timeout", type=float, default=1200.0)
|
||||||
|
args = parser.parse_args()
|
||||||
|
args.variants = args.variants or ["base"]
|
||||||
|
if len(args.variants) > 1 and not args.rates:
|
||||||
|
parser.error("several variants need explicit --rates")
|
||||||
|
return args
|
||||||
|
|
||||||
|
|
||||||
|
def block(args, output, config, variant, repeats):
|
||||||
|
base, settings = layout(config, args, variant)
|
||||||
|
current, streak = apply(base, settings, args.base_env, args.out), 0
|
||||||
|
args.deployment = deployment(current)
|
||||||
|
for rate in rates(args, base):
|
||||||
|
results = []
|
||||||
|
for repeat in repeats:
|
||||||
|
for _ in range(args.retries + 1):
|
||||||
|
row = step(base, rate, repeat, args, current)
|
||||||
|
time.sleep(args.pause)
|
||||||
|
if not row["disturbed"]:
|
||||||
|
break
|
||||||
|
args.rejected.writerow(row)
|
||||||
|
wait_quiet(args)
|
||||||
|
else:
|
||||||
|
raise SystemExit(f"disturbed step exhausted retries: {row['raw_dir']}")
|
||||||
|
results.append(row)
|
||||||
|
output.writerows(results)
|
||||||
|
streak = streak + 1 if not args.rates and all(r["saturated"] for r in results) else 0
|
||||||
|
if streak == 2:
|
||||||
|
break
|
||||||
|
|
||||||
|
|
||||||
|
def series(args, output):
|
||||||
|
every = range(args.first_repeat, args.first_repeat + args.repeats)
|
||||||
|
configs = args.configs.split(",")
|
||||||
|
if not args.rates:
|
||||||
|
for config in configs:
|
||||||
|
block(args, output, config, args.variants[0], every)
|
||||||
|
return
|
||||||
|
for repeat in every:
|
||||||
|
for config in configs:
|
||||||
|
for variant in args.variants:
|
||||||
|
block(args, output, config, variant, [repeat])
|
||||||
|
|
||||||
|
|
||||||
|
@contextlib.contextmanager
|
||||||
|
def table(path):
|
||||||
|
fresh = not path.exists()
|
||||||
|
with path.open("a", newline="", buffering=1) as handle:
|
||||||
|
writer = csv.DictWriter(handle, fieldnames=FIELDS, extrasaction="ignore")
|
||||||
|
if fresh:
|
||||||
|
commit = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip()
|
||||||
|
handle.write(f"# date: {time.strftime('%FT%TZ', time.gmtime())} commit: {commit}\n")
|
||||||
|
writer.writeheader()
|
||||||
|
yield writer
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
args = arguments()
|
||||||
|
out = Path(args.out)
|
||||||
|
out.mkdir(parents=True, exist_ok=True)
|
||||||
|
args.project = json.loads(compose("config", "--format", "json"))["name"]
|
||||||
|
args.commit = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip()
|
||||||
|
args.base_env = dict(os.environ, **(PINNED if args.pin else {}))
|
||||||
|
try:
|
||||||
|
with table(out / "summary.csv") as writer, table(out / "disturbed.csv") as args.rejected:
|
||||||
|
series(args, writer)
|
||||||
|
finally:
|
||||||
|
if not args.keep:
|
||||||
|
compose("up", "-d", "--wait", "--wait-timeout", "180")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -3,50 +3,96 @@ from contextlib import asynccontextmanager
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
from asyncpg import ForeignKeyViolationError, Record
|
from sqlalchemy import (
|
||||||
|
BigInteger,
|
||||||
|
CheckConstraint,
|
||||||
|
DateTime,
|
||||||
|
ForeignKeyConstraint,
|
||||||
|
Index,
|
||||||
|
Integer,
|
||||||
|
RowMapping,
|
||||||
|
Select,
|
||||||
|
Text,
|
||||||
|
UniqueConstraint,
|
||||||
|
delete,
|
||||||
|
func,
|
||||||
|
insert,
|
||||||
|
select,
|
||||||
|
update,
|
||||||
|
)
|
||||||
|
from sqlalchemy.exc import IntegrityError
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
from messenger.attachments.domain.errors import ChatNotFound
|
from messenger.attachments.domain.errors import ChatNotFound
|
||||||
from messenger.attachments.domain.models import Attachment, AttachmentStatus, Quarantine
|
from messenger.attachments.domain.models import Attachment, AttachmentStatus, Quarantine
|
||||||
from messenger.attachments.domain.values import Filename, ImageInfo, ImageKind
|
from messenger.attachments.domain.values import Filename, ImageInfo, ImageKind
|
||||||
from messenger.shared.application.errors import Unavailable
|
from messenger.shared.application.errors import Unavailable
|
||||||
from messenger.shared.infrastructure.postgres import (
|
from messenger.shared.infrastructure.postgres import (
|
||||||
Connection,
|
Base,
|
||||||
Database,
|
Database,
|
||||||
|
DatabaseSession,
|
||||||
EventSource,
|
EventSource,
|
||||||
PostgresUnitOfWork,
|
PostgresUnitOfWork,
|
||||||
)
|
)
|
||||||
|
|
||||||
INSERT = """
|
|
||||||
INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
class AttachmentRow(Base):
|
||||||
width, height, object_key, status, created_at, updated_at)
|
__tablename__ = "attachments"
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
|
__table_args__ = (
|
||||||
"""
|
CheckConstraint(
|
||||||
MARK = "UPDATE attachments SET status = $2, updated_at = $3 WHERE id = $1 AND status = 'pending'"
|
"char_length(filename) BETWEEN 1 AND 255", name="attachments_filename_check"
|
||||||
COLUMNS = """
|
),
|
||||||
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256, width, height,
|
CheckConstraint(
|
||||||
object_key, status, created_at, updated_at, quarantine_reason
|
"content_type IN ('image/png', 'image/jpeg')", name="attachments_content_type_check"
|
||||||
FROM attachments
|
),
|
||||||
"""
|
CheckConstraint("size_bytes BETWEEN 1 AND 10485760", name="attachments_size_bytes_check"),
|
||||||
READY = COLUMNS + "WHERE id = $1 AND status = 'ready'"
|
CheckConstraint("sha256 ~ '^[0-9a-f]{64}$'", name="attachments_sha256_check"),
|
||||||
LOCK = COLUMNS + "WHERE id = $1 FOR UPDATE"
|
CheckConstraint("width > 0", name="attachments_width_check"),
|
||||||
ABANDONED = (
|
CheckConstraint("height > 0", name="attachments_height_check"),
|
||||||
COLUMNS
|
CheckConstraint("status IN ('pending', 'ready')", name="attachments_status_check"),
|
||||||
+ """WHERE status = 'pending' AND created_at < $1
|
CheckConstraint(
|
||||||
ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED"""
|
"quarantine_reason IN ('missing', 'size_mismatch', 'sha_mismatch')",
|
||||||
|
name="attachments_quarantine_reason_check",
|
||||||
|
),
|
||||||
|
CheckConstraint(
|
||||||
|
"(quarantine_reason IS NULL) = (quarantined_at IS NULL)",
|
||||||
|
name="attachments_quarantine_check",
|
||||||
|
),
|
||||||
|
UniqueConstraint("object_key", name="attachments_object_key_key"),
|
||||||
|
UniqueConstraint("id", "chat_id", name="attachments_chat_key"),
|
||||||
|
ForeignKeyConstraint(
|
||||||
|
["chat_id", "owner_id"],
|
||||||
|
["chat_members.chat_id", "chat_members.user_id"],
|
||||||
|
name="attachments_owner_fkey",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[UUID] = mapped_column(primary_key=True)
|
||||||
|
chat_id: Mapped[UUID]
|
||||||
|
owner_id: Mapped[UUID]
|
||||||
|
filename: Mapped[str]
|
||||||
|
content_type: Mapped[str]
|
||||||
|
size_bytes: Mapped[int] = mapped_column(BigInteger)
|
||||||
|
sha256: Mapped[str]
|
||||||
|
width: Mapped[int] = mapped_column(Integer)
|
||||||
|
height: Mapped[int] = mapped_column(Integer)
|
||||||
|
object_key: Mapped[str] = mapped_column(Text(collation="C"))
|
||||||
|
status: Mapped[str]
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||||
|
quarantine_reason: Mapped[str | None]
|
||||||
|
quarantined_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||||
|
|
||||||
|
|
||||||
|
Index(
|
||||||
|
"attachments_pending_idx",
|
||||||
|
AttachmentRow.created_at,
|
||||||
|
postgresql_where=AttachmentRow.status == "pending",
|
||||||
)
|
)
|
||||||
REMOVE = "DELETE FROM attachments WHERE id = $1 AND status = 'pending'"
|
COLUMNS = select(AttachmentRow.__table__)
|
||||||
PAGE = COLUMNS + "WHERE object_key > $1 ORDER BY object_key LIMIT $2"
|
|
||||||
BY_KEY = COLUMNS + "WHERE object_key = $1"
|
|
||||||
CLAIM = LOCK + " SKIP LOCKED"
|
|
||||||
QUARANTINE = """
|
|
||||||
UPDATE attachments
|
|
||||||
SET quarantine_reason = $2::text,
|
|
||||||
quarantined_at = CASE WHEN $2::text IS NULL THEN NULL ELSE now() END
|
|
||||||
WHERE id = $1 AND status = 'ready'
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
def attachment_of(row: Record) -> Attachment:
|
def attachment_of(row: RowMapping) -> Attachment:
|
||||||
return Attachment(
|
return Attachment(
|
||||||
id=row["id"],
|
id=row["id"],
|
||||||
chat_id=row["chat_id"],
|
chat_id=row["chat_id"],
|
||||||
@@ -64,68 +110,94 @@ def attachment_of(row: Record) -> Attachment:
|
|||||||
|
|
||||||
|
|
||||||
class PostgresAttachmentRepository:
|
class PostgresAttachmentRepository:
|
||||||
__slots__ = ("_connection", "_seen")
|
__slots__ = ("_seen", "_session")
|
||||||
|
|
||||||
def __init__(self, connection: Connection, seen: list[EventSource]) -> None:
|
def __init__(self, session: DatabaseSession, seen: list[EventSource]) -> None:
|
||||||
self._connection = connection
|
self._session = session
|
||||||
self._seen = seen
|
self._seen = seen
|
||||||
|
|
||||||
async def add(self, attachment: Attachment) -> None:
|
async def add(self, attachment: Attachment) -> None:
|
||||||
try:
|
try:
|
||||||
await self._connection.execute(
|
await self._session.execute(
|
||||||
INSERT,
|
insert(AttachmentRow).values(
|
||||||
attachment.id,
|
id=attachment.id,
|
||||||
attachment.chat_id,
|
chat_id=attachment.chat_id,
|
||||||
attachment.owner_id,
|
owner_id=attachment.owner_id,
|
||||||
attachment.filename.value,
|
filename=attachment.filename.value,
|
||||||
attachment.content_type,
|
content_type=attachment.content_type,
|
||||||
attachment.size_bytes,
|
size_bytes=attachment.size_bytes,
|
||||||
attachment.sha256,
|
sha256=attachment.sha256,
|
||||||
attachment.image.width,
|
width=attachment.image.width,
|
||||||
attachment.image.height,
|
height=attachment.image.height,
|
||||||
attachment.object_key,
|
object_key=attachment.object_key,
|
||||||
attachment.status.value,
|
status=attachment.status.value,
|
||||||
attachment.created_at,
|
created_at=attachment.created_at,
|
||||||
attachment.updated_at,
|
updated_at=attachment.updated_at,
|
||||||
|
)
|
||||||
)
|
)
|
||||||
except ForeignKeyViolationError as error:
|
except IntegrityError as error:
|
||||||
|
if getattr(error.orig, "sqlstate", None) != "23503":
|
||||||
|
raise
|
||||||
raise ChatNotFound("чат не найден") from error
|
raise ChatNotFound("чат не найден") from error
|
||||||
self._seen.append(attachment)
|
self._seen.append(attachment)
|
||||||
|
|
||||||
async def save(self, attachment: Attachment) -> None:
|
async def save(self, attachment: Attachment) -> None:
|
||||||
done = await self._connection.execute(
|
done = await self._session.scalar(
|
||||||
MARK, attachment.id, attachment.status.value, attachment.updated_at
|
update(AttachmentRow)
|
||||||
|
.where(AttachmentRow.id == attachment.id, AttachmentRow.status == "pending")
|
||||||
|
.values(status=attachment.status.value, updated_at=attachment.updated_at)
|
||||||
|
.returning(AttachmentRow.id)
|
||||||
)
|
)
|
||||||
if done == "UPDATE 0":
|
if done is None:
|
||||||
raise Unavailable("намерение загрузки уже снято уборкой")
|
raise Unavailable("намерение загрузки уже снято уборкой")
|
||||||
self._seen.append(attachment)
|
self._seen.append(attachment)
|
||||||
|
|
||||||
async def lock(self, attachment_id: UUID) -> Attachment | None:
|
async def _one(self, statement: Select) -> Attachment | None:
|
||||||
row = await self._connection.fetchrow(LOCK, attachment_id)
|
row = (await self._session.execute(statement)).mappings().first()
|
||||||
return None if row is None else attachment_of(row)
|
return None if row is None else attachment_of(row)
|
||||||
|
|
||||||
|
async def lock(self, attachment_id: UUID) -> Attachment | None:
|
||||||
|
return await self._one(COLUMNS.where(AttachmentRow.id == attachment_id).with_for_update())
|
||||||
|
|
||||||
async def next_abandoned(self, before: datetime) -> Attachment | None:
|
async def next_abandoned(self, before: datetime) -> Attachment | None:
|
||||||
row = await self._connection.fetchrow(ABANDONED, before)
|
return await self._one(
|
||||||
return None if row is None else attachment_of(row)
|
COLUMNS.where(AttachmentRow.status == "pending", AttachmentRow.created_at < before)
|
||||||
|
.order_by(AttachmentRow.created_at)
|
||||||
|
.limit(1)
|
||||||
|
.with_for_update(skip_locked=True)
|
||||||
|
)
|
||||||
|
|
||||||
async def remove(self, attachment: Attachment) -> None:
|
async def remove(self, attachment: Attachment) -> None:
|
||||||
await self._connection.execute(REMOVE, attachment.id)
|
await self._session.execute(
|
||||||
|
delete(AttachmentRow).where(
|
||||||
|
AttachmentRow.id == attachment.id, AttachmentRow.status == "pending"
|
||||||
|
)
|
||||||
|
)
|
||||||
self._seen.append(attachment)
|
self._seen.append(attachment)
|
||||||
|
|
||||||
async def page_after(self, key: str, limit: int) -> Sequence[Attachment]:
|
async def page_after(self, key: str, limit: int) -> Sequence[Attachment]:
|
||||||
return [attachment_of(row) for row in await self._connection.fetch(PAGE, key, limit)]
|
rows = await self._session.execute(
|
||||||
|
COLUMNS.where(AttachmentRow.object_key > key)
|
||||||
|
.order_by(AttachmentRow.object_key)
|
||||||
|
.limit(limit)
|
||||||
|
)
|
||||||
|
return [attachment_of(row) for row in rows.mappings()]
|
||||||
|
|
||||||
async def by_key(self, key: str) -> Attachment | None:
|
async def by_key(self, key: str) -> Attachment | None:
|
||||||
row = await self._connection.fetchrow(BY_KEY, key)
|
return await self._one(COLUMNS.where(AttachmentRow.object_key == key))
|
||||||
return None if row is None else attachment_of(row)
|
|
||||||
|
|
||||||
async def claim(self, attachment_id: UUID) -> Attachment | None:
|
async def claim(self, attachment_id: UUID) -> Attachment | None:
|
||||||
row = await self._connection.fetchrow(CLAIM, attachment_id)
|
return await self._one(
|
||||||
return None if row is None else attachment_of(row)
|
COLUMNS.where(AttachmentRow.id == attachment_id).with_for_update(skip_locked=True)
|
||||||
|
)
|
||||||
|
|
||||||
async def mark(self, attachment: Attachment) -> None:
|
async def mark(self, attachment: Attachment) -> None:
|
||||||
reason = None if attachment.quarantine is None else attachment.quarantine.value
|
reason = None if attachment.quarantine is None else attachment.quarantine.value
|
||||||
await self._connection.execute(QUARANTINE, attachment.id, reason)
|
await self._session.execute(
|
||||||
|
update(AttachmentRow)
|
||||||
|
.where(AttachmentRow.id == attachment.id, AttachmentRow.status == "ready")
|
||||||
|
.values(quarantine_reason=reason, quarantined_at=None if reason is None else func.now())
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class PostgresAttachmentsUnitOfWork(PostgresUnitOfWork):
|
class PostgresAttachmentsUnitOfWork(PostgresUnitOfWork):
|
||||||
@@ -133,7 +205,7 @@ class PostgresAttachmentsUnitOfWork(PostgresUnitOfWork):
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def attachments(self) -> PostgresAttachmentRepository:
|
def attachments(self) -> PostgresAttachmentRepository:
|
||||||
return PostgresAttachmentRepository(self.connection, self.seen)
|
return PostgresAttachmentRepository(self.session, self.seen)
|
||||||
|
|
||||||
|
|
||||||
class PostgresAttachmentDirectory:
|
class PostgresAttachmentDirectory:
|
||||||
@@ -143,8 +215,18 @@ class PostgresAttachmentDirectory:
|
|||||||
self._database = database
|
self._database = database
|
||||||
|
|
||||||
async def ready(self, attachment_id: UUID) -> Attachment | None:
|
async def ready(self, attachment_id: UUID) -> Attachment | None:
|
||||||
async with self._database.connection() as connection:
|
async with self._database.session() as session:
|
||||||
row = await connection.fetchrow(READY, attachment_id)
|
row = (
|
||||||
|
(
|
||||||
|
await session.execute(
|
||||||
|
COLUMNS.where(
|
||||||
|
AttachmentRow.id == attachment_id, AttachmentRow.status == "ready"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.mappings()
|
||||||
|
.first()
|
||||||
|
)
|
||||||
return None if row is None else attachment_of(row)
|
return None if row is None else attachment_of(row)
|
||||||
|
|
||||||
|
|
||||||
@@ -157,10 +239,13 @@ class PostgresSingleRun:
|
|||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def hold(self) -> AsyncIterator[bool]:
|
async def hold(self) -> AsyncIterator[bool]:
|
||||||
async with self._database.connection() as connection:
|
async with self._database.session() as session:
|
||||||
held = await connection.fetchval("SELECT pg_try_advisory_lock($1)", self._key)
|
connection = await session.connection(
|
||||||
|
execution_options={"isolation_level": "AUTOCOMMIT"}
|
||||||
|
)
|
||||||
|
held = bool(await connection.scalar(select(func.pg_try_advisory_lock(self._key))))
|
||||||
try:
|
try:
|
||||||
yield held
|
yield held
|
||||||
finally:
|
finally:
|
||||||
if held:
|
if held:
|
||||||
await connection.fetchval("SELECT pg_advisory_unlock($1)", self._key)
|
await connection.execute(select(func.pg_advisory_unlock(self._key)))
|
||||||
|
|||||||
@@ -1,85 +1,126 @@
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from uuid import UUID
|
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.errors import UsernameAlreadyTaken
|
||||||
from messenger.identity.domain.models import Session, User
|
from messenger.identity.domain.models import Session, User
|
||||||
from messenger.identity.domain.values import DisplayName, Username
|
from messenger.identity.domain.values import DisplayName, Username
|
||||||
from messenger.shared.infrastructure.postgres import Connection, Database, PostgresUnitOfWork
|
from messenger.shared.infrastructure.postgres import (
|
||||||
|
Base,
|
||||||
INSERT_USER = """
|
Database,
|
||||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
DatabaseSession,
|
||||||
VALUES ($1, $2, $3, $4, $5)
|
PostgresUnitOfWork,
|
||||||
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
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
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:
|
if row is None:
|
||||||
return None
|
return None
|
||||||
return User(
|
return User(
|
||||||
id=row["id"],
|
id=row.id,
|
||||||
username=Username(row["username"]),
|
username=Username(row.username),
|
||||||
display_name=DisplayName(row["display_name"]),
|
display_name=DisplayName(row.display_name),
|
||||||
created_at=row["created_at"],
|
created_at=row.created_at,
|
||||||
password_hash=row["password_hash"],
|
password_hash=row.password_hash,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class PostgresUserRepository:
|
class PostgresUserRepository:
|
||||||
__slots__ = ("_connection",)
|
__slots__ = ("_session",)
|
||||||
|
|
||||||
def __init__(self, connection: Connection) -> None:
|
def __init__(self, session: DatabaseSession) -> None:
|
||||||
self._connection = connection
|
self._session = session
|
||||||
|
|
||||||
async def add(self, user: User) -> None:
|
async def add(self, user: User) -> None:
|
||||||
inserted = await self._connection.fetchval(
|
statement = (
|
||||||
INSERT_USER,
|
insert(UserRow)
|
||||||
user.id,
|
.values(
|
||||||
user.username.value,
|
id=user.id,
|
||||||
user.display_name.value,
|
username=user.username.value,
|
||||||
user.password_hash,
|
display_name=user.display_name.value,
|
||||||
user.created_at,
|
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:
|
if inserted is None:
|
||||||
raise UsernameAlreadyTaken("username уже занят")
|
raise UsernameAlreadyTaken("username уже занят")
|
||||||
|
|
||||||
|
|
||||||
class PostgresSessionRepository:
|
class PostgresSessionRepository:
|
||||||
__slots__ = ("_connection",)
|
__slots__ = ("_session",)
|
||||||
|
|
||||||
def __init__(self, connection: Connection) -> None:
|
def __init__(self, session: DatabaseSession) -> None:
|
||||||
self._connection = connection
|
self._session = session
|
||||||
|
|
||||||
async def add(self, session: Session) -> None:
|
async def add(self, session: Session) -> None:
|
||||||
await self._connection.execute(
|
expired = (
|
||||||
INSERT_SESSION,
|
delete(SessionRow)
|
||||||
session.token_hash,
|
.where(
|
||||||
session.user_id,
|
SessionRow.user_id == session.user_id, SessionRow.expires_at <= session.created_at
|
||||||
session.created_at,
|
)
|
||||||
session.expires_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:
|
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):
|
class PostgresIdentityUnitOfWork(PostgresUnitOfWork):
|
||||||
@@ -87,11 +128,11 @@ class PostgresIdentityUnitOfWork(PostgresUnitOfWork):
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def users(self) -> PostgresUserRepository:
|
def users(self) -> PostgresUserRepository:
|
||||||
return PostgresUserRepository(self.connection)
|
return PostgresUserRepository(self.session)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def sessions(self) -> PostgresSessionRepository:
|
def sessions(self) -> PostgresSessionRepository:
|
||||||
return PostgresSessionRepository(self.connection)
|
return PostgresSessionRepository(self.session)
|
||||||
|
|
||||||
|
|
||||||
class PostgresUserDirectory:
|
class PostgresUserDirectory:
|
||||||
@@ -101,12 +142,18 @@ class PostgresUserDirectory:
|
|||||||
self._database = database
|
self._database = database
|
||||||
|
|
||||||
async def find(self, user_id: UUID) -> User | None:
|
async def find(self, user_id: UUID) -> User | None:
|
||||||
async with self._database.connection() as connection:
|
async with self._database.session() as session:
|
||||||
return user_of(await connection.fetchrow(USER_BY_ID, user_id))
|
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 def find_by_username(self, username: str) -> User | None:
|
||||||
async with self._database.connection() as connection:
|
async with self._database.session() as session:
|
||||||
return user_of(await connection.fetchrow(USER_BY_USERNAME, username))
|
row = (
|
||||||
|
await session.execute(select(UserRow).where(UserRow.username == username))
|
||||||
|
).scalar_one_or_none()
|
||||||
|
return user_of(row)
|
||||||
|
|
||||||
|
|
||||||
class PostgresSessionDirectory:
|
class PostgresSessionDirectory:
|
||||||
@@ -116,6 +163,20 @@ class PostgresSessionDirectory:
|
|||||||
self._database = database
|
self._database = database
|
||||||
|
|
||||||
async def find(self, token_hash: bytes, now: datetime) -> Session | None:
|
async def find(self, token_hash: bytes, now: datetime) -> Session | None:
|
||||||
async with self._database.connection() as connection:
|
async with self._database.session() as session:
|
||||||
row = await connection.fetchrow(ACTIVE_SESSION, token_hash, now)
|
row = (
|
||||||
return None if row is None else Session(**dict(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,
|
||||||
|
)
|
||||||
|
|||||||
@@ -1,9 +1,38 @@
|
|||||||
from collections.abc import Sequence
|
from collections.abc import Sequence
|
||||||
from dataclasses import replace
|
from dataclasses import replace
|
||||||
from datetime import datetime
|
from datetime import datetime, timedelta
|
||||||
|
from typing import cast
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
from asyncpg import ForeignKeyViolationError, Record
|
from sqlalchemy import (
|
||||||
|
CheckConstraint,
|
||||||
|
DateTime,
|
||||||
|
ForeignKey,
|
||||||
|
ForeignKeyConstraint,
|
||||||
|
Index,
|
||||||
|
LargeBinary,
|
||||||
|
RowMapping,
|
||||||
|
Select,
|
||||||
|
SmallInteger,
|
||||||
|
Table,
|
||||||
|
UniqueConstraint,
|
||||||
|
bindparam,
|
||||||
|
column,
|
||||||
|
func,
|
||||||
|
insert,
|
||||||
|
lambda_stmt,
|
||||||
|
literal,
|
||||||
|
select,
|
||||||
|
true,
|
||||||
|
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, UnknownAttachment
|
from messenger.messaging.domain.errors import InvalidChatData, UnknownAttachment
|
||||||
from messenger.messaging.domain.keys import HistoryKey
|
from messenger.messaging.domain.keys import HistoryKey
|
||||||
@@ -11,97 +40,206 @@ from messenger.messaging.domain.models import Chat, Message, Receipt
|
|||||||
from messenger.messaging.domain.values import ChatTitle, MessageText
|
from messenger.messaging.domain.values import ChatTitle, MessageText
|
||||||
from messenger.shared.application.errors import Unavailable
|
from messenger.shared.application.errors import Unavailable
|
||||||
from messenger.shared.infrastructure.postgres import (
|
from messenger.shared.infrastructure.postgres import (
|
||||||
Connection,
|
Base,
|
||||||
Database,
|
Database,
|
||||||
|
DatabaseSession,
|
||||||
EventSource,
|
EventSource,
|
||||||
PostgresUnitOfWork,
|
PostgresUnitOfWork,
|
||||||
)
|
)
|
||||||
|
|
||||||
INSERT_CHAT = "INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)"
|
FOREIGN_KEY_VIOLATED = "23503"
|
||||||
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
|
|
||||||
), links AS (
|
|
||||||
INSERT INTO message_attachments (message_id, position, chat_id, attachment_id)
|
|
||||||
SELECT $1, link.position - 1, $2, link.attachment_id
|
|
||||||
FROM message, unnest($9::uuid[]) WITH ORDINALITY AS link (attachment_id, position)
|
|
||||||
), 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
|
|
||||||
"""
|
|
||||||
ATTACHMENT_FKEY = "message_attachments_attachment_fkey"
|
|
||||||
RECEIPT = """
|
|
||||||
SELECT k.fingerprint, m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
|
||||||
ARRAY(SELECT a.attachment_id FROM message_attachments a
|
|
||||||
WHERE a.message_id = m.id ORDER BY a.position) AS attachment_ids
|
|
||||||
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 m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
|
||||||
ARRAY(SELECT a.attachment_id FROM message_attachments a
|
|
||||||
WHERE a.message_id = m.id ORDER BY a.position) AS attachment_ids
|
|
||||||
FROM messages m
|
|
||||||
WHERE m.chat_id = $1
|
|
||||||
ORDER BY m.created_at, m.id
|
|
||||||
LIMIT $2
|
|
||||||
"""
|
|
||||||
HISTORY_AFTER = """
|
|
||||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
|
||||||
ARRAY(SELECT a.attachment_id FROM message_attachments a
|
|
||||||
WHERE a.message_id = m.id ORDER BY a.position) AS attachment_ids
|
|
||||||
FROM messages m
|
|
||||||
WHERE m.chat_id = $1 AND (m.created_at, m.id) > ($2, $3)
|
|
||||||
ORDER BY m.created_at, m.id
|
|
||||||
LIMIT $4
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
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) <= 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))
|
||||||
|
|
||||||
|
|
||||||
|
class MessageAttachmentRow(Base):
|
||||||
|
__tablename__ = "message_attachments"
|
||||||
|
__table_args__ = (
|
||||||
|
CheckConstraint("position BETWEEN 0 AND 9", name="message_attachments_position_check"),
|
||||||
|
UniqueConstraint("message_id", "attachment_id"),
|
||||||
|
ForeignKeyConstraint(
|
||||||
|
["attachment_id", "chat_id"],
|
||||||
|
["attachments.id", "attachments.chat_id"],
|
||||||
|
name="message_attachments_attachment_fkey",
|
||||||
|
ondelete="RESTRICT",
|
||||||
|
),
|
||||||
|
Index("message_attachments_attachment_idx", "attachment_id"),
|
||||||
|
)
|
||||||
|
|
||||||
|
message_id: Mapped[UUID] = mapped_column(
|
||||||
|
ForeignKey("messages.id", ondelete="CASCADE"), primary_key=True
|
||||||
|
)
|
||||||
|
position: Mapped[int] = mapped_column(SmallInteger, primary_key=True)
|
||||||
|
chat_id: Mapped[UUID]
|
||||||
|
attachment_id: Mapped[UUID]
|
||||||
|
|
||||||
|
|
||||||
|
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")
|
||||||
|
)
|
||||||
|
attachments = (
|
||||||
|
func.unnest(bindparam("attachment_ids", type_=ARRAY(PGUUID)))
|
||||||
|
.table_valued(column("attachment_id", PGUUID), with_ordinality="position")
|
||||||
|
.render_derived(name="attachment")
|
||||||
|
)
|
||||||
|
links = (
|
||||||
|
insert(cast(Table, MessageAttachmentRow.__table__))
|
||||||
|
.from_select(
|
||||||
|
["message_id", "position", "chat_id", "attachment_id"],
|
||||||
|
select(
|
||||||
|
message_id, attachments.c.position - 1, chat_id, attachments.c.attachment_id
|
||||||
|
).select_from(message.join(attachments, true())),
|
||||||
|
)
|
||||||
|
.cte("links")
|
||||||
|
)
|
||||||
|
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(links, touched)
|
||||||
|
|
||||||
|
|
||||||
|
POST_MESSAGE = lambda_stmt(post_message, enable_tracking=False)
|
||||||
|
|
||||||
|
|
||||||
|
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 attachment_ids() -> Label[Sequence[UUID]]:
|
||||||
|
return func.array(
|
||||||
|
select(MessageAttachmentRow.attachment_id)
|
||||||
|
.where(MessageAttachmentRow.message_id == MessageRow.id)
|
||||||
|
.order_by(MessageAttachmentRow.position)
|
||||||
|
.correlate(MessageRow)
|
||||||
|
.scalar_subquery(),
|
||||||
|
type_=ARRAY(PGUUID(as_uuid=True)),
|
||||||
|
).label("attachment_ids")
|
||||||
|
|
||||||
|
|
||||||
|
def chat_of(row: RowMapping) -> Chat:
|
||||||
return Chat(
|
return Chat(
|
||||||
chat_id=row["id"],
|
chat_id=row["id"],
|
||||||
title=ChatTitle(row["title"]),
|
title=ChatTitle(row["title"]),
|
||||||
@@ -110,14 +248,14 @@ def chat_of(row: Record) -> Chat:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def message_of(row: Record) -> Message:
|
def message_of(row: RowMapping) -> Message:
|
||||||
return Message(
|
return Message(
|
||||||
id=row["id"],
|
id=row["id"],
|
||||||
chat_id=row["chat_id"],
|
chat_id=row["chat_id"],
|
||||||
sender_id=row["sender_id"],
|
sender_id=row["sender_id"],
|
||||||
text=MessageText(row["text"]),
|
text=MessageText(row["text"]),
|
||||||
created_at=row["created_at"],
|
|
||||||
attachment_ids=tuple(row["attachment_ids"]),
|
attachment_ids=tuple(row["attachment_ids"]),
|
||||||
|
created_at=row["created_at"],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -126,19 +264,32 @@ def page[ItemT](rows: Sequence[ItemT], limit: int) -> tuple[list[ItemT], bool]:
|
|||||||
|
|
||||||
|
|
||||||
class PostgresChatRepository:
|
class PostgresChatRepository:
|
||||||
__slots__ = ("_connection", "_seen")
|
__slots__ = ("_seen", "_session")
|
||||||
|
|
||||||
def __init__(self, connection: Connection, seen: list[EventSource]) -> None:
|
def __init__(self, session: DatabaseSession, seen: list[EventSource]) -> None:
|
||||||
self._connection = connection
|
self._session = session
|
||||||
self._seen = seen
|
self._seen = seen
|
||||||
|
|
||||||
async def add(self, chat: Chat) -> None:
|
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:
|
try:
|
||||||
await self._connection.execute(
|
await self._session.execute(
|
||||||
INSERT_MEMBERS, chat.id, list(chat.member_ids), chat.created_at
|
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
|
raise InvalidChatData("поле member_ids содержит неизвестного пользователя") from error
|
||||||
self._seen.append(chat)
|
self._seen.append(chat)
|
||||||
|
|
||||||
@@ -153,29 +304,62 @@ class PostgresMessageLog:
|
|||||||
self, message: Message, key: str, fingerprint: bytes, since: datetime
|
self, message: Message, key: str, fingerprint: bytes, since: datetime
|
||||||
) -> Receipt | None:
|
) -> Receipt | None:
|
||||||
chat_id, sender_id = message.chat_id, message.sender_id
|
chat_id, sender_id = message.chat_id, message.sender_id
|
||||||
async with self._database.connection() as connection:
|
async with self._database.session() as session:
|
||||||
try:
|
try:
|
||||||
row = await connection.fetchrow(
|
row = (
|
||||||
POST_MESSAGE,
|
(
|
||||||
message.id,
|
await session.execute(
|
||||||
chat_id,
|
POST_MESSAGE,
|
||||||
sender_id,
|
{
|
||||||
message.text.value,
|
"message_id": message.id,
|
||||||
message.created_at,
|
"chat_id": chat_id,
|
||||||
key,
|
"sender_id": sender_id,
|
||||||
fingerprint,
|
"text": message.text.value,
|
||||||
since,
|
"stamp": message.created_at,
|
||||||
list(message.attachment_ids),
|
"key": key,
|
||||||
|
"fingerprint": fingerprint,
|
||||||
|
"since": since,
|
||||||
|
"attachment_ids": list(message.attachment_ids),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.mappings()
|
||||||
|
.first()
|
||||||
)
|
)
|
||||||
except ForeignKeyViolationError as error:
|
except IntegrityError as error:
|
||||||
if getattr(error, "constraint_name", None) != ATTACHMENT_FKEY:
|
cause = getattr(error.orig, "__cause__", None)
|
||||||
|
if getattr(cause, "constraint_name", None) != "message_attachments_attachment_fkey":
|
||||||
raise
|
raise
|
||||||
raise UnknownAttachment("вложение не найдено в этом чате") from error
|
raise UnknownAttachment("вложение не найдено в этом чате") from error
|
||||||
if row is None or not row["member"]:
|
if row is None or not row["member"]:
|
||||||
return None
|
return None
|
||||||
if row["created_at"] is not None:
|
if row["created_at"] is not None:
|
||||||
|
await session.commit()
|
||||||
return Receipt(key, fingerprint, replace(message, created_at=row["created_at"]))
|
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,
|
||||||
|
attachment_ids(),
|
||||||
|
)
|
||||||
|
.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:
|
if known is None:
|
||||||
raise Unavailable("ключ идемпотентности занят незавершённой записью")
|
raise Unavailable("ключ идемпотентности занят незавершённой записью")
|
||||||
return Receipt(key, known["fingerprint"], message_of(known))
|
return Receipt(key, known["fingerprint"], message_of(known))
|
||||||
@@ -186,7 +370,7 @@ class PostgresMessagingUnitOfWork(PostgresUnitOfWork):
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def chats(self) -> PostgresChatRepository:
|
def chats(self) -> PostgresChatRepository:
|
||||||
return PostgresChatRepository(self.connection, self.seen)
|
return PostgresChatRepository(self.session, self.seen)
|
||||||
|
|
||||||
|
|
||||||
class PostgresChatDirectory:
|
class PostgresChatDirectory:
|
||||||
@@ -196,30 +380,62 @@ class PostgresChatDirectory:
|
|||||||
self._database = database
|
self._database = database
|
||||||
|
|
||||||
async def chat_for_member(self, chat_id: UUID, user_id: UUID) -> Chat | None:
|
async def chat_for_member(self, chat_id: UUID, user_id: UUID) -> Chat | None:
|
||||||
async with self._database.connection() as connection:
|
async with self._database.session() as session:
|
||||||
row = await connection.fetchrow(CHAT_OF_MEMBER, chat_id, user_id)
|
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)
|
return None if row is None else chat_of(row)
|
||||||
|
|
||||||
async def chats_of(
|
async def chats_of(
|
||||||
self, user_id: UUID, *, after: HistoryKey | None, limit: int
|
self, user_id: UUID, *, after: HistoryKey | None, limit: int
|
||||||
) -> tuple[list[Chat], bool]:
|
) -> tuple[list[Chat], bool]:
|
||||||
async with self._database.connection() as connection:
|
statement = (
|
||||||
if after is None:
|
select(ChatRow.id, ChatRow.title, ChatRow.created_at, member_ids())
|
||||||
rows = await connection.fetch(CHATS_FIRST, user_id, limit + 1)
|
.select_from(ChatMemberRow)
|
||||||
else:
|
.join(ChatRow, ChatRow.id == ChatMemberRow.chat_id)
|
||||||
rows = await connection.fetch(
|
.where(ChatMemberRow.user_id == user_id)
|
||||||
CHATS_AFTER, user_id, after[0], UUID(int=after[1]), limit + 1
|
.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)
|
return page([chat_of(row) for row in rows], limit)
|
||||||
|
|
||||||
async def history(
|
async def history(
|
||||||
self, chat_id: UUID, *, after: HistoryKey | None, limit: int
|
self, chat_id: UUID, *, after: HistoryKey | None, limit: int
|
||||||
) -> tuple[list[Message], bool]:
|
) -> tuple[list[Message], bool]:
|
||||||
async with self._database.connection() as connection:
|
statement = (
|
||||||
if after is None:
|
select(
|
||||||
rows = await connection.fetch(HISTORY_FIRST, chat_id, limit + 1)
|
MessageRow.id,
|
||||||
else:
|
MessageRow.chat_id,
|
||||||
rows = await connection.fetch(
|
MessageRow.sender_id,
|
||||||
HISTORY_AFTER, chat_id, after[0], UUID(int=after[1]), limit + 1
|
MessageRow.text,
|
||||||
)
|
MessageRow.created_at,
|
||||||
|
attachment_ids(),
|
||||||
|
)
|
||||||
|
.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)
|
return page([message_of(row) for row in rows], limit)
|
||||||
|
|||||||
@@ -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()
|
|
||||||
@@ -1,32 +1,45 @@
|
|||||||
|
import asyncio
|
||||||
from collections.abc import AsyncIterator
|
from collections.abc import AsyncIterator
|
||||||
from contextlib import asynccontextmanager
|
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.application.errors import Unavailable
|
||||||
from messenger.shared.domain.events import DomainEvent
|
from messenger.shared.domain.events import DomainEvent
|
||||||
|
|
||||||
FAILURES = (
|
FAILURES = (OSError, InterfaceError, OperationalError, PoolTimeout, TimeoutError)
|
||||||
OSError,
|
|
||||||
asyncpg.InterfaceError,
|
|
||||||
asyncpg.PostgresConnectionError,
|
|
||||||
asyncpg.exceptions.OperatorInterventionError,
|
|
||||||
asyncpg.exceptions.InsufficientResourcesError,
|
|
||||||
asyncpg.exceptions.LockNotAvailableError,
|
|
||||||
)
|
|
||||||
|
|
||||||
PING_TIMEOUT_SECONDS = 0.4
|
PING_TIMEOUT_SECONDS = 0.4
|
||||||
|
|
||||||
type Connection = asyncpg.Connection
|
type DatabaseSession = AsyncSession
|
||||||
|
|
||||||
|
|
||||||
class EventSource(Protocol):
|
class EventSource(Protocol):
|
||||||
def collect_events(self) -> list[DomainEvent]: ...
|
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:
|
class Database:
|
||||||
__slots__ = ("_acquire_timeout", "_pool")
|
__slots__ = ("_engine", "_sessions")
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
@@ -37,63 +50,71 @@ class Database:
|
|||||||
acquire_timeout: float,
|
acquire_timeout: float,
|
||||||
command_timeout: float,
|
command_timeout: float,
|
||||||
) -> None:
|
) -> None:
|
||||||
self._acquire_timeout = acquire_timeout
|
self._engine = create_async_engine(
|
||||||
self._pool = asyncpg.create_pool(
|
make_url(dsn).set(drivername="postgresql+asyncpg"),
|
||||||
dsn,
|
pool_size=max_size,
|
||||||
min_size=0,
|
max_overflow=0,
|
||||||
max_size=max_size,
|
pool_timeout=acquire_timeout,
|
||||||
timeout=connect_timeout,
|
pool_recycle=60,
|
||||||
command_timeout=command_timeout,
|
pool_pre_ping=True,
|
||||||
max_inactive_connection_lifetime=60,
|
hide_parameters=True,
|
||||||
server_settings={
|
connect_args={
|
||||||
"statement_timeout": str(int(command_timeout * 1000)),
|
"timeout": connect_timeout,
|
||||||
"lock_timeout": str(int(command_timeout * 1000)),
|
"command_timeout": command_timeout,
|
||||||
"idle_in_transaction_session_timeout": "10000",
|
"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:
|
async def open(self) -> None:
|
||||||
await self._pool
|
pass
|
||||||
|
|
||||||
async def close(self) -> None:
|
async def close(self) -> None:
|
||||||
await self._pool.close()
|
await self._engine.dispose()
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def connection(self, wait: float | None = None) -> AsyncIterator[Connection]:
|
async def session(self) -> AsyncIterator[DatabaseSession]:
|
||||||
try:
|
try:
|
||||||
async with self._pool.acquire(timeout=wait or self._acquire_timeout) as connection:
|
async with self._sessions() as session:
|
||||||
yield connection
|
yield session
|
||||||
except FAILURES as error:
|
except Exception as error:
|
||||||
|
if not unavailable(error):
|
||||||
|
raise
|
||||||
raise Unavailable("PostgreSQL недоступен") from error
|
raise Unavailable("PostgreSQL недоступен") from error
|
||||||
|
|
||||||
async def ping(self) -> None:
|
async def ping(self) -> None:
|
||||||
async with self.connection(PING_TIMEOUT_SECONDS) as connection:
|
try:
|
||||||
await connection.fetchval("SELECT 1", timeout=PING_TIMEOUT_SECONDS)
|
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:
|
class PostgresUnitOfWork:
|
||||||
__slots__ = ("_committed", "_connection", "_database", "_events", "_transaction", "seen")
|
__slots__ = ("_committed", "_database", "_events", "_session", "seen")
|
||||||
|
|
||||||
def __init__(self, database: Database) -> None:
|
def __init__(self, database: Database) -> None:
|
||||||
self._database = database
|
self._database = database
|
||||||
self._connection: Connection | None = None
|
self._session: DatabaseSession | None = None
|
||||||
self._transaction: Any = None
|
|
||||||
self._committed = False
|
self._committed = False
|
||||||
self._events: list[DomainEvent] = []
|
self._events: list[DomainEvent] = []
|
||||||
self.seen: list[EventSource] = []
|
self.seen: list[EventSource] = []
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def connection(self) -> Connection:
|
def session(self) -> DatabaseSession:
|
||||||
if self._connection is None:
|
if self._session is None:
|
||||||
raise RuntimeError("репозиторий используется вне транзакции")
|
raise RuntimeError("репозиторий используется вне транзакции")
|
||||||
return self._connection
|
return self._session
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def transaction(self) -> AsyncIterator[None]:
|
async def transaction(self) -> AsyncIterator[None]:
|
||||||
async with self._database.connection() as connection:
|
async with self._database.session() as session:
|
||||||
self._connection = connection
|
self._session = session
|
||||||
self._transaction = connection.transaction()
|
|
||||||
await self._transaction.start()
|
|
||||||
self._committed = False
|
self._committed = False
|
||||||
mark = len(self._events)
|
mark = len(self._events)
|
||||||
try:
|
try:
|
||||||
@@ -101,12 +122,11 @@ class PostgresUnitOfWork:
|
|||||||
finally:
|
finally:
|
||||||
if not self._committed:
|
if not self._committed:
|
||||||
del self._events[mark:]
|
del self._events[mark:]
|
||||||
await self._transaction.rollback()
|
|
||||||
self.seen.clear()
|
self.seen.clear()
|
||||||
self._connection = None
|
self._session = None
|
||||||
|
|
||||||
async def commit(self) -> None:
|
async def commit(self) -> None:
|
||||||
await self._transaction.commit()
|
await self.session.commit()
|
||||||
self._committed = True
|
self._committed = True
|
||||||
for source in self.seen:
|
for source in self.seen:
|
||||||
self._events.extend(source.collect_events())
|
self._events.extend(source.collect_events())
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ from uuid import uuid4
|
|||||||
import httpx
|
import httpx
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from conftest import STARTUP_SECONDS, container, image, published
|
from conftest import STARTUP_SECONDS, container, free_port, image, published
|
||||||
from messenger.attachments.application.errors import ObjectMissingError
|
from messenger.attachments.application.errors import ObjectMissingError
|
||||||
from messenger.attachments.infrastructure.s3 import S3ObjectStorage, s3_client
|
from messenger.attachments.infrastructure.s3 import S3ObjectStorage, s3_client
|
||||||
from messenger.shared.application.errors import Unavailable
|
from messenger.shared.application.errors import Unavailable
|
||||||
@@ -23,7 +23,7 @@ BUCKET = "messenger-attachments"
|
|||||||
def rustfs() -> Iterator[str]:
|
def rustfs() -> Iterator[str]:
|
||||||
name = f"mtusi-lab4-test-rustfs-{uuid4().hex[:8]}"
|
name = f"mtusi-lab4-test-rustfs-{uuid4().hex[:8]}"
|
||||||
keys = ["-e", f"RUSTFS_ACCESS_KEY={ROOT_KEY}", "-e", f"RUSTFS_SECRET_KEY={ROOT_SECRET}"]
|
keys = ["-e", f"RUSTFS_ACCESS_KEY={ROOT_KEY}", "-e", f"RUSTFS_SECRET_KEY={ROOT_SECRET}"]
|
||||||
container(name, *keys, "-p", "127.0.0.1::9000", image(RUSTFS_IMAGE))
|
container(name, *keys, "-p", f"127.0.0.1:{free_port()}:9000", image(RUSTFS_IMAGE))
|
||||||
try:
|
try:
|
||||||
endpoint = f"http://127.0.0.1:{published(name, 9000)}"
|
endpoint = f"http://127.0.0.1:{published(name, 9000)}"
|
||||||
deadline = time.monotonic() + STARTUP_SECONDS
|
deadline = time.monotonic() + STARTUP_SECONDS
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
import time
|
import time
|
||||||
from uuid import uuid4
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
import asyncpg
|
|
||||||
from httpx import AsyncClient
|
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:
|
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")
|
alice = await register(client, "alice")
|
||||||
eve = await register(client, "eve")
|
eve = await register(client, "eve")
|
||||||
chat = await make_chat(client, alice)
|
chat = await make_chat(client, alice)
|
||||||
holder = await asyncpg.connect(DATABASE["url"])
|
async with sql_connection() as holder:
|
||||||
try:
|
await holder.execute(
|
||||||
async with holder.transaction():
|
select(ChatRow.id).where(ChatRow.id == UUID(chat["id"])).with_for_update()
|
||||||
await holder.execute("SELECT 1 FROM chats WHERE id = $1 FOR UPDATE", chat["id"])
|
)
|
||||||
started = time.perf_counter()
|
started = time.perf_counter()
|
||||||
response = await client.post(
|
response = await client.post(
|
||||||
f"/api/v1/chats/{chat['id']}/messages", json={"text": "чужое"}, headers=keyed(eve)
|
f"/api/v1/chats/{chat['id']}/messages", json={"text": "чужое"}, headers=keyed(eve)
|
||||||
)
|
)
|
||||||
elapsed = time.perf_counter() - started
|
elapsed = time.perf_counter() - started
|
||||||
finally:
|
|
||||||
await holder.close()
|
|
||||||
assert response.status_code == 404
|
assert response.status_code == 404
|
||||||
assert elapsed < 0.5
|
assert elapsed < 0.5
|
||||||
|
|||||||
@@ -230,6 +230,16 @@ def sql_tables(zone: str, tables: tuple[str, ...]) -> set[str]:
|
|||||||
for node in ast.walk(tree):
|
for node in ast.walk(tree):
|
||||||
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
||||||
words.update(re.findall(r"\b(?:FROM|JOIN|INTO|UPDATE)\s+(\w+)", node.value))
|
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)
|
return words & set(tables)
|
||||||
|
|
||||||
|
|
||||||
@@ -250,3 +260,11 @@ def test_messaging_does_not_import_identity_at_all() -> None:
|
|||||||
for path in modules_under("messaging")
|
for path in modules_under("messaging")
|
||||||
}
|
}
|
||||||
assert not {key: value for key, value in borrowed.items() if value}
|
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
|
import time
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from hashlib import sha256
|
from hashlib import sha256
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from redis.asyncio import Redis
|
from redis.asyncio import Redis
|
||||||
|
from sqlalchemy import select
|
||||||
|
|
||||||
from conftest import actor, bearer, keyed, make_chat, register, resolve, running_app, scalar
|
from conftest import actor, bearer, keyed, make_chat, register, resolve, running_app, scalar
|
||||||
from messenger.identity.application.ports import SessionDirectory
|
from messenger.identity.application.ports import SessionDirectory
|
||||||
from messenger.identity.domain.models import Session
|
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.identity.infrastructure.valkey import CachedSessionDirectory
|
||||||
from messenger.shared.application.errors import Unavailable
|
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
|
assert (await cache.info("stats"))["keyspace_hits"] == hits + 1
|
||||||
key = key_of(token_of(alice))
|
key = key_of(token_of(alice))
|
||||||
stored = str(await cache.get(key))
|
stored = str(await cache.get(key))
|
||||||
sql = "SELECT expires_at FROM sessions WHERE user_id = $1::uuid"
|
expires_at: datetime = await scalar(
|
||||||
expires_at: datetime = await scalar(sql, alice["id"])
|
select(SessionRow.expires_at).where(SessionRow.user_id == UUID(alice["id"]))
|
||||||
|
)
|
||||||
assert alice["id"] in stored and token_of(alice) not in stored
|
assert alice["id"] in stored and token_of(alice) not in stored
|
||||||
assert await cache.pexpiretime(key) <= int(expires_at.timestamp() * 1000)
|
assert await cache.pexpiretime(key) <= int(expires_at.timestamp() * 1000)
|
||||||
await cache.aclose()
|
await cache.aclose()
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
from urllib.parse import quote
|
from urllib.parse import quote
|
||||||
from uuid import uuid4
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
from httpx import AsyncClient
|
from httpx import AsyncClient
|
||||||
|
from sqlalchemy import func, select
|
||||||
|
|
||||||
from conftest import PASSWORD, actor, keyed, make_chat, new_user, register, running_app, scalar
|
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
|
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}
|
"/api/v1/users", json={"username": "AB", "display_name": "", "password": PASSWORD}
|
||||||
)
|
)
|
||||||
assert invalid.status_code == 400
|
assert invalid.status_code == 400
|
||||||
sql = "SELECT count(*) FROM users WHERE username = $1"
|
sql = select(func.count()).select_from(UserRow).where(UserRow.username == alice["username"])
|
||||||
assert await scalar(sql, alice["username"]) == 1
|
assert await scalar(sql) == 1
|
||||||
|
|
||||||
|
|
||||||
async def test_failed_chat_creation_rolls_back_both_tables() -> None:
|
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"
|
assert rejected.json()["error"]["code"] == "invalid_request"
|
||||||
after = (await client.get("/api/v1/chats?limit=100", headers=actor(alice))).json()
|
after = (await client.get("/api/v1/chats?limit=100", headers=actor(alice))).json()
|
||||||
assert after["items"] == before["items"]
|
assert after["items"] == before["items"]
|
||||||
assert await scalar("SELECT count(*) FROM chats WHERE title = $1", title) == 0
|
assert (
|
||||||
members = "SELECT count(*) FROM chat_members WHERE user_id = $1::uuid"
|
await scalar(select(func.count()).select_from(ChatRow).where(ChatRow.title == title)) == 0
|
||||||
assert await scalar(members, alice["id"]) == 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:
|
async def test_rejected_message_does_not_enter_history() -> None:
|
||||||
|
|||||||
@@ -5,10 +5,11 @@ import socket
|
|||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
|
|
||||||
from conftest import DATABASE, new_user
|
from conftest import DATABASE, free_port, new_user
|
||||||
from messenger.shared.infrastructure.readiness import DRAINING
|
from messenger.shared.infrastructure.readiness import DRAINING
|
||||||
|
|
||||||
DRAIN = 1.0
|
DRAIN = 1.0
|
||||||
@@ -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
|
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:
|
def status(port: int, path: str) -> int:
|
||||||
try:
|
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:
|
except httpx.TransportError:
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
@@ -71,7 +66,7 @@ def begin_registration(port: int) -> tuple[socket.socket, bytes]:
|
|||||||
return connection, body[8:]
|
return connection, body[8:]
|
||||||
|
|
||||||
|
|
||||||
def test_sigterm_leaves_rotation_then_closes_and_cancels_stuck_requests() -> None:
|
def test_sigterm_leaves_rotation_then_closes_and_cancels_stuck_requests(tmp_path: Path) -> None:
|
||||||
port = free_port()
|
port = free_port()
|
||||||
settings = {
|
settings = {
|
||||||
"HOST": "127.0.0.1",
|
"HOST": "127.0.0.1",
|
||||||
@@ -85,16 +80,18 @@ def test_sigterm_leaves_rotation_then_closes_and_cancels_stuck_requests() -> Non
|
|||||||
"DRAIN_SECONDS": str(DRAIN),
|
"DRAIN_SECONDS": str(DRAIN),
|
||||||
"SHUTDOWN_TIMEOUT_SECONDS": str(SHUTDOWN),
|
"SHUTDOWN_TIMEOUT_SECONDS": str(SHUTDOWN),
|
||||||
}
|
}
|
||||||
|
log_path = tmp_path / "gunicorn.log"
|
||||||
|
log = log_path.open("w")
|
||||||
server = subprocess.Popen(
|
server = subprocess.Popen(
|
||||||
[sys.executable, *GUNICORN],
|
[sys.executable, *GUNICORN],
|
||||||
env={**os.environ, **settings},
|
env={**os.environ, **settings},
|
||||||
stdout=subprocess.DEVNULL,
|
stdout=log,
|
||||||
stderr=subprocess.DEVNULL,
|
stderr=log,
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
deadline = time.monotonic() + 30
|
deadline = time.monotonic() + 30
|
||||||
while status(port, "/health/ready") != 200:
|
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)
|
time.sleep(0.2)
|
||||||
pending, rest = begin_registration(port)
|
pending, rest = begin_registration(port)
|
||||||
stuck, _ = begin_registration(port)
|
stuck, _ = begin_registration(port)
|
||||||
@@ -103,6 +100,7 @@ def test_sigterm_leaves_rotation_then_closes_and_cancels_stuck_requests() -> Non
|
|||||||
time.sleep(0.3)
|
time.sleep(0.3)
|
||||||
during = status(port, "/health/ready"), status(port, "/health/live")
|
during = status(port, "/health/ready"), status(port, "/health/live")
|
||||||
while status(port, "/health/live") == 200:
|
while status(port, "/health/live") == 200:
|
||||||
|
assert time.monotonic() - sent < SHUTDOWN + 2, log_path.read_text()
|
||||||
time.sleep(0.05)
|
time.sleep(0.05)
|
||||||
closed = time.monotonic() - sent
|
closed = time.monotonic() - sent
|
||||||
pending.sendall(rest)
|
pending.sendall(rest)
|
||||||
@@ -114,6 +112,8 @@ def test_sigterm_leaves_rotation_then_closes_and_cancels_stuck_requests() -> Non
|
|||||||
finally:
|
finally:
|
||||||
if server.poll() is None:
|
if server.poll() is None:
|
||||||
server.kill()
|
server.kill()
|
||||||
|
server.wait(timeout=5)
|
||||||
|
log.close()
|
||||||
print(f"окно: ready/live {during}, порт закрыт через {closed:.2f} с, выход {exited:.2f} с")
|
print(f"окно: ready/live {during}, порт закрыт через {closed:.2f} с, выход {exited:.2f} с")
|
||||||
print(f"запрос, принятый до SIGTERM и дописанный после закрытия порта: {answer}")
|
print(f"запрос, принятый до SIGTERM и дописанный после закрытия порта: {answer}")
|
||||||
print(f"запрос, тело которого так и не пришло: {cancelled or 'соединение закрыто без ответа'}")
|
print(f"запрос, тело которого так и не пришло: {cancelled or 'соединение закрыто без ответа'}")
|
||||||
|
|||||||
@@ -4,8 +4,10 @@ from uuid import uuid4
|
|||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from httpx import AsyncClient, Response
|
from httpx import AsyncClient, Response
|
||||||
|
from sqlalchemy import func, select
|
||||||
|
|
||||||
from conftest import actor, keyed, make_chat, register, running_app, scalar
|
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", "ключ"]
|
INVALID_KEYS = ["", "k" * 129, "два слова", "a b", "a/b", "ключ"]
|
||||||
|
|
||||||
@@ -93,12 +95,22 @@ async def test_key_is_scoped_by_user_and_chat(client: AsyncClient) -> None:
|
|||||||
bob = await register(client, "bob")
|
bob = await register(client, "bob")
|
||||||
chat = await make_chat(client, alice, bob)
|
chat = await make_chat(client, alice, bob)
|
||||||
other = await make_chat(client, alice)
|
other = await make_chat(client, alice)
|
||||||
ids = {
|
cases = [(chat, alice, "алиса"), (chat, bob, "боб"), (other, alice, "другой чат")]
|
||||||
(await send(client, chat, alice, "алиса", "shared-1")).json()["id"],
|
messages = []
|
||||||
(await send(client, chat, bob, "боб", "shared-1")).json()["id"],
|
for target, user, text in cases:
|
||||||
(await send(client, other, alice, "другой чат", "shared-1")).json()["id"],
|
response = await send(client, target, user, text, "shared-1")
|
||||||
}
|
assert response.status_code == 201
|
||||||
|
message = response.json()
|
||||||
|
assert (message["chat_id"], message["sender_id"], message["text"]) == (
|
||||||
|
target["id"],
|
||||||
|
user["id"],
|
||||||
|
text,
|
||||||
|
)
|
||||||
|
messages.append(message)
|
||||||
|
ids = {message["id"] for message in messages}
|
||||||
assert len(ids) == 3
|
assert len(ids) == 3
|
||||||
|
for (target, user, text), message in zip(cases, messages, strict=True):
|
||||||
|
assert (await send(client, target, user, text, "shared-1")).json() == message
|
||||||
|
|
||||||
|
|
||||||
async def test_replay_checks_session_and_access_again(client: AsyncClient) -> None:
|
async def test_replay_checks_session_and_access_again(client: AsyncClient) -> None:
|
||||||
@@ -142,4 +154,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 all(response.json() == responses[0].json() for response in responses)
|
||||||
assert [item["text"] for item in await history(second, chat, alice)] == [text]
|
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,156 +1,448 @@
|
|||||||
|
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
|
from uuid import uuid4
|
||||||
|
|
||||||
import asyncpg
|
|
||||||
import pytest
|
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, literal, 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 conftest import DATABASE, ROOT, migration_config, sql_connection, upgrade
|
||||||
from messenger.migrate import MigrationChangedError, migrate, migrations
|
from messenger.attachments.infrastructure.postgres import AttachmentRow
|
||||||
|
from messenger.identity.infrastructure.postgres import SessionRow, UserRow
|
||||||
|
from messenger.messaging.infrastructure.postgres import (
|
||||||
|
ChatMemberRow,
|
||||||
|
ChatRow,
|
||||||
|
IdempotencyKeyRow,
|
||||||
|
MessageAttachmentRow,
|
||||||
|
MessageRow,
|
||||||
|
)
|
||||||
|
from messenger.shared.infrastructure.postgres import Base
|
||||||
|
|
||||||
COUNTS = """
|
VERSIONS = ["0001_init", "0002_idempotency_keys", "0003_attachments", "0004_attachment_quarantine"]
|
||||||
SELECT (SELECT count(*) FROM users), (SELECT count(*) FROM sessions),
|
TABLES = [
|
||||||
(SELECT count(*) FROM chats), (SELECT count(*) FROM chat_members),
|
UserRow,
|
||||||
(SELECT count(*) FROM messages), (SELECT count(*) FROM idempotency_keys),
|
SessionRow,
|
||||||
(SELECT count(*) FROM attachments), (SELECT count(*) FROM message_attachments)
|
ChatRow,
|
||||||
"""
|
ChatMemberRow,
|
||||||
|
MessageRow,
|
||||||
|
IdempotencyKeyRow,
|
||||||
|
AttachmentRow,
|
||||||
|
MessageAttachmentRow,
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
async def counts() -> list[int]:
|
@pytest.fixture
|
||||||
connection = await asyncpg.connect(DATABASE["url"])
|
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:
|
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:
|
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 = 4) -> 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 = 4) -> 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))
|
||||||
|
if versions >= 3:
|
||||||
|
attachment = uuid4()
|
||||||
|
row = {
|
||||||
|
"id": attachment,
|
||||||
|
"chat_id": chat,
|
||||||
|
"owner_id": user,
|
||||||
|
"filename": "legacy.png",
|
||||||
|
"content_type": "image/png",
|
||||||
|
"size_bytes": 17,
|
||||||
|
"sha256": "a" * 64,
|
||||||
|
"width": 1,
|
||||||
|
"height": 1,
|
||||||
|
"object_key": f"attachments/{attachment}",
|
||||||
|
"status": "ready",
|
||||||
|
"created_at": stamp,
|
||||||
|
"updated_at": stamp,
|
||||||
|
}
|
||||||
|
if versions >= 4:
|
||||||
|
row.update(quarantine_reason="missing", quarantined_at=stamp)
|
||||||
|
table = await connection.run_sync(
|
||||||
|
lambda sync: Table("attachments", MetaData(), autoload_with=sync)
|
||||||
|
)
|
||||||
|
await connection.execute(insert(table).values(**row))
|
||||||
|
await connection.execute(
|
||||||
|
insert(MessageAttachmentRow).values(
|
||||||
|
message_id=message, position=0, chat_id=chat, attachment_id=attachment
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
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())
|
||||||
|
result = {}
|
||||||
|
for model in TABLES:
|
||||||
|
if model.__tablename__ not in tables:
|
||||||
|
continue
|
||||||
|
table = await connection.run_sync(
|
||||||
|
lambda sync, name=model.__tablename__: Table(name, MetaData(), autoload_with=sync)
|
||||||
|
)
|
||||||
|
columns = [
|
||||||
|
table.c[col.name] if col.name in table.c else literal(None).label(col.name)
|
||||||
|
for col in model.__table__.columns
|
||||||
|
]
|
||||||
|
result[model.__tablename__] = (
|
||||||
|
await connection.execute(select(*columns).order_by(*table.primary_key))
|
||||||
|
).all()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
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:
|
async def test_migrations_are_ordered_and_versioned() -> None:
|
||||||
versions = [version for version, _ in migrations()]
|
scripts = ScriptDirectory.from_config(migration_config(DATABASE["url"]))
|
||||||
assert versions == sorted(versions)
|
assert [script.revision for script in reversed(list(scripts.walk_revisions()))] == VERSIONS
|
||||||
assert versions == [
|
assert await revision(DATABASE["url"]) == VERSIONS[-1]
|
||||||
"0001_init",
|
|
||||||
"0002_idempotency_keys",
|
|
||||||
"0003_attachments",
|
|
||||||
"0004_attachment_quarantine",
|
|
||||||
]
|
|
||||||
applied = await scalar("SELECT array_agg(version ORDER BY version) FROM schema_migrations")
|
|
||||||
assert applied == versions
|
|
||||||
|
|
||||||
|
|
||||||
async def test_rerun_changes_nothing() -> None:
|
async def test_fresh_schema_matches_models(empty_database: str) -> None:
|
||||||
before = await counts()
|
await upgrade(empty_database)
|
||||||
assert await migrate(DATABASE["url"]) == []
|
async with sql_connection(empty_database) as connection:
|
||||||
assert await counts() == before
|
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:
|
async def test_rerun_changes_nothing(empty_database: str) -> None:
|
||||||
connection = await asyncpg.connect(DATABASE["url"])
|
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, 3, 4])
|
||||||
|
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 users ALTER COLUMN username TYPE text COLLATE "C"',
|
||||||
|
"ALTER TABLE sessions SET UNLOGGED",
|
||||||
|
"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",
|
||||||
|
"ALTER TABLE attachments DROP CONSTRAINT attachments_owner_fkey",
|
||||||
|
"ALTER TABLE attachments DROP CONSTRAINT attachments_quarantine_check",
|
||||||
|
"ALTER TABLE message_attachments DROP CONSTRAINT message_attachments_attachment_fkey",
|
||||||
|
'ALTER TABLE attachments ALTER COLUMN object_key TYPE text COLLATE "default"',
|
||||||
|
"DROP INDEX attachments_pending_idx",
|
||||||
|
"UPDATE schema_migrations SET checksum = 'tampered' WHERE version = '0003_attachments'",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
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:
|
try:
|
||||||
original = await connection.fetchval(
|
for _ in range(2):
|
||||||
"SELECT checksum FROM schema_migrations WHERE version = '0001_init'"
|
processes.append(
|
||||||
)
|
await asyncio.create_subprocess_exec(
|
||||||
await connection.execute(
|
sys.executable,
|
||||||
"UPDATE schema_migrations SET checksum = 'tampered' WHERE version = '0001_init'"
|
"-m",
|
||||||
)
|
"alembic",
|
||||||
with pytest.raises(MigrationChangedError):
|
"upgrade",
|
||||||
await migrate(DATABASE["url"])
|
"head",
|
||||||
await connection.execute(
|
cwd=ROOT,
|
||||||
"UPDATE schema_migrations SET checksum = $1 WHERE version = '0001_init'", original
|
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:
|
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:
|
async def test_sender_must_be_member_even_bypassing_api() -> None:
|
||||||
connection = await asyncpg.connect(DATABASE["url"])
|
with pytest.raises(IntegrityError) as failure:
|
||||||
try:
|
async with sql_connection() as connection:
|
||||||
with pytest.raises(asyncpg.ForeignKeyViolationError):
|
|
||||||
await connection.execute(
|
await connection.execute(
|
||||||
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) "
|
insert(MessageRow).values(
|
||||||
"VALUES (gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), 'x', now())"
|
id=uuid4(), chat_id=uuid4(), sender_id=uuid4(), text="x", created_at=func.now()
|
||||||
|
)
|
||||||
)
|
)
|
||||||
finally:
|
assert getattr(failure.value.orig, "sqlstate", None) == "23503"
|
||||||
await connection.close()
|
|
||||||
|
|
||||||
|
|
||||||
async def test_key_needs_a_member_and_a_message() -> None:
|
async def test_key_needs_a_member_and_a_message() -> None:
|
||||||
connection = await asyncpg.connect(DATABASE["url"])
|
with pytest.raises(IntegrityError) as failure:
|
||||||
try:
|
async with sql_connection() as connection:
|
||||||
with pytest.raises(asyncpg.ForeignKeyViolationError):
|
|
||||||
await connection.execute(
|
await connection.execute(
|
||||||
"INSERT INTO idempotency_keys "
|
insert(IdempotencyKeyRow).values(
|
||||||
"(chat_id, user_id, key, fingerprint, message_id, created_at) "
|
chat_id=uuid4(),
|
||||||
"VALUES (gen_random_uuid(), gen_random_uuid(), 'k-1', "
|
user_id=uuid4(),
|
||||||
"sha256('x'), gen_random_uuid(), now())"
|
key="k-1",
|
||||||
|
fingerprint=b"x" * 32,
|
||||||
|
message_id=uuid4(),
|
||||||
|
created_at=func.now(),
|
||||||
|
)
|
||||||
)
|
)
|
||||||
finally:
|
assert getattr(failure.value.orig, "sqlstate", None) == "23503"
|
||||||
await connection.close()
|
|
||||||
|
|
||||||
|
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 = '0004_attachment_quarantine'\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"))
|
||||||
|
|
||||||
|
|
||||||
async def test_attachment_owner_must_be_member() -> None:
|
async def test_attachment_owner_must_be_member() -> None:
|
||||||
connection = await asyncpg.connect(DATABASE["url"])
|
with pytest.raises(IntegrityError, match="attachments_owner_fkey"):
|
||||||
try:
|
async with sql_connection() as connection:
|
||||||
with pytest.raises(asyncpg.ForeignKeyViolationError, match="attachments_owner_fkey"):
|
|
||||||
await connection.execute(
|
await connection.execute(
|
||||||
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, "
|
insert(AttachmentRow).values(
|
||||||
"size_bytes, sha256, width, height, object_key, status, created_at, updated_at) "
|
id=uuid4(),
|
||||||
"VALUES (gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), 'a.png', "
|
chat_id=uuid4(),
|
||||||
"'image/png', 1, repeat('0', 64), 1, 1, 'attachments/x', 'pending', now(), now())"
|
owner_id=uuid4(),
|
||||||
|
filename="a.png",
|
||||||
|
content_type="image/png",
|
||||||
|
size_bytes=1,
|
||||||
|
sha256="0" * 64,
|
||||||
|
width=1,
|
||||||
|
height=1,
|
||||||
|
object_key="attachments/x",
|
||||||
|
status="pending",
|
||||||
|
created_at=func.now(),
|
||||||
|
updated_at=func.now(),
|
||||||
|
)
|
||||||
)
|
)
|
||||||
finally:
|
|
||||||
await connection.close()
|
|
||||||
|
|
||||||
|
|
||||||
async def test_message_links_only_attachments_of_its_chat() -> None:
|
async def test_message_links_only_attachments_of_its_chat(empty_database: str) -> None:
|
||||||
user, chat_a, chat_b, attachment, message = (uuid4() for _ in range(5))
|
await upgrade(empty_database)
|
||||||
seed = [
|
await seed(empty_database)
|
||||||
(
|
with pytest.raises(IntegrityError, match="message_attachments_attachment_fkey"):
|
||||||
"INSERT INTO users (id, username, display_name, password_hash, created_at) "
|
async with sql_connection(empty_database) as connection:
|
||||||
"VALUES ($1, $2, 'A', '$argon2id$x', now())",
|
attachment = (await connection.execute(select(AttachmentRow.id))).scalar_one()
|
||||||
user,
|
user = (await connection.execute(select(UserRow.id))).scalar_one()
|
||||||
f"u_{user.hex[:12]}",
|
chat, message = uuid4(), uuid4()
|
||||||
),
|
|
||||||
("INSERT INTO chats (id, title, created_at) VALUES ($1, 'A', now())", chat_a),
|
|
||||||
("INSERT INTO chats (id, title, created_at) VALUES ($1, 'B', now())", chat_b),
|
|
||||||
(
|
|
||||||
"INSERT INTO chat_members (chat_id, user_id, position, chat_created_at) "
|
|
||||||
"VALUES ($1, $3, 1, now()), ($2, $3, 1, now())",
|
|
||||||
chat_a,
|
|
||||||
chat_b,
|
|
||||||
user,
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, "
|
|
||||||
"sha256, width, height, object_key, status, created_at, updated_at) VALUES ($1, $2, "
|
|
||||||
"$3, 'a.png', 'image/png', 1, repeat('0', 64), 1, 1, $4, 'ready', now(), now())",
|
|
||||||
attachment,
|
|
||||||
chat_a,
|
|
||||||
user,
|
|
||||||
f"attachments/{attachment}",
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) "
|
|
||||||
"VALUES ($1, $2, $3, '', now())",
|
|
||||||
message,
|
|
||||||
chat_b,
|
|
||||||
user,
|
|
||||||
),
|
|
||||||
]
|
|
||||||
connection = await asyncpg.connect(DATABASE["url"])
|
|
||||||
transaction = connection.transaction()
|
|
||||||
await transaction.start()
|
|
||||||
try:
|
|
||||||
for sql, *arguments in seed:
|
|
||||||
await connection.execute(sql, *arguments)
|
|
||||||
assert await connection.fetchval("SELECT text FROM messages WHERE id = $1", message) == ""
|
|
||||||
with pytest.raises(
|
|
||||||
asyncpg.ForeignKeyViolationError, match="message_attachments_attachment_fkey"
|
|
||||||
):
|
|
||||||
await connection.execute(
|
await connection.execute(
|
||||||
"INSERT INTO message_attachments (message_id, position, chat_id, attachment_id) "
|
insert(ChatRow).values(id=chat, title="Other", created_at=func.now())
|
||||||
"VALUES ($1, 0, $2, $3)",
|
)
|
||||||
message,
|
await connection.execute(
|
||||||
chat_b,
|
insert(ChatMemberRow).values(
|
||||||
attachment,
|
chat_id=chat, user_id=user, position=1, chat_created_at=func.now()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
await connection.execute(
|
||||||
|
insert(MessageRow).values(
|
||||||
|
id=message, chat_id=chat, sender_id=user, text="", created_at=func.now()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
assert (
|
||||||
|
await connection.scalar(select(MessageRow.text).where(MessageRow.id == message))
|
||||||
|
== ""
|
||||||
|
)
|
||||||
|
await connection.execute(
|
||||||
|
insert(MessageAttachmentRow).values(
|
||||||
|
message_id=message,
|
||||||
|
position=0,
|
||||||
|
chat_id=chat,
|
||||||
|
attachment_id=attachment,
|
||||||
|
)
|
||||||
)
|
)
|
||||||
finally:
|
|
||||||
await transaction.rollback()
|
|
||||||
await connection.close()
|
|
||||||
|
|||||||
@@ -1,6 +1,37 @@
|
|||||||
import time
|
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,
|
||||||
|
new_user,
|
||||||
|
register,
|
||||||
|
resolve,
|
||||||
|
running_app,
|
||||||
|
sql_connection,
|
||||||
|
)
|
||||||
|
from messenger.identity.domain.models import Session
|
||||||
|
from messenger.identity.infrastructure.postgres import (
|
||||||
|
PostgresIdentityUnitOfWork,
|
||||||
|
PostgresSessionDirectory,
|
||||||
|
UserRow,
|
||||||
|
)
|
||||||
|
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
|
from messenger.shared.infrastructure.postgres import Database
|
||||||
|
|
||||||
|
|
||||||
@@ -8,7 +39,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:
|
async with running_app(db_pool_max_size=1, db_acquire_timeout_seconds=0.3) as http:
|
||||||
alice = await register(http, "alice")
|
alice = await register(http, "alice")
|
||||||
database = await resolve(http, Database)
|
database = await resolve(http, Database)
|
||||||
async with database.connection():
|
async with database.session() as session:
|
||||||
|
await session.execute(select(1))
|
||||||
started = time.perf_counter()
|
started = time.perf_counter()
|
||||||
starved = await http.get("/api/v1/users/me", headers=actor(alice))
|
starved = await http.get("/api/v1/users/me", headers=actor(alice))
|
||||||
elapsed = time.perf_counter() - started
|
elapsed = time.perf_counter() - started
|
||||||
@@ -22,6 +54,178 @@ async def test_exhausted_pool_answers_503_in_bounded_time() -> None:
|
|||||||
async def test_statement_timeout_is_set_on_connections() -> None:
|
async def test_statement_timeout_is_set_on_connections() -> None:
|
||||||
async with running_app(db_command_timeout_seconds=1.5) as http:
|
async with running_app(db_command_timeout_seconds=1.5) as http:
|
||||||
database = await resolve(http, Database)
|
database = await resolve(http, Database)
|
||||||
async with database.connection() as connection:
|
async with database.session() as session:
|
||||||
assert await connection.fetchval("SHOW statement_timeout") == "1500ms"
|
statement_timeout = await session.scalar(
|
||||||
assert await connection.fetchval("SHOW lock_timeout") == "1500ms"
|
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_closed_idle_connection_is_replaced_before_registration() -> None:
|
||||||
|
async with running_app(db_pool_max_size=1) as http:
|
||||||
|
database = await resolve(http, Database)
|
||||||
|
async with database.session() as session:
|
||||||
|
pid = await session.scalar(select(func.pg_backend_pid()))
|
||||||
|
async with sql_connection() as connection:
|
||||||
|
assert await connection.scalar(select(func.pg_terminate_backend(pid, 1000)))
|
||||||
|
body = new_user("reconnect")
|
||||||
|
response = await http.post("/api/v1/users", json=body)
|
||||||
|
assert response.status_code == 201
|
||||||
|
assert response.headers["X-Instance-Id"] and response.headers["X-Request-Id"]
|
||||||
|
async with database.session() as session:
|
||||||
|
assert (
|
||||||
|
await session.scalar(
|
||||||
|
select(func.count())
|
||||||
|
.select_from(UserRow)
|
||||||
|
.where(UserRow.username == body["username"])
|
||||||
|
)
|
||||||
|
== 1
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
|
|||||||
@@ -7,12 +7,14 @@ from datetime import UTC, datetime, timedelta
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
from uuid import UUID, uuid4
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
import asyncpg
|
|
||||||
import pytest
|
import pytest
|
||||||
from httpx import AsyncClient
|
from httpx import AsyncClient
|
||||||
|
from sqlalchemy import make_url
|
||||||
|
from sqlalchemy.ext.asyncio import create_async_engine
|
||||||
|
from sqlalchemy.pool import NullPool
|
||||||
from test_attachments import storage, trio, upload
|
from test_attachments import storage, trio, upload
|
||||||
|
|
||||||
from conftest import actor, keyed, running_app
|
from conftest import actor, keyed, running_app, upgrade
|
||||||
from fakes import MemoryObjectStorage, NullLogger, RecordingPublisher
|
from fakes import MemoryObjectStorage, NullLogger, RecordingPublisher
|
||||||
from messenger.attachments.application.commands import ReconcileStorage
|
from messenger.attachments.application.commands import ReconcileStorage
|
||||||
from messenger.attachments.application.reconcile import Reconciliation, StorageReconciler
|
from messenger.attachments.application.reconcile import Reconciliation, StorageReconciler
|
||||||
@@ -23,7 +25,6 @@ from messenger.attachments.infrastructure.postgres import (
|
|||||||
PostgresAttachmentsUnitOfWork,
|
PostgresAttachmentsUnitOfWork,
|
||||||
PostgresSingleRun,
|
PostgresSingleRun,
|
||||||
)
|
)
|
||||||
from messenger.migrate import migrate
|
|
||||||
from messenger.shared.application.errors import Unavailable
|
from messenger.shared.application.errors import Unavailable
|
||||||
from messenger.shared.infrastructure.clock import MonotonicUtcClock
|
from messenger.shared.infrastructure.clock import MonotonicUtcClock
|
||||||
from messenger.shared.infrastructure.postgres import Database
|
from messenger.shared.infrastructure.postgres import Database
|
||||||
@@ -45,12 +46,17 @@ def dsn(database: str) -> str:
|
|||||||
name = f"reconcile_{uuid4().hex[:12]}"
|
name = f"reconcile_{uuid4().hex[:12]}"
|
||||||
|
|
||||||
async def create() -> None:
|
async def create() -> None:
|
||||||
connection = await asyncpg.connect(database)
|
engine = create_async_engine(
|
||||||
|
make_url(database).set(drivername="postgresql+asyncpg"),
|
||||||
|
isolation_level="AUTOCOMMIT",
|
||||||
|
poolclass=NullPool,
|
||||||
|
)
|
||||||
try:
|
try:
|
||||||
await connection.execute(f"CREATE DATABASE {name}")
|
async with engine.connect() as connection:
|
||||||
|
await connection.exec_driver_sql(f"CREATE DATABASE {name}")
|
||||||
finally:
|
finally:
|
||||||
await connection.close()
|
await engine.dispose()
|
||||||
await migrate(target)
|
await upgrade(target)
|
||||||
|
|
||||||
target = f"{database.rsplit('/', 1)[0]}/{name}"
|
target = f"{database.rsplit('/', 1)[0]}/{name}"
|
||||||
asyncio.run(create())
|
asyncio.run(create())
|
||||||
@@ -80,8 +86,12 @@ class Stand:
|
|||||||
return await reconciler(command)
|
return await reconciler(command)
|
||||||
|
|
||||||
async def sql(self, query: str, *args: Any) -> Any:
|
async def sql(self, query: str, *args: Any) -> Any:
|
||||||
async with self.database.connection() as connection:
|
async with self.database.session() as session:
|
||||||
return await connection.fetch(query, *args)
|
connection = await session.connection()
|
||||||
|
result = await connection.exec_driver_sql(query, args)
|
||||||
|
rows = result.mappings().all() if result.returns_rows else []
|
||||||
|
await session.commit()
|
||||||
|
return rows
|
||||||
|
|
||||||
async def upload(self) -> dict[str, Any]:
|
async def upload(self) -> dict[str, Any]:
|
||||||
alice, _, _, chat = self.users
|
alice, _, _, chat = self.users
|
||||||
@@ -279,7 +289,7 @@ def test_any_pass_failure_ends_as_reconcile_failed(
|
|||||||
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||||
) -> None:
|
) -> None:
|
||||||
async def broken(*_args: Any) -> Reconciliation:
|
async def broken(*_args: Any) -> Reconciliation:
|
||||||
cancelled = asyncpg.exceptions.QueryCanceledError("statement timeout")
|
cancelled = TimeoutError("statement timeout")
|
||||||
raise ExceptionGroup("pass", [cancelled])
|
raise ExceptionGroup("pass", [cancelled])
|
||||||
|
|
||||||
monkeypatch.setattr(entrypoint, "reconcile", broken)
|
monkeypatch.setattr(entrypoint, "reconcile", broken)
|
||||||
@@ -295,7 +305,7 @@ def test_any_pass_failure_ends_as_reconcile_failed(
|
|||||||
assert stopped.value.code == 1
|
assert stopped.value.code == 1
|
||||||
assert captured.out == ""
|
assert captured.out == ""
|
||||||
assert "reconcile.failed" in captured.err
|
assert "reconcile.failed" in captured.err
|
||||||
assert "QueryCanceledError" in captured.err
|
assert "TimeoutError" in captured.err
|
||||||
assert "Traceback" not in captured.err
|
assert "Traceback" not in captured.err
|
||||||
|
|
||||||
|
|
||||||
@@ -348,3 +358,33 @@ async def test_storage_failure_mid_pass_ends_it_as_unavailable(dsn: str) -> None
|
|||||||
with pytest.raises(Unavailable) as failed:
|
with pytest.raises(Unavailable) as failed:
|
||||||
await s.run(apply=True, deep=True)
|
await s.run(apply=True, deep=True)
|
||||||
assert isinstance(failed.value.__cause__, TimeoutError)
|
assert isinstance(failed.value.__cause__, TimeoutError)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_cancelled_pass_releases_its_autocommit_lock(dsn: str) -> None:
|
||||||
|
async with stand(dsn) as s:
|
||||||
|
entered = asyncio.Event()
|
||||||
|
|
||||||
|
async def hold() -> None:
|
||||||
|
async with PostgresSingleRun(s.database, LOCK_KEY).hold() as held:
|
||||||
|
assert held
|
||||||
|
entered.set()
|
||||||
|
await asyncio.Event().wait()
|
||||||
|
|
||||||
|
task = asyncio.create_task(hold())
|
||||||
|
try:
|
||||||
|
await asyncio.wait_for(entered.wait(), 2)
|
||||||
|
states = await s.sql(
|
||||||
|
"SELECT a.state FROM pg_locks l JOIN pg_stat_activity a ON a.pid = l.pid "
|
||||||
|
"WHERE l.locktype = 'advisory' AND l.objid = $1",
|
||||||
|
LOCK_KEY,
|
||||||
|
)
|
||||||
|
assert [row["state"] for row in states] == ["idle"]
|
||||||
|
finally:
|
||||||
|
task.cancel()
|
||||||
|
with pytest.raises(asyncio.CancelledError):
|
||||||
|
await task
|
||||||
|
locks = await s.sql(
|
||||||
|
"SELECT count(*) AS total FROM pg_locks WHERE locktype = 'advisory' AND objid = $1",
|
||||||
|
LOCK_KEY,
|
||||||
|
)
|
||||||
|
assert locks[0]["total"] == 0
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
|
from hashlib import sha256
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from httpx import AsyncClient
|
from httpx import AsyncClient
|
||||||
|
from sqlalchemy import func, select
|
||||||
|
|
||||||
from conftest import (
|
from conftest import (
|
||||||
PASSWORD,
|
PASSWORD,
|
||||||
@@ -16,6 +19,7 @@ from conftest import (
|
|||||||
running_app,
|
running_app,
|
||||||
scalar,
|
scalar,
|
||||||
)
|
)
|
||||||
|
from messenger.identity.infrastructure.postgres import SessionRow, UserRow
|
||||||
|
|
||||||
BASIC = 'Basic realm="messenger", charset="UTF-8"'
|
BASIC = 'Basic realm="messenger", charset="UTF-8"'
|
||||||
BEARER = 'Bearer realm="messenger"'
|
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:
|
async def test_password_is_stored_as_argon2id(client: AsyncClient) -> None:
|
||||||
alice = await register(client, "alice")
|
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 stored.startswith("$argon2id$v=19$m=19456,t=2,p=1$")
|
||||||
assert PASSWORD not in stored
|
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:
|
async def test_session_stores_only_token_digest(client: AsyncClient) -> None:
|
||||||
alice = await register(client, "alice")
|
alice = await register(client, "alice")
|
||||||
token = actor(alice)["Authorization"].split()[1]
|
token = actor(alice)["Authorization"].split()[1]
|
||||||
sql = "SELECT count(*) FROM sessions WHERE token_hash = sha256(convert_to($1, 'UTF8'))"
|
rows = select(func.count()).select_from(SessionRow)
|
||||||
assert await scalar(sql, token) == 1
|
assert await scalar(rows.where(SessionRow.token_hash == sha256(token.encode()).digest())) == 1
|
||||||
raw = "SELECT count(*) FROM sessions WHERE encode(token_hash, 'escape') = $1"
|
assert await scalar(rows.where(SessionRow.token_hash == token.encode())) == 0
|
||||||
assert await scalar(raw, token) == 0
|
|
||||||
|
|
||||||
|
|
||||||
async def test_wrong_password_and_unknown_user_look_the_same(client: AsyncClient) -> None:
|
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 login(client, body["username"])
|
||||||
await asyncio.sleep(1.2)
|
await asyncio.sleep(1.2)
|
||||||
await login(client, body["username"])
|
await login(client, body["username"])
|
||||||
sql = "SELECT count(*) FROM sessions WHERE user_id = $1::uuid"
|
sql = select(func.count()).select_from(SessionRow).where(SessionRow.user_id == UUID(user["id"]))
|
||||||
assert await scalar(sql, user["id"]) == 1
|
assert await scalar(sql) == 1
|
||||||
|
|
||||||
|
|
||||||
async def test_chat_routes_require_bearer(client: AsyncClient) -> None:
|
async def test_chat_routes_require_bearer(client: AsyncClient) -> None:
|
||||||
|
|||||||
@@ -3,12 +3,11 @@ from collections.abc import AsyncIterator
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
import asyncpg
|
|
||||||
from httpx import AsyncClient
|
from httpx import AsyncClient
|
||||||
from starlette.types import Message
|
from starlette.types import Message
|
||||||
from test_attachments import storage, trio, upload
|
from test_attachments import storage, trio, upload
|
||||||
|
|
||||||
from conftest import APPS, DATABASE, actor, keyed, resolve, running_app, scalar
|
from conftest import APPS, actor, keyed, resolve, running_app, scalar, sql_connection
|
||||||
from messenger.attachments.domain.events import AttachmentDiscarded
|
from messenger.attachments.domain.events import AttachmentDiscarded
|
||||||
from messenger.attachments.entrypoints.sweeper import UploadSweeper
|
from messenger.attachments.entrypoints.sweeper import UploadSweeper
|
||||||
from messenger.shared.application.messagebus import EventBus
|
from messenger.shared.application.messagebus import EventBus
|
||||||
@@ -18,11 +17,8 @@ AGED = "UPDATE attachments SET created_at = created_at - interval '1 hour' WHERE
|
|||||||
|
|
||||||
|
|
||||||
async def execute(sql: str, *args: Any) -> None:
|
async def execute(sql: str, *args: Any) -> None:
|
||||||
connection = await asyncpg.connect(DATABASE["url"])
|
async with sql_connection() as connection:
|
||||||
try:
|
await connection.exec_driver_sql(sql, args)
|
||||||
await connection.execute(sql, *args)
|
|
||||||
finally:
|
|
||||||
await connection.close()
|
|
||||||
|
|
||||||
|
|
||||||
def sweeper(http: AsyncClient) -> UploadSweeper:
|
def sweeper(http: AsyncClient) -> UploadSweeper:
|
||||||
@@ -69,15 +65,18 @@ async def test_commit_failure_after_put_is_compensated(client: AsyncClient) -> N
|
|||||||
trigger = f"lab4_fail_{uuid4().hex[:8]}"
|
trigger = f"lab4_fail_{uuid4().hex[:8]}"
|
||||||
await execute(
|
await execute(
|
||||||
f"""CREATE FUNCTION {trigger}() RETURNS trigger LANGUAGE plpgsql AS $$
|
f"""CREATE FUNCTION {trigger}() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||||
BEGIN RAISE EXCEPTION 'injected' USING ERRCODE = '55P03'; END $$;
|
BEGIN RAISE EXCEPTION 'injected' USING ERRCODE = '55P03'; END $$"""
|
||||||
CREATE TRIGGER {trigger} BEFORE UPDATE ON attachments FOR EACH ROW
|
)
|
||||||
|
await execute(
|
||||||
|
f"""CREATE TRIGGER {trigger} BEFORE UPDATE ON attachments FOR EACH ROW
|
||||||
WHEN (NEW.filename = '{name}' AND NEW.status = 'ready') EXECUTE FUNCTION {trigger}()"""
|
WHEN (NEW.filename = '{name}' AND NEW.status = 'ready') EXECUTE FUNCTION {trigger}()"""
|
||||||
)
|
)
|
||||||
before, seen = set(store.objects), await discarded(client)
|
before, seen = set(store.objects), await discarded(client)
|
||||||
try:
|
try:
|
||||||
response = await upload(client, alice, chat, filename=name)
|
response = await upload(client, alice, chat, filename=name)
|
||||||
finally:
|
finally:
|
||||||
await execute(f"DROP TRIGGER {trigger} ON attachments; DROP FUNCTION {trigger}()")
|
await execute(f"DROP TRIGGER {trigger} ON attachments")
|
||||||
|
await execute(f"DROP FUNCTION {trigger}()")
|
||||||
assert response.status_code == 503
|
assert response.status_code == 503
|
||||||
assert response.json()["error"]["code"] == "unavailable"
|
assert response.json()["error"]["code"] == "unavailable"
|
||||||
assert await scalar("SELECT count(*) FROM attachments WHERE filename = $1", name) == 0
|
assert await scalar("SELECT count(*) FROM attachments WHERE filename = $1", name) == 0
|
||||||
|
|||||||
+54
-13
@@ -1,5 +1,6 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import re
|
import re
|
||||||
|
import socket
|
||||||
import subprocess
|
import subprocess
|
||||||
import time
|
import time
|
||||||
from base64 import b64encode
|
from base64 import b64encode
|
||||||
@@ -9,19 +10,23 @@ from pathlib import Path
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
import asyncpg
|
|
||||||
import pytest
|
import pytest
|
||||||
|
from alembic import command
|
||||||
|
from alembic.config import Config
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from httpx import ASGITransport, AsyncClient
|
from httpx import ASGITransport, AsyncClient
|
||||||
|
from sqlalchemy import make_url
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine
|
||||||
|
from sqlalchemy.pool import NullPool
|
||||||
|
|
||||||
from fakes import MemoryStorageProvider
|
from fakes import MemoryStorageProvider
|
||||||
from messenger.attachments.config import AttachmentsSettings
|
from messenger.attachments.config import AttachmentsSettings
|
||||||
from messenger.identity.config import IdentitySettings
|
from messenger.identity.config import IdentitySettings
|
||||||
from messenger.main import create_app
|
from messenger.main import create_app
|
||||||
from messenger.messaging.config import MessagingSettings
|
from messenger.messaging.config import MessagingSettings
|
||||||
from messenger.migrate import migrate
|
|
||||||
from messenger.shared.config import PlatformSettings
|
from messenger.shared.config import PlatformSettings
|
||||||
from messenger.shared.entrypoints.config import TransportSettings
|
from messenger.shared.entrypoints.config import TransportSettings
|
||||||
|
from messenger.shared.infrastructure.postgres import unavailable
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parents[1]
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
POSTGRES_IMAGE = re.compile(r"image: (postgres:\S+)")
|
POSTGRES_IMAGE = re.compile(r"image: (postgres:\S+)")
|
||||||
@@ -38,18 +43,53 @@ def docker(*args: str) -> str:
|
|||||||
return done.stdout.strip()
|
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:
|
async def migrated(dsn: str) -> None:
|
||||||
deadline = time.monotonic() + STARTUP_SECONDS
|
deadline = time.monotonic() + STARTUP_SECONDS
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
await migrate(dsn)
|
await upgrade(dsn)
|
||||||
return
|
return
|
||||||
except OSError, asyncpg.PostgresError, asyncpg.InterfaceError:
|
except Exception as error:
|
||||||
if time.monotonic() > deadline:
|
if not unavailable(error) or time.monotonic() > deadline:
|
||||||
raise
|
raise
|
||||||
await asyncio.sleep(0.5)
|
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(24000, 25000):
|
||||||
|
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 24000–24999")
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
@pytest.fixture(autouse=True)
|
||||||
def database_for_api(request: pytest.FixtureRequest) -> None:
|
def database_for_api(request: pytest.FixtureRequest) -> None:
|
||||||
if "api" in request.node.path.parts:
|
if "api" in request.node.path.parts:
|
||||||
@@ -78,7 +118,7 @@ def answering(name: str, *probe: str) -> bool:
|
|||||||
@pytest.fixture(scope="session")
|
@pytest.fixture(scope="session")
|
||||||
def valkey() -> Iterator[dict[str, str]]:
|
def valkey() -> Iterator[dict[str, str]]:
|
||||||
name = f"mtusi-lab4-test-valkey-{uuid4().hex[:8]}"
|
name = f"mtusi-lab4-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:
|
try:
|
||||||
deadline = time.monotonic() + STARTUP_SECONDS
|
deadline = time.monotonic() + STARTUP_SECONDS
|
||||||
while not answering(name, "valkey-cli", "ping"):
|
while not answering(name, "valkey-cli", "ping"):
|
||||||
@@ -94,7 +134,9 @@ def database() -> Iterator[str]:
|
|||||||
name = f"mtusi-lab4-test-{uuid4().hex[:8]}"
|
name = f"mtusi-lab4-test-{uuid4().hex[:8]}"
|
||||||
tuning = ["-c", "fsync=off", "-c", "synchronous_commit=off", "-c", "full_page_writes=off"]
|
tuning = ["-c", "fsync=off", "-c", "synchronous_commit=off", "-c", "full_page_writes=off"]
|
||||||
environment = ["-e", "POSTGRES_PASSWORD=test", "-e", "POSTGRES_DB=messenger"]
|
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:
|
try:
|
||||||
dsn = f"postgresql://postgres:test@127.0.0.1:{published(name, 5432)}/messenger"
|
dsn = f"postgresql://postgres:test@127.0.0.1:{published(name, 5432)}/messenger"
|
||||||
asyncio.run(migrated(dsn))
|
asyncio.run(migrated(dsn))
|
||||||
@@ -152,12 +194,11 @@ async def client() -> AsyncIterator[AsyncClient]:
|
|||||||
yield http
|
yield http
|
||||||
|
|
||||||
|
|
||||||
async def scalar(sql: str, *args: Any) -> Any:
|
async def scalar(statement: Any, *args: Any) -> Any:
|
||||||
connection = await asyncpg.connect(DATABASE["url"])
|
async with sql_connection() as connection:
|
||||||
try:
|
if isinstance(statement, str):
|
||||||
return await connection.fetchval(sql, *args)
|
return (await connection.exec_driver_sql(statement, args)).scalar()
|
||||||
finally:
|
return await connection.scalar(statement)
|
||||||
await connection.close()
|
|
||||||
|
|
||||||
|
|
||||||
def basic(username: str, password: str) -> dict[str, str]:
|
def basic(username: str, password: str) -> dict[str, str]:
|
||||||
|
|||||||
@@ -211,6 +211,13 @@ async def test_postgres_stopped_gives_bounded_503_and_recovers(http: AsyncClient
|
|||||||
me = await http.get("/api/v1/users/me", headers=bearer(token))
|
me = await http.get("/api/v1/users/me", headers=bearer(token))
|
||||||
print(f"postgres запущен: готовность через {recovered:.1f} с, прежний токен {me.status_code}")
|
print(f"postgres запущен: готовность через {recovered:.1f} с, прежний токен {me.status_code}")
|
||||||
assert me.json() == user
|
assert me.json() == user
|
||||||
|
instances = set()
|
||||||
|
for _ in range(40):
|
||||||
|
response = await http.post("/api/v1/users", json=new_user("recovered"))
|
||||||
|
assert response.status_code == 201
|
||||||
|
instances.add(response.headers["X-Instance-Id"])
|
||||||
|
print(f"postgres запущен: 40 регистраций 201 через {len(instances)} реплики без рестарта API")
|
||||||
|
assert len(instances) >= 2
|
||||||
assert started_at("api") == api_started
|
assert started_at("api") == api_started
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -7,13 +7,18 @@ from datetime import UTC, datetime, timedelta
|
|||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
import asyncpg
|
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
|
from sqlalchemy import func, insert, make_url, select
|
||||||
|
from sqlalchemy.ext.asyncio import create_async_engine
|
||||||
|
|
||||||
from messenger.attachments.config import AttachmentsSettings
|
from messenger.attachments.config import AttachmentsSettings
|
||||||
|
from messenger.attachments.infrastructure.postgres import AttachmentRow
|
||||||
from messenger.attachments.infrastructure.s3 import S3ObjectStorage, s3_client
|
from messenger.attachments.infrastructure.s3 import S3ObjectStorage, s3_client
|
||||||
|
from messenger.identity.infrastructure.postgres import UserRow
|
||||||
|
from messenger.messaging.infrastructure.postgres import ChatMemberRow
|
||||||
from messenger.shared.config import PlatformSettings
|
from messenger.shared.config import PlatformSettings
|
||||||
|
|
||||||
|
MODELS = (UserRow, ChatMemberRow, AttachmentRow)
|
||||||
COLUMNS = (
|
COLUMNS = (
|
||||||
"id",
|
"id",
|
||||||
"chat_id",
|
"chat_id",
|
||||||
@@ -41,9 +46,21 @@ async def seed(count: int, concurrency: int) -> dict[str, object]:
|
|||||||
platform, settings = PlatformSettings(), AttachmentsSettings()
|
platform, settings = PlatformSettings(), AttachmentsSettings()
|
||||||
body = picture()
|
body = picture()
|
||||||
digest = hashlib.sha256(body).hexdigest()
|
digest = hashlib.sha256(body).hexdigest()
|
||||||
connection = await asyncpg.connect(platform.database_url.get_secret_value())
|
engine = create_async_engine(
|
||||||
|
make_url(platform.database_url.get_secret_value()).set(drivername="postgresql+asyncpg"),
|
||||||
|
hide_parameters=True,
|
||||||
|
)
|
||||||
try:
|
try:
|
||||||
member = await connection.fetchrow("SELECT chat_id, user_id FROM chat_members LIMIT 1")
|
async with engine.connect() as connection:
|
||||||
|
member = (
|
||||||
|
(
|
||||||
|
await connection.execute(
|
||||||
|
select(ChatMemberRow.chat_id, ChatMemberRow.user_id).limit(1)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.mappings()
|
||||||
|
.first()
|
||||||
|
)
|
||||||
if member is None:
|
if member is None:
|
||||||
raise SystemExit("нет ни одного чата: сначала make test")
|
raise SystemExit("нет ни одного чата: сначала make test")
|
||||||
ids = [uuid4() for _ in range(count)]
|
ids = [uuid4() for _ in range(count)]
|
||||||
@@ -85,17 +102,22 @@ async def seed(count: int, concurrency: int) -> dict[str, object]:
|
|||||||
)
|
)
|
||||||
for number, attachment_id in enumerate(ids)
|
for number, attachment_id in enumerate(ids)
|
||||||
]
|
]
|
||||||
await connection.copy_records_to_table("attachments", records=records, columns=COLUMNS)
|
async with engine.begin() as connection:
|
||||||
total = await connection.fetchval("SELECT count(*) FROM attachments")
|
for start in range(0, count, 1000):
|
||||||
|
await connection.execute(
|
||||||
|
insert(AttachmentRow),
|
||||||
|
[dict(zip(COLUMNS, row, strict=True)) for row in records[start : start + 1000]],
|
||||||
|
)
|
||||||
|
total = await connection.scalar(select(func.count()).select_from(AttachmentRow))
|
||||||
finally:
|
finally:
|
||||||
await connection.close()
|
await engine.dispose()
|
||||||
return {
|
return {
|
||||||
"added": count,
|
"added": count,
|
||||||
"rows_total": total,
|
"rows_total": total,
|
||||||
"object_bytes": len(body),
|
"object_bytes": len(body),
|
||||||
"seconds": {
|
"seconds": {
|
||||||
"s3_put": round(stored - started, 3),
|
"s3_put": round(stored - started, 3),
|
||||||
"pg_copy": round(time.monotonic() - stored, 3),
|
"pg_insert": round(time.monotonic() - stored, 3),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import importlib.util
|
||||||
|
from pathlib import Path
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
SPEC = importlib.util.spec_from_file_location(
|
||||||
|
"grade4_probe", Path(__file__).resolve().parents[2] / "scripts/probe.py"
|
||||||
|
)
|
||||||
|
assert SPEC is not None and SPEC.loader is not None
|
||||||
|
probe = importlib.util.module_from_spec(SPEC)
|
||||||
|
SPEC.loader.exec_module(probe)
|
||||||
|
ARGS = SimpleNamespace(
|
||||||
|
label="old", command=[], expect="replace", max_failed_ratio=0.01, max_recovery=10
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def result_of(probes: list[tuple]) -> dict:
|
||||||
|
result = probe.summarize(
|
||||||
|
ARGS, probes, [(99, 2), (101, 2)], {"start": 100, "end": 101, "exit": 0, "load_end": 120}, 2
|
||||||
|
)
|
||||||
|
result["k6"] = {"exit": 0, "failed_ratio": 0, "requests": 100, "dropped_iterations": 0}
|
||||||
|
result["history"] = {"exact_match": True, "unique": True}
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("attempts", "recovery", "passed"),
|
||||||
|
[
|
||||||
|
([(100, 503, 20, "old")], None, False),
|
||||||
|
([(100, 503, 20, "old"), (109, 201, 2000, "new")], 11, False),
|
||||||
|
([(100, 503, 20, "old"), (101, 201, 500, "new")], 1.5, True),
|
||||||
|
([(101, 201, 500, "new")], 0, True),
|
||||||
|
([], 0, False),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_recovery_requires_completed_success(attempts: list, recovery: float, passed: bool) -> None:
|
||||||
|
result = result_of([(99, 201, 1, "old"), *attempts])
|
||||||
|
assert result["probe"]["recovery_s"] == recovery
|
||||||
|
assert probe.verdict(ARGS, result)["write_recovery_ok"] is passed
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("field", "value", "check"),
|
||||||
|
[("requests", 0, "load_delivered"), ("dropped_iterations", 1, "load_delivered")],
|
||||||
|
)
|
||||||
|
def test_incomplete_load_fails(field: str, value: int, check: str) -> None:
|
||||||
|
result = result_of([(99, 201, 1, "old"), (102, 201, 1, "new")])
|
||||||
|
result["k6"][field] = value
|
||||||
|
assert not probe.verdict(ARGS, result)[check]
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_lb_sample_fails() -> None:
|
||||||
|
result = result_of([(99, 201, 1, "old"), (102, 201, 1, "new")])
|
||||||
|
result["lb_samples_missing"] = 1
|
||||||
|
assert not probe.verdict(ARGS, result)["lb_observed"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("corruption", ["none", "missing", "duplicate", "changed", "http", "cycle"])
|
||||||
|
def test_full_history_matches_confirmed_bodies(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, corruption: str
|
||||||
|
) -> None:
|
||||||
|
messages = [{"id": str(n), "text": "original"} for n in range(101)]
|
||||||
|
stored = list(reversed(messages))
|
||||||
|
if corruption == "missing":
|
||||||
|
stored.pop()
|
||||||
|
if corruption == "duplicate":
|
||||||
|
stored.append(stored[0])
|
||||||
|
if corruption == "changed":
|
||||||
|
stored[0] = dict(stored[0], text="changed")
|
||||||
|
pages = iter(
|
||||||
|
[
|
||||||
|
(200, "", {"items": stored[:100], "next_cursor": "next"}),
|
||||||
|
(
|
||||||
|
503 if corruption == "http" else 200,
|
||||||
|
"",
|
||||||
|
{"items": stored[100:], "next_cursor": "next" if corruption == "cycle" else None},
|
||||||
|
),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(probe, "call", lambda *_a, **_kw: next(pages))
|
||||||
|
result = probe.history_check({"auth": {}}, "chat", messages)
|
||||||
|
assert (result["exact_match"] and result["unique"]) is (corruption == "none")
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import importlib.util
|
||||||
|
from pathlib import Path
|
||||||
|
from types import ModuleType, SimpleNamespace
|
||||||
|
from unittest.mock import Mock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def scaling(monkeypatch: pytest.MonkeyPatch) -> ModuleType:
|
||||||
|
scripts = Path(__file__).resolve().parents[2] / "scripts"
|
||||||
|
monkeypatch.syspath_prepend(str(scripts))
|
||||||
|
spec = importlib.util.spec_from_file_location("scaling", scripts / "scaling.py")
|
||||||
|
assert spec is not None and spec.loader is not None
|
||||||
|
module = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(module)
|
||||||
|
return module
|
||||||
|
|
||||||
|
|
||||||
|
def test_retry_preserves_previous_raw_data(scaling: ModuleType, tmp_path: Path) -> None:
|
||||||
|
base = {"variant": "base", "config": "1x1"}
|
||||||
|
first = scaling.attempt_folder(tmp_path, base, 100, 1)
|
||||||
|
(first / "k6.txt").write_text("failed attempt")
|
||||||
|
second = scaling.attempt_folder(tmp_path, base, 100, 1)
|
||||||
|
assert first != second
|
||||||
|
assert (first / "k6.txt").read_text() == "failed attempt"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("recover", [False, True])
|
||||||
|
def test_disturbed_runs_never_enter_summary(
|
||||||
|
scaling: ModuleType, monkeypatch: pytest.MonkeyPatch, recover: bool
|
||||||
|
) -> None:
|
||||||
|
args = SimpleNamespace(
|
||||||
|
base_env={}, out="unused", retries=1, pause=0, rates="100", rejected=Mock()
|
||||||
|
)
|
||||||
|
rejected = {"raw_dir": "attempt1", "disturbed": True, "saturated": False}
|
||||||
|
accepted = {"raw_dir": "attempt2", "disturbed": False, "saturated": False}
|
||||||
|
monkeypatch.setattr(scaling, "layout", lambda *_: ({}, {}))
|
||||||
|
monkeypatch.setattr(scaling, "apply", lambda *_: {})
|
||||||
|
monkeypatch.setattr(scaling, "deployment", lambda *_: [])
|
||||||
|
monkeypatch.setattr(scaling, "wait_quiet", lambda *_: None)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
scaling, "step", Mock(side_effect=[rejected, accepted if recover else rejected])
|
||||||
|
)
|
||||||
|
output = Mock()
|
||||||
|
if recover:
|
||||||
|
scaling.block(args, output, "1x1", "base", [1])
|
||||||
|
output.writerows.assert_called_once_with([accepted])
|
||||||
|
args.rejected.writerow.assert_called_once_with(rejected)
|
||||||
|
else:
|
||||||
|
with pytest.raises(SystemExit, match="exhausted retries"):
|
||||||
|
scaling.block(args, output, "1x1", "base", [1])
|
||||||
|
output.writerows.assert_not_called()
|
||||||
|
assert args.rejected.writerow.call_count == 2
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("fixed", "expected"),
|
||||||
|
[
|
||||||
|
(True, [("4x1", [2]), ("8x0.5", [2]), ("4x1", [3]), ("8x0.5", [3])]),
|
||||||
|
(False, [("4x1", [2, 3]), ("8x0.5", [2, 3])]),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_series_order(
|
||||||
|
scaling: ModuleType,
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
fixed: bool,
|
||||||
|
expected: list[tuple[str, list[int]]],
|
||||||
|
) -> None:
|
||||||
|
args = SimpleNamespace(
|
||||||
|
first_repeat=2,
|
||||||
|
repeats=2,
|
||||||
|
configs="4x1,8x0.5",
|
||||||
|
variants=["pinned"],
|
||||||
|
rates="3040,4560" if fixed else None,
|
||||||
|
)
|
||||||
|
block = Mock()
|
||||||
|
monkeypatch.setattr(scaling, "block", block)
|
||||||
|
scaling.series(args, Mock())
|
||||||
|
assert [(call.args[2], list(call.args[4])) for call in block.call_args_list] == expected
|
||||||
@@ -0,0 +1,414 @@
|
|||||||
|
import argparse
|
||||||
|
import collections
|
||||||
|
import csv
|
||||||
|
import statistics
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
|
||||||
|
ORDER = ("1x1", "2x1", "4x1", "8x1", "2x2", "1x4")
|
||||||
|
PALETTE = ("#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300", "#6250d6", "#e34948")
|
||||||
|
MARKERS = ("o", "s", "^", "D", "v", "P", "X", "*")
|
||||||
|
USL_POINTS = 3
|
||||||
|
MIN_REPEATS = 3
|
||||||
|
COMPONENTS = (("api", "API"), ("postgres", "PostgreSQL"), ("lb", "HAProxy"), ("k6", "k6"))
|
||||||
|
INK, MUTED, GRID, SURFACE = "#0b0b0b", "#52514e", "#e4e3df", "#fcfcfb"
|
||||||
|
STAMP = (
|
||||||
|
f"date: {time.strftime('%FT%TZ', time.gmtime())} commit: "
|
||||||
|
+ subprocess.check_output(["/usr/bin/env", "git", "rev-parse", "HEAD"], text=True).strip()
|
||||||
|
)
|
||||||
|
SUMMARY = [
|
||||||
|
"series",
|
||||||
|
"variant",
|
||||||
|
"config",
|
||||||
|
"rates",
|
||||||
|
"capacity_rate",
|
||||||
|
"capacity_label",
|
||||||
|
"capacity_ok_rps",
|
||||||
|
"capacity_p95_ms",
|
||||||
|
"capacity_p99_ms",
|
||||||
|
"peak_rate",
|
||||||
|
"peak_ok_rps",
|
||||||
|
"peak_ok_min",
|
||||||
|
"peak_ok_max",
|
||||||
|
"peak_p95_ms",
|
||||||
|
"peak_failed_ratio",
|
||||||
|
"peak_dropped",
|
||||||
|
"cpu_api",
|
||||||
|
"cpu_api_limit",
|
||||||
|
"cpu_postgres",
|
||||||
|
"cpu_lb",
|
||||||
|
"cpu_k6",
|
||||||
|
"pg_active_avg",
|
||||||
|
"pg_lock_avg",
|
||||||
|
"pg_idle_tx_avg",
|
||||||
|
"pg_idle_avg",
|
||||||
|
"pool_total",
|
||||||
|
"pg_backends_max",
|
||||||
|
"lb_qcur_max",
|
||||||
|
]
|
||||||
|
|
||||||
|
plt.rcParams.update(
|
||||||
|
{
|
||||||
|
"figure.facecolor": SURFACE,
|
||||||
|
"axes.facecolor": SURFACE,
|
||||||
|
"axes.edgecolor": MUTED,
|
||||||
|
"axes.labelcolor": MUTED,
|
||||||
|
"axes.titlecolor": INK,
|
||||||
|
"axes.titleweight": "bold",
|
||||||
|
"axes.grid": True,
|
||||||
|
"grid.color": GRID,
|
||||||
|
"grid.linewidth": 0.8,
|
||||||
|
"axes.spines.top": False,
|
||||||
|
"axes.spines.right": False,
|
||||||
|
"xtick.color": MUTED,
|
||||||
|
"ytick.color": MUTED,
|
||||||
|
"legend.frameon": False,
|
||||||
|
"lines.linewidth": 2,
|
||||||
|
"lines.markersize": 7,
|
||||||
|
"font.size": 10,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
VARIANTS = {
|
||||||
|
"before": {"color": MUTED, "marker": "o"},
|
||||||
|
"after": {"color": PALETTE[1], "marker": "s"},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def style(name):
|
||||||
|
index = ORDER.index(name) if name in ORDER else len(ORDER)
|
||||||
|
return {"color": PALETTE[index], "marker": MARKERS[index]}
|
||||||
|
|
||||||
|
|
||||||
|
def load(paths):
|
||||||
|
groups = collections.defaultdict(lambda: collections.defaultdict(list))
|
||||||
|
for path in paths:
|
||||||
|
with Path(path).open() as handle:
|
||||||
|
for row in csv.DictReader(line for line in handle if not line.startswith("#")):
|
||||||
|
if row["disturbed"] == "True":
|
||||||
|
raise ValueError(f"disturbed run in accepted sample: {path}")
|
||||||
|
key = (Path(path).parent.name, row["variant"], row["config"])
|
||||||
|
groups[key][int(row["rate"])].append(row)
|
||||||
|
for key, rates in groups.items():
|
||||||
|
for rate, rows in rates.items():
|
||||||
|
if len(rows) < MIN_REPEATS or len({row["repeat"] for row in rows}) != len(rows):
|
||||||
|
raise ValueError(f"need at least three distinct repeats: {key}, {rate}")
|
||||||
|
return groups
|
||||||
|
|
||||||
|
|
||||||
|
def med(rows, field):
|
||||||
|
values = [float(r[field]) for r in rows]
|
||||||
|
middle = statistics.median(values)
|
||||||
|
return middle, middle - min(values), max(values) - middle
|
||||||
|
|
||||||
|
|
||||||
|
def label(key):
|
||||||
|
return key[2] if key[1] == "base" else f"{key[2]} {key[1]}"
|
||||||
|
|
||||||
|
|
||||||
|
def summarize(key, rates):
|
||||||
|
series, variant, config = key
|
||||||
|
sat = {
|
||||||
|
rate: 2 * sum(r["saturated"] == "True" for r in rows) > len(rows)
|
||||||
|
for rate, rows in rates.items()
|
||||||
|
}
|
||||||
|
capacity = max((rate for rate, bad in sat.items() if not bad), default=None)
|
||||||
|
peak = max(rates, key=lambda rate: med(rates[rate], "ok_rps")[0])
|
||||||
|
top, first = rates[peak], rates[peak][0]
|
||||||
|
replicas, workers, pool = (int(first[f]) for f in ("replicas", "workers", "pool"))
|
||||||
|
row = {
|
||||||
|
"series": series,
|
||||||
|
"variant": variant,
|
||||||
|
"config": config,
|
||||||
|
"rates": " ".join(str(r) for r in sorted(rates)),
|
||||||
|
"peak_rate": peak,
|
||||||
|
"peak_ok_rps": med(top, "ok_rps")[0],
|
||||||
|
"peak_ok_min": min(float(r["ok_rps"]) for r in top),
|
||||||
|
"peak_ok_max": max(float(r["ok_rps"]) for r in top),
|
||||||
|
"peak_p95_ms": med(top, "p95_ms")[0],
|
||||||
|
"peak_failed_ratio": med(top, "failed_ratio")[0],
|
||||||
|
"peak_dropped": med(top, "dropped_iterations")[0],
|
||||||
|
"cpu_api_limit": round(replicas * float(first["cpus"]) * 100),
|
||||||
|
"pool_total": replicas * workers * pool,
|
||||||
|
}
|
||||||
|
for field in [
|
||||||
|
"cpu_api",
|
||||||
|
"cpu_postgres",
|
||||||
|
"cpu_lb",
|
||||||
|
"cpu_k6",
|
||||||
|
"pg_active_avg",
|
||||||
|
"pg_lock_avg",
|
||||||
|
"pg_idle_tx_avg",
|
||||||
|
"pg_idle_avg",
|
||||||
|
"pg_backends_max",
|
||||||
|
"lb_qcur_max",
|
||||||
|
]:
|
||||||
|
row[field] = round(med(top, field)[0], 2)
|
||||||
|
if capacity is not None:
|
||||||
|
for field, name in (("ok_rps", "ok_rps"), ("p95_ms", "p95_ms"), ("p99_ms", "p99_ms")):
|
||||||
|
row[f"capacity_{name}"] = med(rates[capacity], field)[0]
|
||||||
|
row["capacity_rate"] = capacity
|
||||||
|
row["capacity_label"] = (
|
||||||
|
f"≥{capacity}" if capacity in (min(rates), max(rates)) else str(capacity)
|
||||||
|
)
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
def direct_label(axis, x, y, text):
|
||||||
|
axis.annotate(
|
||||||
|
text, (x, y), xytext=(6, 0), textcoords="offset points", va="center", color=INK, fontsize=9
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def save(figure, path):
|
||||||
|
figure.tight_layout()
|
||||||
|
figure.savefig(path, dpi=150, metadata={"Description": STAMP})
|
||||||
|
plt.close(figure)
|
||||||
|
|
||||||
|
|
||||||
|
def lines(axis, keys, groups, field, categorical=False):
|
||||||
|
for index, key in enumerate(keys):
|
||||||
|
rates = sorted(groups[key])
|
||||||
|
values = [med(groups[key][rate], field) for rate in rates]
|
||||||
|
look = VARIANTS.get(key[1]) or style(key[2])
|
||||||
|
if categorical:
|
||||||
|
look = {"color": PALETTE[index], "marker": MARKERS[index]}
|
||||||
|
axis.errorbar(
|
||||||
|
[index] if categorical else rates,
|
||||||
|
[v[0] for v in values],
|
||||||
|
yerr=[[v[1] for v in values], [v[2] for v in values]],
|
||||||
|
capsize=3,
|
||||||
|
label=label(key),
|
||||||
|
markeredgecolor=SURFACE,
|
||||||
|
markeredgewidth=1.5,
|
||||||
|
**look,
|
||||||
|
)
|
||||||
|
if categorical:
|
||||||
|
axis.set_xticks(range(len(keys)), [label(k) for k in keys], rotation=25, ha="right")
|
||||||
|
|
||||||
|
|
||||||
|
def throughput(series, keys, groups, out):
|
||||||
|
figure, axes = plt.subplots(1, 3, figsize=(17, 4.8))
|
||||||
|
top = max(rate for key in keys for rate in groups[key])
|
||||||
|
categorical = len({rate for key in keys for rate in groups[key]}) == 1
|
||||||
|
if not categorical:
|
||||||
|
axes[0].plot(
|
||||||
|
[0, top], [0, top], color=MUTED, linestyle="--", linewidth=1, label="RPS = нагрузка"
|
||||||
|
)
|
||||||
|
lines(axes[0], keys, groups, "ok_rps", categorical)
|
||||||
|
axes[0].set_title("Успешные RPS")
|
||||||
|
for axis, field, title in ((axes[1], "p95_ms", "p95, мс"), (axes[2], "p99_ms", "p99, мс")):
|
||||||
|
lines(axis, keys, groups, field, categorical)
|
||||||
|
if not categorical:
|
||||||
|
axis.set_yscale("log")
|
||||||
|
axis.set_title(title)
|
||||||
|
for axis in axes:
|
||||||
|
axis.set_xlabel(
|
||||||
|
f"Вариант при {top} запросах/с" if categorical else "Предложенная нагрузка, запросов/с"
|
||||||
|
)
|
||||||
|
if not categorical:
|
||||||
|
axis.legend(loc="best", fontsize=9)
|
||||||
|
figure.suptitle(f"{series}: медиана повторов, усы — min–max", color=INK)
|
||||||
|
save(figure, out / f"{series}-throughput.png")
|
||||||
|
|
||||||
|
|
||||||
|
def cpu(series, keys, groups, out):
|
||||||
|
figure, axes = plt.subplots(1, len(keys), figsize=(5 * len(keys), 4.2), squeeze=False)
|
||||||
|
for axis, key in zip(axes[0], keys, strict=True):
|
||||||
|
rates = sorted(groups[key])
|
||||||
|
first = groups[key][rates[0]][0]
|
||||||
|
limit = int(first["replicas"]) * float(first["cpus"]) * 100
|
||||||
|
for index, (field, name) in enumerate(COMPONENTS):
|
||||||
|
values = [med(groups[key][rate], f"cpu_{field}") for rate in rates]
|
||||||
|
axis.errorbar(
|
||||||
|
rates,
|
||||||
|
[v[0] for v in values],
|
||||||
|
yerr=[[v[1] for v in values], [v[2] for v in values]],
|
||||||
|
capsize=3,
|
||||||
|
color=PALETTE[index],
|
||||||
|
marker=MARKERS[index],
|
||||||
|
label=name,
|
||||||
|
)
|
||||||
|
axis.axhline(limit, color=PALETTE[0], linestyle=":", linewidth=1.2, label="лимит API")
|
||||||
|
axis.axhline(200, color=PALETTE[1], linestyle=":", linewidth=1.2, label="лимит PostgreSQL")
|
||||||
|
axis.set_title(f"CPU, % ядра — {label(key)}")
|
||||||
|
axis.set_xlabel("Предложенная нагрузка, запросов/с")
|
||||||
|
axis.legend(fontsize=8, loc="best")
|
||||||
|
figure.suptitle("Медиана CPU по повторам, усы — min–max", color=INK)
|
||||||
|
save(figure, out / f"{series}-cpu.png")
|
||||||
|
|
||||||
|
|
||||||
|
def usl(points):
|
||||||
|
base = points[0][1] / points[0][0]
|
||||||
|
pairs = [(n - 1, n * (n - 1), n * base / x - 1) for n, x in points]
|
||||||
|
a, b, c = (sum(p[i] * p[j] for p in pairs) for i, j in ((0, 0), (0, 1), (1, 1)))
|
||||||
|
d, e = (sum(p[i] * p[2] for p in pairs) for i in (0, 1))
|
||||||
|
det = a * c - b * b
|
||||||
|
sigma, kappa = (d * c - b * e) / det, (a * e - b * d) / det
|
||||||
|
peak = ((1 - sigma) / kappa) ** 0.5 if kappa > 0 else None
|
||||||
|
return base, sigma, kappa, peak
|
||||||
|
|
||||||
|
|
||||||
|
def scaling(rows, out):
|
||||||
|
by = {(r["series"], r["config"]): r for r in rows if r["variant"] == "base"}
|
||||||
|
growth = [
|
||||||
|
by.get(("series-b", c)) or by.get(("series-a", c)) for c in ("1x1", "2x1", "4x1", "8x1")
|
||||||
|
]
|
||||||
|
growth = [r for r in growth if r]
|
||||||
|
if not growth:
|
||||||
|
return
|
||||||
|
figure, axis = plt.subplots(figsize=(7.5, 4.8))
|
||||||
|
cpus = [r["cpu_api_limit"] / 100 for r in growth]
|
||||||
|
unit = growth[0]["peak_ok_rps"] / cpus[0]
|
||||||
|
axis.plot(cpus, [unit * c for c in cpus], color=MUTED, linestyle="--", linewidth=1)
|
||||||
|
axis.annotate("линейный рост", (cpus[-1], unit * cpus[-1]), color=MUTED, fontsize=9)
|
||||||
|
fit = None
|
||||||
|
if len(growth) >= USL_POINTS:
|
||||||
|
fit = usl([(c, r["peak_ok_rps"]) for c, r in zip(cpus, growth, strict=True)])
|
||||||
|
base, sigma, kappa, _ = fit
|
||||||
|
grid = [1 + i * (cpus[-1] - 1) / 60 for i in range(61)]
|
||||||
|
model = [base * n / (1 + sigma * (n - 1) + kappa * n * (n - 1)) for n in grid]
|
||||||
|
axis.plot(
|
||||||
|
grid, model, color=PALETTE[6], linewidth=1.5, label=f"USL: σ={sigma:.3f}, κ={kappa:.4f}"
|
||||||
|
)
|
||||||
|
axis.errorbar(
|
||||||
|
cpus,
|
||||||
|
[r["peak_ok_rps"] for r in growth],
|
||||||
|
yerr=[
|
||||||
|
[r["peak_ok_rps"] - r["peak_ok_min"] for r in growth],
|
||||||
|
[r["peak_ok_max"] - r["peak_ok_rps"] for r in growth],
|
||||||
|
],
|
||||||
|
color=PALETTE[0],
|
||||||
|
marker="o",
|
||||||
|
capsize=3,
|
||||||
|
label="серия B: N × 1 CPU",
|
||||||
|
)
|
||||||
|
for r, c in zip(growth, cpus, strict=True):
|
||||||
|
direct_label(axis, c, r["peak_ok_rps"], r["config"])
|
||||||
|
for config in ("2x2", "1x4"):
|
||||||
|
r = by.get(("series-a", config))
|
||||||
|
if r:
|
||||||
|
look = style(config)
|
||||||
|
axis.errorbar(
|
||||||
|
4,
|
||||||
|
r["peak_ok_rps"],
|
||||||
|
yerr=[[r["peak_ok_rps"] - r["peak_ok_min"]], [r["peak_ok_max"] - r["peak_ok_rps"]]],
|
||||||
|
capsize=3,
|
||||||
|
linestyle="none",
|
||||||
|
label=f"серия A: {config}",
|
||||||
|
**look,
|
||||||
|
)
|
||||||
|
after = [r for r in rows if r["variant"] == "after"]
|
||||||
|
for r in after:
|
||||||
|
width = r["cpu_api_limit"] / 100
|
||||||
|
axis.errorbar(
|
||||||
|
width,
|
||||||
|
r["peak_ok_rps"],
|
||||||
|
yerr=[[r["peak_ok_rps"] - r["peak_ok_min"]], [r["peak_ok_max"] - r["peak_ok_rps"]]],
|
||||||
|
capsize=3,
|
||||||
|
linestyle="none",
|
||||||
|
label=f"{r['config']} после улучшения",
|
||||||
|
**VARIANTS["after"],
|
||||||
|
)
|
||||||
|
axis.set_xlabel("Суммарный CPU реплик API")
|
||||||
|
axis.set_ylabel("Пик успешных RPS")
|
||||||
|
axis.set_title("Пропускная способность от ресурсов API")
|
||||||
|
axis.set_xticks(cpus)
|
||||||
|
axis.legend(loc="best", fontsize=9)
|
||||||
|
save(figure, out / "scaling.png")
|
||||||
|
return fit
|
||||||
|
|
||||||
|
|
||||||
|
def utilisation(rows, out):
|
||||||
|
picked = [r for r in rows if r["variant"] == "base" and r["series"] != "compare"]
|
||||||
|
seen, ordered = set(), []
|
||||||
|
for config in ORDER:
|
||||||
|
for r in picked:
|
||||||
|
if r["config"] == config and config not in seen:
|
||||||
|
seen.add(config)
|
||||||
|
ordered.append(r)
|
||||||
|
if not ordered:
|
||||||
|
return
|
||||||
|
metrics = (
|
||||||
|
("CPU API, % лимита", lambda r: 100 * r["cpu_api"] / r["cpu_api_limit"]),
|
||||||
|
("CPU PostgreSQL, % лимита", lambda r: r["cpu_postgres"] / 2),
|
||||||
|
("CPU HAProxy, % лимита", lambda r: r["cpu_lb"]),
|
||||||
|
("ждут блокировку, % пула", lambda r: 100 * r["pg_lock_avg"] / r["pool_total"]),
|
||||||
|
)
|
||||||
|
figure, axis = plt.subplots(figsize=(10, 4.8))
|
||||||
|
width = 0.8 / len(metrics)
|
||||||
|
for index, (name, value) in enumerate(metrics):
|
||||||
|
xs = [i + (index - 1.5) * width for i in range(len(ordered))]
|
||||||
|
axis.bar(
|
||||||
|
xs,
|
||||||
|
[value(r) for r in ordered],
|
||||||
|
width=width - 0.02,
|
||||||
|
color=PALETTE[index],
|
||||||
|
label=name,
|
||||||
|
edgecolor=SURFACE,
|
||||||
|
)
|
||||||
|
axis.set_xticks(range(len(ordered)), [r["config"] for r in ordered])
|
||||||
|
axis.axhline(100, color=MUTED, linestyle=":", linewidth=1)
|
||||||
|
axis.set_ylabel("%")
|
||||||
|
axis.set_ylim(0, 115)
|
||||||
|
axis.set_title("Загрузка звеньев в точке пика успешных RPS", pad=34)
|
||||||
|
axis.legend(fontsize=9, ncols=4, loc="lower left", bbox_to_anchor=(0, 1.0))
|
||||||
|
save(figure, out / "utilisation.png")
|
||||||
|
|
||||||
|
|
||||||
|
def write(rows, out, fit):
|
||||||
|
with (out / "capacity.csv").open("w", newline="") as handle:
|
||||||
|
handle.write(f"# {STAMP}\n")
|
||||||
|
writer = csv.DictWriter(handle, fieldnames=SUMMARY, extrasaction="ignore")
|
||||||
|
writer.writeheader()
|
||||||
|
writer.writerows(rows)
|
||||||
|
head = (
|
||||||
|
"| серия | вариант | конфигурация | потолок по SLO, rps | p95 там, мс | пик успешных RPS "
|
||||||
|
"[min–max] | при нагрузке | CPU API / лимит | CPU PG | CPU LB | ждут блокировку / пул |"
|
||||||
|
)
|
||||||
|
lines_ = [head, "|" + " --- |" * 11]
|
||||||
|
for r in rows:
|
||||||
|
lines_.append(
|
||||||
|
f"| {r['series']} | {r['variant']} | {r['config']} | {r.get('capacity_label', '—')} | "
|
||||||
|
f"{r.get('capacity_p95_ms', '—')} | {r['peak_ok_rps']:.0f} "
|
||||||
|
f"[{r['peak_ok_min']:.0f}–{r['peak_ok_max']:.0f}] | {r['peak_rate']} | "
|
||||||
|
f"{r['cpu_api']:.0f} / {r['cpu_api_limit']} | {r['cpu_postgres']:.0f} | "
|
||||||
|
f"{r['cpu_lb']:.0f} | {r['pg_lock_avg']:.1f} / {r['pool_total']} |"
|
||||||
|
)
|
||||||
|
if fit:
|
||||||
|
_, sigma, kappa, peak = fit
|
||||||
|
best = f"{peak:.1f}" if peak else "—"
|
||||||
|
lines_.append(
|
||||||
|
f"\nОписательная USL-аппроксимация серии B: σ = {sigma:.4f}, κ = {kappa:.5f}, "
|
||||||
|
f"модельный N* = {best} CPU. Это не измеренный оптимум и не доказательство причины."
|
||||||
|
)
|
||||||
|
(out / "capacity.md").write_text(STAMP + "\n\n" + "\n".join(lines_) + "\n")
|
||||||
|
print("\n".join(lines_))
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description="Графики и сводка трека 1 из summary.csv")
|
||||||
|
parser.add_argument("summaries", nargs="+")
|
||||||
|
parser.add_argument("--out", required=True)
|
||||||
|
args = parser.parse_args()
|
||||||
|
out = Path(args.out)
|
||||||
|
out.mkdir(parents=True, exist_ok=True)
|
||||||
|
groups = load(args.summaries)
|
||||||
|
rank = {name: index for index, name in enumerate(ORDER)}
|
||||||
|
keys = sorted(groups, key=lambda k: (k[0], k[1] != "before", rank.get(k[2], 99)))
|
||||||
|
rows = [summarize(key, groups[key]) for key in keys]
|
||||||
|
for series in dict.fromkeys(k[0] for k in keys):
|
||||||
|
chosen = [k for k in keys if k[0] == series]
|
||||||
|
throughput(series, chosen, groups, out)
|
||||||
|
cpu(series, chosen, groups, out)
|
||||||
|
fit = scaling(rows, out)
|
||||||
|
utilisation(rows, out)
|
||||||
|
write(rows, out, fit)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -109,6 +109,20 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/fb/76/641ae371508676492379f16e2fa48f4e2c11741bd63c48be4b12a6b09cba/aiosignal-1.4.0-py3-none-any.whl", hash = "sha256:053243f8b92b990551949e63930a839ff0cf0b0ebbe0597b0f3fb19e1a0fe82e", size = 7490, upload-time = "2025-07-03T22:54:42.156Z" },
|
{ url = "https://files.pythonhosted.org/packages/fb/76/641ae371508676492379f16e2fa48f4e2c11741bd63c48be4b12a6b09cba/aiosignal-1.4.0-py3-none-any.whl", hash = "sha256:053243f8b92b990551949e63930a839ff0cf0b0ebbe0597b0f3fb19e1a0fe82e", size = 7490, upload-time = "2025-07-03T22:54:42.156Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[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]]
|
[[package]]
|
||||||
name = "annotated-doc"
|
name = "annotated-doc"
|
||||||
version = "0.0.5"
|
version = "0.0.5"
|
||||||
@@ -423,6 +437,33 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/9a/9a/e35b4a917281c0b8419d4207f4334c8e8c5dbf4f3f5f9ada73958d937dcc/frozenlist-1.8.0-py3-none-any.whl", hash = "sha256:0c18a16eab41e82c295618a77502e17b195883241c563b00f0aa5106fc4eaa0d", size = 13409, upload-time = "2025-10-06T05:38:16.721Z" },
|
{ url = "https://files.pythonhosted.org/packages/9a/9a/e35b4a917281c0b8419d4207f4334c8e8c5dbf4f3f5f9ada73958d937dcc/frozenlist-1.8.0-py3-none-any.whl", hash = "sha256:0c18a16eab41e82c295618a77502e17b195883241c563b00f0aa5106fc4eaa0d", size = 13409, upload-time = "2025-10-06T05:38:16.721Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[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]]
|
[[package]]
|
||||||
name = "gunicorn"
|
name = "gunicorn"
|
||||||
version = "26.2.0"
|
version = "26.2.0"
|
||||||
@@ -586,12 +627,68 @@ 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" },
|
{ 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]]
|
[[package]]
|
||||||
name = "mtusi-messenger"
|
name = "mtusi-messenger"
|
||||||
version = "1.4.0"
|
version = "1.4.0"
|
||||||
source = { editable = "." }
|
source = { editable = "." }
|
||||||
dependencies = [
|
dependencies = [
|
||||||
{ name = "aiobotocore" },
|
{ name = "aiobotocore" },
|
||||||
|
{ name = "alembic" },
|
||||||
{ name = "argon2-cffi" },
|
{ name = "argon2-cffi" },
|
||||||
{ name = "asyncpg" },
|
{ name = "asyncpg" },
|
||||||
{ name = "dishka" },
|
{ name = "dishka" },
|
||||||
@@ -602,6 +699,7 @@ dependencies = [
|
|||||||
{ name = "pydantic" },
|
{ name = "pydantic" },
|
||||||
{ name = "pydantic-settings" },
|
{ name = "pydantic-settings" },
|
||||||
{ name = "redis" },
|
{ name = "redis" },
|
||||||
|
{ name = "sqlalchemy", extra = ["asyncio"] },
|
||||||
{ name = "structlog" },
|
{ name = "structlog" },
|
||||||
{ name = "uvicorn", extra = ["standard"] },
|
{ name = "uvicorn", extra = ["standard"] },
|
||||||
{ name = "uvicorn-worker" },
|
{ name = "uvicorn-worker" },
|
||||||
@@ -620,6 +718,7 @@ dev = [
|
|||||||
[package.metadata]
|
[package.metadata]
|
||||||
requires-dist = [
|
requires-dist = [
|
||||||
{ name = "aiobotocore", specifier = ">=3.10.0" },
|
{ name = "aiobotocore", specifier = ">=3.10.0" },
|
||||||
|
{ name = "alembic", specifier = "==1.16.5" },
|
||||||
{ name = "argon2-cffi", specifier = ">=25.1.0" },
|
{ name = "argon2-cffi", specifier = ">=25.1.0" },
|
||||||
{ name = "asyncpg", specifier = ">=0.32.0" },
|
{ name = "asyncpg", specifier = ">=0.32.0" },
|
||||||
{ name = "dishka", specifier = ">=1.7.0" },
|
{ name = "dishka", specifier = ">=1.7.0" },
|
||||||
@@ -630,6 +729,7 @@ requires-dist = [
|
|||||||
{ name = "pydantic", specifier = ">=2.11.0" },
|
{ name = "pydantic", specifier = ">=2.11.0" },
|
||||||
{ name = "pydantic-settings", specifier = ">=2.11.0" },
|
{ name = "pydantic-settings", specifier = ">=2.11.0" },
|
||||||
{ name = "redis", specifier = ">=8.1.0" },
|
{ name = "redis", specifier = ">=8.1.0" },
|
||||||
|
{ name = "sqlalchemy", extras = ["asyncio"], specifier = "==2.0.45" },
|
||||||
{ name = "structlog", specifier = ">=26.1.0" },
|
{ name = "structlog", specifier = ">=26.1.0" },
|
||||||
{ name = "uvicorn", extras = ["standard"], specifier = ">=0.37.0" },
|
{ name = "uvicorn", extras = ["standard"], specifier = ">=0.37.0" },
|
||||||
{ name = "uvicorn-worker", specifier = ">=0.4.0" },
|
{ name = "uvicorn-worker", specifier = ">=0.4.0" },
|
||||||
@@ -1127,6 +1227,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" },
|
{ 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]]
|
[[package]]
|
||||||
name = "starlette"
|
name = "starlette"
|
||||||
version = "1.7.0"
|
version = "1.7.0"
|
||||||
|
|||||||
Reference in New Issue
Block a user