Реализовать PostgreSQL, Redis-сессии и backup-трек для сдачи lab2 на 5.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Wladislava1
2026-10-23 11:35:32 +03:00
co-authored by Cursor
parent 65003b6119
commit 70790af646
29 changed files with 2583 additions and 19 deletions
+20
View File
@@ -0,0 +1,20 @@
class ApiError(Exception):
def __init__(self, status, code, message, headers=None):
self.status = status
self.code = code
self.message = message
self.headers = headers or {}
class DependencyDown(Exception):
pass
def error_body(code, message, request_id):
return {
"error": {
"code": code,
"message": message,
"request_id": request_id,
}
}
+353
View File
@@ -0,0 +1,353 @@
import base64
import logging
import os
import uuid
from contextlib import asynccontextmanager
import anyio
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response
from pydantic import ValidationError
from errors import ApiError, DependencyDown, error_body
from schemas import CreateChat, CreateMessage, CreateUser
from store import Store
LOGGER = logging.getLogger("messenger")
store = Store()
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
BEARER_CHALLENGE = 'Bearer realm="messenger"'
@asynccontextmanager
async def lifespan(_app):
await anyio.to_thread.run_sync(store.startup)
yield
await anyio.to_thread.run_sync(store.shutdown)
app = FastAPI(
title="mtusi-messenger",
lifespan=lifespan,
redirect_slashes=False,
docs_url=None,
redoc_url=None,
openapi_url=None,
)
def request_id_of(request: Request):
rid = getattr(request.state, "request_id", None)
if rid:
return rid
return str(uuid.uuid4())
def json_ok(request: Request, payload, status_code=200):
return JSONResponse(payload, status_code=status_code, headers={"X-Request-Id": request_id_of(request)})
def json_error(request: Request, status, code, message, extra_headers=None):
rid = request_id_of(request)
headers = {"X-Request-Id": rid}
if extra_headers:
headers.update(extra_headers)
return JSONResponse(error_body(code, message, rid), status_code=status, headers=headers)
@app.middleware("http")
async def wrap_request(request: Request, call_next):
incoming = request.headers.get("X-Request-Id")
request.state.request_id = incoming.strip() if incoming and incoming.strip() else str(uuid.uuid4())
response = await call_next(request)
response.headers["X-Request-Id"] = request.state.request_id
path = request.url.path
if not path.startswith("/health"):
LOGGER.info(
"%s %s %s rid=%s user=%s",
request.method,
path,
response.status_code,
request.state.request_id,
getattr(request.state, "user_id", "-"),
)
return response
@app.exception_handler(ApiError)
async def api_error_handler(request: Request, exc: ApiError):
return json_error(request, exc.status, exc.code, exc.message, exc.headers)
@app.exception_handler(RequestValidationError)
async def request_validation_handler(request: Request, _exc: RequestValidationError):
return json_error(request, 400, "invalid_request", "Некорректный запрос")
@app.exception_handler(ValidationError)
async def pydantic_handler(request: Request, _exc: ValidationError):
return json_error(request, 400, "invalid_request", "Некорректный запрос")
@app.exception_handler(Exception)
async def unexpected_handler(request: Request, exc: Exception):
if isinstance(exc, ApiError):
return json_error(request, exc.status, exc.code, exc.message, exc.headers)
LOGGER.exception("unhandled")
return json_error(request, 500, "internal_error", "Внутренняя ошибка")
def unavailable():
raise ApiError(503, "unavailable", "Сервис временно недоступен")
def bearer_unauthorized():
raise ApiError(401, "unauthorized", "Требуется авторизация", {"WWW-Authenticate": BEARER_CHALLENGE})
def basic_unauthorized():
raise ApiError(401, "unauthorized", "Неверные учётные данные", {"WWW-Authenticate": BASIC_CHALLENGE})
async def call_store(func, *args):
try:
return await anyio.to_thread.run_sync(func, *args)
except DependencyDown:
unavailable()
async def read_json(request: Request):
content_type = request.headers.get("content-type", "")
media = content_type.split(";")[0].strip().lower()
if media != "application/json":
raise ApiError(415, "unsupported_media_type", "Ожидается application/json")
try:
raw = await request.body()
if not raw:
raise ApiError(400, "invalid_request", "Некорректный JSON")
data = await request.json()
except ApiError:
raise
except Exception:
raise ApiError(400, "invalid_request", "Некорректный JSON")
if not isinstance(data, dict):
raise ApiError(400, "invalid_request", "Некорректный запрос")
return data
def parse_basic(request: Request):
header = request.headers.get("Authorization", "")
if not header.lower().startswith("basic "):
basic_unauthorized()
raw = header.split(" ", 1)[1].strip()
try:
decoded = base64.b64decode(raw, validate=True).decode("utf-8")
except (ValueError, UnicodeError):
basic_unauthorized()
if ":" not in decoded:
basic_unauthorized()
username, password = decoded.split(":", 1)
return username, password
def parse_bearer(request: Request):
header = request.headers.get("Authorization", "")
# Basic на бизнес-методе не открывает сессию. X-User-Id ниже тоже не смотрим.
if not header.lower().startswith("bearer "):
bearer_unauthorized()
token = header.split(" ", 1)[1].strip()
if len(token) < 32 or len(token) > 512 or any(ch.isspace() for ch in token):
bearer_unauthorized()
return token
async def current_user(request: Request):
token = parse_bearer(request)
user = await call_store(store.user_for_token, token)
if user is None:
bearer_unauthorized()
request.state.user_id = user["id"]
request.state.token = token
return user
def parse_chat_id(chat_id):
try:
uuid.UUID(chat_id)
except ValueError:
raise ApiError(400, "invalid_request", "Некорректный идентификатор")
return chat_id
def parse_limit(request: Request):
raw = request.query_params.get("limit")
if raw is None:
return 50
try:
value = int(raw)
except (TypeError, ValueError):
raise ApiError(400, "invalid_request", "Некорректный limit")
if value < 1 or value > 100:
raise ApiError(400, "invalid_request", "Некорректный limit")
return value
def parse_cursor(request: Request):
if "cursor" not in request.query_params:
return None
value = request.query_params.get("cursor")
if value is None or value == "":
raise ApiError(400, "invalid_request", "Некорректный cursor")
return value
@app.get("/health/live")
async def liveness(request: Request):
return json_ok(request, {"status": "ok"})
@app.get("/health/ready")
async def readiness(request: Request):
if store.shutting_down:
raise ApiError(503, "unavailable", "Сервер завершает работу")
ok = await call_store(store.ready)
if not ok:
unavailable()
return json_ok(request, {"status": "ok"})
@app.post("/api/v1/users")
async def register_user(request: Request):
data = await read_json(request)
try:
body = CreateUser.model_validate(data)
except ValidationError:
raise ApiError(400, "invalid_request", "Некорректный запрос")
user = await call_store(store.create_user, body.username, body.display_name, body.password)
if user is None:
raise ApiError(409, "conflict", "Имя пользователя занято")
return json_ok(request, user, 201)
@app.post("/api/v1/auth/sessions")
async def create_session(request: Request):
username, password = parse_basic(request)
session = await call_store(store.login, username, password)
if session is None:
basic_unauthorized()
request.state.user_id = session["user"]["id"]
return json_ok(request, session, 201)
@app.delete("/api/v1/auth/sessions/current")
async def revoke_session(request: Request):
user = await current_user(request)
request.state.user_id = user["id"]
removed = await call_store(store.revoke, request.state.token)
if not removed:
bearer_unauthorized()
return Response(status_code=204, headers={"X-Request-Id": request_id_of(request)})
@app.get("/api/v1/users/me")
async def me(request: Request):
user = await current_user(request)
return json_ok(request, user)
@app.post("/api/v1/chats")
async def create_chat(request: Request):
user = await current_user(request)
data = await read_json(request)
try:
body = CreateChat.model_validate(data)
except ValidationError:
raise ApiError(400, "invalid_request", "Некорректный запрос")
try:
chat = await call_store(store.create_chat, body.title, body.member_ids, user["id"])
except ValueError:
raise ApiError(400, "invalid_request", "Некорректный список участников")
return json_ok(request, chat, 201)
@app.get("/api/v1/chats")
async def list_chats(request: Request):
user = await current_user(request)
try:
items, next_cursor = await call_store(
store.list_chats,
user["id"],
parse_limit(request),
parse_cursor(request),
)
except ValueError:
raise ApiError(400, "invalid_request", "Некорректный cursor")
return json_ok(request, {"items": items, "next_cursor": next_cursor})
@app.get("/api/v1/chats/{chat_id}")
async def get_chat(request: Request, chat_id: str):
user = await current_user(request)
chat = await call_store(store.get_chat, parse_chat_id(chat_id), user["id"])
if chat is None:
raise ApiError(404, "not_found", "Объект не найден")
return json_ok(request, chat)
@app.post("/api/v1/chats/{chat_id}/messages")
async def create_message(request: Request, chat_id: str):
user = await current_user(request)
parse_chat_id(chat_id)
data = await read_json(request)
try:
body = CreateMessage.model_validate(data)
except ValidationError:
raise ApiError(400, "invalid_request", "Некорректный запрос")
message = await call_store(store.add_message, chat_id, user["id"], body.text)
if message is None:
raise ApiError(404, "not_found", "Объект не найден")
return json_ok(request, message, 201)
@app.get("/api/v1/chats/{chat_id}/messages")
async def list_messages(request: Request, chat_id: str):
user = await current_user(request)
parse_chat_id(chat_id)
try:
result = await call_store(
store.list_messages,
chat_id,
user["id"],
parse_limit(request),
parse_cursor(request),
)
except ValueError:
raise ApiError(400, "invalid_request", "Некорректный cursor")
if result is None:
raise ApiError(404, "not_found", "Объект не найден")
items, next_cursor = result
return json_ok(request, {"items": items, "next_cursor": next_cursor})
def setup_logging():
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
if __name__ == "__main__":
import uvicorn
setup_logging()
host = os.environ.get("APP_HOST", "0.0.0.0")
port = int(os.environ.get("APP_PORT", "8080"))
uvicorn.run(
app,
host=host,
port=port,
timeout_graceful_shutdown=10,
access_log=False,
)
+26
View File
@@ -0,0 +1,26 @@
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHash, VerificationError, VerifyMismatchError
# Параметры ближе к учебному стенду, чем к максимальным: time=2, 19 MiB, Argon2id.
# Хеш всё равно медленный password KDF, не SHA-256 и не открытый текст.
hasher = PasswordHasher(
time_cost=2,
memory_cost=19456,
parallelism=1,
hash_len=32,
salt_len=16,
)
# Чтобы неизвестный username не отвечал заметно быстрее известного.
DUMMY_HASH = hasher.hash("dummy-password-not-a-user")
def hash_password(password):
return hasher.hash(password)
def verify_password(password, encoded):
try:
return hasher.verify(encoded, password)
except (VerifyMismatchError, VerificationError, InvalidHash):
return False
+81
View File
@@ -0,0 +1,81 @@
import re
import uuid
from pydantic import BaseModel, ConfigDict, field_validator
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
class StrictModel(BaseModel):
model_config = ConfigDict(extra="forbid")
def _visible(value, limit):
if not isinstance(value, str) or not value.strip() or len(value) > limit:
raise ValueError("text")
return value
class CreateUser(StrictModel):
username: str
display_name: str
password: str
@field_validator("username")
@classmethod
def username_ok(cls, value):
if not isinstance(value, str) or not USERNAME_RE.fullmatch(value):
raise ValueError("username")
return value
@field_validator("display_name")
@classmethod
def display_name_ok(cls, value):
return _visible(value, 100)
@field_validator("password")
@classmethod
def password_ok(cls, value):
if not isinstance(value, str) or not value.strip():
raise ValueError("password")
# Длина в code points, не в байтах: bcrypt тут не подходит из-за усечения UTF-8.
if len(value) < 12 or len(value) > 128:
raise ValueError("password")
return value
class CreateChat(StrictModel):
title: str
member_ids: list
@field_validator("title")
@classmethod
def title_ok(cls, value):
return _visible(value, 100)
@field_validator("member_ids")
@classmethod
def member_ids_ok(cls, value):
if not isinstance(value, list) or not (1 <= len(value) <= 100):
raise ValueError("member_ids")
seen = set()
for item in value:
if not isinstance(item, str):
raise ValueError("member_ids")
try:
uuid.UUID(item)
except ValueError as exc:
raise ValueError("member_ids") from exc
if item in seen:
raise ValueError("member_ids")
seen.add(item)
return value
class CreateMessage(StrictModel):
text: str
@field_validator("text")
@classmethod
def text_ok(cls, value):
return _visible(value, 4000)
+548
View File
@@ -0,0 +1,548 @@
import base64
import hashlib
import json
import logging
import os
import secrets
import time
import uuid
from datetime import datetime, timedelta, timezone
from pathlib import Path
import psycopg
import redis
from psycopg.errors import ForeignKeyViolation
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool, PoolTimeout
from errors import DependencyDown
from passwords import DUMMY_HASH, hash_password, verify_password
LOGGER = logging.getLogger("messenger")
POOL_MAX = 8
POOL_TIMEOUT_SECONDS = 3
STATEMENT_TIMEOUT_MS = 5000
LOCK_TIMEOUT_MS = 3000
REDIS_MAX_CONNECTIONS = 16
REDIS_SOCKET_TIMEOUT = 2
MIGRATION_LOCK = 421002
# Два отдельных текста, чтобы планировщик видел простой range, а не OR с параметром.
SQL_MESSAGES_FIRST = """
SELECT id, chat_id, sender_id, body AS text, created_at
FROM messages
WHERE chat_id = %s
ORDER BY created_at, id
LIMIT %s
"""
SQL_MESSAGES_AFTER = """
SELECT id, chat_id, sender_id, body AS text, created_at
FROM messages
WHERE chat_id = %s
AND (created_at, id) > (%s, %s)
ORDER BY created_at, id
LIMIT %s
"""
def utc_now():
return datetime.now(timezone.utc)
def dump_time(value):
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
text = value.astimezone(timezone.utc).isoformat(timespec="microseconds")
if text.endswith("+00:00"):
text = text[:-6] + "Z"
return text
def parse_time(value):
if not isinstance(value, str) or not value.endswith("Z"):
raise ValueError("time")
return datetime.fromisoformat(value[:-1] + "+00:00")
def encode_cursor(scope, created_at, item_id):
raw = "{}|{}|{}".format(scope, created_at, item_id).encode("utf-8")
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
def decode_cursor(cursor, expected_scope):
if not isinstance(cursor, str) or not cursor or len(cursor) > 512:
raise ValueError("cursor")
pad = "=" * (-len(cursor) % 4)
try:
decoded = base64.urlsafe_b64decode(cursor + pad).decode("utf-8")
except (ValueError, UnicodeError) as exc:
raise ValueError("cursor") from exc
parts = decoded.split("|")
if len(parts) != 3:
raise ValueError("cursor")
scope, created_at, item_id = parts
if scope != expected_scope:
raise ValueError("cursor")
parse_time(created_at)
try:
uuid.UUID(item_id)
except ValueError as exc:
raise ValueError("cursor") from exc
return created_at, item_id
def session_key(token):
digest = hashlib.sha256(token.encode("utf-8")).hexdigest()
return "sess:" + digest
def public_user(row):
return {
"id": str(row["id"]),
"username": row["username"],
"display_name": row["display_name"],
"created_at": dump_time(row["created_at"]),
}
def public_message(row):
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"sender_id": str(row["sender_id"]),
"text": row["text"],
"created_at": dump_time(row["created_at"]),
}
def public_chat(row, member_ids=None):
members = member_ids if member_ids is not None else row["member_ids"]
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": [str(item) for item in members],
"created_at": dump_time(row["created_at"]),
}
def read_secret_file(path):
with open(path, encoding="utf-8") as handle:
return handle.read().strip()
def split_sql(script):
parts = []
buf = []
for line in script.splitlines():
if line.strip().startswith("--"):
continue
buf.append(line)
if line.strip().endswith(";"):
statement = "\n".join(buf).strip()
if statement.endswith(";"):
statement = statement[:-1].strip()
if statement:
parts.append(statement)
buf = []
tail = "\n".join(buf).strip().rstrip(";").strip()
if tail:
parts.append(tail)
return parts
def _db_down(exc):
raise DependencyDown() from exc
class Store:
def __init__(self):
self.pool = None
self.redis = None
self.ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
self.shutting_down = False
if self.ttl < 1:
raise RuntimeError("SESSION_TTL_SECONDS")
kind = os.environ.get("SESSION_STORE", "redis").strip().lower()
if kind != "redis":
raise RuntimeError("SESSION_STORE")
def database_url(self):
path = os.environ.get("DATABASE_URL_FILE")
if path:
return read_secret_file(path)
url = os.environ.get("DATABASE_URL", "").strip()
if not url:
raise RuntimeError("DATABASE_URL_FILE")
return url
def redis_url(self):
path = os.environ.get("CACHE_URL_FILE")
if path:
return read_secret_file(path)
url = os.environ.get("CACHE_URL", "").strip()
if not url:
raise RuntimeError("CACHE_URL_FILE")
return url
def startup(self):
conninfo = self.database_url()
self._migrate(conninfo)
self.pool = ConnectionPool(
conninfo,
min_size=1,
max_size=POOL_MAX,
timeout=POOL_TIMEOUT_SECONDS,
max_waiting=32,
max_lifetime=300,
kwargs={
"connect_timeout": POOL_TIMEOUT_SECONDS,
"row_factory": dict_row,
"application_name": "mtusi-lab2",
"options": "-c statement_timeout={} -c lock_timeout={} -c idle_in_transaction_session_timeout=8000".format(
STATEMENT_TIMEOUT_MS,
LOCK_TIMEOUT_MS,
),
},
open=True,
)
pool = redis.ConnectionPool.from_url(
self.redis_url(),
max_connections=REDIS_MAX_CONNECTIONS,
socket_timeout=REDIS_SOCKET_TIMEOUT,
socket_connect_timeout=REDIS_SOCKET_TIMEOUT,
health_check_interval=30,
decode_responses=True,
)
self.redis = redis.Redis(connection_pool=pool)
self._wait_redis()
LOGGER.info("ready ttl=%s pool_max=%s", self.ttl, POOL_MAX)
def shutdown(self):
self.shutting_down = True
if self.pool is not None:
self.pool.close()
if self.redis is not None:
self.redis.close()
def ready(self):
if self.shutting_down or self.pool is None or self.redis is None:
return False
try:
with self.pool.connection(timeout=POOL_TIMEOUT_SECONDS) as conn:
conn.execute("SELECT 1")
self.redis.ping()
except Exception:
LOGGER.warning("ready check failed")
return False
return True
def _wait_redis(self):
last = None
for _ in range(60):
try:
self.redis.ping()
return
except redis.RedisError as exc:
last = type(exc).__name__
time.sleep(1)
LOGGER.error("redis not ready: %s", last)
raise SystemExit(1)
def _migrate(self, conninfo):
directory = Path(__file__).resolve().parents[1] / "migrations"
last = None
conn = None
for _ in range(60):
try:
conn = psycopg.connect(conninfo, connect_timeout=POOL_TIMEOUT_SECONDS, row_factory=dict_row)
conn.execute("SELECT 1")
conn.commit()
break
except psycopg.OperationalError as exc:
last = type(exc).__name__
time.sleep(1)
else:
LOGGER.error("postgres not ready: %s", last)
raise SystemExit(1)
try:
conn.execute("SELECT pg_advisory_lock(%s)", (MIGRATION_LOCK,))
conn.commit()
conn.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT now()
)
"""
)
conn.commit()
for path in sorted(directory.glob("*.sql")):
version = path.stem
found = conn.execute(
"SELECT 1 FROM schema_migrations WHERE version = %s",
(version,),
).fetchone()
conn.rollback()
if found:
LOGGER.info("migration %s already applied", version)
continue
with conn.transaction():
for statement in split_sql(path.read_text(encoding="utf-8")):
conn.execute(statement)
conn.execute(
"INSERT INTO schema_migrations (version) VALUES (%s)",
(version,),
)
LOGGER.info("migration %s applied", version)
finally:
conn.execute("SELECT pg_advisory_unlock(%s)", (MIGRATION_LOCK,))
conn.commit()
conn.close()
def _connect(self):
try:
return self.pool.connection(timeout=POOL_TIMEOUT_SECONDS)
except PoolTimeout as exc:
_db_down(exc)
def create_user(self, username, display_name, password):
password_hash = hash_password(password)
user_id = uuid.uuid4()
created = utc_now()
try:
with self._connect() as conn:
with conn.transaction():
row = conn.execute(
"""
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (username) DO NOTHING
RETURNING id, username, display_name, created_at
""",
(user_id, username, display_name, password_hash, created),
).fetchone()
except psycopg.OperationalError as exc:
_db_down(exc)
if row is None:
return None
return public_user(row)
def login(self, username, password):
try:
with self._connect() as conn:
row = conn.execute(
"""
SELECT id, username, display_name, password_hash, created_at
FROM users
WHERE username = %s
""",
(username,),
).fetchone()
except psycopg.OperationalError as exc:
_db_down(exc)
if row is None:
verify_password(password, DUMMY_HASH)
return None
if not verify_password(password, row["password_hash"]):
return None
return self._issue(public_user(row))
def _issue(self, user):
token = secrets.token_urlsafe(32)
expires = utc_now() + timedelta(seconds=self.ttl)
payload = json.dumps(
{"user_id": user["id"], "expires_at": dump_time(expires)},
separators=(",", ":"),
)
# pxat — абсолютное время. Рестарт Redis не должен сдвигать срок.
# В значении тоже лежит expires_at: даже если TTL ключа разъедется, сессия кончится вовремя.
try:
self.redis.set(session_key(token), payload, pxat=int(expires.timestamp() * 1000))
except redis.RedisError as exc:
raise DependencyDown() from exc
return {
"token": token,
"token_type": "Bearer",
"expires_at": dump_time(expires),
"user": user,
}
def user_for_token(self, token):
key = session_key(token)
try:
raw = self.redis.get(key)
except redis.RedisError as exc:
raise DependencyDown() from exc
if not raw:
return None
try:
payload = json.loads(raw)
expires = parse_time(payload["expires_at"])
user_id = payload["user_id"]
uuid.UUID(user_id)
except (ValueError, KeyError, TypeError):
return None
if utc_now() >= expires:
try:
self.redis.delete(key)
except redis.RedisError as exc:
raise DependencyDown() from exc
return None
try:
with self._connect() as conn:
row = conn.execute(
"""
SELECT id, username, display_name, created_at
FROM users
WHERE id = %s
""",
(user_id,),
).fetchone()
except psycopg.OperationalError as exc:
_db_down(exc)
if row is None:
return None
return public_user(row)
def revoke(self, token):
try:
deleted = self.redis.delete(session_key(token))
except redis.RedisError as exc:
raise DependencyDown() from exc
return deleted == 1
def create_chat(self, title, member_ids, caller_id):
if caller_id not in member_ids:
raise ValueError("members")
chat_id = uuid.uuid4()
created = utc_now()
member_uuids = [uuid.UUID(item) for item in member_ids]
try:
with self._connect() as conn:
try:
with conn.transaction():
# Сначала чат, потом участники. Ошибка внешнего ключа откатывает оба шага.
conn.execute(
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)",
(chat_id, title, created),
)
for ordinal, member_id in enumerate(member_uuids):
conn.execute(
"""
INSERT INTO chat_members (chat_id, user_id, ordinal)
VALUES (%s, %s, %s)
""",
(chat_id, member_id, ordinal),
)
row = conn.execute(
"SELECT id, title, created_at FROM chats WHERE id = %s",
(chat_id,),
).fetchone()
except ForeignKeyViolation as exc:
raise ValueError("members") from exc
except psycopg.OperationalError as exc:
_db_down(exc)
return public_chat(row, member_ids)
def _member(self, conn, chat_id, user_id):
return conn.execute(
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
(chat_id, user_id),
).fetchone()
def get_chat(self, chat_id, user_id):
try:
with self._connect() as conn:
if self._member(conn, chat_id, user_id) is None:
return None
row = conn.execute(
"""
SELECT c.id, c.title, c.created_at,
array_agg(m.user_id ORDER BY m.ordinal) AS member_ids
FROM chats c
JOIN chat_members m ON m.chat_id = c.id
WHERE c.id = %s
GROUP BY c.id
""",
(chat_id,),
).fetchone()
except psycopg.OperationalError as exc:
_db_down(exc)
if row is None:
return None
return public_chat(row)
def list_chats(self, user_id, limit, cursor):
after = None
if cursor is not None:
created_at, item_id = decode_cursor(cursor, "chats:" + user_id)
after = (parse_time(created_at), uuid.UUID(item_id))
sql = """
SELECT c.id, c.title, c.created_at,
array_agg(m.user_id ORDER BY m.ordinal) AS member_ids
FROM chats c
JOIN chat_members mine ON mine.chat_id = c.id AND mine.user_id = %s
JOIN chat_members m ON m.chat_id = c.id
"""
params = [user_id]
if after is not None:
sql += " WHERE (c.created_at, c.id) > (%s, %s)"
params.extend(after)
sql += " GROUP BY c.id ORDER BY c.created_at, c.id LIMIT %s"
params.append(limit + 1)
try:
with self._connect() as conn:
rows = conn.execute(sql, params).fetchall()
except psycopg.OperationalError as exc:
_db_down(exc)
page = [public_chat(row) for row in rows[:limit]]
if len(rows) > limit and page:
last = page[-1]
return page, encode_cursor("chats:" + user_id, last["created_at"], last["id"])
return page, None
def add_message(self, chat_id, sender_id, text):
message_id = uuid.uuid4()
created = utc_now()
try:
with self._connect() as conn:
with conn.transaction():
if self._member(conn, chat_id, sender_id) is None:
return None
row = conn.execute(
"""
INSERT INTO messages (id, chat_id, sender_id, body, created_at)
VALUES (%s, %s, %s, %s, %s)
RETURNING id, chat_id, sender_id, body AS text, created_at
""",
(message_id, chat_id, sender_id, text, created),
).fetchone()
except psycopg.OperationalError as exc:
_db_down(exc)
return public_message(row)
def list_messages(self, chat_id, user_id, limit, cursor):
after = None
if cursor is not None:
created_at, item_id = decode_cursor(cursor, chat_id)
after = (parse_time(created_at), uuid.UUID(item_id))
try:
with self._connect() as conn:
if self._member(conn, chat_id, user_id) is None:
return None
if after is None:
rows = conn.execute(SQL_MESSAGES_FIRST, (chat_id, limit + 1)).fetchall()
else:
rows = conn.execute(
SQL_MESSAGES_AFTER,
(chat_id, after[0], after[1], limit + 1),
).fetchall()
except psycopg.OperationalError as exc:
_db_down(exc)
page = [public_message(row) for row in rows[:limit]]
if len(rows) > limit and page:
last = page[-1]
return page, encode_cursor(chat_id, last["created_at"], last["id"])
return page, None