forked from mtusi2026/mtusi2026lab6
Перенести и адаптировать базу лабораторной 5 для отдельного стенда 6
This commit is contained in:
+166
@@ -0,0 +1,166 @@
|
||||
import uuid
|
||||
import os
|
||||
import socket
|
||||
from contextlib import asynccontextmanager
|
||||
import psycopg
|
||||
from psycopg_pool import PoolTimeout, TooManyRequests
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import ValidationError as PydanticValidationError
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from src.models import ErrorResponse
|
||||
from src.routes import chats, health, messages, users, attachments
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from src.storage import storage
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
"""Создать и настроить приложение FastAPI."""
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
await run_in_threadpool(storage.pool.open, wait=True)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
await run_in_threadpool(storage.pool.close)
|
||||
|
||||
instance_id = os.getenv("INSTANCE_ID", socket.gethostname()) + "-" + uuid.uuid4().hex[:8]
|
||||
app = FastAPI(title="MTUSI Messenger Lab6", version="1.6.0", lifespan=lifespan)
|
||||
|
||||
@app.exception_handler(BotoCoreError)
|
||||
@app.exception_handler(ClientError)
|
||||
@app.exception_handler(psycopg.OperationalError)
|
||||
@app.exception_handler(psycopg.errors.QueryCanceled)
|
||||
@app.exception_handler(psycopg.errors.LockNotAvailable)
|
||||
@app.exception_handler(PoolTimeout)
|
||||
@app.exception_handler(TooManyRequests)
|
||||
async def dependency_error(request, exc):
|
||||
return JSONResponse(status_code=503, content=ErrorResponse(error={
|
||||
"code": "unavailable", "message": "хранилище временно недоступно",
|
||||
"request_id": request.state.request_id}).model_dump(),
|
||||
headers={"X-Request-Id": request.state.request_id})
|
||||
|
||||
@app.middleware("http")
|
||||
async def add_request_id(request: Request, call_next):
|
||||
"""Добавляет идентификаторы запроса и процесса, ограничивает очередь."""
|
||||
request_id = request.headers.get("X-Request-Id", "") or str(uuid.uuid4())
|
||||
request.state.request_id = request_id
|
||||
|
||||
# Ограничение числа обслуживаемых запросов в процессе.
|
||||
if not storage.acquire_request_slot():
|
||||
return JSONResponse(
|
||||
status_code=503,
|
||||
content=ErrorResponse(
|
||||
error={
|
||||
"code": "unavailable",
|
||||
"message": "сервер перегружен, попробуйте позже",
|
||||
"request_id": request_id,
|
||||
}
|
||||
).model_dump(),
|
||||
headers={"X-Request-Id": request_id, "X-Instance-Id": instance_id},
|
||||
)
|
||||
|
||||
try:
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
response.headers["X-Instance-Id"] = instance_id
|
||||
return response
|
||||
finally:
|
||||
storage.release_request_slot()
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
|
||||
"""Обработчик HTTPException: возвращает ошибку в формате контракта {"error": ...}."""
|
||||
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
||||
if isinstance(exc.detail, dict) and "error" in exc.detail:
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content=exc.detail,
|
||||
headers={"X-Request-Id": request_id, **(exc.headers or {})},
|
||||
)
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content=ErrorResponse(
|
||||
error={
|
||||
"code": "internal_error",
|
||||
"message": str(exc.detail),
|
||||
"request_id": request_id,
|
||||
}
|
||||
).model_dump(),
|
||||
headers={"X-Request-Id": request_id, "X-Instance-Id": instance_id},
|
||||
)
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def request_validation_handler(request: Request, exc: RequestValidationError):
|
||||
"""Перехватываем ошибки валидации запроса (422 -> 400 по контракту)."""
|
||||
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
||||
errors = exc.errors()
|
||||
messages = []
|
||||
for err in errors:
|
||||
loc = ".".join(str(x) for x in err.get("loc", []))
|
||||
messages.append(f"{loc}: {err.get('msg', 'invalid')}")
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content=ErrorResponse(
|
||||
error={
|
||||
"code": "invalid_request",
|
||||
"message": "; ".join(messages),
|
||||
"request_id": request_id,
|
||||
}
|
||||
).model_dump(),
|
||||
headers={"X-Request-Id": request_id, "X-Instance-Id": instance_id},
|
||||
)
|
||||
|
||||
@app.exception_handler(PydanticValidationError)
|
||||
async def validation_exception_handler(request: Request, exc: PydanticValidationError):
|
||||
"""Перехватываем ошибки Pydantic (422 -> 400 по контракту)."""
|
||||
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
||||
errors = exc.errors()
|
||||
messages = []
|
||||
for err in errors:
|
||||
loc = ".".join(str(x) for x in err.get("loc", []))
|
||||
messages.append(f"{loc}: {err.get('msg', 'invalid')}")
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content=ErrorResponse(
|
||||
error={
|
||||
"code": "invalid_request",
|
||||
"message": "; ".join(messages),
|
||||
"request_id": request_id,
|
||||
}
|
||||
).model_dump(),
|
||||
headers={"X-Request-Id": request_id, "X-Instance-Id": instance_id},
|
||||
)
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def generic_exception_handler(request: Request, exc: Exception):
|
||||
"""Обработчик непредвиденных исключений: скрываем детали, возвращаем 500."""
|
||||
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content=ErrorResponse(
|
||||
error={
|
||||
"code": "internal_error",
|
||||
"message": "внутренняя ошибка сервера",
|
||||
"request_id": request_id,
|
||||
}
|
||||
).model_dump(),
|
||||
headers={"X-Request-Id": request_id, "X-Instance-Id": instance_id},
|
||||
)
|
||||
|
||||
# Подключаем роуты
|
||||
app.include_router(health.router)
|
||||
app.include_router(users.router)
|
||||
app.include_router(chats.router)
|
||||
app.include_router(messages.router)
|
||||
app.include_router(attachments.router)
|
||||
|
||||
return app
|
||||
|
||||
|
||||
# Экземпляр приложения для uvicorn
|
||||
app = create_app()
|
||||
@@ -0,0 +1,36 @@
|
||||
"""RabbitMQ с подтверждаемой публикацией и ручным ack."""
|
||||
|
||||
import json
|
||||
from contextlib import contextmanager
|
||||
|
||||
import pika
|
||||
|
||||
from src.config import setting
|
||||
|
||||
QUEUE = 'attachment.process.v1'
|
||||
|
||||
|
||||
@contextmanager
|
||||
def channel(heartbeat=90):
|
||||
params = pika.URLParameters(setting('BROKER_URL'))
|
||||
params.heartbeat = heartbeat
|
||||
params.socket_timeout = 4
|
||||
params.stack_timeout = 6
|
||||
params.blocked_connection_timeout = 5
|
||||
connection = pika.BlockingConnection(params)
|
||||
try:
|
||||
result = connection.channel()
|
||||
result.queue_declare(queue=QUEUE, durable=True)
|
||||
yield connection, result
|
||||
finally:
|
||||
if connection.is_open:
|
||||
connection.close()
|
||||
|
||||
|
||||
def publish(ch, message):
|
||||
ch.basic_publish(
|
||||
exchange='', routing_key=QUEUE, body=json.dumps(message, separators=(',', ':')).encode(),
|
||||
properties=pika.BasicProperties(content_type='application/json', delivery_mode=2,
|
||||
message_id=message['job_id']),
|
||||
mandatory=True,
|
||||
)
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Необязательный кэш неизменяемого публичного профиля; ошибки обходятся через БД."""
|
||||
import logging
|
||||
import os
|
||||
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeout
|
||||
import threading
|
||||
from redis import Redis, RedisError
|
||||
from pydantic import ValidationError
|
||||
from src.config import setting
|
||||
from src.models import User
|
||||
|
||||
|
||||
class ProfileCache:
|
||||
def __init__(self):
|
||||
url = setting('CACHE_URL')
|
||||
self.client = Redis.from_url(url, decode_responses=True, socket_connect_timeout=0.2,
|
||||
socket_timeout=0.2, max_connections=16) if url else None
|
||||
self.ttl = int(os.getenv('PROFILE_CACHE_TTL_SECONDS','60'))
|
||||
self.hits = self.misses = self.errors = 0
|
||||
# DNS может ждать дольше socket timeout; один фоновый вызов ограничивает и время, и очередь.
|
||||
self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix='profile-cache')
|
||||
self._pending = None
|
||||
self._guard = threading.Lock()
|
||||
|
||||
def _bounded(self, action, *args, **kwargs):
|
||||
with self._guard:
|
||||
if self._pending is not None and not self._pending.done():
|
||||
raise RedisError('кэш занят')
|
||||
self._pending = self._executor.submit(action, *args, **kwargs)
|
||||
future = self._pending
|
||||
try:
|
||||
return future.result(timeout=0.25)
|
||||
except FutureTimeout:
|
||||
raise RedisError('истекло время ожидания кэша') from None
|
||||
|
||||
def get(self, user_id):
|
||||
if not self.client:
|
||||
return None
|
||||
try:
|
||||
value = self._bounded(self.client.get, 'profile:v1:'+user_id)
|
||||
if value:
|
||||
user=User.model_validate_json(value)
|
||||
if user.id != user_id:
|
||||
raise ValueError('неверный ключ кэша')
|
||||
self.hits += 1
|
||||
return user
|
||||
self.misses += 1
|
||||
except (RedisError, ValidationError, ValueError):
|
||||
self.errors += 1
|
||||
logging.getLogger(__name__).warning('Кэш профиля недоступен; чтение из PostgreSQL')
|
||||
return None
|
||||
|
||||
def put(self, user):
|
||||
if self.client:
|
||||
try:
|
||||
self._bounded(self.client.set, 'profile:v1:'+user.id,user.model_dump_json(),ex=self.ttl)
|
||||
except RedisError:
|
||||
self.errors += 1
|
||||
|
||||
|
||||
profile_cache = ProfileCache()
|
||||
@@ -0,0 +1,10 @@
|
||||
"""Настройки окружения и чтение секретов из файлов."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def setting(name, default=None):
|
||||
path = os.getenv(name + '_FILE')
|
||||
if path:
|
||||
return Path(path).read_text(encoding='utf-8').strip()
|
||||
return os.getenv(name, default)
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Отдельный relay: lease публикации, publisher confirm, восстановление jobs."""
|
||||
|
||||
import logging
|
||||
import signal
|
||||
import threading
|
||||
import time
|
||||
|
||||
import pika
|
||||
import psycopg
|
||||
from psycopg_pool import PoolTimeout
|
||||
|
||||
from src import broker, jobs, faults
|
||||
from src.storage import storage
|
||||
|
||||
|
||||
def main():
|
||||
logging.basicConfig(level=logging.WARNING)
|
||||
stopping = threading.Event()
|
||||
for sig in (signal.SIGINT, signal.SIGTERM):
|
||||
signal.signal(sig, lambda *_: stopping.set())
|
||||
storage.pool.open(wait=True)
|
||||
next_recovery = 0.0
|
||||
try:
|
||||
while not stopping.is_set():
|
||||
reserved = None
|
||||
try:
|
||||
with broker.channel(heartbeat=10) as (connection, channel):
|
||||
channel.confirm_delivery()
|
||||
while not stopping.is_set():
|
||||
if time.monotonic() >= next_recovery:
|
||||
jobs.recover_expired()
|
||||
next_recovery = time.monotonic() + 1
|
||||
reserved = jobs.reserve_publish()
|
||||
if reserved:
|
||||
faults.hit('before_publish', reserved)
|
||||
broker.publish(channel, jobs.envelope(reserved))
|
||||
faults.hit('after_publish', reserved)
|
||||
jobs.confirm_publish(reserved)
|
||||
reserved = None
|
||||
else:
|
||||
connection.process_data_events(time_limit=0.2)
|
||||
except (pika.exceptions.AMQPError, OSError, psycopg.Error, PoolTimeout) as exc:
|
||||
logging.warning('dispatch temporarily unavailable: %s', type(exc).__name__)
|
||||
if reserved:
|
||||
try:
|
||||
jobs.publish_failed(reserved)
|
||||
except (psycopg.Error, PoolTimeout):
|
||||
pass # expires through the durable publication deadline
|
||||
stopping.wait(1)
|
||||
finally:
|
||||
storage.pool.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Одноразовые точки отказа. Выключены без LAB5_FAULT_INJECTION=1."""
|
||||
import os
|
||||
import time
|
||||
|
||||
from src.storage import storage
|
||||
|
||||
|
||||
def hit(point, job):
|
||||
if os.getenv('LAB5_FAULT_INJECTION') != '1':
|
||||
return
|
||||
with storage.pool.connection() as conn:
|
||||
fault = conn.execute(
|
||||
"UPDATE experiment_faults SET hit_at=clock_timestamp(), process_id=%s "
|
||||
"WHERE job_id=%s AND point=%s AND hit_at IS NULL RETURNING action",
|
||||
(os.getpid(), job['id'], point),
|
||||
).fetchone()
|
||||
if not fault:
|
||||
return
|
||||
if fault['action'] == 'crash':
|
||||
os._exit(91) # Реальная смерть процесса без finally/ack.
|
||||
while True:
|
||||
with storage.pool.connection() as conn:
|
||||
released = conn.execute(
|
||||
'SELECT released FROM experiment_faults WHERE job_id=%s AND point=%s',
|
||||
(job['id'], point),
|
||||
).fetchone()['released']
|
||||
if released:
|
||||
return
|
||||
time.sleep(0.1)
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Преобразования Pillow в отдельном процессе с жёстким таймаутом родителя."""
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
from src.pipeline_versions import ENCODING
|
||||
|
||||
Image.MAX_IMAGE_PIXELS = 40_000_000
|
||||
|
||||
|
||||
def fit(image, limit):
|
||||
width, height = image.size
|
||||
longest = max(width, height)
|
||||
if longest <= limit:
|
||||
return image
|
||||
size = (max(1, width * limit // longest), max(1, height * limit // longest))
|
||||
return image.resize(size, Image.Resampling.LANCZOS)
|
||||
|
||||
|
||||
def render(source, target, version=1):
|
||||
jpeg_quality, webp_quality = ENCODING[version]
|
||||
with Image.open(source) as opened:
|
||||
if opened.width * opened.height > Image.MAX_IMAGE_PIXELS:
|
||||
raise ValueError('pixel limit')
|
||||
image = ImageOps.exif_transpose(opened)
|
||||
if 'A' in image.getbands() or 'transparency' in image.info:
|
||||
rgba = image.convert('RGBA')
|
||||
rgb = Image.new('RGB', rgba.size, 'white')
|
||||
rgb.paste(rgba, mask=rgba.getchannel('A'))
|
||||
else:
|
||||
rgb = image.convert('RGB')
|
||||
rgb.info.clear()
|
||||
del image
|
||||
thumbnail = fit(rgb, 256)
|
||||
thumbnail.save(target / 'thumbnail', 'JPEG', quality=jpeg_quality)
|
||||
crop = ImageOps.fit(rgb, (128, 128), Image.Resampling.LANCZOS)
|
||||
crop.save(target / 'crop', 'JPEG', quality=jpeg_quality)
|
||||
optimized = fit(rgb, 1280)
|
||||
optimized.save(target / 'optimized', 'WEBP', quality=webp_quality, method=4)
|
||||
return [
|
||||
['thumbnail', 'image/jpeg', *thumbnail.size],
|
||||
['crop', 'image/jpeg', *crop.size],
|
||||
['optimized', 'image/webp', *optimized.size],
|
||||
]
|
||||
|
||||
|
||||
def main():
|
||||
directory = Path(sys.argv[1])
|
||||
try:
|
||||
result = render(directory / 'original', directory, int(sys.argv[2]))
|
||||
except (OSError, ValueError, SyntaxError, Image.DecompressionBombError):
|
||||
return 2
|
||||
(directory / 'manifest.json').write_text(json.dumps(result), encoding='utf-8')
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
+238
@@ -0,0 +1,238 @@
|
||||
"""Устойчивое намерение обработки, lease и атомарная публикация manifest."""
|
||||
|
||||
import random
|
||||
import re
|
||||
from datetime import datetime
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from src.config import setting
|
||||
from src.objects import BUCKET, client, object_lock
|
||||
from src.pipeline_versions import ENCODING
|
||||
from src.storage import storage, timestamp
|
||||
|
||||
JOB_TIMEOUT = int(setting('JOB_TIMEOUT_SECONDS', '60'))
|
||||
LEASE_SECONDS = max(JOB_TIMEOUT + 5, int(setting('JOB_LEASE_SECONDS', str(JOB_TIMEOUT + 30))))
|
||||
|
||||
|
||||
def envelope(job):
|
||||
return {
|
||||
'schema_version': 1,
|
||||
'job_id': str(job['id']),
|
||||
'type': 'attachment.process.v1',
|
||||
'attachment_id': str(job['attachment_id']),
|
||||
'pipeline_version': job['pipeline_version'],
|
||||
'attempt': job['attempt'],
|
||||
'created_at': timestamp(job['created_at']),
|
||||
}
|
||||
|
||||
|
||||
def validate(message):
|
||||
required = {'schema_version', 'job_id', 'type', 'attachment_id', 'pipeline_version', 'attempt', 'created_at'}
|
||||
if not isinstance(message, dict) or not required <= message.keys() <= required | {'traceparent', 'tracestate'}:
|
||||
raise ValueError('invalid fields')
|
||||
if (type(message['schema_version']) is not int or message['schema_version'] != 1
|
||||
or message['type'] != 'attachment.process.v1'
|
||||
or type(message['pipeline_version']) is not int or message['pipeline_version'] not in ENCODING
|
||||
or type(message['attempt']) is not int or message['attempt'] < 1):
|
||||
raise ValueError('invalid job')
|
||||
UUID(message['job_id'])
|
||||
UUID(message['attachment_id'])
|
||||
if datetime.fromisoformat(message['created_at'].replace('Z', '+00:00')).tzinfo is None:
|
||||
raise ValueError('missing timezone')
|
||||
if 'traceparent' in message and not re.fullmatch(r'00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}',
|
||||
message['traceparent']):
|
||||
raise ValueError('invalid traceparent')
|
||||
if 'tracestate' in message and (not isinstance(message['tracestate'], str) or len(message['tracestate']) > 512):
|
||||
raise ValueError('invalid tracestate')
|
||||
return {key: message[key] for key in required}
|
||||
|
||||
|
||||
def reserve_publish():
|
||||
with storage.pool.connection() as conn:
|
||||
return conn.execute(
|
||||
"""WITH candidate AS (
|
||||
SELECT id FROM attachment_jobs WHERE state='queued'
|
||||
AND next_publish_at <= clock_timestamp()
|
||||
ORDER BY next_publish_at, id LIMIT 1 FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
UPDATE attachment_jobs j
|
||||
SET next_publish_at=clock_timestamp()+interval '15 seconds'
|
||||
FROM candidate WHERE j.id=candidate.id RETURNING j.*"""
|
||||
).fetchone()
|
||||
|
||||
|
||||
def confirm_publish(job):
|
||||
with storage.pool.connection() as conn:
|
||||
conn.execute(
|
||||
"""UPDATE attachment_jobs SET next_publish_at=NULL, published_at=clock_timestamp(),
|
||||
publish_failures=0 WHERE id=%s AND attempt=%s""",
|
||||
(job['id'], job['attempt']),
|
||||
)
|
||||
|
||||
|
||||
def publish_failed(job):
|
||||
with storage.pool.connection() as conn:
|
||||
conn.execute(
|
||||
"""UPDATE attachment_jobs SET publish_failures=publish_failures+1,
|
||||
next_publish_at=clock_timestamp()+%s * interval '1 second'
|
||||
WHERE id=%s AND attempt=%s AND state='queued' AND next_publish_at IS NOT NULL""",
|
||||
(delay(job['publish_failures'] + 1), job['id'], job['attempt']),
|
||||
)
|
||||
|
||||
|
||||
def locked_job(conn, job_id, attachment_id):
|
||||
attachment = conn.execute('SELECT * FROM attachments WHERE id=%s FOR UPDATE',
|
||||
(attachment_id,)).fetchone()
|
||||
if not attachment:
|
||||
return None, None
|
||||
job = conn.execute('SELECT * FROM attachment_jobs WHERE id=%s AND attachment_id=%s FOR UPDATE',
|
||||
(job_id, attachment_id)).fetchone()
|
||||
return job, attachment
|
||||
|
||||
|
||||
def claim(message):
|
||||
with storage.pool.connection() as conn:
|
||||
job, attachment = locked_job(conn, message['job_id'], message['attachment_id'])
|
||||
if (not job or envelope(job) != message or job['state'] != 'queued'
|
||||
or job['pipeline_version'] != attachment['target_pipeline_version']):
|
||||
return None
|
||||
token = uuid4()
|
||||
conn.execute(
|
||||
"""UPDATE attachment_jobs SET state='processing', lease_token=%s,
|
||||
lease_until=clock_timestamp()+%s * interval '1 second', next_publish_at=NULL
|
||||
WHERE id=%s""", (token, LEASE_SECONDS, job['id']),
|
||||
)
|
||||
conn.execute("UPDATE attachments SET state='processing',updated_at=clock_timestamp() "
|
||||
"WHERE id=%s AND published_pipeline_version IS NULL",
|
||||
(job['attachment_id'],))
|
||||
return job | {'lease_token': token, 'attachment': attachment}
|
||||
|
||||
|
||||
def owns(conn, job, claimed):
|
||||
return (
|
||||
job and (job['state'], job['lease_token']) == ('processing', claimed['lease_token'])
|
||||
and conn.execute('SELECT clock_timestamp() < %s AS active', (job['lease_until'],)).fetchone()['active']
|
||||
)
|
||||
|
||||
|
||||
def complete(claimed, variants):
|
||||
with storage.pool.connection() as conn:
|
||||
job, attachment = locked_job(conn, claimed['id'], claimed['attachment_id'])
|
||||
if not owns(conn, job, claimed) or job['pipeline_version'] != attachment['target_pipeline_version']:
|
||||
return False
|
||||
for variant in variants:
|
||||
conn.execute(
|
||||
"""INSERT INTO attachment_variants
|
||||
(attachment_id,pipeline_version,name,object_key,content_type,size_bytes,sha256,width,height)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
|
||||
(job['attachment_id'], job['pipeline_version'], *variant),
|
||||
)
|
||||
conn.execute("UPDATE attachments SET state='ready',published_pipeline_version=%s,"
|
||||
"updated_at=clock_timestamp(),error_code=NULL WHERE id=%s",
|
||||
(job['pipeline_version'], job['attachment_id']))
|
||||
conn.execute("UPDATE attachment_jobs SET state='ready',lease_token=NULL,lease_until=NULL,"
|
||||
"last_error=NULL,settled_at=clock_timestamp() WHERE id=%s", (job['id'],))
|
||||
return True
|
||||
|
||||
|
||||
def delay(attempt):
|
||||
return min(30, 2 ** min(attempt - 1, 5)) * random.uniform(0.75, 1.25)
|
||||
|
||||
|
||||
def settle_error(conn, job, code, permanent=False):
|
||||
exhausted = job['attempt'] >= job['attempt_limit']
|
||||
if permanent or exhausted:
|
||||
error = code if permanent else 'retry_exhausted'
|
||||
conn.execute("UPDATE attachments SET state='failed',error_code=%s,updated_at=clock_timestamp() "
|
||||
"WHERE id=%s AND published_pipeline_version IS NULL", (error, job['attachment_id']))
|
||||
conn.execute("UPDATE attachment_jobs SET state='failed',lease_token=NULL,lease_until=NULL,"
|
||||
"last_error=%s,next_publish_at=NULL,settled_at=clock_timestamp() WHERE id=%s",
|
||||
(code, job['id']))
|
||||
return
|
||||
conn.execute("UPDATE attachments SET state='queued',updated_at=clock_timestamp() "
|
||||
"WHERE id=%s AND published_pipeline_version IS NULL",
|
||||
(job['attachment_id'],))
|
||||
conn.execute("""UPDATE attachment_jobs SET state='queued',lease_token=NULL,lease_until=NULL,
|
||||
last_error=%s,attempt=attempt+1,published_at=NULL,
|
||||
next_publish_at=clock_timestamp()+%s*interval '1 second' WHERE id=%s""",
|
||||
(code, delay(job['attempt']), job['id']))
|
||||
|
||||
|
||||
def fail(claimed, code, permanent=False):
|
||||
with storage.pool.connection() as conn:
|
||||
job, _ = locked_job(conn, claimed['id'], claimed['attachment_id'])
|
||||
if owns(conn, job, claimed):
|
||||
settle_error(conn, job, code, permanent)
|
||||
|
||||
|
||||
def recover_expired():
|
||||
with storage.pool.connection() as conn:
|
||||
expired = conn.execute("SELECT id,attachment_id FROM attachment_jobs "
|
||||
"WHERE lease_until <= clock_timestamp() ORDER BY lease_until LIMIT 16").fetchall()
|
||||
for candidate in expired:
|
||||
with storage.pool.connection() as conn:
|
||||
job, _ = locked_job(conn, candidate['id'], candidate['attachment_id'])
|
||||
if (job and job['state'] == 'processing'
|
||||
and not owns(conn, job, job)):
|
||||
settle_error(conn, job, 'lease_expired')
|
||||
|
||||
|
||||
def replay(attachment_id):
|
||||
with storage.pool.connection() as conn:
|
||||
attachment = conn.execute('SELECT * FROM attachments WHERE id=%s FOR UPDATE',
|
||||
(attachment_id,)).fetchone()
|
||||
if not attachment:
|
||||
return None
|
||||
job = conn.execute('SELECT * FROM attachment_jobs WHERE attachment_id=%s AND pipeline_version=%s FOR UPDATE',
|
||||
(attachment_id, attachment['target_pipeline_version'])).fetchone()
|
||||
if not job or job['state'] != 'failed':
|
||||
return None
|
||||
source = attachment['object_key'] if attachment['published_pipeline_version'] else job['staging_key']
|
||||
object_lock(conn, source)
|
||||
client().head_object(Bucket=BUCKET, Key=source)
|
||||
new_attempt = job['attempt'] + 1
|
||||
budget = int(setting('JOB_MAX_ATTEMPTS', '5'))
|
||||
conn.execute(
|
||||
"""UPDATE attachment_jobs SET state='queued', attempt=%s, attempt_limit=%s,
|
||||
next_publish_at=clock_timestamp(), published_at=NULL, publish_failures=0, settled_at=NULL
|
||||
WHERE id=%s""", (new_attempt, new_attempt + budget - 1, job['id']),
|
||||
)
|
||||
conn.execute("INSERT INTO attachment_replays(job_id,attempt,reason) VALUES (%s,%s,'operator')",
|
||||
(job['id'], new_attempt))
|
||||
conn.execute("UPDATE attachments SET state='queued',error_code=NULL,updated_at=clock_timestamp() "
|
||||
"WHERE id=%s AND published_pipeline_version IS NULL", (attachment_id,))
|
||||
return job['id'], new_attempt
|
||||
|
||||
|
||||
def upgrade(attachment_id, version):
|
||||
with storage.pool.connection() as conn:
|
||||
attachment = conn.execute('SELECT * FROM attachments WHERE id=%s FOR UPDATE', (attachment_id,)).fetchone()
|
||||
if not attachment or version not in ENCODING or version <= attachment['target_pipeline_version']:
|
||||
return None
|
||||
previous = conn.execute(
|
||||
'SELECT staging_key FROM attachment_jobs WHERE attachment_id=%s AND pipeline_version=%s',
|
||||
(attachment_id, attachment['target_pipeline_version']),
|
||||
).fetchone()
|
||||
if not previous and not attachment['published_pipeline_version']:
|
||||
return None
|
||||
source = attachment['object_key'] if attachment['published_pipeline_version'] else previous['staging_key']
|
||||
object_lock(conn, source)
|
||||
client().head_object(Bucket=BUCKET, Key=source)
|
||||
conn.execute(
|
||||
"""UPDATE attachment_jobs SET state='superseded', lease_token=NULL, lease_until=NULL,
|
||||
next_publish_at=NULL, settled_at=clock_timestamp()
|
||||
WHERE attachment_id=%s AND state IN ('queued','processing')""", (attachment_id,),
|
||||
)
|
||||
conn.execute(
|
||||
"""UPDATE attachments SET target_pipeline_version=%s,
|
||||
state=CASE WHEN published_pipeline_version IS NULL THEN 'queued' ELSE 'ready' END,
|
||||
error_code=NULL,updated_at=clock_timestamp() WHERE id=%s""",
|
||||
(version, attachment_id),
|
||||
)
|
||||
job_id = uuid4()
|
||||
conn.execute(
|
||||
"""INSERT INTO attachment_jobs(id,attachment_id,staging_key,attempt_limit,next_publish_at,pipeline_version)
|
||||
VALUES (%s,%s,%s,%s,clock_timestamp(),%s)""",
|
||||
(job_id, attachment_id, f'staging/{attachment_id}', int(setting('JOB_MAX_ATTEMPTS', '5')), version),
|
||||
)
|
||||
return job_id
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Версионируемые миграции: одна транзакция, блокировка от параллельного запуска."""
|
||||
from pathlib import Path
|
||||
import psycopg
|
||||
from src.config import setting
|
||||
|
||||
|
||||
def main():
|
||||
with psycopg.connect(setting('DATABASE_URL'), connect_timeout=5) as conn:
|
||||
conn.execute('SELECT pg_advisory_xact_lock(2301002)')
|
||||
conn.execute('CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY)')
|
||||
for path in sorted(Path('/app/migrations' if Path('/app/migrations').exists() else 'migrations').glob('*.sql')):
|
||||
if not conn.execute('SELECT 1 FROM schema_migrations WHERE version=%s', (path.name,)).fetchone():
|
||||
conn.execute(path.read_text(encoding='utf-8'))
|
||||
conn.execute('INSERT INTO schema_migrations VALUES (%s)', (path.name,))
|
||||
print('Применена миграция:', path.name)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
import uuid
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
|
||||
def utc_now() -> str:
|
||||
"""Возвращает текущее время в формате RFC 3339 UTC с суффиксом Z."""
|
||||
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
class ErrorDetail(BaseModel):
|
||||
"""Детали ошибки API."""
|
||||
code: str
|
||||
message: str
|
||||
request_id: str
|
||||
|
||||
|
||||
class ErrorResponse(BaseModel):
|
||||
"""Стандартный ответ об ошибке."""
|
||||
error: ErrorDetail
|
||||
|
||||
|
||||
class Health(BaseModel):
|
||||
"""Ответ проверки работоспособности."""
|
||||
status: str = "ok"
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
"""Модель пользователя."""
|
||||
id: str
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: str
|
||||
|
||||
|
||||
class CreateUser(BaseModel):
|
||||
"""Данные для создания пользователя."""
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
password: str = Field(..., min_length=12, max_length=128)
|
||||
username: str = Field(..., pattern=r"^[a-z0-9_]{3,32}$")
|
||||
display_name: str = Field(..., min_length=1, max_length=100)
|
||||
|
||||
@field_validator("display_name")
|
||||
@classmethod
|
||||
def display_name_not_whitespace_only(cls, v: str) -> str:
|
||||
"""Запрещаем display_name, состоящий только из пробельных символов."""
|
||||
if v.strip() == "":
|
||||
raise ValueError("display_name не может состоять только из пробелов")
|
||||
return v
|
||||
|
||||
|
||||
class Chat(BaseModel):
|
||||
"""Модель чата."""
|
||||
id: str
|
||||
title: str
|
||||
member_ids: list[str]
|
||||
created_at: str
|
||||
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
"""Данные для создания чата."""
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
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 valid_members(cls, values):
|
||||
"""Проверить UUID и привести их к единому представлению."""
|
||||
return [str(uuid.UUID(value)) for value in values]
|
||||
|
||||
@field_validator("title")
|
||||
@classmethod
|
||||
def title_not_whitespace_only(cls, v: str) -> str:
|
||||
"""Запрещаем title, состоящий только из пробельных символов."""
|
||||
if v.strip() == "":
|
||||
raise ValueError("title не может состоять только из пробелов")
|
||||
return v
|
||||
|
||||
|
||||
class Message(BaseModel):
|
||||
"""Модель сообщения."""
|
||||
id: str
|
||||
chat_id: str
|
||||
sender_id: str
|
||||
text: str
|
||||
created_at: str
|
||||
attachment_ids: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
"""Данные для отправки сообщения."""
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
text: str = Field(..., max_length=4000)
|
||||
attachment_ids: list[str] = Field(default_factory=list, max_length=10)
|
||||
|
||||
@field_validator('attachment_ids')
|
||||
@classmethod
|
||||
def valid_attachments(cls, values):
|
||||
ids = [str(uuid.UUID(v)) for v in values]
|
||||
if len(set(ids)) != len(ids):
|
||||
raise ValueError('duplicate attachment_id')
|
||||
return ids
|
||||
|
||||
@model_validator(mode='after')
|
||||
def valid_content(self):
|
||||
if not self.text.strip() and not self.attachment_ids:
|
||||
raise ValueError('empty message')
|
||||
return self
|
||||
|
||||
|
||||
class ChatPage(BaseModel):
|
||||
"""Страница списка чатов с курсорной пагинацией."""
|
||||
items: list[Chat]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
|
||||
class MessagePage(BaseModel):
|
||||
"""Страница истории сообщений с курсорной пагинацией."""
|
||||
items: list[Message]
|
||||
next_cursor: Optional[str] = None
|
||||
@@ -0,0 +1,36 @@
|
||||
"""S3 operations with bounded timeouts and immutable server-generated keys."""
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import ClientError
|
||||
from src.config import setting
|
||||
|
||||
def client():
|
||||
return boto3.client('s3', endpoint_url=setting('S3_ENDPOINT','http://s3:9000'),
|
||||
aws_access_key_id=setting('S3_ACCESS_KEY'), aws_secret_access_key=setting('S3_SECRET_KEY'),
|
||||
region_name='us-east-1', config=Config(connect_timeout=2,read_timeout=5,
|
||||
retries={'total_max_attempts':1},s3={'addressing_style':'path'}))
|
||||
|
||||
BUCKET = setting('S3_BUCKET','attachments')
|
||||
|
||||
|
||||
class ObjectConflict(Exception):
|
||||
"""Неизменяемый ключ уже содержит другие данные."""
|
||||
|
||||
|
||||
def put_immutable(s3, key, stream, size, content_type, digest):
|
||||
try:
|
||||
s3.put_object(Bucket=BUCKET, Key=key, Body=stream, ContentLength=size,
|
||||
ContentType=content_type, Metadata={'sha256': digest}, IfNoneMatch='*')
|
||||
except ClientError as exc:
|
||||
if exc.response['ResponseMetadata']['HTTPStatusCode'] != 412:
|
||||
raise
|
||||
existing = s3.head_object(Bucket=BUCKET, Key=key)
|
||||
if (existing['ContentLength'], existing['ContentType'], existing['Metadata'].get('sha256')) != (
|
||||
size, content_type, digest):
|
||||
raise ObjectConflict(key) from None
|
||||
|
||||
|
||||
def object_lock(conn, key, wait=True):
|
||||
fn = 'pg_advisory_xact_lock' if wait else 'pg_try_advisory_xact_lock'
|
||||
row = conn.execute('SELECT '+fn+'(hashtextextended(%s,42)) AS locked',(key,)).fetchone()
|
||||
return wait or row['locked']
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Локальные операции над реестром заданий."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from uuid import UUID
|
||||
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
|
||||
from src import jobs
|
||||
from src.storage import storage, timestamp
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('action', choices=('failed', 'replay', 'upgrade'))
|
||||
parser.add_argument('attachment_id', type=UUID, nargs='?')
|
||||
parser.add_argument('--version', type=int, default=2)
|
||||
args = parser.parse_args()
|
||||
if args.action in ('replay', 'upgrade') and args.attachment_id is None:
|
||||
parser.error('operation requires attachment_id')
|
||||
storage.pool.open(wait=True)
|
||||
try:
|
||||
if args.action in ('replay', 'upgrade'):
|
||||
try:
|
||||
if args.action == 'replay':
|
||||
result = jobs.replay(args.attachment_id)
|
||||
else:
|
||||
job_id = jobs.upgrade(args.attachment_id, args.version)
|
||||
result = (job_id, 1) if job_id else None
|
||||
except (BotoCoreError, ClientError):
|
||||
raise SystemExit('Источник обработки недоступен') from None
|
||||
if result is None:
|
||||
raise SystemExit('Операция неприменима к текущему состоянию или версии')
|
||||
print(json.dumps({'job_id': str(result[0]), 'attempt': result[1]}))
|
||||
else:
|
||||
with storage.pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"""SELECT id, attachment_id, pipeline_version, attempt, last_error, settled_at
|
||||
FROM attachment_jobs WHERE state='failed' ORDER BY settled_at DESC NULLS LAST LIMIT 100"""
|
||||
).fetchall()
|
||||
print(json.dumps(rows, default=lambda value: str(value) if isinstance(value, UUID) else timestamp(value)))
|
||||
finally:
|
||||
storage.pool.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,6 @@
|
||||
"""Версии преобразований и операция перехода на следующий manifest."""
|
||||
|
||||
ENCODING = {
|
||||
1: (85, 82),
|
||||
2: (90, 88),
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Bounded synchronous image uploads; one decode per process."""
|
||||
import asyncio
|
||||
import hashlib
|
||||
import tempfile
|
||||
import unicodedata
|
||||
import uuid
|
||||
import warnings
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from starlette.responses import StreamingResponse
|
||||
from starlette.requests import ClientDisconnect
|
||||
from src.routes.common import require_user, make_error, get_request_id
|
||||
from src.storage import storage, timestamp
|
||||
from src.objects import client, BUCKET, object_lock, put_immutable
|
||||
from src.config import setting
|
||||
|
||||
router = APIRouter()
|
||||
slots = asyncio.Semaphore(1)
|
||||
MAX_BYTES=10*1024*1024
|
||||
Image.MAX_IMAGE_PIXELS=40_000_000
|
||||
|
||||
class InvalidImage(Exception):
|
||||
def __init__(self,status):
|
||||
self.status=status
|
||||
|
||||
def error(request, status, code, message):
|
||||
return HTTPException(status, detail=make_error(code,message,get_request_id(request)).model_dump())
|
||||
|
||||
def inspect_image(stream, declared):
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter('error', Image.DecompressionBombWarning)
|
||||
with Image.open(stream) as image:
|
||||
if image.width*image.height>40_000_000:
|
||||
raise InvalidImage(413)
|
||||
actual={'PNG':'image/png','JPEG':'image/jpeg'}.get(image.format)
|
||||
if not actual or actual != declared:
|
||||
raise InvalidImage(415)
|
||||
image.verify()
|
||||
stream.seek(0)
|
||||
with Image.open(stream) as image:
|
||||
image.load()
|
||||
except (Image.DecompressionBombError,Image.DecompressionBombWarning):
|
||||
raise InvalidImage(413) from None
|
||||
except (UnidentifiedImageError,OSError,SyntaxError,ValueError):
|
||||
raise InvalidImage(415) from None
|
||||
finally:
|
||||
stream.seek(0)
|
||||
|
||||
def metadata(row, variants=()):
|
||||
return {k: str(row[k]) for k in ('id','chat_id','owner_id')} | {
|
||||
k:row[k] for k in ('filename','content_type','size_bytes','sha256')} | {
|
||||
'status':row['state'],'variants':list(variants),'error_code':row['error_code'],
|
||||
'created_at':timestamp(row['created_at']),'updated_at':timestamp(row['updated_at'])}
|
||||
|
||||
def save(stream, chat_id, owner, filename, content_type, size, digest):
|
||||
attachment_id=uuid.uuid4()
|
||||
key=f'originals/{attachment_id}'
|
||||
staging_key=f'staging/{attachment_id}'
|
||||
with storage.pool.connection() as conn:
|
||||
object_lock(conn, staging_key)
|
||||
put_immutable(client(), staging_key, stream, size, content_type, digest)
|
||||
row=conn.execute("INSERT INTO attachments(id,chat_id,owner_id,object_key,filename,content_type,size_bytes,sha256,state) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,'queued') RETURNING *",
|
||||
(attachment_id,chat_id,owner,key,filename,content_type,size,digest)).fetchone()
|
||||
conn.execute(
|
||||
"INSERT INTO attachment_jobs(id,attachment_id,staging_key,attempt_limit,next_publish_at) "
|
||||
"VALUES (%s,%s,%s,%s,clock_timestamp())",
|
||||
(uuid.uuid4(), attachment_id, staging_key, int(setting('JOB_MAX_ATTEMPTS', '5'))),
|
||||
)
|
||||
return metadata(row)
|
||||
|
||||
@router.post('/api/v1/chats/{chat_id}/attachments',status_code=202)
|
||||
async def upload(request:Request,chat_id:uuid.UUID,filename:str='',actor:str=Depends(require_user)):
|
||||
if not await run_in_threadpool(storage.is_chat_member,str(chat_id),actor):
|
||||
raise error(request,404,'not_found','chat not found')
|
||||
if not 1<=len(filename)<=255 or any(c in '/\\' or unicodedata.category(c)=='Cc' for c in filename):
|
||||
raise error(request,400,'invalid_request','invalid filename')
|
||||
mime=request.headers.get('content-type','').lower()
|
||||
if mime not in ('image/png','image/jpeg'):
|
||||
raise error(request,415,'unsupported_media_type','PNG/JPEG required')
|
||||
length=request.headers.get('content-length')
|
||||
if length is not None:
|
||||
if not length.isdecimal():
|
||||
raise error(request,400,'invalid_request','invalid length')
|
||||
if int(length)>MAX_BYTES:
|
||||
raise error(request,413,'payload_too_large','limit 10 MiB')
|
||||
try:
|
||||
await asyncio.wait_for(slots.acquire(),timeout=25)
|
||||
except asyncio.TimeoutError:
|
||||
raise error(request,503,'unavailable','upload queue busy') from None
|
||||
try:
|
||||
with tempfile.TemporaryFile() as stream:
|
||||
size=0; digest=hashlib.sha256()
|
||||
async def receive():
|
||||
nonlocal size
|
||||
async for chunk in request.stream():
|
||||
size+=len(chunk)
|
||||
if size>MAX_BYTES:
|
||||
raise error(request,413,'payload_too_large','limit 10 MiB')
|
||||
digest.update(chunk)
|
||||
await run_in_threadpool(stream.write,chunk)
|
||||
try:
|
||||
await asyncio.wait_for(receive(),timeout=20)
|
||||
await run_in_threadpool(stream.seek,0)
|
||||
await run_in_threadpool(inspect_image,stream,mime)
|
||||
except ClientDisconnect:
|
||||
raise error(request,400,'invalid_request','upload disconnected') from None
|
||||
except asyncio.TimeoutError:
|
||||
raise error(request,400,'invalid_request','upload timed out') from None
|
||||
except InvalidImage as exc:
|
||||
raise error(request,exc.status,'payload_too_large' if exc.status==413 else 'unsupported_media_type','invalid image') from None
|
||||
return await run_in_threadpool(save,stream,str(chat_id),actor,filename,mime,size,digest.hexdigest())
|
||||
finally:
|
||||
slots.release()
|
||||
|
||||
def accessible(conn, request, attachment_id, actor):
|
||||
# One consistent manifest for all reads in the enclosing transaction.
|
||||
row=conn.execute('SELECT a.* FROM attachments a JOIN chat_members m ON a.chat_id=m.chat_id '
|
||||
'WHERE a.id=%s AND m.user_id=%s FOR SHARE OF a',(attachment_id,actor)).fetchone()
|
||||
if not row:
|
||||
raise error(request,404,'not_found','attachment not found')
|
||||
return row
|
||||
|
||||
@router.get('/api/v1/attachments/{attachment_id}')
|
||||
def get_attachment(request:Request,attachment_id:uuid.UUID,actor:str=Depends(require_user)):
|
||||
with storage.pool.connection() as conn:
|
||||
row = accessible(conn, request, attachment_id, actor)
|
||||
variants = conn.execute(
|
||||
'SELECT name,content_type,size_bytes,sha256,width,height FROM attachment_variants '
|
||||
'WHERE attachment_id=%s AND pipeline_version=%s ORDER BY name',
|
||||
(attachment_id, row['published_pipeline_version']),
|
||||
).fetchall()
|
||||
return metadata(row, variants)
|
||||
|
||||
@router.get('/api/v1/attachments/{attachment_id}/content')
|
||||
def content(request:Request,attachment_id:uuid.UUID,variant:str='original',actor:str=Depends(require_user)):
|
||||
with storage.pool.connection() as conn:
|
||||
row = accessible(conn, request, attachment_id, actor)
|
||||
if variant not in ('original','thumbnail','crop','optimized'):
|
||||
raise error(request,400,'invalid_request','invalid variant')
|
||||
if row['state'] != 'ready':
|
||||
raise error(request,409,'conflict','attachment not ready')
|
||||
if variant != 'original':
|
||||
row = conn.execute(
|
||||
'SELECT * FROM attachment_variants WHERE attachment_id=%s AND pipeline_version=%s AND name=%s',
|
||||
(attachment_id, row['published_pipeline_version'], variant),
|
||||
).fetchone()
|
||||
if not row:
|
||||
raise error(request,404,'not_found','variant not found')
|
||||
obj=client().get_object(Bucket=BUCKET,Key=row['object_key'])
|
||||
def chunks():
|
||||
try:
|
||||
yield from obj['Body'].iter_chunks(chunk_size=64*1024)
|
||||
finally:
|
||||
obj['Body'].close()
|
||||
return StreamingResponse(chunks(),media_type=row['content_type'],headers={'Content-Length':str(row['size_bytes'])})
|
||||
@@ -0,0 +1,79 @@
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
|
||||
from src.models import Chat, ChatPage, CreateChat
|
||||
from src.routes.common import get_request_id, make_error, require_user
|
||||
from src.storage import LimitExceeded, ValidationError, storage
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/api/v1/chats", response_model=Chat, status_code=201)
|
||||
def create_chat(
|
||||
request: Request,
|
||||
body: CreateChat,
|
||||
x_user_id: str = Depends(require_user),
|
||||
):
|
||||
"""Создать чат. Создатель обязательно должен входить в member_ids."""
|
||||
request_id = get_request_id(request)
|
||||
|
||||
try:
|
||||
chat = storage.create_chat(body.title, body.member_ids, x_user_id)
|
||||
return chat
|
||||
except ValidationError as e:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=make_error("invalid_request", str(e), request_id).model_dump(),
|
||||
)
|
||||
except LimitExceeded as e:
|
||||
raise HTTPException(
|
||||
status_code=429,
|
||||
detail=make_error("rate_limited", str(e), request_id).model_dump(),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats", response_model=ChatPage)
|
||||
def list_chats(
|
||||
request: Request,
|
||||
x_user_id: str = Depends(require_user),
|
||||
limit: int = 50,
|
||||
cursor: str | None = None,
|
||||
):
|
||||
"""Список чатов текущего пользователя с курсорной пагинацией."""
|
||||
request_id = get_request_id(request)
|
||||
|
||||
if limit < 1 or limit > 100:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=make_error("invalid_request", "limit должен быть от 1 до 100", request_id).model_dump(),
|
||||
)
|
||||
|
||||
try:
|
||||
items, next_cursor = storage.list_chats_for_user(x_user_id, cursor, limit)
|
||||
return ChatPage(items=items, next_cursor=next_cursor)
|
||||
except ValidationError as e:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=make_error("invalid_request", str(e), request_id).model_dump(),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}", response_model=Chat)
|
||||
def get_chat(
|
||||
request: Request,
|
||||
chat_id: UUID,
|
||||
x_user_id: str = Depends(require_user),
|
||||
):
|
||||
"""Получить чат по id. Доступен только участникам чата (чужой — 404)."""
|
||||
request_id = get_request_id(request)
|
||||
|
||||
chat_id_str = str(chat_id)
|
||||
chat = storage.get_chat(chat_id_str)
|
||||
if not chat or x_user_id not in chat.member_ids:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=make_error("not_found", "чат не найден", request_id).model_dump(),
|
||||
)
|
||||
|
||||
return chat
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Общие ошибки и проверка Bearer-сессии; X-User-Id не используется."""
|
||||
from fastapi import HTTPException, Request
|
||||
from src.models import ErrorResponse
|
||||
from src.storage import storage
|
||||
|
||||
|
||||
def make_error(code, message, request_id):
|
||||
return ErrorResponse(error={'code': code, 'message': message, 'request_id': request_id})
|
||||
|
||||
|
||||
def get_request_id(request):
|
||||
return request.state.request_id
|
||||
|
||||
|
||||
def unauthorized(request, basic=False):
|
||||
challenge = 'Basic realm="messenger", charset="UTF-8"' if basic else 'Bearer realm="messenger"'
|
||||
raise HTTPException(401, detail=make_error('unauthorized', 'неверные учётные данные', get_request_id(request)).model_dump(), headers={'WWW-Authenticate': challenge})
|
||||
|
||||
|
||||
def require_user(request: Request):
|
||||
authorization = request.headers.get('Authorization', '')
|
||||
parts = authorization.split()
|
||||
if len(parts) != 2 or parts[0].lower() != 'bearer':
|
||||
unauthorized(request)
|
||||
user_id = storage.session_user(parts[1])
|
||||
if not user_id:
|
||||
unauthorized(request)
|
||||
request.state.token = parts[1]
|
||||
return user_id
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Жизнь процесса и готовность критичного хранилища проверяются отдельно."""
|
||||
from fastapi import APIRouter
|
||||
from src.models import Health
|
||||
from src.storage import storage
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get('/health/live')
|
||||
def liveness():
|
||||
return Health()
|
||||
|
||||
|
||||
@router.get('/health/ready')
|
||||
def readiness():
|
||||
storage.ready()
|
||||
from src.objects import client, BUCKET
|
||||
client().list_objects_v2(Bucket=BUCKET, Prefix="staging/", MaxKeys=1)
|
||||
return Health()
|
||||
|
||||
|
||||
@router.get('/stats')
|
||||
def stats():
|
||||
return storage.get_stats()
|
||||
@@ -0,0 +1,85 @@
|
||||
from uuid import UUID
|
||||
import re
|
||||
import os
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
|
||||
from src.models import CreateMessage, Message, MessagePage
|
||||
from src.routes.common import get_request_id, make_error, require_user
|
||||
from src.storage import NotFoundError, ConflictError, LimitExceeded, ValidationError, storage
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/api/v1/chats/{chat_id}/messages", response_model=Message, status_code=201)
|
||||
def create_message(
|
||||
request: Request,
|
||||
chat_id: UUID,
|
||||
body: CreateMessage,
|
||||
x_user_id: str = Depends(require_user),
|
||||
):
|
||||
"""Отправить сообщение от владельца Bearer-сессии с общей защитой повторов."""
|
||||
request_id = get_request_id(request)
|
||||
|
||||
chat_id_str = str(chat_id)
|
||||
if os.getenv('OPTIMIZED_WRITES','1') == '1':
|
||||
allowed = storage.is_chat_member(chat_id_str, x_user_id)
|
||||
else:
|
||||
chat = storage.get_chat(chat_id_str)
|
||||
allowed = bool(chat and x_user_id in chat.member_ids)
|
||||
if not allowed:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=make_error("not_found", "чат не найден", request_id).model_dump(),
|
||||
)
|
||||
|
||||
try:
|
||||
key = request.headers.get('Idempotency-Key', '')
|
||||
if not re.fullmatch(r'[A-Za-z0-9._:-]{1,128}', key):
|
||||
raise HTTPException(400, detail=make_error('invalid_request', 'неверный Idempotency-Key', request_id).model_dump())
|
||||
msg = storage.create_message(chat_id_str, x_user_id, body.text, key, body.attachment_ids)
|
||||
return msg
|
||||
except NotFoundError as e:
|
||||
raise HTTPException(404, detail=make_error('not_found', str(e), request_id).model_dump())
|
||||
except ConflictError as e:
|
||||
raise HTTPException(409, detail=make_error('conflict', str(e), request_id).model_dump())
|
||||
except LimitExceeded as e:
|
||||
raise HTTPException(
|
||||
status_code=429,
|
||||
detail=make_error("rate_limited", str(e), request_id).model_dump(),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
||||
def list_messages(
|
||||
request: Request,
|
||||
chat_id: UUID,
|
||||
x_user_id: str = Depends(require_user),
|
||||
limit: int = 50,
|
||||
cursor: str | None = None,
|
||||
):
|
||||
"""История сообщений чата с курсорной пагинацией. Доступно только участникам."""
|
||||
request_id = get_request_id(request)
|
||||
|
||||
chat_id_str = str(chat_id)
|
||||
chat = storage.get_chat(chat_id_str)
|
||||
if not chat or x_user_id not in chat.member_ids:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=make_error("not_found", "чат не найден", request_id).model_dump(),
|
||||
)
|
||||
|
||||
if limit < 1 or limit > 100:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=make_error("invalid_request", "limit должен быть от 1 до 100", request_id).model_dump(),
|
||||
)
|
||||
|
||||
try:
|
||||
items, next_cursor = storage.list_messages(chat_id_str, cursor, limit)
|
||||
return MessagePage(items=items, next_cursor=next_cursor)
|
||||
except ValidationError as e:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=make_error("invalid_request", str(e), request_id).model_dump(),
|
||||
)
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Регистрация, вход, текущий пользователь и отзыв сессии."""
|
||||
import base64
|
||||
import binascii
|
||||
from fastapi import APIRouter, Request, Response, HTTPException
|
||||
from src.models import CreateUser, User
|
||||
from src.routes.common import get_request_id, make_error, require_user, unauthorized
|
||||
from src.storage import ConflictError, storage
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post('/api/v1/users', response_model=User, status_code=201)
|
||||
def register_user(request: Request, body: CreateUser):
|
||||
try:
|
||||
return storage.create_user(body.username,body.display_name,body.password)
|
||||
except ConflictError as exc:
|
||||
raise HTTPException(409,detail=make_error('conflict',str(exc),get_request_id(request)).model_dump())
|
||||
|
||||
|
||||
@router.post('/api/v1/auth/sessions', status_code=201)
|
||||
async def login(request: Request):
|
||||
if await request.body():
|
||||
raise HTTPException(400, detail=make_error('invalid_request','тело запроса не допускается',get_request_id(request)).model_dump())
|
||||
parts = request.headers.get('Authorization','').split()
|
||||
try:
|
||||
if len(parts) != 2 or parts[0].lower() != 'basic':
|
||||
unauthorized(request, basic=True)
|
||||
username,password = base64.b64decode(parts[1],validate=True).decode('utf-8').split(':',1)
|
||||
username.encode('ascii')
|
||||
except (ValueError, UnicodeError, binascii.Error):
|
||||
unauthorized(request,basic=True)
|
||||
# Вычисление KDF и синхронные запросы выполняются вне цикла событий.
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
result = await run_in_threadpool(storage.login,username,password)
|
||||
if not result:
|
||||
unauthorized(request,basic=True)
|
||||
return result
|
||||
|
||||
|
||||
@router.get('/api/v1/users/me',response_model=User)
|
||||
def current_user(request: Request):
|
||||
return storage.get_user(require_user(request))
|
||||
|
||||
|
||||
@router.delete('/api/v1/auth/sessions/current',status_code=204)
|
||||
def logout(request: Request):
|
||||
require_user(request)
|
||||
storage.logout(request.state.token)
|
||||
return Response(status_code=204)
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Очистка staging с блокировкой, общей с HTTP upload и replay."""
|
||||
|
||||
import logging
|
||||
import signal
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import psycopg
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from psycopg_pool import PoolTimeout
|
||||
|
||||
from src.config import setting
|
||||
from src.objects import BUCKET, client, object_lock
|
||||
from src.storage import storage
|
||||
|
||||
|
||||
def cleanup(s3, retention):
|
||||
count = 0
|
||||
now = datetime.now(timezone.utc)
|
||||
pages = s3.get_paginator('list_objects_v2')
|
||||
for page in pages.paginate(Bucket=BUCKET, Prefix='staging/'):
|
||||
for item in page.get('Contents', []):
|
||||
key = item['Key']
|
||||
with storage.pool.connection() as conn:
|
||||
if not object_lock(conn, key, wait=False):
|
||||
continue
|
||||
job = conn.execute(
|
||||
'SELECT state,settled_at FROM attachment_jobs WHERE staging_key=%s '
|
||||
'ORDER BY pipeline_version DESC LIMIT 1', (key,),
|
||||
).fetchone()
|
||||
retention_start = (job['settled_at'] if job else None) or item['LastModified']
|
||||
age = (now - retention_start).total_seconds()
|
||||
if job and job['state'] in ('queued', 'processing'):
|
||||
continue
|
||||
if (job and job['state'] == 'ready') or age >= retention:
|
||||
s3.delete_object(Bucket=BUCKET, Key=key)
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def main():
|
||||
stop = threading.Event()
|
||||
for sig in (signal.SIGTERM, signal.SIGINT):
|
||||
signal.signal(sig, lambda *_: stop.set())
|
||||
retention = max(60, int(setting('STAGING_RETENTION_SECONDS', '86400')))
|
||||
storage.pool.open(wait=True)
|
||||
try:
|
||||
while not stop.is_set():
|
||||
try:
|
||||
cleanup(client(), retention)
|
||||
except (BotoCoreError, ClientError, OSError, psycopg.Error, PoolTimeout) as exc:
|
||||
logging.warning('staging cleanup temporarily unavailable: %s', type(exc).__name__)
|
||||
stop.wait(30)
|
||||
finally:
|
||||
storage.pool.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+276
@@ -0,0 +1,276 @@
|
||||
"""PostgreSQL — источник истины; каждый контекст подключения завершает транзакцию."""
|
||||
import base64
|
||||
import binascii
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import threading
|
||||
import uuid
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError, VerificationError, InvalidHashError
|
||||
from psycopg.errors import UniqueViolation, ForeignKeyViolation
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
from src.config import setting
|
||||
from src.cache import profile_cache
|
||||
from src.models import User, Chat, Message
|
||||
|
||||
_CURSOR_FIELDS = {"scope", "resource_id", "created_at", "id"}
|
||||
PASSWORDS = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
|
||||
DUMMY_HASH = PASSWORDS.hash('synthetic-dummy-password')
|
||||
|
||||
|
||||
class ValidationError(Exception):
|
||||
"""Неверный запрос."""
|
||||
|
||||
|
||||
class ConflictError(Exception):
|
||||
"""Имя уже занято."""
|
||||
|
||||
|
||||
class LimitExceeded(Exception):
|
||||
"""Перегрузка сервера."""
|
||||
|
||||
|
||||
class NotFoundError(Exception):
|
||||
"""Объект отсутствует или недоступен."""
|
||||
|
||||
|
||||
def timestamp(value):
|
||||
return value.astimezone(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
|
||||
|
||||
|
||||
def public_row(row):
|
||||
return {k: timestamp(v) if isinstance(v, datetime) else str(v) if isinstance(v, uuid.UUID) else v
|
||||
for k, v in row.items() if k != 'password_hash'}
|
||||
|
||||
|
||||
class PostgresStorage:
|
||||
def __init__(self):
|
||||
self.pool = ConnectionPool(setting('DATABASE_URL', ''), min_size=1, max_size=int(os.getenv("POOL_SIZE", "10")),
|
||||
timeout=3, max_waiting=32, open=False, check=ConnectionPool.check_connection,
|
||||
kwargs={'row_factory': dict_row, 'connect_timeout': 3,
|
||||
'options': '-c statement_timeout=3000 -c lock_timeout=2000'})
|
||||
self._lock = threading.Lock()
|
||||
self._requests = 0
|
||||
|
||||
@staticmethod
|
||||
def _encode_cursor(scope: str, resource_id: str, created_at: str, item_id: str) -> str:
|
||||
"""Собрать непрозрачный курсор, привязанный к конкретному ресурсу."""
|
||||
payload = {
|
||||
"scope": scope,
|
||||
"resource_id": resource_id,
|
||||
"created_at": created_at,
|
||||
"id": item_id,
|
||||
}
|
||||
raw = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii")
|
||||
|
||||
@staticmethod
|
||||
def _decode_cursor(cursor: str, expected_scope: str, expected_resource_id: str) -> tuple[str, str]:
|
||||
"""Разобрать и проверить курсор.
|
||||
|
||||
Клиент видит курсор как непрозрачную строку, поэтому любые пустые,
|
||||
повреждённые или относящиеся к другому ресурсу значения отклоняем.
|
||||
"""
|
||||
if cursor == "":
|
||||
raise ValidationError("некорректный cursor")
|
||||
|
||||
allowed_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_="
|
||||
if any(char not in allowed_chars for char in cursor) or "=" in cursor.rstrip("="):
|
||||
raise ValidationError("некорректный cursor")
|
||||
|
||||
try:
|
||||
raw = base64.b64decode(cursor.encode("ascii"), altchars=b"-_", validate=True)
|
||||
payload = json.loads(raw.decode("utf-8"))
|
||||
except (UnicodeEncodeError, UnicodeDecodeError, binascii.Error, json.JSONDecodeError):
|
||||
raise ValidationError("некорректный cursor")
|
||||
|
||||
if not isinstance(payload, dict) or set(payload) != _CURSOR_FIELDS:
|
||||
raise ValidationError("некорректный cursor")
|
||||
|
||||
if not all(isinstance(payload[field], str) for field in _CURSOR_FIELDS):
|
||||
raise ValidationError("некорректный cursor")
|
||||
|
||||
if payload["scope"] != expected_scope or payload["resource_id"] != expected_resource_id:
|
||||
raise ValidationError("некорректный cursor")
|
||||
|
||||
try:
|
||||
uuid.UUID(payload["resource_id"])
|
||||
uuid.UUID(payload["id"])
|
||||
datetime.fromisoformat(payload["created_at"].replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
raise ValidationError("некорректный cursor")
|
||||
|
||||
return payload["created_at"], payload["id"]
|
||||
|
||||
|
||||
def create_user(self, username, display_name, password):
|
||||
password_hash = PASSWORDS.hash(password)
|
||||
try:
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute('INSERT INTO users (id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) RETURNING id,username,display_name,created_at',
|
||||
(uuid.uuid4(), username, display_name, password_hash)).fetchone()
|
||||
return User(**public_row(row))
|
||||
except UniqueViolation:
|
||||
raise ConflictError('имя пользователя уже занято') from None
|
||||
|
||||
def get_user(self, user_id):
|
||||
cached = profile_cache.get(user_id)
|
||||
if cached:
|
||||
return cached
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute('SELECT id,username,display_name,created_at FROM users WHERE id=%s', (user_id,)).fetchone()
|
||||
user = User(**public_row(row)) if row else None
|
||||
if user:
|
||||
profile_cache.put(user)
|
||||
return user
|
||||
|
||||
def login(self, username, password):
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute('SELECT * FROM users WHERE username=%s', (username,)).fetchone()
|
||||
try:
|
||||
PASSWORDS.verify(row['password_hash'] if row else DUMMY_HASH, password)
|
||||
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
||||
return None
|
||||
if not row:
|
||||
return None
|
||||
token = secrets.token_urlsafe(32)
|
||||
with self.pool.connection() as conn:
|
||||
session = conn.execute("INSERT INTO sessions VALUES (%s,%s,clock_timestamp() + %s * interval '1 second') RETURNING expires_at",
|
||||
(self.token_hash(token), row['id'], int(os.getenv('SESSION_TTL_SECONDS', '3600')))).fetchone()
|
||||
return {'token': token, 'token_type': 'Bearer', 'expires_at': timestamp(session['expires_at']), 'user': User(**public_row(row)).model_dump()}
|
||||
|
||||
@staticmethod
|
||||
def token_hash(token):
|
||||
return hashlib.sha256(token.encode()).hexdigest()
|
||||
|
||||
def session_user(self, token):
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute('SELECT user_id FROM sessions WHERE token_hash=%s AND expires_at > clock_timestamp()', (self.token_hash(token),)).fetchone()
|
||||
return str(row['user_id']) if row else None
|
||||
|
||||
def logout(self, token):
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute('DELETE FROM sessions WHERE token_hash=%s', (self.token_hash(token),))
|
||||
|
||||
def create_chat(self, title, member_ids, creator_id):
|
||||
if len(set(member_ids)) != len(member_ids) or creator_id not in member_ids:
|
||||
raise ValidationError('неверный список участников')
|
||||
chat_id = uuid.uuid4()
|
||||
try:
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute('INSERT INTO chats (id,title) VALUES (%s,%s) RETURNING *', (chat_id,title)).fetchone()
|
||||
for member in member_ids:
|
||||
conn.execute('INSERT INTO chat_members VALUES (%s,%s)', (chat_id,member))
|
||||
return Chat(**public_row(row), member_ids=sorted(member_ids))
|
||||
except ForeignKeyViolation:
|
||||
raise ValidationError('участник не существует') from None
|
||||
|
||||
def get_chat(self, chat_id):
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute('SELECT * FROM chats WHERE id=%s', (chat_id,)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
members = conn.execute('SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY user_id', (chat_id,)).fetchall()
|
||||
return Chat(**public_row(row), member_ids=[str(x['user_id']) for x in members])
|
||||
|
||||
def is_chat_member(self, chat_id, user_id):
|
||||
"""Проверить доступ без загрузки всего чата и списка участников."""
|
||||
with self.pool.connection() as conn:
|
||||
return conn.execute('SELECT 1 FROM chat_members WHERE chat_id=%s AND user_id=%s', (chat_id,user_id)).fetchone() is not None
|
||||
|
||||
def list_chats_for_user(self, user_id, cursor, limit):
|
||||
with self.pool.connection() as conn:
|
||||
params = [user_id]
|
||||
boundary = ''
|
||||
if cursor is not None:
|
||||
when, item = self._decode_cursor(cursor, 'chats', user_id)
|
||||
marker = conn.execute('SELECT 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', (item,user_id)).fetchone()
|
||||
if not marker or timestamp(marker['created_at']) != when:
|
||||
raise ValidationError('некорректный cursor')
|
||||
boundary = ' AND (c.created_at,c.id) > (%s,%s)'
|
||||
params += [when,item]
|
||||
rows = conn.execute('SELECT c.* FROM chats c JOIN chat_members m ON m.chat_id=c.id WHERE m.user_id=%s' + boundary + ' ORDER BY c.created_at,c.id LIMIT %s', params+[limit+1]).fetchall()
|
||||
page = [self.get_chat(str(row['id'])) for row in rows[:limit]]
|
||||
next_cursor = self._encode_cursor('chats',user_id,page[-1].created_at,page[-1].id) if len(rows)>limit else None
|
||||
return page,next_cursor
|
||||
|
||||
def create_message(self, chat_id, sender_id, text, key, attachment_ids=None):
|
||||
attachment_ids = attachment_ids or []
|
||||
normalized = {'text': text, 'attachment_ids': attachment_ids}
|
||||
# Блокировка сериализует один ключ на всех репликах; результат и сообщение атомарны.
|
||||
with self.pool.connection() as conn:
|
||||
scope = json.dumps([sender_id, chat_id, key])
|
||||
conn.execute('SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))', (scope,))
|
||||
old = conn.execute('SELECT * FROM message_requests WHERE user_id=%s AND chat_id=%s AND key=%s AND expires_at>clock_timestamp()', (sender_id,chat_id,key)).fetchone()
|
||||
if old:
|
||||
if json.loads(old['body']) != normalized:
|
||||
raise ConflictError('ключ уже использован с другим сообщением')
|
||||
row = conn.execute('SELECT * FROM messages WHERE id=%s', (old['message_id'],)).fetchone()
|
||||
return self.message_model(conn, row)
|
||||
for attachment_id in sorted(attachment_ids):
|
||||
attachment = conn.execute('SELECT state FROM attachments WHERE id=%s AND chat_id=%s FOR SHARE', (attachment_id,chat_id)).fetchone()
|
||||
if not attachment:
|
||||
raise NotFoundError('вложение не найдено')
|
||||
if attachment['state'] == 'failed':
|
||||
raise ConflictError('вложение недоступно')
|
||||
optimized = os.getenv('OPTIMIZED_WRITES','1') == '1'
|
||||
if not optimized:
|
||||
conn.execute('DELETE FROM message_requests WHERE user_id=%s AND chat_id=%s AND key=%s', (sender_id,chat_id,key))
|
||||
row = conn.execute('INSERT INTO messages (id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) RETURNING *', (uuid.uuid4(),chat_id,sender_id,text)).fetchone()
|
||||
# Под той же блокировкой UPSERT заменяет просроченный результат без отдельного DELETE.
|
||||
suffix = ' ON CONFLICT (user_id,chat_id,key) DO UPDATE SET body=EXCLUDED.body,message_id=EXCLUDED.message_id,expires_at=EXCLUDED.expires_at' if optimized else ''
|
||||
conn.execute("INSERT INTO message_requests VALUES (%s,%s,%s,%s,%s,clock_timestamp()+interval '24 hours')"+suffix, (sender_id,chat_id,key,json.dumps(normalized,ensure_ascii=False),row['id']))
|
||||
for position, attachment_id in enumerate(attachment_ids):
|
||||
conn.execute('INSERT INTO message_attachments VALUES (%s,%s,%s)', (row['id'],attachment_id,position))
|
||||
result = self.message_model(conn,row)
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def message_model(conn, row):
|
||||
ids = conn.execute('SELECT attachment_id FROM message_attachments WHERE message_id=%s ORDER BY position', (row['id'],)).fetchall()
|
||||
return Message(**public_row(row), attachment_ids=[str(x['attachment_id']) for x in ids])
|
||||
|
||||
def list_messages(self, chat_id, cursor, limit):
|
||||
with self.pool.connection() as conn:
|
||||
params = [chat_id]
|
||||
boundary = ''
|
||||
if cursor is not None:
|
||||
when,item = self._decode_cursor(cursor,'messages',chat_id)
|
||||
marker = conn.execute('SELECT created_at FROM messages WHERE id=%s AND chat_id=%s', (item,chat_id)).fetchone()
|
||||
if not marker or timestamp(marker['created_at']) != when:
|
||||
raise ValidationError('некорректный cursor')
|
||||
boundary = ' AND (created_at,id) > (%s,%s)'
|
||||
params += [when,item]
|
||||
rows = conn.execute('SELECT * FROM messages WHERE chat_id=%s' + boundary + ' ORDER BY created_at,id LIMIT %s', params+[limit+1]).fetchall()
|
||||
page = [self.message_model(conn,row) for row in rows[:limit]]
|
||||
next_cursor = self._encode_cursor('messages',chat_id,page[-1].created_at,page[-1].id) if len(rows)>limit else None
|
||||
return page,next_cursor
|
||||
|
||||
def ready(self):
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute('SELECT 1 FROM schema_migrations LIMIT 1')
|
||||
|
||||
def acquire_request_slot(self):
|
||||
with self._lock:
|
||||
if self._requests >= 100:
|
||||
return False
|
||||
self._requests += 1
|
||||
return True
|
||||
|
||||
def release_request_slot(self):
|
||||
with self._lock:
|
||||
self._requests -= 1
|
||||
|
||||
def get_stats(self):
|
||||
with self.pool.connection() as conn:
|
||||
result = {table: conn.execute('SELECT count(*) AS n FROM '+table).fetchone()['n'] for table in ('users','chats','messages')}
|
||||
result['profile_cache'] = {'hits': profile_cache.hits, 'misses': profile_cache.misses, 'errors': profile_cache.errors, 'ttl_seconds': profile_cache.ttl}
|
||||
return result
|
||||
|
||||
|
||||
storage = PostgresStorage()
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
"""Worker обрабатывает одну доставку за раз и подтверждает после COMMIT."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
|
||||
import pika
|
||||
import psycopg
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from psycopg_pool import PoolTimeout
|
||||
|
||||
from src import broker, jobs, faults
|
||||
from src.objects import BUCKET, ObjectConflict, client, put_immutable
|
||||
from src.storage import storage
|
||||
|
||||
|
||||
class PermanentError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def fetch(s3, key, attachment, destination):
|
||||
digest = hashlib.sha256()
|
||||
size = 0
|
||||
obj = s3.get_object(Bucket=BUCKET, Key=key)
|
||||
with closing(obj['Body']) as stream, destination.open('wb') as output:
|
||||
for chunk in stream.iter_chunks(chunk_size=64 * 1024):
|
||||
size += len(chunk)
|
||||
if size > attachment['size_bytes']:
|
||||
raise PermanentError('staging_integrity')
|
||||
digest.update(chunk)
|
||||
output.write(chunk)
|
||||
if (size, digest.hexdigest()) != (attachment['size_bytes'], attachment['sha256']):
|
||||
raise PermanentError('staging_integrity')
|
||||
|
||||
|
||||
def process(job):
|
||||
faults.hit('before_effect', job)
|
||||
attachment = job['attachment']
|
||||
s3 = client()
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
directory = Path(temp)
|
||||
original = directory / 'original'
|
||||
source = attachment['object_key'] if attachment['published_pipeline_version'] else job['staging_key']
|
||||
fetch(s3, source, attachment, original)
|
||||
result = subprocess.run([sys.executable, '-m', 'src.image_pipeline', temp, str(job['pipeline_version'])],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
timeout=jobs.JOB_TIMEOUT, check=False)
|
||||
if result.returncode == 2:
|
||||
raise PermanentError('invalid_image')
|
||||
result.check_returncode()
|
||||
with original.open('rb') as stream:
|
||||
put_immutable(s3, attachment['object_key'], stream, attachment['size_bytes'],
|
||||
attachment['content_type'], attachment['sha256'])
|
||||
variants = []
|
||||
faults.hit('after_original', job)
|
||||
for name, mime, width, height in json.loads((directory / 'manifest.json').read_text()):
|
||||
key = f"variants/{attachment['id']}/v{job['pipeline_version']}/{name}"
|
||||
output = directory / name
|
||||
size = output.stat().st_size
|
||||
with output.open('rb') as stream:
|
||||
digest = hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
stream.seek(0)
|
||||
put_immutable(s3, key, stream, size, mime, digest)
|
||||
variants.append((name, key, mime, size, digest, width, height))
|
||||
faults.hit('after_variants', job)
|
||||
jobs.complete(job, variants)
|
||||
faults.hit('after_commit', job)
|
||||
|
||||
|
||||
def handle(channel, delivery, body):
|
||||
try:
|
||||
message = jobs.validate(json.loads(body))
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
logging.warning('invalid broker job')
|
||||
channel.basic_reject(delivery.delivery_tag, requeue=False)
|
||||
return
|
||||
|
||||
job = jobs.claim(message)
|
||||
if job:
|
||||
try:
|
||||
process(job)
|
||||
except PermanentError as exc:
|
||||
jobs.fail(job, str(exc), permanent=True)
|
||||
except ObjectConflict:
|
||||
jobs.fail(job, 'object_conflict', permanent=True)
|
||||
except (BotoCoreError, ClientError, OSError, subprocess.SubprocessError) as exc:
|
||||
logging.warning('processing retry job=%s cause=%s', job['id'], type(exc).__name__)
|
||||
jobs.fail(job, 'processing_timeout' if isinstance(exc, subprocess.TimeoutExpired) else 'processing_failed')
|
||||
channel.basic_ack(delivery.delivery_tag)
|
||||
|
||||
|
||||
def main():
|
||||
logging.basicConfig(level=logging.WARNING)
|
||||
stopping = threading.Event()
|
||||
for sig in (signal.SIGINT, signal.SIGTERM):
|
||||
signal.signal(sig, lambda *_: stopping.set())
|
||||
storage.pool.open(wait=True)
|
||||
try:
|
||||
while not stopping.is_set():
|
||||
try:
|
||||
with broker.channel(heartbeat=jobs.LEASE_SECONDS + 15) as (_, channel):
|
||||
channel.basic_qos(prefetch_count=1)
|
||||
for delivery, _, body in channel.consume(broker.QUEUE, inactivity_timeout=0.5):
|
||||
if stopping.is_set():
|
||||
break
|
||||
if delivery:
|
||||
handle(channel, delivery, body)
|
||||
except (pika.exceptions.AMQPError, OSError, psycopg.Error, PoolTimeout) as exc:
|
||||
logging.warning('worker temporarily unavailable: %s', type(exc).__name__)
|
||||
stopping.wait(1)
|
||||
finally:
|
||||
storage.pool.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user