forked from mtusi2026/mtusi2026lab2
ЛР 2 — БПИ-2304 — Саламатин — на 4
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Laboratory 1: a single-process, in-memory messenger."""
|
||||
@@ -0,0 +1,17 @@
|
||||
import logging
|
||||
import os
|
||||
|
||||
import uvicorn
|
||||
|
||||
|
||||
def main():
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
logging.getLogger("psycopg.pool").setLevel(logging.CRITICAL)
|
||||
logging.info("Starting lab2 environment=%s with PostgreSQL and Redis", os.getenv("APP_ENV", "lab"))
|
||||
uvicorn.run("app.api:app", host=os.getenv("APP_HOST", "0.0.0.0"),
|
||||
port=int(os.getenv("APP_PORT", "8080")), workers=1,
|
||||
access_log=False, timeout_graceful_shutdown=5)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import re
|
||||
from time import perf_counter
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import Depends, FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.responses import Response
|
||||
import psycopg
|
||||
from psycopg_pool import PoolTimeout, TooManyRequests
|
||||
from redis.exceptions import RedisError
|
||||
from pydantic import ValidationError
|
||||
from starlette.exceptions import HTTPException
|
||||
|
||||
from .config import Settings
|
||||
from .errors import APIError, invalid, unavailable
|
||||
from .models import CreateChat, CreateMessage, CreateUser
|
||||
from .security import basic_credentials, identifier
|
||||
from .store import Store
|
||||
|
||||
logger = logging.getLogger("messenger")
|
||||
|
||||
|
||||
def error_response(request, status, code, message, headers=None):
|
||||
return JSONResponse(status_code=status, headers=headers, content={"error": {
|
||||
"code": code, "message": message, "request_id": request.state.request_id}})
|
||||
|
||||
|
||||
async def body(request, model):
|
||||
content_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
|
||||
if content_type != "application/json":
|
||||
raise APIError(415, "unsupported_media_type", "Use application/json")
|
||||
try:
|
||||
raw = (await request.body()).decode("utf-8")
|
||||
def reject_constant(value):
|
||||
raise ValueError("Nonstandard JSON constant")
|
||||
data = json.loads(raw, parse_constant=reject_constant)
|
||||
return model.model_validate(data)
|
||||
except (ValueError, UnicodeError, ValidationError):
|
||||
raise invalid("Body must be valid UTF-8 JSON with the required fields and types") from None
|
||||
|
||||
|
||||
def pagination(request):
|
||||
raw = request.query_params.get("limit", "50")
|
||||
if re.fullmatch(r"[0-9]+", raw) is None or len(raw) > 3 or not 1 <= int(raw) <= 100:
|
||||
raise invalid("Limit must be an integer from 1 to 100")
|
||||
return int(raw), request.query_params.get("cursor")
|
||||
|
||||
|
||||
def create_app(settings=None):
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
store = Store(settings or Settings.load())
|
||||
app.state.store = store
|
||||
try:
|
||||
await store.open()
|
||||
yield
|
||||
finally:
|
||||
await store.close()
|
||||
|
||||
app = FastAPI(title="Lab 2 messenger", docs_url=None, redoc_url=None,
|
||||
openapi_url=None, redirect_slashes=False, lifespan=lifespan)
|
||||
|
||||
@app.middleware("http")
|
||||
async def request_context(request, call_next):
|
||||
request.state.request_id = str(uuid4())
|
||||
start = perf_counter()
|
||||
try:
|
||||
async with asyncio.timeout(5):
|
||||
response = await call_next(request)
|
||||
except (psycopg.Error, PoolTimeout, TooManyRequests, RedisError, TimeoutError):
|
||||
error = unavailable()
|
||||
logger.warning("Storage unavailable request_id=%s", request.state.request_id)
|
||||
response = error_response(request, error.status, error.code, error.message)
|
||||
except Exception:
|
||||
logger.error("Unhandled error request_id=%s", request.state.request_id)
|
||||
response = error_response(request, 500, "internal_error", "Internal server error")
|
||||
response.headers["X-Request-Id"] = request.state.request_id
|
||||
logger.info("request_id=%s method=%s path=%s status=%s duration_ms=%.2f",
|
||||
request.state.request_id, request.method, request.url.path,
|
||||
response.status_code, (perf_counter() - start) * 1000)
|
||||
return response
|
||||
|
||||
@app.exception_handler(APIError)
|
||||
async def api_error(request, error):
|
||||
return error_response(request, error.status, error.code, error.message, error.headers)
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error(request, error):
|
||||
return error_response(request, 400, "invalid_request", "Invalid request parameters")
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def routing_error(request, error):
|
||||
code = "not_found" if error.status_code == 404 else "invalid_request"
|
||||
return error_response(request, error.status_code, code, "Unknown path or unsupported method")
|
||||
|
||||
async def current_user(request: Request):
|
||||
user, token = await app.state.store.authenticate(request.headers.get("authorization"))
|
||||
request.state.session_token = token
|
||||
return user
|
||||
|
||||
@app.get("/health/live")
|
||||
async def health():
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.get("/health/ready")
|
||||
async def readiness():
|
||||
await app.state.store.ready()
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.post("/api/v1/auth/sessions", status_code=201)
|
||||
async def login(request: Request):
|
||||
credentials = basic_credentials(request.headers.get("authorization"))
|
||||
if await request.body():
|
||||
raise invalid("Session creation does not accept a body")
|
||||
return await app.state.store.login(*credentials)
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
async def logout(request: Request, user=Depends(current_user)):
|
||||
await app.state.store.logout(request.state.session_token)
|
||||
return Response(status_code=204)
|
||||
|
||||
@app.post("/api/v1/users", status_code=201)
|
||||
async def create_user(request: Request):
|
||||
return await app.state.store.create_user(await body(request, CreateUser))
|
||||
|
||||
@app.get("/api/v1/users/me")
|
||||
async def me(user=Depends(current_user)):
|
||||
return user
|
||||
|
||||
@app.post("/api/v1/chats", status_code=201)
|
||||
async def create_chat(request: Request, user=Depends(current_user)):
|
||||
return await app.state.store.create_chat(user["id"], await body(request, CreateChat))
|
||||
|
||||
@app.get("/api/v1/chats")
|
||||
async def list_chats(request: Request, user=Depends(current_user)):
|
||||
return await app.state.store.list_chats(user["id"], *pagination(request))
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}")
|
||||
async def get_chat(chat_id: str, user=Depends(current_user)):
|
||||
return await app.state.store.get_chat(user["id"], identifier(chat_id))
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||||
async def create_message(chat_id: str, request: Request, user=Depends(current_user)):
|
||||
chat_id = identifier(chat_id)
|
||||
await app.state.store.get_chat(user["id"], chat_id)
|
||||
return await app.state.store.create_message(user["id"], chat_id, await body(request, CreateMessage))
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||
async def list_messages(chat_id: str, request: Request, user=Depends(current_user)):
|
||||
chat_id = identifier(chat_id)
|
||||
await app.state.store.get_chat(user["id"], chat_id)
|
||||
return await app.state.store.list_messages(user["id"], chat_id, *pagination(request))
|
||||
|
||||
@app.get("/openapi.json", include_in_schema=False)
|
||||
async def contract():
|
||||
path = Path(__file__).resolve().parents[1] / "contracts" / "openapi.json"
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
return app
|
||||
|
||||
|
||||
app = create_app()
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Runtime settings; credential values are never logged."""
|
||||
from dataclasses import dataclass
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def secret(name):
|
||||
return Path(os.environ[name + "_FILE"]).read_text(encoding="utf-8").strip()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
database_url: str
|
||||
cache_url: str
|
||||
cursor_key: bytes
|
||||
session_ttl: int
|
||||
|
||||
@classmethod
|
||||
def load(cls):
|
||||
ttl = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
if not 1 <= ttl <= 604800:
|
||||
raise ValueError("SESSION_TTL_SECONDS must be in 1..604800")
|
||||
if os.getenv("SESSION_STORE", "redis") != "redis":
|
||||
raise ValueError("This deployment uses SESSION_STORE=redis")
|
||||
key = secret("CURSOR_KEY").encode()
|
||||
if len(key) < 32:
|
||||
raise ValueError("Cursor key must contain at least 32 bytes")
|
||||
return cls(secret("DATABASE_URL"), secret("CACHE_URL"), key, ttl)
|
||||
@@ -0,0 +1,22 @@
|
||||
class APIError(Exception):
|
||||
def __init__(self, status: int, code: str, message: str, headers=None):
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.headers = headers or {}
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
def invalid(message="Invalid request"):
|
||||
return APIError(400, "invalid_request", message)
|
||||
|
||||
|
||||
def unauthorized(basic=False):
|
||||
challenge = ('Basic realm="messenger", charset="UTF-8"' if basic
|
||||
else 'Bearer realm="messenger"')
|
||||
return APIError(401, "unauthorized", "Valid credentials required",
|
||||
{"WWW-Authenticate": challenge})
|
||||
|
||||
|
||||
def unavailable():
|
||||
return APIError(503, "unavailable", "Storage temporarily unavailable")
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Apply numbered migrations atomically; safe to repeat and serialize."""
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
|
||||
from .config import secret
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def migrate():
|
||||
with psycopg.connect(secret("DATABASE_URL"), connect_timeout=2,
|
||||
options="-c statement_timeout=10000 -c lock_timeout=5000") as conn:
|
||||
conn.execute("SELECT pg_advisory_xact_lock(202602)")
|
||||
conn.execute("""CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY, sha256 text NOT NULL,
|
||||
applied_at timestamptz NOT NULL DEFAULT clock_timestamp())""")
|
||||
for path in sorted((ROOT / "migrations").glob("[0-9]*.sql")):
|
||||
# Git checkout may change LF to CRLF on Windows; SQL is unchanged.
|
||||
content = path.read_text(encoding="utf-8").encode("utf-8")
|
||||
checksum = hashlib.sha256(content).hexdigest()
|
||||
row = conn.execute("SELECT sha256 FROM schema_migrations WHERE version=%s", (path.name,)).fetchone()
|
||||
if row:
|
||||
if row[0] != checksum:
|
||||
raise RuntimeError("Applied migration checksum differs: " + path.name)
|
||||
print("Unchanged:", path.name)
|
||||
continue
|
||||
conn.execute(content.decode("utf-8"))
|
||||
conn.execute("INSERT INTO schema_migrations(version, sha256) VALUES (%s, %s)",
|
||||
(path.name, checksum))
|
||||
print("Applied:", path.name)
|
||||
print("PASS: migrations committed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
migrate()
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Strict request models; strings retain their original Unicode content."""
|
||||
import re
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
|
||||
class Input(BaseModel):
|
||||
model_config = ConfigDict(strict=True, extra="forbid")
|
||||
|
||||
@field_validator("*", check_fields=False)
|
||||
@classmethod
|
||||
def valid_text(cls, value):
|
||||
if isinstance(value, str):
|
||||
if not value.strip():
|
||||
raise ValueError("A string must not be blank")
|
||||
value.encode("utf-8")
|
||||
if "\x00" in value:
|
||||
raise ValueError("NUL is not supported")
|
||||
return value
|
||||
|
||||
|
||||
class CreateUser(Input):
|
||||
username: str
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
password: str = Field(min_length=12, max_length=128)
|
||||
|
||||
@field_validator("username")
|
||||
@classmethod
|
||||
def username_format(cls, value):
|
||||
if re.fullmatch(r"[a-z0-9_]{3,32}", value) is None:
|
||||
raise ValueError("Invalid username")
|
||||
return value
|
||||
|
||||
|
||||
class CreateChat(Input):
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: list[str] = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator("member_ids")
|
||||
@classmethod
|
||||
def members(cls, values):
|
||||
normalized = [str(UUID(value)) for value in values]
|
||||
if len(set(normalized)) != len(normalized):
|
||||
raise ValueError("Duplicate members")
|
||||
return normalized
|
||||
|
||||
|
||||
class CreateMessage(Input):
|
||||
text: str = Field(min_length=1, max_length=4000)
|
||||
@@ -0,0 +1,93 @@
|
||||
"""scrypt passwords, strict Basic credentials and persistent signed cursors."""
|
||||
import base64
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
from uuid import UUID
|
||||
|
||||
from .errors import invalid, unauthorized
|
||||
|
||||
|
||||
def password_hash(password, salt=None):
|
||||
salt = salt or secrets.token_bytes(16)
|
||||
digest = hashlib.scrypt(password.encode("utf-8"), salt=salt, n=16384,
|
||||
r=8, p=1, dklen=32, maxmem=64 * 1024 * 1024)
|
||||
return "scrypt$16384$8$1$" + salt.hex() + "$" + digest.hex()
|
||||
|
||||
|
||||
def password_matches(password, encoded):
|
||||
try:
|
||||
algorithm, n, r, p, salt, digest = encoded.split("$")
|
||||
if (algorithm, n, r, p) != ("scrypt", "16384", "8", "1"):
|
||||
return False
|
||||
actual = password_hash(password, bytes.fromhex(salt)).rsplit("$", 1)[1]
|
||||
return hmac.compare_digest(actual, digest)
|
||||
except (ValueError, UnicodeError):
|
||||
return False
|
||||
|
||||
|
||||
def basic_credentials(header):
|
||||
try:
|
||||
scheme, encoded = header.split(" ", 1)
|
||||
if scheme.lower() != "basic" or len(encoded) > 2048:
|
||||
raise ValueError
|
||||
value = base64.b64decode(encoded, validate=True).decode("utf-8")
|
||||
username, password = value.split(":", 1)
|
||||
if re.fullmatch(r"[a-z0-9_]{3,32}", username) is None:
|
||||
raise ValueError
|
||||
if not 12 <= len(password) <= 128:
|
||||
raise ValueError
|
||||
return username, password
|
||||
except (AttributeError, ValueError, UnicodeError):
|
||||
raise unauthorized(basic=True) from None
|
||||
|
||||
|
||||
def bearer(header):
|
||||
try:
|
||||
scheme, token = header.split(" ", 1)
|
||||
if scheme.lower() != "bearer" or re.fullmatch(r"[A-Za-z0-9_-]{43}", token) is None:
|
||||
raise ValueError
|
||||
return token
|
||||
except (AttributeError, ValueError):
|
||||
raise unauthorized() from None
|
||||
|
||||
|
||||
def identifier(value):
|
||||
try:
|
||||
return UUID(value)
|
||||
except (ValueError, AttributeError, TypeError):
|
||||
raise invalid("Invalid UUID") from None
|
||||
|
||||
|
||||
def stamp(value):
|
||||
return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
class Cursors:
|
||||
def __init__(self, key):
|
||||
self.key = key
|
||||
|
||||
def encode(self, scope, item):
|
||||
payload = json.dumps([scope, item["created_at"], item["id"]], separators=(",", ":")).encode()
|
||||
signature = hmac.digest(self.key, payload, hashlib.sha256)
|
||||
return base64.urlsafe_b64encode(signature + payload).decode().rstrip("=")
|
||||
|
||||
def decode(self, scope, token):
|
||||
try:
|
||||
if not token or len(token) > 1024:
|
||||
raise ValueError
|
||||
raw = base64.b64decode(token + "=" * (-len(token) % 4), altchars=b"-_", validate=True)
|
||||
signature, payload = raw[:32], raw[32:]
|
||||
if not hmac.compare_digest(signature, hmac.digest(self.key, payload, hashlib.sha256)):
|
||||
raise ValueError
|
||||
parts = json.loads(payload)
|
||||
if not isinstance(parts, list) or len(parts) != 3 or parts[0] != scope:
|
||||
raise ValueError
|
||||
if not all(isinstance(x, str) for x in parts) or not parts[1].endswith("Z"):
|
||||
raise ValueError
|
||||
return datetime.fromisoformat(parts[1].replace("Z", "+00:00")), UUID(parts[2])
|
||||
except (ValueError, TypeError, UnicodeError):
|
||||
raise invalid("Invalid cursor for this resource") from None
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
"""Persistent business data and durable Redis sessions; no local state cache."""
|
||||
import asyncio
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import secrets
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from psycopg.errors import ForeignKeyViolation, UniqueViolation
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import AsyncConnectionPool
|
||||
import redis.asyncio as redis
|
||||
from redis.asyncio.retry import Retry
|
||||
from redis.backoff import NoBackoff
|
||||
|
||||
from .errors import APIError, invalid, unauthorized
|
||||
from .security import Cursors, bearer, password_hash, password_matches, stamp
|
||||
|
||||
USER_COLUMNS = "id, username, display_name, created_at"
|
||||
MESSAGE_COLUMNS = "id, chat_id, sender_id, text, created_at"
|
||||
|
||||
|
||||
def public(row):
|
||||
return {key: (str(value) if isinstance(value, UUID) else
|
||||
stamp(value) if isinstance(value, datetime) else value)
|
||||
for key, value in row.items()}
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self, settings):
|
||||
self.settings = settings
|
||||
self.cursors = Cursors(settings.cursor_key)
|
||||
self.kdf_slots = asyncio.Semaphore(4)
|
||||
self.dummy_hash = password_hash("dummy-password-for-missing-user", b"0" * 16)
|
||||
self.pool = AsyncConnectionPool(
|
||||
settings.database_url, min_size=1, max_size=10, max_waiting=20,
|
||||
timeout=1, open=False, reconnect_timeout=5,
|
||||
check=AsyncConnectionPool.check_connection,
|
||||
kwargs={"row_factory": dict_row, "connect_timeout": 2,
|
||||
"keepalives": 1, "keepalives_idle": 2, "keepalives_interval": 1,
|
||||
"keepalives_count": 2, "tcp_user_timeout": 2000,
|
||||
"options": "-c timezone=UTC -c statement_timeout=2000 -c lock_timeout=1000"})
|
||||
self.sessions = redis.Redis.from_url(
|
||||
settings.cache_url, decode_responses=True, max_connections=10,
|
||||
socket_connect_timeout=1, socket_timeout=1,
|
||||
retry=Retry(NoBackoff(), 0), retry_on_timeout=False)
|
||||
|
||||
async def open(self):
|
||||
await self.pool.open()
|
||||
await self.pool.wait(timeout=10)
|
||||
await self.sessions.ping()
|
||||
|
||||
async def close(self):
|
||||
await self.sessions.aclose()
|
||||
await self.pool.close()
|
||||
|
||||
async def ready(self):
|
||||
async with self.pool.connection() as conn:
|
||||
await conn.execute("SELECT 1")
|
||||
await self.sessions.ping()
|
||||
|
||||
async def create_user(self, data):
|
||||
async with self.kdf_slots:
|
||||
encoded = await asyncio.to_thread(password_hash, data.password)
|
||||
try:
|
||||
async with self.pool.connection() as conn:
|
||||
cur = await conn.execute(
|
||||
"INSERT INTO users(id, username, display_name, password_hash) "
|
||||
"VALUES (%s, %s, %s, %s) RETURNING " + USER_COLUMNS,
|
||||
(uuid4(), data.username, data.display_name, encoded))
|
||||
result = public(await cur.fetchone())
|
||||
return result
|
||||
except UniqueViolation:
|
||||
raise APIError(409, "conflict", "Username is already taken") from None
|
||||
|
||||
async def login(self, username, password):
|
||||
async with self.pool.connection() as conn:
|
||||
cur = await conn.execute("SELECT " + USER_COLUMNS + ", password_hash FROM users WHERE username=%s",
|
||||
(username,))
|
||||
row = await cur.fetchone()
|
||||
async with self.kdf_slots:
|
||||
valid = await asyncio.to_thread(password_matches, password,
|
||||
row["password_hash"] if row else self.dummy_hash)
|
||||
if not valid or row is None:
|
||||
raise unauthorized(basic=True)
|
||||
row.pop("password_hash")
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires_ms = int(datetime.now(timezone.utc).timestamp() * 1000) + self.settings.session_ttl * 1000
|
||||
await self.sessions.set(self.session_key(token), json.dumps(
|
||||
{"user_id": str(row["id"]), "expires_ms": expires_ms}), pxat=expires_ms)
|
||||
return {"token": token, "token_type": "Bearer",
|
||||
"expires_at": stamp(datetime.fromtimestamp(expires_ms / 1000, timezone.utc)),
|
||||
"user": public(row)}
|
||||
|
||||
@staticmethod
|
||||
def session_key(token):
|
||||
return "session:" + hashlib.sha256(token.encode("ascii")).hexdigest()
|
||||
|
||||
async def authenticate(self, header):
|
||||
token = bearer(header)
|
||||
value = await self.sessions.get(self.session_key(token))
|
||||
if value is None:
|
||||
raise unauthorized()
|
||||
session = json.loads(value)
|
||||
if session["expires_ms"] <= int(datetime.now(timezone.utc).timestamp() * 1000):
|
||||
raise unauthorized()
|
||||
async with self.pool.connection() as conn:
|
||||
cur = await conn.execute("SELECT " + USER_COLUMNS + " FROM users WHERE id=%s",
|
||||
(UUID(session["user_id"]),))
|
||||
row = await cur.fetchone()
|
||||
if row is None:
|
||||
raise unauthorized()
|
||||
return public(row), token
|
||||
|
||||
async def logout(self, token):
|
||||
await self.sessions.delete(self.session_key(token))
|
||||
|
||||
async def create_chat(self, actor, data):
|
||||
if actor not in data.member_ids:
|
||||
raise invalid("Members must include the current user")
|
||||
try:
|
||||
async with self.pool.connection() as conn:
|
||||
cur = await conn.execute("INSERT INTO chats(id, title) VALUES (%s, %s) "
|
||||
"RETURNING id, title, created_at", (uuid4(), data.title))
|
||||
row = await cur.fetchone()
|
||||
async with conn.cursor() as cur:
|
||||
await cur.executemany("INSERT INTO chat_members(chat_id, user_id) VALUES (%s, %s)",
|
||||
[(row["id"], UUID(member)) for member in data.member_ids])
|
||||
result = public(row)
|
||||
result["member_ids"] = sorted(data.member_ids)
|
||||
return result
|
||||
except ForeignKeyViolation:
|
||||
raise invalid("All members must exist") from None
|
||||
|
||||
async def accessible_chat(self, conn, actor, chat_id):
|
||||
cur = await conn.execute("""SELECT c.id, c.title, c.created_at FROM chats c
|
||||
JOIN chat_members m ON m.chat_id=c.id
|
||||
WHERE c.id=%s AND m.user_id=%s""", (chat_id, UUID(actor)))
|
||||
row = await cur.fetchone()
|
||||
if row is None:
|
||||
raise APIError(404, "not_found", "Chat not found")
|
||||
return row
|
||||
|
||||
async def get_chat(self, actor, chat_id):
|
||||
async with self.pool.connection() as conn:
|
||||
row = await self.accessible_chat(conn, actor, chat_id)
|
||||
cur = await conn.execute("SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY user_id", (chat_id,))
|
||||
result = public(row)
|
||||
result["member_ids"] = [str(x["user_id"]) for x in await cur.fetchall()]
|
||||
return result
|
||||
|
||||
async def create_message(self, actor, chat_id, data):
|
||||
async with self.pool.connection() as conn:
|
||||
await self.accessible_chat(conn, actor, chat_id)
|
||||
# Evaluate clock_timestamp AFTER obtaining the per-chat lock.
|
||||
await conn.execute("SELECT id FROM chats WHERE id=%s FOR UPDATE", (chat_id,))
|
||||
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())["last_message_at"]
|
||||
cur = await conn.execute("INSERT INTO messages(id, chat_id, sender_id, text, created_at) "
|
||||
"VALUES (%s, %s, %s, %s, %s) RETURNING " + MESSAGE_COLUMNS,
|
||||
(uuid4(), chat_id, UUID(actor), data.text, created_at))
|
||||
result = public(await cur.fetchone())
|
||||
return result
|
||||
|
||||
def page(self, rows, scope, limit):
|
||||
items = rows[:limit]
|
||||
return {"items": items, "next_cursor": self.cursors.encode(scope, items[-1])
|
||||
if len(rows) > limit else None}
|
||||
|
||||
async def list_messages(self, actor, chat_id, limit, cursor):
|
||||
scope = "messages:" + str(chat_id)
|
||||
boundary = self.cursors.decode(scope, cursor) if cursor is not None else None
|
||||
async with self.pool.connection() as conn:
|
||||
await self.accessible_chat(conn, actor, chat_id)
|
||||
query = "SELECT " + MESSAGE_COLUMNS + " FROM messages WHERE chat_id=%s"
|
||||
params = [chat_id]
|
||||
if boundary:
|
||||
query += " AND (created_at, id) > (%s, %s)"
|
||||
params.extend(boundary)
|
||||
query += " ORDER BY created_at, id LIMIT %s"
|
||||
params.append(limit + 1)
|
||||
cur = await conn.execute(query, params)
|
||||
rows = [public(row) for row in await cur.fetchall()]
|
||||
return self.page(rows, scope, limit)
|
||||
|
||||
async def list_chats(self, actor, limit, cursor):
|
||||
scope = "chats:" + actor
|
||||
boundary = self.cursors.decode(scope, cursor) if cursor is not None else None
|
||||
query = """SELECT c.id, c.title, c.created_at FROM chats c
|
||||
JOIN chat_members m ON m.chat_id=c.id WHERE m.user_id=%s"""
|
||||
params = [UUID(actor)]
|
||||
if boundary:
|
||||
query += " AND (c.created_at, c.id) > (%s, %s)"
|
||||
params.extend(boundary)
|
||||
query += " ORDER BY c.created_at, c.id LIMIT %s"
|
||||
params.append(limit + 1)
|
||||
async with self.pool.connection() as conn:
|
||||
cur = await conn.execute(query, params)
|
||||
rows = [public(row) for row in await cur.fetchall()]
|
||||
if rows:
|
||||
ids = [UUID(row["id"]) for row in rows]
|
||||
cur = await conn.execute("SELECT chat_id, user_id FROM chat_members WHERE chat_id=ANY(%s) ORDER BY user_id",
|
||||
(ids,))
|
||||
members = {row["id"]: [] for row in rows}
|
||||
for member in await cur.fetchall():
|
||||
members[str(member["chat_id"])].append(str(member["user_id"]))
|
||||
for row in rows:
|
||||
row["member_ids"] = members[row["id"]]
|
||||
return self.page(rows, scope, limit)
|
||||
Reference in New Issue
Block a user