4_grade
This commit is contained in:
+2
-1
@@ -11,9 +11,10 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
|||||||
COPY requirements.txt .
|
COPY requirements.txt .
|
||||||
RUN pip install --no-cache-dir -r requirements.txt
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
# Копируем код API и Воркера
|
# Копируем код API, Воркера и скрипты (включая migrate.py)
|
||||||
COPY src/ ./src/
|
COPY src/ ./src/
|
||||||
COPY worker/ ./worker/
|
COPY worker/ ./worker/
|
||||||
|
COPY scripts/ ./scripts/
|
||||||
|
|
||||||
ENV PYTHONPATH=/app
|
ENV PYTHONPATH=/app
|
||||||
|
|
||||||
|
|||||||
+29
-26
@@ -1,15 +1,14 @@
|
|||||||
x-api-common: &api-common
|
x-api-common: &api-common
|
||||||
build: .
|
build: .
|
||||||
environment:
|
environment:
|
||||||
- DATABASE_URL_FILE=/run/secrets/database_url
|
- DATABASE_URL=postgresql://messenger:messenger_password@postgres:5432/messenger
|
||||||
- S3_ENDPOINT=http://minio:9000
|
- S3_ENDPOINT=http://minio:9000
|
||||||
- S3_ACCESS_KEY=minioadmin
|
- S3_ACCESS_KEY=minioadmin
|
||||||
- S3_SECRET_KEY=minioadmin
|
- S3_SECRET_KEY=minioadmin
|
||||||
- S3_BUCKET=messenger-attachments
|
- S3_BUCKET=messenger-attachments
|
||||||
- BROKER_URL=amqp://guest:guest@broker:5672/
|
- BROKER_URL=amqp://guest:guest@broker:5672/
|
||||||
|
- REDIS_URL=redis://redis:6379/0
|
||||||
- APP_ENV=lab5
|
- APP_ENV=lab5
|
||||||
secrets:
|
|
||||||
- database_url
|
|
||||||
depends_on:
|
depends_on:
|
||||||
postgres:
|
postgres:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
@@ -17,7 +16,9 @@ x-api-common: &api-common
|
|||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
broker:
|
broker:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
minio-init:
|
redis:
|
||||||
|
condition: service_healthy
|
||||||
|
migrate:
|
||||||
condition: service_completed_successfully
|
condition: service_completed_successfully
|
||||||
|
|
||||||
services:
|
services:
|
||||||
@@ -45,14 +46,13 @@ services:
|
|||||||
build: .
|
build: .
|
||||||
command: python -m worker.main
|
command: python -m worker.main
|
||||||
environment:
|
environment:
|
||||||
- DATABASE_URL_FILE=/run/secrets/database_url
|
- DATABASE_URL=postgresql://messenger:messenger_password@postgres:5432/messenger
|
||||||
- S3_ENDPOINT=http://minio:9000
|
- S3_ENDPOINT=http://minio:9000
|
||||||
- S3_ACCESS_KEY=minioadmin
|
- S3_ACCESS_KEY=minioadmin
|
||||||
- S3_SECRET_KEY=minioadmin
|
- S3_SECRET_KEY=minioadmin
|
||||||
- S3_BUCKET=messenger-attachments
|
- S3_BUCKET=messenger-attachments
|
||||||
- BROKER_URL=amqp://guest:guest@broker:5672/
|
- BROKER_URL=amqp://guest:guest@broker:5672/
|
||||||
secrets:
|
- REDIS_URL=redis://redis:6379/0
|
||||||
- database_url
|
|
||||||
depends_on:
|
depends_on:
|
||||||
postgres:
|
postgres:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
@@ -60,19 +60,22 @@ services:
|
|||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
broker:
|
broker:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
minio-init:
|
redis:
|
||||||
|
condition: service_healthy
|
||||||
|
migrate:
|
||||||
condition: service_completed_successfully
|
condition: service_completed_successfully
|
||||||
|
|
||||||
migrate:
|
migrate:
|
||||||
build: .
|
build: .
|
||||||
command: python scripts/migrate.py
|
command: python scripts/migrate.py
|
||||||
environment:
|
environment:
|
||||||
- DATABASE_URL_FILE=/run/secrets/database_url
|
- DATABASE_URL=postgresql://messenger:messenger_password@postgres:5432/messenger
|
||||||
secrets:
|
- REDIS_URL=redis://redis:6379/0
|
||||||
- database_url
|
|
||||||
depends_on:
|
depends_on:
|
||||||
postgres:
|
postgres:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
|
redis:
|
||||||
|
condition: service_healthy
|
||||||
|
|
||||||
postgres:
|
postgres:
|
||||||
image: postgres:16-alpine
|
image: postgres:16-alpine
|
||||||
@@ -89,7 +92,7 @@ services:
|
|||||||
retries: 5
|
retries: 5
|
||||||
|
|
||||||
minio:
|
minio:
|
||||||
image: quay.io/minio/minio:RELEASE.2024-02-24T06-42-55Z
|
image: pgsty/minio:latest
|
||||||
command: server /data --console-address ":9001"
|
command: server /data --console-address ":9001"
|
||||||
environment:
|
environment:
|
||||||
- MINIO_ROOT_USER=minioadmin
|
- MINIO_ROOT_USER=minioadmin
|
||||||
@@ -101,20 +104,12 @@ services:
|
|||||||
interval: 5s
|
interval: 5s
|
||||||
timeout: 5s
|
timeout: 5s
|
||||||
retries: 5
|
retries: 5
|
||||||
|
|
||||||
minio-init:
|
|
||||||
image: quay.io/minio/mc:latest
|
|
||||||
depends_on:
|
|
||||||
minio:
|
|
||||||
condition: service_healthy
|
|
||||||
volumes:
|
|
||||||
- ./infra/minio-policy.json:/minio-policy.json
|
|
||||||
entrypoint: >
|
entrypoint: >
|
||||||
/bin/sh -c "
|
/bin/sh -c "
|
||||||
/usr/bin/mc alias set myminio http://minio:9000 minioadmin minioadmin;
|
/usr/bin/mc alias set myminio http://localhost:9000 minioadmin minioadmin;
|
||||||
/usr/bin/mc mb myminio/messenger-attachments --ignore-existing;
|
/usr/bin/mc mb myminio/messenger-attachments --ignore-existing;
|
||||||
/usr/bin/mc anonymous set-json /minio-policy.json myminio/messenger-attachments;
|
/usr/bin/mc anonymous set private myminio/messenger-attachments;
|
||||||
exit 0;
|
/usr/bin/minio server /data --console-address ':9001'
|
||||||
"
|
"
|
||||||
|
|
||||||
broker:
|
broker:
|
||||||
@@ -130,11 +125,19 @@ services:
|
|||||||
timeout: 5s
|
timeout: 5s
|
||||||
retries: 5
|
retries: 5
|
||||||
|
|
||||||
secrets:
|
redis:
|
||||||
database_url:
|
image: redis:7-alpine
|
||||||
file: ./secrets/database_url
|
command: redis-server --appendonly yes
|
||||||
|
volumes:
|
||||||
|
- redisdata:/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "redis-cli", "ping"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
pgdata:
|
pgdata:
|
||||||
s3data:
|
s3data:
|
||||||
brokerdata:
|
brokerdata:
|
||||||
|
redisdata:
|
||||||
@@ -7,3 +7,4 @@ boto3>=1.34.0
|
|||||||
python-multipart>=0.0.9
|
python-multipart>=0.0.9
|
||||||
Pillow>=10.2.0
|
Pillow>=10.2.0
|
||||||
aio-pika>=9.4.0
|
aio-pika>=9.4.0
|
||||||
|
redis[hiredis]>=5.0.1
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
import psycopg
|
||||||
|
|
||||||
|
def get_dsn():
|
||||||
|
file_path = os.environ.get("DATABASE_URL_FILE")
|
||||||
|
if file_path and os.path.exists(file_path):
|
||||||
|
return Path(file_path).read_text().strip()
|
||||||
|
return os.environ.get("DATABASE_URL")
|
||||||
|
|
||||||
|
def main():
|
||||||
|
dsn = get_dsn()
|
||||||
|
if not dsn:
|
||||||
|
print("ERROR: DATABASE_URL or DATABASE_URL_FILE not set", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
for i in range(10):
|
||||||
|
try:
|
||||||
|
with psycopg.connect(dsn, autocommit=True) as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT 1")
|
||||||
|
break
|
||||||
|
except psycopg.OperationalError:
|
||||||
|
print("Waiting for database...")
|
||||||
|
time.sleep(2)
|
||||||
|
else:
|
||||||
|
print("ERROR: Database is not ready", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# ВАЖНО: путь к миграциям. Раз они лежат в src/migrations:
|
||||||
|
migrations_dir = Path(__file__).parent.parent / "src" / "migrations"
|
||||||
|
sql_files = sorted(migrations_dir.glob("*.sql"))
|
||||||
|
|
||||||
|
with psycopg.connect(dsn, autocommit=True) as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute("""
|
||||||
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||||
|
version text PRIMARY KEY,
|
||||||
|
applied_at timestamptz DEFAULT now()
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
|
||||||
|
for sql_file in sql_files:
|
||||||
|
version = sql_file.name
|
||||||
|
cur.execute("SELECT 1 FROM schema_migrations WHERE version = %s", (version,))
|
||||||
|
if cur.fetchone():
|
||||||
|
continue
|
||||||
|
|
||||||
|
print(f"Applying {version}...")
|
||||||
|
sql = sql_file.read_text(encoding="utf-8")
|
||||||
|
cur.execute(sql)
|
||||||
|
cur.execute("INSERT INTO schema_migrations (version) VALUES (%s)", (version,))
|
||||||
|
print(f"Applied {version}.")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
echo "Restarting API and Postgres (preserving volumes)..."
|
||||||
|
docker compose restart api1 api2 postgres
|
||||||
|
echo "Waiting for Postgres to be healthy..."
|
||||||
|
sleep 5
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||||
|
if [ "$TARGET_INSTANCE_ID" != "api-1" ] && [ "$TARGET_INSTANCE_ID" != "api-2" ]; then
|
||||||
|
echo "Unknown instance: $TARGET_INSTANCE_ID" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
SERVICE_NAME="$TARGET_INSTANCE_ID"
|
||||||
|
if [ "$SERVICE_NAME" = "api-1" ]; then SERVICE_NAME="api1"; fi
|
||||||
|
if [ "$SERVICE_NAME" = "api-2" ]; then SERVICE_NAME="api2"; fi
|
||||||
|
|
||||||
|
echo "Stopping container for $SERVICE_NAME..."
|
||||||
|
docker compose stop "$SERVICE_NAME"
|
||||||
@@ -42,6 +42,8 @@ class Settings(BaseSettings):
|
|||||||
broker_url: str = "amqp://guest:guest@broker:5672/"
|
broker_url: str = "amqp://guest:guest@broker:5672/"
|
||||||
broker_queue: str = "attachment_processing"
|
broker_queue: str = "attachment_processing"
|
||||||
|
|
||||||
|
redis_url: str = "redis://redis:6379/0"
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def db_dsn(self) -> str:
|
def db_dsn(self) -> str:
|
||||||
from_file = _read_secret(self.database_url_file)
|
from_file = _read_secret(self.database_url_file)
|
||||||
|
|||||||
+32
-44
@@ -1,18 +1,19 @@
|
|||||||
import hashlib
|
import hashlib
|
||||||
import json
|
import json
|
||||||
|
import redis
|
||||||
from typing import Any, Callable
|
from typing import Any, Callable
|
||||||
|
|
||||||
import psycopg
|
import psycopg
|
||||||
|
|
||||||
from .db import transaction
|
from .config import get_settings
|
||||||
from .errors import ApiError
|
from .errors import ApiError
|
||||||
|
from .db import transaction
|
||||||
|
|
||||||
|
redis_client = redis.Redis.from_url(get_settings().redis_url, decode_responses=True)
|
||||||
|
|
||||||
def _body_hash(body: dict[str, Any]) -> str:
|
def _body_hash(body: dict[str, Any]) -> str:
|
||||||
raw = json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
raw = json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
||||||
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
|
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
def run_idempotent(
|
def run_idempotent(
|
||||||
*,
|
*,
|
||||||
user_id: str,
|
user_id: str,
|
||||||
@@ -21,52 +22,39 @@ def run_idempotent(
|
|||||||
body: dict[str, Any],
|
body: dict[str, Any],
|
||||||
action: Callable[[psycopg.Connection], tuple[int, dict[str, Any]]],
|
action: Callable[[psycopg.Connection], tuple[int, dict[str, Any]]],
|
||||||
) -> tuple[int, dict[str, Any]]:
|
) -> tuple[int, dict[str, Any]]:
|
||||||
"""Атомарно: либо побочный эффект + сохранённый ответ, либо повтор."""
|
|
||||||
h = _body_hash(body)
|
h = _body_hash(body)
|
||||||
try:
|
redis_key = f"idem:{user_id}:{scope}:{key}"
|
||||||
with transaction() as conn:
|
ttl = get_settings().idempotency_ttl_seconds
|
||||||
with conn.cursor() as cur:
|
|
||||||
cur.execute(
|
|
||||||
"""
|
|
||||||
INSERT INTO idempotency_keys
|
|
||||||
(user_id, scope, key, request_hash, status_code, response_json)
|
|
||||||
VALUES (%s, %s, %s, %s, 0, '{}'::jsonb)
|
|
||||||
""",
|
|
||||||
(user_id, scope, key, h),
|
|
||||||
)
|
|
||||||
result = action(conn)
|
|
||||||
status, payload = result
|
|
||||||
with conn.cursor() as cur:
|
|
||||||
cur.execute(
|
|
||||||
"""
|
|
||||||
UPDATE idempotency_keys
|
|
||||||
SET status_code = %s, response_json = %s::jsonb
|
|
||||||
WHERE user_id = %s AND scope = %s AND key = %s
|
|
||||||
""",
|
|
||||||
(status, json.dumps(payload, ensure_ascii=False), user_id, scope, key),
|
|
||||||
)
|
|
||||||
return status, payload
|
|
||||||
except psycopg.errors.UniqueViolation:
|
|
||||||
pass
|
|
||||||
|
|
||||||
with transaction() as conn:
|
# Блокировка
|
||||||
with conn.cursor() as cur:
|
locked = redis_client.set(redis_key, json.dumps({"status": 0, "hash": h}), nx=True, ex=ttl)
|
||||||
cur.execute(
|
|
||||||
"""
|
if locked:
|
||||||
SELECT request_hash, status_code, response_json
|
try:
|
||||||
FROM idempotency_keys
|
with transaction() as conn:
|
||||||
WHERE user_id = %s AND scope = %s AND key = %s
|
status, payload = action(conn)
|
||||||
""",
|
|
||||||
(user_id, scope, key),
|
redis_client.setex(
|
||||||
|
redis_key,
|
||||||
|
ttl,
|
||||||
|
json.dumps({"status": status, "hash": h, "payload": payload})
|
||||||
)
|
)
|
||||||
row = cur.fetchone()
|
return status, payload
|
||||||
|
except Exception:
|
||||||
|
redis_client.delete(redis_key)
|
||||||
|
raise
|
||||||
|
|
||||||
if row is None:
|
# Повторный запрос
|
||||||
|
existing_raw = redis_client.get(redis_key)
|
||||||
|
if not existing_raw:
|
||||||
raise ApiError(409, "conflict", "Конфликт идемпотентности, повторите")
|
raise ApiError(409, "conflict", "Конфликт идемпотентности, повторите")
|
||||||
|
|
||||||
existing_hash, status, payload = row
|
existing = json.loads(existing_raw)
|
||||||
if existing_hash != h:
|
|
||||||
|
if existing.get("hash") != h:
|
||||||
raise ApiError(409, "conflict", "Тот же ключ с другим телом запроса")
|
raise ApiError(409, "conflict", "Тот же ключ с другим телом запроса")
|
||||||
if status == 0:
|
|
||||||
|
if existing.get("status") == 0:
|
||||||
raise ApiError(409, "conflict", "Повтор ещё не завершён")
|
raise ApiError(409, "conflict", "Повтор ещё не завершён")
|
||||||
return status, payload
|
|
||||||
|
return existing["status"], existing["payload"]
|
||||||
+23
-42
@@ -1,11 +1,12 @@
|
|||||||
import base64
|
import base64
|
||||||
|
import json
|
||||||
|
import redis
|
||||||
from fastapi import APIRouter, Depends, Request
|
from fastapi import APIRouter, Depends, Request
|
||||||
from fastapi.responses import Response
|
from fastapi.responses import Response
|
||||||
from psycopg.rows import dict_row
|
from psycopg.rows import dict_row
|
||||||
|
|
||||||
from ..config import get_settings
|
from ..config import get_settings
|
||||||
from ..db import connection, transaction
|
from ..db import connection
|
||||||
from ..errors import ApiError
|
from ..errors import ApiError
|
||||||
from ..security import (
|
from ..security import (
|
||||||
new_session_token,
|
new_session_token,
|
||||||
@@ -20,6 +21,8 @@ router = APIRouter(prefix="/api/v1")
|
|||||||
WWW_BASIC = 'Basic realm="messenger", charset="UTF-8"'
|
WWW_BASIC = 'Basic realm="messenger", charset="UTF-8"'
|
||||||
WWW_BEARER = 'Bearer realm="messenger"'
|
WWW_BEARER = 'Bearer realm="messenger"'
|
||||||
|
|
||||||
|
# Подключение к Redis
|
||||||
|
redis_client = redis.Redis.from_url(get_settings().redis_url, decode_responses=True)
|
||||||
|
|
||||||
def _parse_basic(header: str | None) -> tuple[str, str]:
|
def _parse_basic(header: str | None) -> tuple[str, str]:
|
||||||
if not header or not header.lower().startswith("basic "):
|
if not header or not header.lower().startswith("basic "):
|
||||||
@@ -35,7 +38,6 @@ def _parse_basic(header: str | None) -> tuple[str, str]:
|
|||||||
username, password = decoded.split(":", 1)
|
username, password = decoded.split(":", 1)
|
||||||
return username, password
|
return username, password
|
||||||
|
|
||||||
|
|
||||||
@router.post("/auth/sessions", status_code=201)
|
@router.post("/auth/sessions", status_code=201)
|
||||||
def create_session(request: Request):
|
def create_session(request: Request):
|
||||||
header = request.headers.get("Authorization")
|
header = request.headers.get("Authorization")
|
||||||
@@ -50,32 +52,24 @@ def create_session(request: Request):
|
|||||||
)
|
)
|
||||||
row = cur.fetchone()
|
row = cur.fetchone()
|
||||||
|
|
||||||
# Одинаковый 401 для «нет пользователя» и «неверный пароль».
|
|
||||||
if row is None or not verify_password(password, row["password_hash"]):
|
if row is None or not verify_password(password, row["password_hash"]):
|
||||||
raise ApiError(401, "unauthorized", "Неверные учётные данные", {"WWW-Authenticate": WWW_BASIC})
|
raise ApiError(401, "unauthorized", "Неверные учётные данные", {"WWW-Authenticate": WWW_BASIC})
|
||||||
|
|
||||||
settings = get_settings()
|
settings = get_settings()
|
||||||
token = new_session_token()
|
token = new_session_token()
|
||||||
expires_at = session_expiry(settings.session_ttl_seconds)
|
ttl = settings.session_ttl_seconds
|
||||||
|
digest = token_digest(token)
|
||||||
|
|
||||||
with transaction() as conn:
|
# СОХРАНЯЕМ В REDIS
|
||||||
with conn.cursor() as cur:
|
redis_client.setex(f"session:{digest}", ttl, str(row["id"]))
|
||||||
cur.execute(
|
|
||||||
"""
|
|
||||||
INSERT INTO sessions (user_id, token_hash, expires_at)
|
|
||||||
VALUES (%s, %s, %s)
|
|
||||||
""",
|
|
||||||
(row["id"], token_digest(token), expires_at),
|
|
||||||
)
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"token": token,
|
"token": token,
|
||||||
"token_type": "Bearer",
|
"token_type": "Bearer",
|
||||||
"expires_at": expires_at.isoformat().replace("+00:00", "Z"),
|
"expires_at": session_expiry(ttl).isoformat().replace("+00:00", "Z"),
|
||||||
"user": row_to_user(row),
|
"user": row_to_user(row),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def _extract_bearer(request: Request) -> str:
|
def _extract_bearer(request: Request) -> str:
|
||||||
header = request.headers.get("Authorization")
|
header = request.headers.get("Authorization")
|
||||||
if not header or not header.lower().startswith("bearer "):
|
if not header or not header.lower().startswith("bearer "):
|
||||||
@@ -85,47 +79,34 @@ def _extract_bearer(request: Request) -> str:
|
|||||||
raise ApiError(401, "unauthorized", "Требуется Bearer", {"WWW-Authenticate": WWW_BEARER})
|
raise ApiError(401, "unauthorized", "Требуется Bearer", {"WWW-Authenticate": WWW_BEARER})
|
||||||
return token
|
return token
|
||||||
|
|
||||||
|
|
||||||
def require_actor(request: Request) -> dict:
|
def require_actor(request: Request) -> dict:
|
||||||
"""Зависимость: валидирует Bearer и возвращает actor с user и token_hash."""
|
|
||||||
token = _extract_bearer(request)
|
token = _extract_bearer(request)
|
||||||
digest = token_digest(token)
|
digest = token_digest(token)
|
||||||
|
|
||||||
|
# ЧИТАЕМ ИЗ REDIS
|
||||||
|
user_id = redis_client.get(f"session:{digest}")
|
||||||
|
if user_id is None:
|
||||||
|
raise ApiError(401, "unauthorized", "Сессия недействительна или истекла", {"WWW-Authenticate": WWW_BEARER})
|
||||||
|
|
||||||
with connection() as conn:
|
with connection() as conn:
|
||||||
with conn.cursor(row_factory=dict_row) as cur:
|
with conn.cursor(row_factory=dict_row) as cur:
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"""
|
"SELECT id, username, display_name, created_at FROM users WHERE id = %s",
|
||||||
SELECT s.user_id, s.expires_at,
|
(user_id,),
|
||||||
u.id, u.username, u.display_name, u.created_at
|
|
||||||
FROM sessions s
|
|
||||||
JOIN users u ON u.id = s.user_id
|
|
||||||
WHERE s.token_hash = %s
|
|
||||||
""",
|
|
||||||
(digest,),
|
|
||||||
)
|
)
|
||||||
row = cur.fetchone()
|
row = cur.fetchone()
|
||||||
if row is None:
|
|
||||||
raise ApiError(401, "unauthorized", "Сессия недействительна", {"WWW-Authenticate": WWW_BEARER})
|
|
||||||
|
|
||||||
# Проверка срока на стороне БД
|
if row is None:
|
||||||
with connection() as conn:
|
raise ApiError(401, "unauthorized", "Пользователь не найден", {"WWW-Authenticate": WWW_BEARER})
|
||||||
with conn.cursor() as cur:
|
|
||||||
cur.execute(
|
|
||||||
"SELECT 1 FROM sessions WHERE token_hash = %s AND expires_at > now()",
|
|
||||||
(digest,),
|
|
||||||
)
|
|
||||||
if cur.fetchone() is None:
|
|
||||||
raise ApiError(401, "unauthorized", "Сессия истекла", {"WWW-Authenticate": WWW_BEARER})
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"user": row_to_user(row),
|
"user": row_to_user(row),
|
||||||
"user_id": row["user_id"],
|
"user_id": user_id,
|
||||||
"token_hash": digest,
|
"token_hash": digest,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@router.delete("/auth/sessions/current", status_code=204)
|
@router.delete("/auth/sessions/current", status_code=204)
|
||||||
def revoke_session(request: Request, actor: dict = Depends(require_actor)):
|
def revoke_session(request: Request, actor: dict = Depends(require_actor)):
|
||||||
with transaction() as conn:
|
# УДАЛЯЕМ ИЗ REDIS
|
||||||
with conn.cursor() as cur:
|
redis_client.delete(f"session:{actor['token_hash']}")
|
||||||
cur.execute("DELETE FROM sessions WHERE token_hash = %s", (actor["token_hash"],))
|
|
||||||
return Response(status_code=204)
|
return Response(status_code=204)
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# Базовый URL
|
||||||
|
BASE_URL="http://localhost:8080"
|
||||||
|
|
||||||
|
# 1. Создаем уникального пользователя (добавляем случайное число, чтобы не было конфликта)
|
||||||
|
RANDOM_NUM=$RANDOM
|
||||||
|
USERNAME="test_user_$RANDOM_NUM"
|
||||||
|
PASSWORD="verysecretpassword123"
|
||||||
|
|
||||||
|
echo "1. Создаем пользователя: $USERNAME..."
|
||||||
|
RESPONSE=$(echo "{\"username\": \"$USERNAME\", \"display_name\": \"Тест\", \"password\": \"$PASSWORD\"}" | curl -s -X POST $BASE_URL/api/v1/users -H "Content-Type: application/json" -d @-)
|
||||||
|
USER_ID=$(echo $RESPONSE | jq -r '.id')
|
||||||
|
echo " Пользователь создан. ID: $USER_ID"
|
||||||
|
|
||||||
|
# 2. Логинимся
|
||||||
|
echo "2. Логинимся..."
|
||||||
|
RESPONSE=$(curl -s -X POST $BASE_URL/api/v1/auth/sessions -H "Authorization: Basic $(echo -n "$USERNAME:$PASSWORD" | base64)")
|
||||||
|
TOKEN=$(echo $RESPONSE | jq -r '.token')
|
||||||
|
if [ "$TOKEN" == "null" ]; then
|
||||||
|
echo " Ошибка логина: $RESPONSE"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo " Токен получен."
|
||||||
|
|
||||||
|
# 3. Создаем чат
|
||||||
|
echo "3. Создаем чат..."
|
||||||
|
RESPONSE=$(echo "{\"title\": \"Чат для теста\", \"member_ids\": [\"$USER_ID\"]}" | curl -s -X POST $BASE_URL/api/v1/chats -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d @-)
|
||||||
|
CHAT_ID=$(echo $RESPONSE | jq -r '.id')
|
||||||
|
echo " Чат создан. ID: $CHAT_ID"
|
||||||
|
|
||||||
|
# 4. Загружаем картинку
|
||||||
|
echo "4. Загружаем картинку (sample.png)..."
|
||||||
|
# Убедимся, что файл существует
|
||||||
|
if [ ! -f "tests/fixtures/sample.png" ]; then
|
||||||
|
echo " ОШИБКА: Файл tests/fixtures/sample.png не найден!"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
RESPONSE=$(curl -s -X POST "$BASE_URL/api/v1/chats/$CHAT_ID/attachments?filename=sample.png" \
|
||||||
|
-H "Content-Type: image/png" \
|
||||||
|
-H "Authorization: Bearer $TOKEN" \
|
||||||
|
--data-binary "@tests/fixtures/sample.png")
|
||||||
|
|
||||||
|
ATTACHMENT_ID=$(echo $RESPONSE | jq -r '.id')
|
||||||
|
STATUS=$(echo $RESPONSE | jq -r '.status')
|
||||||
|
|
||||||
|
echo " Вложение загружено. ID: $ATTACHMENT_ID"
|
||||||
|
echo " Статус сразу после загрузки: $STATUS (ожидаем queued)"
|
||||||
|
|
||||||
|
if [ "$STATUS" != "queued" ]; then
|
||||||
|
echo " ВНИМАНИЕ: Статус не queued! Проверь API."
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 5. Ждем, пока воркер обработает
|
||||||
|
echo "5. Ждем 3 секунды, пока воркер обработает картинку..."
|
||||||
|
sleep 3
|
||||||
|
|
||||||
|
# 6. Проверяем статус
|
||||||
|
echo "6. Проверяем итоговый статус вложения..."
|
||||||
|
RESPONSE=$(curl -s -X GET "$BASE_URL/api/v1/attachments/$ATTACHMENT_ID" -H "Authorization: Bearer $TOKEN")
|
||||||
|
FINAL_STATUS=$(echo $RESPONSE | jq -r '.status')
|
||||||
|
VARIANTS_COUNT=$(echo $RESPONSE | jq '.variants | length')
|
||||||
|
|
||||||
|
echo " Итоговый статус: $FINAL_STATUS (ожидаем ready)"
|
||||||
|
echo " Количество вариантов: $VARIANTS_COUNT (ожидаем 3)"
|
||||||
|
|
||||||
|
if [ "$FINAL_STATUS" == "ready" ] && [ "$VARIANTS_COUNT" -eq 3 ]; then
|
||||||
|
echo "✅ УСПЕХ! Асинхронная обработка работает."
|
||||||
|
else
|
||||||
|
echo "❌ ОШИБКА! Воркер не обработал файл. Проверь логи: docker compose logs worker"
|
||||||
|
fi
|
||||||
+26
-15
@@ -2,30 +2,35 @@ import asyncio
|
|||||||
import io
|
import io
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
from datetime import datetime, timezone
|
import hashlib
|
||||||
|
|
||||||
import aio_pika
|
import aio_pika
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
import psycopg
|
|
||||||
from psycopg.rows import dict_row
|
from psycopg.rows import dict_row
|
||||||
|
|
||||||
from src.app.config import get_settings
|
from src.app.config import get_settings
|
||||||
from src.app.db import init_pool, transaction
|
from src.app.db import init_pool, transaction
|
||||||
from src.app.s3 import get_s3_client, download_fileobj, upload_fileobj
|
from src.app.s3 import download_fileobj, upload_fileobj
|
||||||
|
|
||||||
logging.basicConfig(level=logging.INFO)
|
logging.basicConfig(level=logging.INFO)
|
||||||
logger = logging.getLogger("worker")
|
logger = logging.getLogger("worker")
|
||||||
|
|
||||||
|
|
||||||
def generate_variants(img: Image.Image):
|
def generate_variants(img: Image.Image):
|
||||||
variants = {}
|
variants = {}
|
||||||
|
|
||||||
# 1. Thumbnail (макс 256x256, сохраняем пропорции)
|
# 1. Thumbnail (макс 256x256, сохраняем пропорции)
|
||||||
thumb = img.copy()
|
thumb = img.copy()
|
||||||
|
# Если картинка имеет прозрачность (RGBA), конвертируем в RGB для JPEG
|
||||||
|
if thumb.mode in ("RGBA", "P"):
|
||||||
|
thumb = thumb.convert("RGB")
|
||||||
thumb.thumbnail((256, 256))
|
thumb.thumbnail((256, 256))
|
||||||
variants["thumbnail"] = thumb
|
variants["thumbnail"] = thumb
|
||||||
|
|
||||||
# 2. Crop (квадрат 512x512 по центру)
|
# 2. Crop (квадрат 512x512 по центру)
|
||||||
crop = img.copy()
|
crop = img.copy()
|
||||||
|
if crop.mode in ("RGBA", "P"):
|
||||||
|
crop = crop.convert("RGB")
|
||||||
min_dim = min(crop.size)
|
min_dim = min(crop.size)
|
||||||
left = (crop.width - min_dim) // 2
|
left = (crop.width - min_dim) // 2
|
||||||
top = (crop.height - min_dim) // 2
|
top = (crop.height - min_dim) // 2
|
||||||
@@ -33,14 +38,13 @@ def generate_variants(img: Image.Image):
|
|||||||
crop = crop.resize((512, 512), Image.Resampling.LANCZOS)
|
crop = crop.resize((512, 512), Image.Resampling.LANCZOS)
|
||||||
variants["crop"] = crop
|
variants["crop"] = crop
|
||||||
|
|
||||||
# 3. Optimized (просто оригинал в JPEG с качеством 85)
|
# 3. Optimized (просто оригинал в JPEG)
|
||||||
opt = img.convert("RGB")
|
opt = img.convert("RGB")
|
||||||
buf = io.BytesIO()
|
variants["optimized"] = opt
|
||||||
opt.save(buf, format="JPEG", quality=85)
|
|
||||||
variants["optimized"] = Image.open(buf)
|
|
||||||
|
|
||||||
return variants
|
return variants
|
||||||
|
|
||||||
|
|
||||||
async def process_message(message: aio_pika.IncomingMessage):
|
async def process_message(message: aio_pika.IncomingMessage):
|
||||||
async with message.process():
|
async with message.process():
|
||||||
data = json.loads(message.body)
|
data = json.loads(message.body)
|
||||||
@@ -68,15 +72,12 @@ async def process_message(message: aio_pika.IncomingMessage):
|
|||||||
with conn.cursor() as cur:
|
with conn.cursor() as cur:
|
||||||
for name, var_img in variants.items():
|
for name, var_img in variants.items():
|
||||||
buf = io.BytesIO()
|
buf = io.BytesIO()
|
||||||
|
# Всегда сохраняем как JPEG (так требует контракт)
|
||||||
ct = "image/jpeg"
|
ct = "image/jpeg"
|
||||||
if name == "thumbnail":
|
var_img.save(buf, format="JPEG", quality=85)
|
||||||
var_img.save(buf, format="PNG")
|
|
||||||
ct = "image/png"
|
|
||||||
else:
|
|
||||||
var_img.save(buf, format="JPEG", quality=85)
|
|
||||||
|
|
||||||
var_bytes = buf.getvalue()
|
var_bytes = buf.getvalue()
|
||||||
sha256 = __import__("hashlib").sha256(var_bytes).hexdigest()
|
sha256 = hashlib.sha256(var_bytes).hexdigest()
|
||||||
var_key = f"chats/{att_id}/variants/{name}"
|
var_key = f"chats/{att_id}/variants/{name}"
|
||||||
|
|
||||||
upload_fileobj(io.BytesIO(var_bytes), var_key, ct)
|
upload_fileobj(io.BytesIO(var_bytes), var_key, ct)
|
||||||
@@ -104,13 +105,22 @@ async def process_message(message: aio_pika.IncomingMessage):
|
|||||||
with transaction() as conn:
|
with transaction() as conn:
|
||||||
with conn.cursor() as cur:
|
with conn.cursor() as cur:
|
||||||
cur.execute("UPDATE attachments SET status='failed', error_code=%s, updated_at=now() WHERE id=%s", ("processing_error", att_id))
|
cur.execute("UPDATE attachments SET status='failed', error_code=%s, updated_at=now() WHERE id=%s", ("processing_error", att_id))
|
||||||
raise e # Пробрасываем ошибку, чтобы RabbitMQ не удалил сообщение (at-least-once)
|
raise e
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
async def main():
|
||||||
init_pool()
|
init_pool()
|
||||||
settings = get_settings()
|
settings = get_settings()
|
||||||
|
|
||||||
connection = await aio_pika.connect_robust(settings.broker_url)
|
# Ждем, пока брокер станет доступен
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
connection = await aio_pika.connect_robust(settings.broker_url)
|
||||||
|
break # если подключились - выходим из цикла
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"Broker not ready, waiting 5 seconds... ({e})")
|
||||||
|
await asyncio.sleep(5)
|
||||||
|
|
||||||
async with connection:
|
async with connection:
|
||||||
channel = await connection.channel()
|
channel = await connection.channel()
|
||||||
await channel.set_qos(prefetch_count=1)
|
await channel.set_qos(prefetch_count=1)
|
||||||
@@ -119,5 +129,6 @@ async def main():
|
|||||||
await queue.consume(process_message)
|
await queue.consume(process_message)
|
||||||
await asyncio.Future()
|
await asyncio.Future()
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
asyncio.run(main())
|
asyncio.run(main())
|
||||||
Reference in New Issue
Block a user