forked from mtusi2026/mtusi2026lab3
perf: идемпотентная отправка сообщения одним вызовом SQL (трек 1)
Гипотеза из профиля (py-spy, 2 x 1.0 CPU, 240 req/s): ~57 % CPU реплики уходит в psycopg — накладные расходы на каждый оператор; на одно сообщение ~11 обращений к PostgreSQL в двух транзакциях (проверка членства, BEGIN, ключ, часы чата, сообщение, COMMIT, проверки пула). - migrations/0003: функция post_message — та же логика и тот же SQL, что в многооператорном пути; вызывается в autocommit, поэтому вызов и есть транзакция (ключ, часы чата и сообщение — всё или ничего). - пул: autocommit-соединения; многооператорная работа по-прежнему в явной conn.transaction(); ping — один оператор без транзакции. - MESSAGE_WRITE_PATH=function (по умолчанию) | multi (прежний путь) — A/B на одном образе. Порядок ответов одинаков: постороннему всегда 404, даже при неверном ключе/теле. - Оба режима проходят одни и те же тесты идемпотентности и контракта. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
26a0d86431
commit
4830be414e
+30
-11
@@ -287,23 +287,41 @@ async def get_chat(request: Request) -> JSONResponse:
|
||||
return ok((await repo.get_chat(db_of(request), user_id, chat_id)).to_json())
|
||||
|
||||
|
||||
async def create_message(request: Request) -> JSONResponse:
|
||||
user_id = await authenticate(request)
|
||||
chat_id = path_uuid(request, "chat_id")
|
||||
db = db_of(request)
|
||||
await repo.ensure_member(db, user_id, chat_id) # outsiders get 404 before key/body are looked at
|
||||
key = idempotency_key(request)
|
||||
data = await read_json(request)
|
||||
def parse_message(data: dict[str, Any]) -> tuple[str, list[str]]:
|
||||
validation.check_fields(data, {"text"}, frozenset({"attachment_ids"}))
|
||||
text = validation.text_field(data, "text", 4000)
|
||||
attachment_ids = validation.attachment_ids_field(data)
|
||||
if attachment_ids:
|
||||
# Lab 3 has no attachments: every referenced ID is unknown (lab 4 semantics: 404).
|
||||
raise NotFound("Вложение не найдено")
|
||||
# sender_id is derived from the session, never taken from the body.
|
||||
return text, attachment_ids
|
||||
|
||||
|
||||
async def create_message(request: Request) -> JSONResponse:
|
||||
"""Order of answers for both write paths: 401 -> 400 bad chat id -> 404 outsider -> 400 key/body
|
||||
-> 409 other body with the same key -> 201 (new or replayed). sender_id comes from the session."""
|
||||
user_id = await authenticate(request)
|
||||
chat_id = path_uuid(request, "chat_id")
|
||||
db = db_of(request)
|
||||
settings = request.app.state.settings
|
||||
result = await repo.post_message(db, user_id, chat_id, key, request_fingerprint(text, attachment_ids), text,
|
||||
settings.idempotency_ttl_seconds)
|
||||
if settings.message_write_path == "multi":
|
||||
await repo.ensure_member(db, user_id, chat_id) # outsiders get 404 before key/body are looked at
|
||||
key = idempotency_key(request)
|
||||
text, attachment_ids = parse_message(await read_json(request))
|
||||
result = await repo.post_message(db, user_id, chat_id, key, request_fingerprint(text, attachment_ids), text,
|
||||
settings.idempotency_ttl_seconds)
|
||||
else:
|
||||
try:
|
||||
key = idempotency_key(request)
|
||||
text, attachment_ids = parse_message(await read_json(request))
|
||||
except ApiError:
|
||||
# Rare error path only: an outsider must still get 404, not a hint about the body.
|
||||
await repo.ensure_member(db, user_id, chat_id)
|
||||
raise
|
||||
# Membership check, key claim, chat clock and message: one SQL call, one transaction.
|
||||
result = await repo.post_message_single_call(db, user_id, chat_id, key,
|
||||
request_fingerprint(text, attachment_ids), text,
|
||||
settings.idempotency_ttl_seconds)
|
||||
if result.replayed:
|
||||
log.info("idempotent_replay", extra={"fields": {"request_id": request.state.request_id,
|
||||
"message_id": result.message.id}})
|
||||
@@ -361,7 +379,8 @@ def create_app(settings: Settings | None = None) -> Starlette:
|
||||
log.info("dependencies_configured", extra={"fields": {
|
||||
"session_store": sessions.name, "session_ttl_s": settings.session_ttl_seconds,
|
||||
"db_pool_max": settings.db_pool_max, "db_timeout_s": settings.db_timeout_seconds,
|
||||
"instance_id": settings.instance_id, "drain_s": settings.drain_seconds}})
|
||||
"instance_id": settings.instance_id, "drain_s": settings.drain_seconds,
|
||||
"message_write_path": settings.message_write_path}})
|
||||
tasks = [asyncio.create_task(purge_loop())]
|
||||
if settings.stats_log_seconds > 0:
|
||||
tasks.append(asyncio.create_task(stats_loop(settings.stats_log_seconds)))
|
||||
|
||||
@@ -69,6 +69,13 @@ def _bool(name: str, default: bool) -> bool:
|
||||
return raw in {"true", "1"}
|
||||
|
||||
|
||||
def _choice(name: str, default: str, allowed: set[str]) -> str:
|
||||
value = os.environ.get(name, "").strip().lower() or default
|
||||
if value not in allowed:
|
||||
raise ConfigError(f"{name} must be one of {sorted(allowed)}, got {value!r}")
|
||||
return value
|
||||
|
||||
|
||||
def _secret(name: str, required: bool) -> str:
|
||||
"""Value of <NAME>_FILE (preferred, Docker secret) or <NAME> (local runs/tests)."""
|
||||
path = os.environ.get(f"{name}_FILE", "").strip()
|
||||
@@ -107,6 +114,7 @@ class Settings:
|
||||
drain_seconds: float = 0.0
|
||||
idempotency_ttl_seconds: int = 86400
|
||||
stats_log_seconds: float = 0.0
|
||||
message_write_path: str = "function"
|
||||
|
||||
@property
|
||||
def db_statement_timeout_ms(self) -> int:
|
||||
@@ -154,4 +162,7 @@ class Settings:
|
||||
idempotency_ttl_seconds=_int("IDEMPOTENCY_TTL_SECONDS", 86400, 86400, 30 * 24 * 3600),
|
||||
# Experiments (bench/track1): log DB pool counters and process CPU every N s; 0 = off.
|
||||
stats_log_seconds=_float("STATS_LOG_SECONDS", 0.0, 0.0, 60.0),
|
||||
# Track 1: `function` = one SQL call per send (migration 0003), `multi` = the previous
|
||||
# multi-statement transaction; both have identical semantics (A/B on one image).
|
||||
message_write_path=_choice("MESSAGE_WRITE_PATH", "function", {"function", "multi"}),
|
||||
)
|
||||
|
||||
+9
-2
@@ -74,6 +74,10 @@ class Database:
|
||||
"options": options,
|
||||
"connect_timeout": max(1, int(settings.db_timeout_seconds)),
|
||||
"application_name": "messenger-api",
|
||||
# Autocommit connections: a single statement (post_message function, ping) is its
|
||||
# own transaction with ONE round trip; multi-statement work uses an explicit
|
||||
# conn.transaction() (BEGIN ... COMMIT), see run().
|
||||
"autocommit": True,
|
||||
# Detect a dead peer / lost network without any cancel request (see module doc).
|
||||
"keepalives": 1,
|
||||
"keepalives_idle": 5,
|
||||
@@ -91,14 +95,17 @@ class Database:
|
||||
async def close(self) -> None:
|
||||
await self.pool.close(timeout=2)
|
||||
|
||||
async def run(self, work: Work[T], deadline: float | None = None) -> T:
|
||||
async def run(self, work: Work[T], deadline: float | None = None, *, transaction: bool = True) -> T:
|
||||
"""Run `work(conn)` in one transaction (COMMIT on success, ROLLBACK on any exception).
|
||||
transaction=False: `work` issues exactly ONE statement, which autocommit makes atomic.
|
||||
|
||||
Domain errors raised by `work` (NotFound, Conflict, ...) propagate unchanged;
|
||||
database unavailability and the deadline become Unavailable (503).
|
||||
"""
|
||||
async def unit() -> T:
|
||||
async with self.pool.connection() as conn:
|
||||
if not transaction:
|
||||
return await work(conn)
|
||||
async with conn.transaction():
|
||||
return await work(conn)
|
||||
|
||||
@@ -118,7 +125,7 @@ class Database:
|
||||
async def select_one(conn: psycopg.AsyncConnection) -> None:
|
||||
await conn.execute("SELECT 1")
|
||||
try:
|
||||
await self.run(select_one, deadline=timeout)
|
||||
await self.run(select_one, deadline=timeout, transaction=False)
|
||||
return True
|
||||
except Unavailable:
|
||||
return False
|
||||
|
||||
@@ -268,6 +268,29 @@ async def post_message(db: Database, user_id: str, chat_id: str, key: str, reque
|
||||
return await db.run(work)
|
||||
|
||||
|
||||
POST_MESSAGE_CALL = "SELECT o_status, o_id, o_text, o_created_at FROM post_message(%s, %s, %s, %s, %s, %s, %s)"
|
||||
|
||||
|
||||
async def post_message_single_call(db: Database, user_id: str, chat_id: str, key: str, request_hash: bytes,
|
||||
text: str, ttl_seconds: int) -> PostResult:
|
||||
"""Same contract as post_message, ONE round trip: SQL function post_message (migration 0003)
|
||||
in autocommit mode, i.e. the call is the whole transaction. Track 1 improvement."""
|
||||
message_id = uuid.uuid4()
|
||||
|
||||
async def work(conn: psycopg.AsyncConnection) -> tuple:
|
||||
cur = await conn.execute(POST_MESSAGE_CALL,
|
||||
(user_id, chat_id, key, request_hash, message_id, _b(text), ttl_seconds))
|
||||
return await cur.fetchone()
|
||||
status, stored_id, stored_text, created_at = await db.run(work, transaction=False)
|
||||
if status == "not_found":
|
||||
raise NotFound("Чат не найден")
|
||||
if status == "conflict":
|
||||
raise Conflict("Idempotency-Key уже использован с другим сообщением")
|
||||
if status == "retry":
|
||||
raise Unavailable("Повторите запрос с тем же Idempotency-Key")
|
||||
return PostResult(Message(str(stored_id), chat_id, user_id, _s(stored_text), created_at), status == "replayed")
|
||||
|
||||
|
||||
async def purge_idempotency_keys(db: Database, ttl_seconds: int, batch: int = 5000) -> int:
|
||||
"""Delete expired keys in bounded batches; one replica at a time (advisory xact lock)."""
|
||||
async def work(conn: psycopg.AsyncConnection) -> int:
|
||||
|
||||
Reference in New Issue
Block a user