Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a7b10a1d56 |
@@ -0,0 +1,2 @@
|
||||
*.sh text eol=lf
|
||||
*.cmd text eol=crlf
|
||||
@@ -30,3 +30,5 @@ coverage/
|
||||
.vscode/
|
||||
# Keep small, sanitized evidence summaries in evidence/ under version control.
|
||||
# Inspect git diff --cached: ignore rules are not a secret scanner.
|
||||
|
||||
evidence/build-local.tmp
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
FROM python:3.12.8-slim
|
||||
WORKDIR /app
|
||||
COPY app/requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt && useradd --uid 10001 messenger
|
||||
COPY app/ .
|
||||
USER messenger
|
||||
CMD ["uvicorn","main:app","--host","0.0.0.0","--port","8080","--no-access-log"]
|
||||
@@ -1,37 +1,35 @@
|
||||
# Отчёт — лабораторная 2
|
||||
# ЛР2. PostgreSQL и сессии
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
Максим Макаренко. группа БВТ2302. Целевой уровень 3.
|
||||
|
||||
## Запуск из чистого clone
|
||||
## Запуск в PowerShell
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Понадобятся Docker Desktop с Linux-контейнерами и Python 3.12. Команды выполняются из папки этой лабораторной. Стенд использует именованные volumes. `docker compose down` останавливает его с сохранением данных. Для намеренного удаления volumes используется `docker compose down -v`.
|
||||
|
||||
## Архитектура и решения
|
||||
```powershell
|
||||
python -X utf8 scripts/check_contract.py
|
||||
python scripts/setup.py
|
||||
docker compose up -d --build
|
||||
python -X utf8 tests/smoke.py --base-url http://127.0.0.1:8080
|
||||
python -X utf8 tests/resilience.py --mode persistence --action-script scripts/restart.cmd --base-url http://127.0.0.1:8080
|
||||
docker compose down
|
||||
```
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
setup создаёт локальный .env. Для проверки с нестандартным портом задайте PORT в окружении Compose и передайте соответствующий --base-url тестам.
|
||||
|
||||
## Доказательства критериев
|
||||
## Архитектура и транзакционные границы
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
PostgreSQL хранит пользователей, участников, сообщения и сессии. Уникальный индекс защищает имя пользователя. Создание чата и добавление его участников выполняются в одной транзакции. Пароль проверяется с помощью Argon2id. В БД сохраняется SHA-256 случайного токена и время истечения. Logout удаляет одну сессию.
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
## Проверка и ограничения
|
||||
|
||||
## Эксперименты и отказы
|
||||
Вывод публичного сценария хранится в [evidence/smoke.txt](evidence/smoke.txt). Проверка перезапуска создаёт синтетические данные, запускает hook из scripts, затем читает прежние данные с действующей сессией. Результат записан в [evidence/persistence.txt](evidence/persistence.txt).
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
У стенда одна БД. Именованный volume позволяет восстановить состояние после остановки процесса. Потеря диска требует отдельного резервного копирования. История чата загружается в память для курсорной пагинации, поэтому размер истории влияет на стоимость чтения.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
## Результаты локальной проверки
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
- [check.txt](evidence/check.txt) — PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
- [persistence.txt](evidence/persistence.txt) — PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
- [smoke.txt](evidence/smoke.txt) — PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
CREATE TABLE IF NOT EXISTS users(id text PRIMARY KEY, username text UNIQUE NOT NULL, password_hash text NOT NULL, doc jsonb NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS sessions(digest text PRIMARY KEY, owner text REFERENCES users, expires timestamptz NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS chats(id text PRIMARY KEY, doc jsonb NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS members(chat text REFERENCES chats, owner text REFERENCES users, PRIMARY KEY(chat,owner));
|
||||
CREATE TABLE IF NOT EXISTS messages(id text PRIMARY KEY, chat text REFERENCES chats, sender text REFERENCES users, retry_key text, doc jsonb NOT NULL, UNIQUE(chat,sender,retry_key));
|
||||
CREATE INDEX IF NOT EXISTS messages_chat ON messages(chat);
|
||||
CREATE TABLE IF NOT EXISTS attachments(id text PRIMARY KEY, chat text REFERENCES chats, owner text REFERENCES users, doc jsonb NOT NULL, attempts integer DEFAULT 0);
|
||||
+279
@@ -0,0 +1,279 @@
|
||||
import base64
|
||||
import re
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import ValidationError
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from models import CreateChat, CreateMessage, CreateUser, USERNAME_RE, valid_text
|
||||
from pagination import paginate
|
||||
from store import Store, db, digest
|
||||
|
||||
HOST = os.environ.get("APP_HOST", "0.0.0.0")
|
||||
PORT = int(os.environ.get("APP_PORT", "8080"))
|
||||
APP_ENV = os.environ.get("APP_ENV", "lab")
|
||||
INSTANCE_ID = os.environ.get("INSTANCE_ID") or str(uuid.uuid4())
|
||||
MAX_BODY_BYTES = int(os.environ.get("MAX_BODY_BYTES") or 1 << 20)
|
||||
SHUTDOWN_TIMEOUT_SECONDS = min(int(os.environ.get("SHUTDOWN_TIMEOUT_SECONDS") or 10), 10)
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
|
||||
logger = logging.getLogger("messenger")
|
||||
|
||||
store = Store()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_: FastAPI):
|
||||
logger.info("event=start addr=%s:%s env=%s instance_id=%s", HOST, PORT, APP_ENV, INSTANCE_ID)
|
||||
store.migrate()
|
||||
yield
|
||||
logger.info("event=shutdown_done instance_id=%s", INSTANCE_ID)
|
||||
|
||||
|
||||
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
|
||||
|
||||
|
||||
def err(request: Request, status: int, code: str, message: str) -> JSONResponse:
|
||||
rid = getattr(request.state, "request_id", "")
|
||||
return JSONResponse(status_code=status, content={"error": {"code": code, "message": message, "request_id": rid}})
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def context(request: Request, call_next):
|
||||
start = time.monotonic()
|
||||
rid = (request.headers.get("X-Request-Id") or "").strip() or uuid.uuid4().hex
|
||||
request.state.request_id = rid
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except Exception:
|
||||
logger.error("event=unhandled request_id=%s", rid)
|
||||
response = err(request, 500, "internal_error", "internal error")
|
||||
if response.status_code == 401:
|
||||
response.headers["WWW-Authenticate"] = 'Basic realm="messenger", charset="UTF-8"' if request.url.path.endswith("/auth/sessions") else 'Bearer realm="messenger"'
|
||||
response.headers["X-Request-Id"] = rid
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
logger.info(
|
||||
"level=info method=%s path=%s status=%d duration_ms=%.1f request_id=%s instance_id=%s",
|
||||
request.method, request.url.path, response.status_code,
|
||||
(time.monotonic() - start) * 1000, rid, INSTANCE_ID,
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_exception(request: Request, exc: StarletteHTTPException):
|
||||
code = {401: "unauthorized", 404: "not_found", 409: "conflict", 413: "payload_too_large", 415: "unsupported_media_type", 503: "unavailable", 429: "rate_limited"}.get(exc.status_code, "invalid_request")
|
||||
return err(request, exc.status_code, code, "request failed")
|
||||
|
||||
|
||||
@app.exception_handler(ValidationError)
|
||||
async def validation_exception(request: Request, exc: ValidationError):
|
||||
return err(request, 400, "invalid_request", "invalid request")
|
||||
|
||||
|
||||
def actor(request: Request):
|
||||
scheme, _, token = request.headers.get("Authorization", "").partition(" ")
|
||||
return store.session(token) if token and scheme.lower() == "bearer" else None
|
||||
|
||||
|
||||
@app.post("/api/v1/auth/sessions")
|
||||
async def login(request: Request):
|
||||
scheme, _, value = request.headers.get("Authorization","").partition(" ")
|
||||
try:
|
||||
if scheme.lower() != "basic" or await request.body():
|
||||
raise ValueError()
|
||||
name, password = base64.b64decode(value,validate=True).decode().split(":",1)
|
||||
except (ValueError, UnicodeError):
|
||||
return err(request,401,"unauthorized","invalid credentials")
|
||||
session = store.login(name,password)
|
||||
return JSONResponse(session,status_code=201) if session else err(request,401,"unauthorized","invalid credentials")
|
||||
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current")
|
||||
def logout(request: Request):
|
||||
from fastapi import Response
|
||||
if not actor(request):
|
||||
return err(request,401,"unauthorized","invalid session")
|
||||
with db() as c:
|
||||
c.execute("delete from sessions where digest=%s",(digest(request.headers["Authorization"].split(" ",1)[1]),))
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
def is_json(request: Request) -> bool:
|
||||
media = (request.headers.get("Content-Type") or "").split(";")[0].strip().lower()
|
||||
return media == "application/json"
|
||||
|
||||
|
||||
async def read_body(request: Request):
|
||||
raw = bytearray()
|
||||
async for chunk in request.stream():
|
||||
raw.extend(chunk)
|
||||
if len(raw) > MAX_BODY_BYTES:
|
||||
return None, "payload_too_large"
|
||||
if len(raw) > MAX_BODY_BYTES:
|
||||
return None, "payload_too_large"
|
||||
try:
|
||||
return json.loads(raw), None
|
||||
except Exception:
|
||||
return None, "invalid_request"
|
||||
|
||||
|
||||
def valid_uuid(value: str) -> bool:
|
||||
try:
|
||||
uuid.UUID(value)
|
||||
return True
|
||||
except (ValueError, AttributeError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
@app.get("/health/live")
|
||||
async def live(request: Request):
|
||||
return JSONResponse(content={"status": "ok"})
|
||||
|
||||
|
||||
@app.get("/health/ready")
|
||||
async def ready(request: Request):
|
||||
try:
|
||||
with db() as c:
|
||||
c.execute("select 1")
|
||||
except Exception:
|
||||
return err(request,503,"unavailable","database unavailable")
|
||||
return JSONResponse(content={"status": "ok"})
|
||||
|
||||
|
||||
@app.post("/api/v1/users")
|
||||
async def register_user(request: Request):
|
||||
if not is_json(request):
|
||||
return err(request, 415, "unsupported_media_type", "expected application/json")
|
||||
data, code = await read_body(request)
|
||||
if code:
|
||||
return err(request, 413 if code == "payload_too_large" else 400, code, "invalid request body")
|
||||
try:
|
||||
body = CreateUser.model_validate(data)
|
||||
except ValidationError:
|
||||
return err(request, 400, "invalid_request", "invalid user fields")
|
||||
if not USERNAME_RE.fullmatch(body.username) or not valid_text(body.display_name, 100):
|
||||
return err(request, 400, "invalid_request", "invalid user fields")
|
||||
user, code = store.create_user(body.username, body.display_name, body.password)
|
||||
if code == "conflict":
|
||||
return err(request, 409, "conflict", "username already taken")
|
||||
return JSONResponse(status_code=201, content=user)
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me")
|
||||
async def current_user(request: Request):
|
||||
user = actor(request)
|
||||
if user is None:
|
||||
return err(request, 401, "unauthorized", "invalid session")
|
||||
return JSONResponse(content=user)
|
||||
|
||||
|
||||
@app.post("/api/v1/chats")
|
||||
async def create_chat(request: Request):
|
||||
user = actor(request)
|
||||
if user is None:
|
||||
return err(request, 401, "unauthorized", "invalid session")
|
||||
if not is_json(request):
|
||||
return err(request, 415, "unsupported_media_type", "expected application/json")
|
||||
data, code = await read_body(request)
|
||||
if code:
|
||||
return err(request, 413 if code == "payload_too_large" else 400, code, "invalid request body")
|
||||
try:
|
||||
body = CreateChat.model_validate(data)
|
||||
except ValidationError:
|
||||
return err(request, 400, "invalid_request", "invalid chat fields")
|
||||
if not valid_text(body.title, 100):
|
||||
return err(request, 400, "invalid_request", "invalid chat title")
|
||||
if not (1 <= len(body.member_ids) <= 100) or any(not valid_uuid(m) for m in body.member_ids):
|
||||
return err(request, 400, "invalid_request", "invalid member_ids")
|
||||
chat, code = store.create_chat(user["id"], body.title, body.member_ids)
|
||||
if code:
|
||||
return err(request, 400, "invalid_request", "invalid member_ids")
|
||||
return JSONResponse(status_code=201, content=chat)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats")
|
||||
async def list_chats(request: Request):
|
||||
user = actor(request)
|
||||
if user is None:
|
||||
return err(request, 401, "unauthorized", "invalid session")
|
||||
page, next_cursor, code = paginate(
|
||||
store.list_chats(user["id"]), user["id"],
|
||||
request.query_params.get("limit"), request.query_params.get("cursor"),
|
||||
)
|
||||
if code:
|
||||
return err(request, 400, "invalid_request", "invalid pagination parameters")
|
||||
return JSONResponse(content={"items": page, "next_cursor": next_cursor})
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}")
|
||||
async def get_chat(chat_id: str, request: Request):
|
||||
user = actor(request)
|
||||
if user is None:
|
||||
return err(request, 401, "unauthorized", "invalid session")
|
||||
if not valid_uuid(chat_id):
|
||||
return err(request, 400, "invalid_request", "invalid chat id")
|
||||
chat = store.member_chat(chat_id, user["id"])
|
||||
if chat is None:
|
||||
return err(request, 404, "not_found", "chat not found")
|
||||
return JSONResponse(content=chat)
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages")
|
||||
async def create_message(chat_id: str, request: Request):
|
||||
user = actor(request)
|
||||
if user is None:
|
||||
return err(request, 401, "unauthorized", "invalid session")
|
||||
if not valid_uuid(chat_id):
|
||||
return err(request, 400, "invalid_request", "invalid chat id")
|
||||
if store.member_chat(chat_id, user["id"]) is None:
|
||||
return err(request, 404, "not_found", "chat not found")
|
||||
if not is_json(request):
|
||||
return err(request, 415, "unsupported_media_type", "expected application/json")
|
||||
data, code = await read_body(request)
|
||||
if code:
|
||||
return err(request, 413 if code == "payload_too_large" else 400, code, "invalid request body")
|
||||
try:
|
||||
body = CreateMessage.model_validate(data)
|
||||
except ValidationError:
|
||||
return err(request, 400, "invalid_request", "invalid message text")
|
||||
if not valid_text(body.text, 4000):
|
||||
return err(request, 400, "invalid_request", "invalid message text")
|
||||
key = None
|
||||
message = store.add_message(chat_id, user["id"], body.text, key, None)
|
||||
return JSONResponse(status_code=201, content=message)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||
async def list_messages(chat_id: str, request: Request):
|
||||
user = actor(request)
|
||||
if user is None:
|
||||
return err(request, 401, "unauthorized", "invalid session")
|
||||
if not valid_uuid(chat_id):
|
||||
return err(request, 400, "invalid_request", "invalid chat id")
|
||||
if store.member_chat(chat_id, user["id"]) is None:
|
||||
return err(request, 404, "not_found", "chat not found")
|
||||
page, next_cursor, code = paginate(
|
||||
store.list_messages(chat_id), chat_id,
|
||||
request.query_params.get("limit"), request.query_params.get("cursor"),
|
||||
)
|
||||
if code:
|
||||
return err(request, 400, "invalid_request", "invalid pagination parameters")
|
||||
return JSONResponse(content={"items": page, "next_cursor": next_cursor})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
uvicorn.run(
|
||||
app, host=HOST, port=PORT,
|
||||
timeout_graceful_shutdown=SHUTDOWN_TIMEOUT_SECONDS,
|
||||
access_log=False,
|
||||
)
|
||||
@@ -0,0 +1,27 @@
|
||||
import re
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||
|
||||
|
||||
class CreateUser(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
password: str = Field(min_length=12,max_length=128)
|
||||
username: str
|
||||
display_name: str
|
||||
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
title: str
|
||||
member_ids: list[str]
|
||||
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
text: str
|
||||
|
||||
|
||||
def valid_text(value: str, maximum: int) -> bool:
|
||||
return isinstance(value, str) and value.strip() != "" and 1 <= len(value) <= maximum
|
||||
@@ -0,0 +1,57 @@
|
||||
import base64
|
||||
import json
|
||||
import uuid
|
||||
from bisect import bisect_right
|
||||
|
||||
|
||||
def _key(item: dict):
|
||||
return (item["created_at"], uuid.UUID(item["id"]).int)
|
||||
|
||||
|
||||
def encode_cursor(scope: str, created_at: str, item_id: str) -> str:
|
||||
raw = json.dumps({"s": scope, "c": created_at, "i": item_id}, separators=(",", ":")).encode()
|
||||
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(value: str):
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
|
||||
obj = json.loads(raw)
|
||||
except Exception:
|
||||
return None
|
||||
if not isinstance(obj, dict) or not obj.get("c") or not obj.get("i"):
|
||||
return None
|
||||
return obj
|
||||
|
||||
|
||||
def paginate(items: list[dict], scope: str, limit_raw, cursor_raw):
|
||||
if not limit_raw:
|
||||
limit = 50
|
||||
else:
|
||||
try:
|
||||
limit = int(limit_raw)
|
||||
except (ValueError, TypeError):
|
||||
return None, None, "invalid_request"
|
||||
if limit < 1 or limit > 100:
|
||||
return None, None, "invalid_request"
|
||||
|
||||
ordered = sorted(items, key=_key)
|
||||
keys = [_key(x) for x in ordered]
|
||||
|
||||
start = 0
|
||||
if cursor_raw:
|
||||
cur = decode_cursor(cursor_raw)
|
||||
if cur is None or cur.get("s") != scope:
|
||||
return None, None, "invalid_request"
|
||||
try:
|
||||
cursor_key = (cur["c"], uuid.UUID(cur["i"]).int)
|
||||
except (KeyError, ValueError, TypeError):
|
||||
return None, None, "invalid_request"
|
||||
start = bisect_right(keys, cursor_key)
|
||||
|
||||
page = ordered[start:start + limit]
|
||||
next_cursor = None
|
||||
if start + limit < len(ordered):
|
||||
last = page[-1]
|
||||
next_cursor = encode_cursor(scope, last["created_at"], last["id"])
|
||||
return page, next_cursor, None
|
||||
@@ -0,0 +1,4 @@
|
||||
fastapi==0.115.6
|
||||
uvicorn==0.34.0
|
||||
psycopg[binary]==3.2.9
|
||||
argon2-cffi==25.1.0
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
import hashlib
|
||||
import os
|
||||
import secrets
|
||||
import uuid
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from psycopg.types.json import Jsonb
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerificationError
|
||||
from fastapi import HTTPException
|
||||
|
||||
kdf = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
|
||||
dummy = kdf.hash(secrets.token_hex(16))
|
||||
|
||||
|
||||
def db():
|
||||
return psycopg.connect(os.environ["DATABASE_URL"], connect_timeout=3)
|
||||
|
||||
|
||||
def stamp(moment=None):
|
||||
return (moment or datetime.now(timezone.utc)).isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def entity(**fields):
|
||||
return dict(id=str(uuid.uuid4()), created_at=stamp(), **fields)
|
||||
|
||||
|
||||
def digest(token):
|
||||
return hashlib.sha256(token.encode()).hexdigest()
|
||||
|
||||
|
||||
class Store:
|
||||
def migrate(self):
|
||||
with db() as c:
|
||||
c.execute("select pg_advisory_xact_lock(2081)")
|
||||
c.execute(Path(__file__).with_name("001.sql").read_text())
|
||||
|
||||
def create_user(self, username, display_name, password):
|
||||
user = entity(username=username, display_name=display_name)
|
||||
with db() as c:
|
||||
row = c.execute("insert into users values (%s,%s,%s,%s) on conflict do nothing returning id",
|
||||
(user["id"], username, kdf.hash(password), Jsonb(user))).fetchone()
|
||||
return (user, None) if row else (None, "conflict")
|
||||
|
||||
def login(self, username, password):
|
||||
with db() as c:
|
||||
row = c.execute("select password_hash,doc from users where username=%s",(username,)).fetchone()
|
||||
try:
|
||||
kdf.verify(row[0] if row else dummy, password)
|
||||
except VerificationError:
|
||||
return None
|
||||
if not row:
|
||||
return None
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires = datetime.now(timezone.utc) + timedelta(seconds=int(os.getenv("SESSION_TTL_SECONDS","3600")))
|
||||
c.execute("insert into sessions values (%s,%s,%s)",(digest(token),row[1]["id"],expires))
|
||||
return dict(token=token,token_type="Bearer",expires_at=stamp(expires),user=row[1])
|
||||
|
||||
def session(self, token):
|
||||
with db() as c:
|
||||
row = c.execute("select doc from users join sessions on owner=id where digest=%s and expires>now()", (digest(token),)).fetchone()
|
||||
return row[0] if row else None
|
||||
|
||||
def create_chat(self, owner, title, members):
|
||||
if owner not in members or len(set(members)) != len(members):
|
||||
return None, "invalid_request"
|
||||
chat = entity(title=title, member_ids=members)
|
||||
with db() as c:
|
||||
if c.execute("select count(*) from users where id=any(%s)",(members,)).fetchone()[0] != len(members):
|
||||
return None, "invalid_request"
|
||||
c.execute("insert into chats values(%s,%s)",(chat["id"],Jsonb(chat)))
|
||||
c.execute("insert into members select %s,unnest(%s::text[])",(chat["id"],members))
|
||||
return chat, None
|
||||
|
||||
def list_chats(self, owner):
|
||||
with db() as c:
|
||||
return [r[0] for r in c.execute("select doc from chats join members on chat=id where owner=%s",(owner,))]
|
||||
|
||||
def member_chat(self, chat, owner):
|
||||
with db() as c:
|
||||
row = c.execute("select doc from chats join members on chat=id where id=%s and owner=%s",(chat,owner)).fetchone()
|
||||
return row[0] if row else None
|
||||
|
||||
def add_message(self, chat, sender, text, key, attachments):
|
||||
message = entity(chat_id=chat,sender_id=sender,text=text)
|
||||
if attachments is not None:
|
||||
message["attachment_ids"] = attachments
|
||||
with db() as c:
|
||||
for att in attachments or []:
|
||||
row = c.execute("select doc->>'status' from attachments where id=%s and chat=%s",(att,chat)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404)
|
||||
if row[0]=="failed":
|
||||
raise HTTPException(409)
|
||||
result = c.execute("insert into messages values (%s,%s,%s,%s,%s) on conflict(chat,sender,retry_key) do nothing returning doc",
|
||||
(message["id"],chat,sender,key,Jsonb(message))).fetchone()
|
||||
if result:
|
||||
return result[0]
|
||||
prev = c.execute("select doc from messages where chat=%s and sender=%s and retry_key=%s",(chat,sender,key)).fetchone()[0]
|
||||
if prev["text"] != text or prev.get("attachment_ids") != attachments:
|
||||
raise HTTPException(409)
|
||||
return prev
|
||||
|
||||
def list_messages(self, chat):
|
||||
with db() as c:
|
||||
return [r[0] for r in c.execute("select doc from messages where chat=%s",(chat,))]
|
||||
@@ -0,0 +1,45 @@
|
||||
{
|
||||
"services": {
|
||||
"db": {
|
||||
"image": "postgres:16-alpine",
|
||||
"environment": {
|
||||
"POSTGRES_USER": "messenger",
|
||||
"POSTGRES_PASSWORD": "${DB_PASSWORD:?run setup}"
|
||||
},
|
||||
"volumes": [
|
||||
"db:/var/lib/postgresql/data"
|
||||
],
|
||||
"healthcheck": {
|
||||
"test": [
|
||||
"CMD",
|
||||
"pg_isready",
|
||||
"-U",
|
||||
"messenger"
|
||||
],
|
||||
"interval": "2s",
|
||||
"timeout": "2s",
|
||||
"retries": 30
|
||||
}
|
||||
},
|
||||
"api": {
|
||||
"build": ".",
|
||||
"restart": "unless-stopped",
|
||||
"environment": {
|
||||
"DATABASE_URL": "postgresql://messenger:${DB_PASSWORD}@db/messenger",
|
||||
"SESSION_TTL_SECONDS": "${SESSION_TTL_SECONDS:-3600}",
|
||||
"LAB": "2"
|
||||
},
|
||||
"depends_on": {
|
||||
"db": {
|
||||
"condition": "service_healthy"
|
||||
}
|
||||
},
|
||||
"ports": [
|
||||
"127.0.0.1:${PORT:-8080}:8080"
|
||||
]
|
||||
}
|
||||
},
|
||||
"volumes": {
|
||||
"db": {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
@@ -0,0 +1,2 @@
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1 @@
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -0,0 +1,2 @@
|
||||
@cd /d "%~dp0.."
|
||||
@docker compose restart
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose restart
|
||||
@@ -0,0 +1,8 @@
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
|
||||
target = Path(__file__).resolve().parents[1] / ".env"
|
||||
if not target.exists():
|
||||
with target.open("x", encoding="utf-8") as output:
|
||||
for name in ("DB_PASSWORD","S3_PASSWORD"):
|
||||
output.write(f"{name}={secrets.token_hex(32)}\n")
|
||||
Reference in New Issue
Block a user