forked from mtusi2026/mtusi2026lab3
feat: HAProxy и N API-реплик, X-Instance-Id, общая идемпотентность, drain при SIGTERM
- compose: один масштабируемый сервис api (deploy.replicas=2, без ports и container_name), HAProxy 3.2 LTS по digest — единственная точка входа (127.0.0.1), разовый migrate до старта реплик, CPU/RAM-лимиты у всех сервисов, каждому сервису только его secrets. - HAProxy: server-template + Docker DNS (re-resolve 1 с), активная проверка GET /health/ready каждую 1 с (fall 2 / rise 2), без backup-серверов, retry только conn-failure, ошибки самого LB — в формате контракта с X-Request-Id. - API: X-Instance-Id = hostname контейнера на каждом ответе (и на 500/503); Idempotency-Key обязателен; ключ, сообщение и результат пишутся в ОДНОЙ транзакции (миграция 0002), конкурентный повтор ждёт уникальный индекс; другой body — 409, посторонний — всегда 404; attachment_ids=[] равен отсутствию поля; дубли ключей JSON и тело у POST /auth/sessions — 400. - SIGTERM: readiness 503 + DRAIN_SECONDS=3 обслуживания, затем graceful stop. - scripts: stop-one.sh (+ .cmd для Windows), restore-api.sh, restart.sh перезапускает и LB, lbctl.py — состояние бэкендов HAProxy -> контейнеры. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
4f6cfda37a
commit
3f12698676
+32
-10
@@ -1,16 +1,20 @@
|
||||
"""Entry point: `python -m messenger`. The HTTP server is the main process (PID 1 in Docker).
|
||||
|
||||
Shutdown sequence on SIGTERM/SIGINT:
|
||||
1. readiness flips to 503 (`app.state.draining = True`);
|
||||
2. uvicorn closes the listening socket, so new connections are refused;
|
||||
3. in-flight requests get up to SHUTDOWN_TIMEOUT_SECONDS (default 8 s < Docker's 10 s) to finish;
|
||||
Shutdown sequence on SIGTERM/SIGINT (lab 3: the replica stands behind HAProxy):
|
||||
1. readiness flips to 503 (`app.state.draining = True`), requests are still served;
|
||||
2. after DRAIN_SECONDS (compose: 3 s > HAProxy detection 2 x 1 s) the load balancer has
|
||||
marked this replica DOWN and sends nothing new here;
|
||||
3. uvicorn closes the listening socket; in-flight requests get up to
|
||||
SHUTDOWN_TIMEOUT_SECONDS (compose: 8 s) to finish;
|
||||
4. the lifespan closes the DB pool and the Valkey client; the process exits with code 0.
|
||||
Data stays in PostgreSQL and Valkey volumes.
|
||||
DRAIN + SHUTDOWN (11 s) < compose stop_grace_period (15 s), so Docker never needs SIGKILL.
|
||||
A second signal during the drain skips the rest of it. Data stays in PostgreSQL and Valkey.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sys
|
||||
import threading
|
||||
from types import FrameType
|
||||
|
||||
import uvicorn
|
||||
@@ -23,12 +27,30 @@ log = logging.getLogger("messenger")
|
||||
|
||||
|
||||
class GracefulServer(uvicorn.Server):
|
||||
"""uvicorn.Server that marks the app as draining before the normal graceful stop."""
|
||||
"""uvicorn.Server that drains (readiness 503, still serving) before the normal graceful stop."""
|
||||
|
||||
def __init__(self, config: uvicorn.Config, drain_seconds: float):
|
||||
super().__init__(config)
|
||||
self.drain_seconds = drain_seconds
|
||||
self.drain_timer: threading.Timer | None = None
|
||||
|
||||
def handle_exit(self, sig: int, frame: FrameType | None) -> None:
|
||||
if not self.should_exit:
|
||||
log.info("shutdown_requested", extra={"fields": {"signal": sig, "timeout_s": self.config.timeout_graceful_shutdown}})
|
||||
self.config.app.state.draining = True # config.app is our Starlette instance
|
||||
if self.drain_timer is None and self.drain_seconds > 0 and not self.should_exit:
|
||||
log.info("drain_started", extra={"fields": {"signal": sig, "drain_s": self.drain_seconds,
|
||||
"timeout_s": self.config.timeout_graceful_shutdown}})
|
||||
# uvicorn polls should_exit in its main loop, so setting it from a timer thread is safe.
|
||||
self.drain_timer = threading.Timer(self.drain_seconds, self._stop, args=(sig, frame))
|
||||
self.drain_timer.daemon = True
|
||||
self.drain_timer.start()
|
||||
return
|
||||
if self.drain_timer is not None:
|
||||
self.drain_timer.cancel() # second signal: stop draining now
|
||||
self._stop(sig, frame)
|
||||
|
||||
def _stop(self, sig: int, frame: FrameType | None) -> None:
|
||||
if not self.should_exit:
|
||||
log.info("shutdown_requested", extra={"fields": {"signal": sig}})
|
||||
super().handle_exit(sig, frame)
|
||||
|
||||
|
||||
@@ -51,10 +73,10 @@ def main() -> int:
|
||||
lifespan="on",
|
||||
timeout_graceful_shutdown=settings.shutdown_timeout,
|
||||
)
|
||||
server = GracefulServer(config)
|
||||
server = GracefulServer(config, settings.drain_seconds)
|
||||
log.info("starting", extra={"fields": {
|
||||
"version": __version__, "env": settings.env, "host": settings.host, "port": settings.port,
|
||||
"python": sys.version.split()[0], "storage": "postgresql",
|
||||
"python": sys.version.split()[0], "storage": "postgresql", "instance_id": settings.instance_id,
|
||||
}})
|
||||
server.run()
|
||||
log.info("stopped")
|
||||
|
||||
+65
-12
@@ -3,6 +3,8 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
@@ -19,7 +21,7 @@ from starlette.types import ASGIApp, Message as AsgiMessage, Receive, Scope, Sen
|
||||
from . import authhdr, cursor, docs, passwords, repo, validation
|
||||
from .config import Settings
|
||||
from .db import Database
|
||||
from .errors import BASIC_CHALLENGE, ApiError, InvalidRequest, PayloadTooLarge, Unauthorized, Unavailable
|
||||
from .errors import BASIC_CHALLENGE, ApiError, InvalidRequest, NotFound, PayloadTooLarge, Unauthorized, Unavailable
|
||||
from .sessions import SessionStore, build_store
|
||||
from .timefmt import rfc3339
|
||||
|
||||
@@ -56,10 +58,12 @@ async def http_exception_handler(request: Request, exc: Exception) -> JSONRespon
|
||||
# Middleware (pure ASGI, so it also covers 404/405 and unexpected exceptions)
|
||||
# --------------------------------------------------------------------------
|
||||
class RequestContextMiddleware:
|
||||
"""Assigns X-Request-Id to every response, writes one access-log line, turns crashes into 500."""
|
||||
"""Adds X-Request-Id and X-Instance-Id to EVERY response (errors, health and crash 500/503
|
||||
included), writes one access-log line, turns crashes into 500."""
|
||||
|
||||
def __init__(self, app: ASGIApp):
|
||||
def __init__(self, app: ASGIApp, instance_id: str):
|
||||
self.app = app
|
||||
self.instance_id = instance_id.encode("ascii")
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
if scope["type"] != "http":
|
||||
@@ -77,8 +81,10 @@ class RequestContextMiddleware:
|
||||
if message["type"] == "http.response.start":
|
||||
started = True
|
||||
status = message["status"]
|
||||
headers = [(k, v) for k, v in message.get("headers", []) if k.lower() != b"x-request-id"]
|
||||
headers = [(k, v) for k, v in message.get("headers", [])
|
||||
if k.lower() not in (b"x-request-id", b"x-instance-id")]
|
||||
headers.append((b"x-request-id", request_id.encode("latin-1")))
|
||||
headers.append((b"x-instance-id", self.instance_id))
|
||||
message = {**message, "headers": headers}
|
||||
await send(message)
|
||||
|
||||
@@ -90,20 +96,21 @@ class RequestContextMiddleware:
|
||||
if not started:
|
||||
status = 503
|
||||
response = error_response(request_id, 503, "unavailable", "Сервер завершает работу")
|
||||
await response(scope, receive, send)
|
||||
await response(scope, receive, send_with_id)
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("unhandled_error", extra={"fields": {"request_id": request_id}})
|
||||
if not started:
|
||||
status = 500
|
||||
response = error_response(request_id, 500, "internal_error", "Внутренняя ошибка сервера")
|
||||
await response(scope, receive, send)
|
||||
await response(scope, receive, send_with_id)
|
||||
finally:
|
||||
access_log.info("request", extra={"fields": {
|
||||
"request_id": request_id,
|
||||
"method": scope["method"],
|
||||
"path": scope["path"], # ids only; query (cursor) and bodies are never logged
|
||||
"status": status,
|
||||
"instance_id": self.instance_id.decode("ascii"),
|
||||
"duration_ms": round((time.perf_counter() - begin) * 1000, 3),
|
||||
}})
|
||||
|
||||
@@ -166,6 +173,27 @@ def page_params(request: Request) -> tuple[int, str | None]:
|
||||
return limit, raw_cursor
|
||||
|
||||
|
||||
async def reject_body(request: Request) -> None:
|
||||
"""POST /auth/sessions takes credentials only from the Basic header; any body is 400."""
|
||||
if request.headers.get("transfer-encoding") or request.headers.get("content-length", "0") != "0":
|
||||
raise InvalidRequest("Вход принимает только заголовок Authorization: Basic, без тела")
|
||||
async for chunk in request.stream():
|
||||
if chunk:
|
||||
raise InvalidRequest("Вход принимает только заголовок Authorization: Basic, без тела")
|
||||
|
||||
|
||||
def idempotency_key(request: Request) -> str:
|
||||
values = request.headers.getlist("idempotency-key")
|
||||
return validation.idempotency_key(values[0] if len(values) == 1 else None)
|
||||
|
||||
|
||||
def request_fingerprint(text: str, attachment_ids: list[str]) -> bytes:
|
||||
"""SHA-256 of the canonical body: key order and an absent attachment_ids vs [] do not matter."""
|
||||
canonical = json.dumps({"attachment_ids": attachment_ids, "text": text},
|
||||
ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
||||
return hashlib.sha256(canonical.encode("utf-8")).digest()
|
||||
|
||||
|
||||
def ok(body: Any, status: int = 200) -> JSONResponse:
|
||||
return JSONResponse(body, status_code=status)
|
||||
|
||||
@@ -205,6 +233,7 @@ async def register_user(request: Request) -> JSONResponse:
|
||||
async def create_session(request: Request) -> JSONResponse:
|
||||
"""Login: only `Authorization: Basic`; wrong user and wrong password give the same 401."""
|
||||
username, password = authhdr.parse_basic(request.headers.get("authorization"))
|
||||
await reject_body(request)
|
||||
found = await repo.get_credentials(db_of(request), username)
|
||||
user, stored_hash = found if found else (None, None)
|
||||
if not await passwords.verify_password(stored_hash, password) or user is None:
|
||||
@@ -262,13 +291,23 @@ 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 the body is read
|
||||
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)
|
||||
validation.check_fields(data, {"text"})
|
||||
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.
|
||||
message = await repo.add_message(db, user_id, chat_id, text)
|
||||
return ok(message.to_json(), 201)
|
||||
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 result.replayed:
|
||||
log.info("idempotent_replay", extra={"fields": {"request_id": request.state.request_id,
|
||||
"message_id": result.message.id}})
|
||||
return ok(result.message.to_json(), 201)
|
||||
|
||||
|
||||
async def list_messages(request: Request) -> JSONResponse:
|
||||
@@ -288,16 +327,30 @@ def create_app(settings: Settings | None = None) -> Starlette:
|
||||
db = Database(settings)
|
||||
sessions = build_store(settings, db)
|
||||
|
||||
async def purge_loop() -> None:
|
||||
"""Housekeeping: expired Idempotency-Key rows (older than IDEMPOTENCY_TTL_SECONDS)."""
|
||||
while True:
|
||||
await asyncio.sleep(600)
|
||||
try:
|
||||
deleted = await repo.purge_idempotency_keys(db, settings.idempotency_ttl_seconds)
|
||||
if deleted:
|
||||
log.info("idempotency_keys_purged", extra={"fields": {"deleted": deleted}})
|
||||
except ApiError:
|
||||
pass # database unavailable right now; next round
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def lifespan(app: Starlette):
|
||||
passwords.configure(settings.hash_concurrency)
|
||||
await db.open()
|
||||
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}})
|
||||
"db_pool_max": settings.db_pool_max, "db_timeout_s": settings.db_timeout_seconds,
|
||||
"instance_id": settings.instance_id, "drain_s": settings.drain_seconds}})
|
||||
purge = asyncio.create_task(purge_loop())
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
purge.cancel()
|
||||
await sessions.close()
|
||||
await db.close()
|
||||
|
||||
@@ -324,7 +377,7 @@ def create_app(settings: Settings | None = None) -> Starlette:
|
||||
exception_handlers={ApiError: api_error_handler, HTTPException: http_exception_handler},
|
||||
lifespan=lifespan,
|
||||
)
|
||||
app.add_middleware(RequestContextMiddleware)
|
||||
app.add_middleware(RequestContextMiddleware, instance_id=settings.instance_id)
|
||||
app.state.settings = settings
|
||||
app.state.db = db
|
||||
app.state.sessions = sessions
|
||||
|
||||
+29
-2
@@ -8,6 +8,8 @@ Invalid values stop the process at startup with a clear message.
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
@@ -16,6 +18,22 @@ class ConfigError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
INSTANCE_ID_RE = re.compile(r"[A-Za-z0-9._-]{1,64}")
|
||||
|
||||
|
||||
def _instance_id() -> str:
|
||||
"""X-Instance-Id of this process: INSTANCE_ID or the container hostname.
|
||||
|
||||
Docker sets the hostname of a container to its short container ID, so the value
|
||||
is unique per replica, stable for the life of the process and maps 1:1 to a real
|
||||
container (`docker inspect`), which scripts/stop-one.sh relies on.
|
||||
"""
|
||||
value = os.environ.get("INSTANCE_ID", "").strip() or socket.gethostname()
|
||||
if INSTANCE_ID_RE.fullmatch(value) is None:
|
||||
raise ConfigError("INSTANCE_ID must match [A-Za-z0-9._-]{1,64}")
|
||||
return value
|
||||
|
||||
|
||||
def _int(name: str, default: int, low: int, high: int) -> int:
|
||||
raw = os.environ.get(name)
|
||||
if raw is None or raw.strip() == "":
|
||||
@@ -85,6 +103,9 @@ class Settings:
|
||||
db_timeout_seconds: float = 3.0
|
||||
cache_timeout_seconds: float = 0.5
|
||||
hash_concurrency: int = 2
|
||||
instance_id: str = "local"
|
||||
drain_seconds: float = 0.0
|
||||
idempotency_ttl_seconds: int = 86400
|
||||
|
||||
@property
|
||||
def db_statement_timeout_ms(self) -> int:
|
||||
@@ -110,8 +131,8 @@ class Settings:
|
||||
port=_int("APP_PORT", 8080, 1, 65535),
|
||||
env=os.environ.get("APP_ENV", "lab").strip() or "lab",
|
||||
log_level=log_level,
|
||||
# Docker sends SIGKILL 10 s after SIGTERM by default; finish earlier.
|
||||
shutdown_timeout=_float("SHUTDOWN_TIMEOUT_SECONDS", 8.0, 0.0, 9.0),
|
||||
# DRAIN_SECONDS + SHUTDOWN_TIMEOUT_SECONDS must stay below compose stop_grace_period.
|
||||
shutdown_timeout=_float("SHUTDOWN_TIMEOUT_SECONDS", 8.0, 0.0, 30.0),
|
||||
max_body_bytes=_int("MAX_BODY_BYTES", 64 * 1024, 1024, 1024 * 1024),
|
||||
docs_enabled=_bool("DOCS_ENABLED", True),
|
||||
database_url=_secret("DATABASE_URL", required=True),
|
||||
@@ -124,4 +145,10 @@ class Settings:
|
||||
db_timeout_seconds=_float("DB_TIMEOUT_SECONDS", 3.0, 0.5, 30.0),
|
||||
cache_timeout_seconds=_float("CACHE_TIMEOUT_SECONDS", 0.5, 0.05, 10.0),
|
||||
hash_concurrency=_int("PASSWORD_HASH_CONCURRENCY", 2, 1, 16),
|
||||
instance_id=_instance_id(),
|
||||
# After SIGTERM: readiness is 503 but requests are still served for this long,
|
||||
# so the load balancer stops routing here before the listener closes.
|
||||
drain_seconds=_float("DRAIN_SECONDS", 0.0, 0.0, 10.0),
|
||||
# Contract: a replay within 24 h returns the original result.
|
||||
idempotency_ttl_seconds=_int("IDEMPOTENCY_TTL_SECONDS", 86400, 86400, 30 * 24 * 3600),
|
||||
)
|
||||
|
||||
+74
-13
@@ -15,7 +15,7 @@ from psycopg import errors as pg_errors
|
||||
|
||||
from .cursor import SortKey
|
||||
from .db import Database
|
||||
from .errors import Conflict, InvalidRequest, NotFound
|
||||
from .errors import Conflict, InvalidRequest, NotFound, Unavailable
|
||||
from .timefmt import from_us, rfc3339, to_us
|
||||
|
||||
|
||||
@@ -198,28 +198,89 @@ async def list_chats(db: Database, user_id: str, after: SortKey | None, limit: i
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ messages
|
||||
async def add_message(db: Database, user_id: str, chat_id: str, text: str) -> Message:
|
||||
@dataclass(slots=True, frozen=True)
|
||||
class PostResult:
|
||||
message: Message
|
||||
replayed: bool # True: the key was already used with this body, nothing new was written
|
||||
|
||||
|
||||
async def _insert_message(conn: psycopg.AsyncConnection, message_id: uuid.UUID, user_id: str, chat_id: str,
|
||||
text: str) -> dt.datetime:
|
||||
"""Insert with a per-chat strictly increasing timestamp.
|
||||
|
||||
`UPDATE chats ... RETURNING` locks the chat row until COMMIT, so writers of one
|
||||
chat are serialised: a message with a smaller created_at can never commit after
|
||||
a message with a bigger one, and a reader paging by cursor cannot skip it.
|
||||
"""
|
||||
cur = await conn.execute(
|
||||
"UPDATE chats SET last_message_at = greatest(clock_timestamp(), "
|
||||
"last_message_at + interval '1 microsecond') WHERE id = %s RETURNING last_message_at",
|
||||
(chat_id,))
|
||||
(created_at,) = await cur.fetchone()
|
||||
await conn.execute(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES (%s, %s, %s, %s, %s)",
|
||||
(message_id, chat_id, user_id, _b(text), created_at))
|
||||
return created_at
|
||||
|
||||
|
||||
# Claim the key. A row of a concurrent transaction that is not committed yet makes this
|
||||
# INSERT wait on the unique index until that transaction ends: after COMMIT it is a conflict
|
||||
# (the key is taken), after ROLLBACK the INSERT goes through. A key older than the TTL is
|
||||
# re-used as if it were new (ON CONFLICT ... DO UPDATE ... WHERE expired).
|
||||
CLAIM_KEY = (
|
||||
"INSERT INTO idempotency_keys (user_id, chat_id, key, request_hash, message_id) "
|
||||
"VALUES (%s, %s, %s, %s, %s) "
|
||||
"ON CONFLICT (user_id, chat_id, key) DO UPDATE SET "
|
||||
"request_hash = EXCLUDED.request_hash, message_id = EXCLUDED.message_id, created_at = clock_timestamp() "
|
||||
"WHERE idempotency_keys.created_at < clock_timestamp() - make_interval(secs => %s) "
|
||||
"RETURNING 1")
|
||||
STORED_RESULT = (
|
||||
"SELECT k.request_hash, m.id, m.text, m.created_at FROM idempotency_keys k "
|
||||
"JOIN messages m ON m.id = k.message_id "
|
||||
"WHERE k.user_id = %s AND k.chat_id = %s AND k.key = %s")
|
||||
|
||||
|
||||
async def post_message(db: Database, user_id: str, chat_id: str, key: str, request_hash: bytes, text: str,
|
||||
ttl_seconds: int) -> PostResult:
|
||||
"""Idempotent send: the key, the message and the stored result commit in ONE transaction.
|
||||
|
||||
* first request -> key row + message + chat clock, all or nothing (no "pending" key is
|
||||
ever left behind: a crash or 5xx rolls everything back and the client may retry);
|
||||
* same key, same body (any replica, also concurrently) -> the stored Message, 201, replayed;
|
||||
* same key, other body -> 409; the membership check comes first, so outsiders always get 404.
|
||||
"""
|
||||
message_id = uuid.uuid4()
|
||||
|
||||
async def work(conn: psycopg.AsyncConnection) -> dt.datetime:
|
||||
async def work(conn: psycopg.AsyncConnection) -> PostResult:
|
||||
await _check_member(conn, user_id, chat_id)
|
||||
cur = await conn.execute(CLAIM_KEY, (user_id, chat_id, key, request_hash, message_id, ttl_seconds))
|
||||
if await cur.fetchone() is not None:
|
||||
created_at = await _insert_message(conn, message_id, user_id, chat_id, text)
|
||||
return PostResult(Message(str(message_id), chat_id, user_id, text, created_at), False)
|
||||
cur = await conn.execute(STORED_RESULT, (user_id, chat_id, key))
|
||||
row = await cur.fetchone()
|
||||
if row is None:
|
||||
# The key row vanished between the two statements (expired-key cleanup): retryable.
|
||||
raise Unavailable("Повторите запрос с тем же Idempotency-Key")
|
||||
if bytes(row[0]) != request_hash:
|
||||
raise Conflict("Idempotency-Key уже использован с другим сообщением")
|
||||
return PostResult(Message(str(row[1]), chat_id, user_id, _s(row[2]), row[3]), True)
|
||||
return await db.run(work)
|
||||
|
||||
|
||||
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:
|
||||
cur = await conn.execute("SELECT pg_try_advisory_xact_lock(%s)", (2026_03,))
|
||||
if not (await cur.fetchone())[0]:
|
||||
return 0
|
||||
cur = await conn.execute(
|
||||
"UPDATE chats SET last_message_at = greatest(clock_timestamp(), "
|
||||
"last_message_at + interval '1 microsecond') WHERE id = %s RETURNING last_message_at",
|
||||
(chat_id,))
|
||||
(created_at,) = await cur.fetchone()
|
||||
await conn.execute(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES (%s, %s, %s, %s, %s)",
|
||||
(message_id, chat_id, user_id, _b(text), created_at))
|
||||
return created_at
|
||||
created_at = await db.run(work)
|
||||
return Message(str(message_id), chat_id, user_id, text, created_at)
|
||||
"DELETE FROM idempotency_keys WHERE ctid = ANY(ARRAY("
|
||||
"SELECT ctid FROM idempotency_keys "
|
||||
"WHERE created_at < clock_timestamp() - make_interval(secs => %s) LIMIT %s))",
|
||||
(ttl_seconds, batch))
|
||||
return cur.rowcount
|
||||
return await db.run(work)
|
||||
|
||||
|
||||
# Two statements instead of one with "(%s IS NULL OR ...)": with a generic plan the OR
|
||||
|
||||
@@ -16,6 +16,8 @@ USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}")
|
||||
# Canonical textual UUID (8-4-4-4-12 hex). Case-insensitive, normalised to lower case.
|
||||
UUID_RE = re.compile(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")
|
||||
LIMIT_RE = re.compile(r"[0-9]{1,3}")
|
||||
# Idempotency-Key (contract, lab 3): ASCII [A-Za-z0-9._:-]{1,128}.
|
||||
IDEMPOTENCY_KEY_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}")
|
||||
SURROGATES_RE = re.compile("[\ud800-\udfff]")
|
||||
|
||||
DEFAULT_LIMIT = 50
|
||||
@@ -27,11 +29,19 @@ def _reject_constant(name: str) -> Any:
|
||||
raise ValueError(f"invalid JSON constant {name}")
|
||||
|
||||
|
||||
def _unique_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
||||
# {"text":"a","text":"b"} is ambiguous (which one is meant?) -> 400, not "last one wins".
|
||||
result = dict(pairs)
|
||||
if len(result) != len(pairs):
|
||||
raise ValueError("duplicate key in JSON object")
|
||||
return result
|
||||
|
||||
|
||||
def parse_json_object(body: bytes) -> dict[str, Any]:
|
||||
"""Decode a UTF-8 JSON object or raise InvalidRequest (malformed JSON -> 400)."""
|
||||
try:
|
||||
text = body.decode("utf-8")
|
||||
value = json.loads(text, parse_constant=_reject_constant)
|
||||
value = json.loads(text, parse_constant=_reject_constant, object_pairs_hook=_unique_keys)
|
||||
except (UnicodeDecodeError, ValueError):
|
||||
raise InvalidRequest("Тело запроса должно быть корректным JSON в UTF-8") from None
|
||||
if not isinstance(value, dict):
|
||||
@@ -102,6 +112,26 @@ def member_ids_field(data: dict[str, Any]) -> list[str]:
|
||||
return ids
|
||||
|
||||
|
||||
def attachment_ids_field(data: dict[str, Any]) -> list[str]:
|
||||
"""Optional `attachment_ids` (lab 4+). Absent and [] are the same message (contracts/README.md);
|
||||
lab 3 has no attachments yet, so a non-empty list can only reference unknown objects."""
|
||||
value = data.get("attachment_ids", [])
|
||||
if not isinstance(value, list):
|
||||
raise InvalidRequest("attachment_ids должен быть массивом")
|
||||
if len(value) > 10:
|
||||
raise InvalidRequest("attachment_ids содержит больше 10 элементов")
|
||||
ids = [parse_uuid(item, "UUID вложения") for item in value]
|
||||
if len(set(ids)) != len(ids):
|
||||
raise InvalidRequest("attachment_ids содержит дубликаты")
|
||||
return ids
|
||||
|
||||
|
||||
def idempotency_key(raw: str | None) -> str:
|
||||
if raw is None or IDEMPOTENCY_KEY_RE.fullmatch(raw) is None:
|
||||
raise InvalidRequest("Заголовок Idempotency-Key обязателен: [A-Za-z0-9._:-]{1,128}")
|
||||
return raw
|
||||
|
||||
|
||||
def single_query_param(query: list[tuple[str, str]], name: str) -> str | None:
|
||||
values = [v for k, v in query if k == name]
|
||||
if len(values) > 1:
|
||||
|
||||
Reference in New Issue
Block a user