ЛР 3 — БПИ2303 — Унру — на 3
This commit is contained in:
@@ -0,0 +1,297 @@
|
||||
"""Contract-compatible synchronous REST API, with short bounded I/O in worker threads."""
|
||||
import json
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
from contextlib import asynccontextmanager
|
||||
from uuid import uuid4
|
||||
|
||||
import psycopg
|
||||
from fastapi import Depends, FastAPI, Request, Response
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from psycopg_pool import PoolTimeout, TooManyRequests
|
||||
from redis.exceptions import RedisError
|
||||
from starlette.exceptions import HTTPException
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from .db import Database
|
||||
from .errors import ApiError, invalid, not_found, unauthorized
|
||||
from .models import CreateChat, CreateMessage, CreateUser, uuid_value
|
||||
from .messages import store_message, validate_key, MESSAGE_FIELDS
|
||||
from .object_store import ObjectStore, unavailable
|
||||
from . import attachments
|
||||
from urllib.parse import quote
|
||||
from .pagination import decode_cursor, page, page_limit, public, stamp
|
||||
from .security import HASHER, DUMMY_HASH, basic_credentials, bearer, check_password, digest, new_session
|
||||
|
||||
LOG = logging.getLogger('messenger')
|
||||
USER_FIELDS = 'id, username, display_name, created_at'
|
||||
|
||||
|
||||
def error_response(request, error):
|
||||
return JSONResponse({'error': {'code': error.code, 'message': error.message,
|
||||
'request_id': request.state.request_id}},
|
||||
status_code=error.status, headers=error.headers)
|
||||
|
||||
|
||||
def authenticate(request: Request):
|
||||
token = bearer(request.headers.get('Authorization', ''))
|
||||
token_hash = digest(token)
|
||||
with request.app.state.db.pool.connection() as conn:
|
||||
row = conn.execute('SELECT user_id FROM sessions WHERE token_hash=%s AND expires_at > clock_timestamp()',
|
||||
(token_hash,)).fetchone()
|
||||
if not row:
|
||||
raise unauthorized()
|
||||
request.state.token_hash = token_hash
|
||||
return row['user_id']
|
||||
|
||||
|
||||
def require_member(conn, chat_id, user_id):
|
||||
found = conn.execute('SELECT 1 FROM chat_members WHERE chat_id=%s AND user_id=%s', (chat_id, user_id)).fetchone()
|
||||
if not found:
|
||||
raise not_found()
|
||||
|
||||
|
||||
def chat_public(conn, row):
|
||||
item = public(row)
|
||||
item['member_ids'] = [str(member['user_id']) for member in conn.execute(
|
||||
'SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY user_id', (row['id'],)).fetchall()]
|
||||
return item
|
||||
|
||||
|
||||
def create_app():
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
app.state.db = Database()
|
||||
app.state.storage = ObjectStore()
|
||||
app.state.upload_slots = asyncio.Semaphore(6)
|
||||
app.state.db.open()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
app.state.storage.close()
|
||||
app.state.db.close()
|
||||
|
||||
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
|
||||
app.state.instance_id = uuid4().hex
|
||||
app.state.release = os.environ.get('APP_RELEASE', 'lab4-v1')
|
||||
|
||||
@app.middleware('http')
|
||||
async def request_context(request: Request, call_next):
|
||||
request.state.request_id = str(uuid4())
|
||||
try:
|
||||
path = request.url.path
|
||||
json_endpoint = path in ('/api/v1/users', '/api/v1/chats') or re.fullmatch(r'/api/v1/chats/[^/]+/messages', path)
|
||||
if request.method == 'POST' and json_endpoint:
|
||||
media = request.headers.get('Content-Type', '').split(';')
|
||||
unsupported = media[0].strip().lower() != 'application/json'
|
||||
for parameter in media[1:]:
|
||||
name, _, value = parameter.strip().partition('=')
|
||||
if name.lower() == 'charset' and value.strip('"').lower() not in ('utf-8', 'utf8'):
|
||||
unsupported = True
|
||||
if unsupported:
|
||||
if path != '/api/v1/users':
|
||||
await run_in_threadpool(authenticate, request)
|
||||
raise ApiError(415, 'unsupported_media_type', 'Требуется application/json в UTF-8')
|
||||
try:
|
||||
json.loads((await request.body()).decode('utf-8'))
|
||||
except (UnicodeError, json.JSONDecodeError):
|
||||
raise invalid() from None
|
||||
response = await call_next(request)
|
||||
except ApiError as exc:
|
||||
response = error_response(request, exc)
|
||||
except (psycopg.OperationalError, psycopg.InterfaceError, PoolTimeout, TooManyRequests):
|
||||
response = error_response(request, ApiError(503, 'unavailable', 'Хранилище временно недоступно'))
|
||||
except Exception as exc:
|
||||
# Log exception class only: credentials, SQL and message content stay out of logs.
|
||||
LOG.error('request_failed request_id=%s type=%s', request.state.request_id, type(exc).__name__)
|
||||
response = error_response(request, ApiError(500, 'internal_error', 'Внутренняя ошибка'))
|
||||
response.headers['X-Request-Id'] = request.state.request_id
|
||||
response.headers['X-Instance-Id'] = app.state.instance_id
|
||||
response.headers['X-App-Release'] = app.state.release
|
||||
return response
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
async def api_error(request, exc):
|
||||
return error_response(request, exc)
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error(request, exc):
|
||||
return error_response(request, invalid())
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def http_error(request, exc):
|
||||
return error_response(request, not_found() if exc.status_code == 404 else invalid())
|
||||
|
||||
@app.get('/health/live')
|
||||
def live():
|
||||
return {'status': 'ok'}
|
||||
|
||||
@app.get('/health/ready')
|
||||
def ready(request: Request):
|
||||
try:
|
||||
with request.app.state.db.pool.connection() as conn:
|
||||
conn.execute('SELECT 1 FROM idempotency_records LIMIT 0')
|
||||
conn.execute('SELECT 1 FROM attachments LIMIT 0')
|
||||
except (psycopg.errors.UndefinedTable, psycopg.errors.UndefinedColumn):
|
||||
raise ApiError(503, 'unavailable', 'Схема хранилища ещё не готова') from None
|
||||
request.app.state.storage.check()
|
||||
return {'status': 'ok'}
|
||||
|
||||
@app.post('/api/v1/users', status_code=201)
|
||||
def register(body: CreateUser, request: Request):
|
||||
password_hash = HASHER.hash(body.password)
|
||||
try:
|
||||
with request.app.state.db.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
f'INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) RETURNING {USER_FIELDS}',
|
||||
(uuid4(), body.username, body.display_name, password_hash)).fetchone()
|
||||
except psycopg.errors.UniqueViolation:
|
||||
raise ApiError(409, 'conflict', 'Имя пользователя занято') from None
|
||||
return public(row)
|
||||
|
||||
@app.post('/api/v1/auth/sessions', status_code=201)
|
||||
async def create_session(request: Request):
|
||||
# Run hashing and synchronous database calls outside the event loop.
|
||||
username, password = basic_credentials(request.headers.get('Authorization', ''))
|
||||
if await request.body():
|
||||
raise invalid()
|
||||
return await run_in_threadpool(login, request, username, password)
|
||||
|
||||
def login(request, username, password):
|
||||
db = request.app.state.db
|
||||
with db.pool.connection() as conn:
|
||||
row = conn.execute('SELECT '+USER_FIELDS+', password_hash FROM users WHERE username=%s', (username,)).fetchone()
|
||||
valid = check_password(row['password_hash'] if row else DUMMY_HASH, password)
|
||||
if not row or not valid:
|
||||
raise unauthorized(basic=True)
|
||||
row.pop('password_hash')
|
||||
token, expires_at = new_session(db.session_ttl)
|
||||
with db.pool.connection() as conn:
|
||||
conn.execute('INSERT INTO sessions(token_hash,user_id,expires_at) VALUES (%s,%s,%s)',
|
||||
(digest(token), row['id'], expires_at))
|
||||
return {'token': token, 'token_type': 'Bearer', 'expires_at': stamp(expires_at), 'user': public(row)}
|
||||
|
||||
@app.get('/api/v1/users/me')
|
||||
def me(request: Request, user_id=Depends(authenticate)):
|
||||
db = request.app.state.db
|
||||
key = 'user:' + str(user_id)
|
||||
try:
|
||||
cached = db.cache.get(key)
|
||||
if cached:
|
||||
return json.loads(cached)
|
||||
except (RedisError, ValueError):
|
||||
pass
|
||||
with db.pool.connection() as conn:
|
||||
row = conn.execute('SELECT '+USER_FIELDS+' FROM users WHERE id=%s', (user_id,)).fetchone()
|
||||
if not row:
|
||||
raise unauthorized()
|
||||
result = public(row)
|
||||
try:
|
||||
db.cache.set(key, json.dumps(result), ex=60)
|
||||
except RedisError:
|
||||
pass
|
||||
return result
|
||||
|
||||
@app.delete('/api/v1/auth/sessions/current', status_code=204)
|
||||
def logout(request: Request, user_id=Depends(authenticate)):
|
||||
with request.app.state.db.pool.connection() as conn:
|
||||
conn.execute('DELETE FROM sessions WHERE token_hash=%s', (request.state.token_hash,))
|
||||
return Response(status_code=204)
|
||||
|
||||
@app.post('/api/v1/chats', status_code=201)
|
||||
def create_chat(body: CreateChat, request: Request, user_id=Depends(authenticate)):
|
||||
if str(user_id) not in body.member_ids:
|
||||
raise invalid()
|
||||
try:
|
||||
with request.app.state.db.pool.connection() as conn:
|
||||
row = conn.execute('INSERT INTO chats(id,title) VALUES (%s,%s) RETURNING id,title,created_at',
|
||||
(uuid4(), body.title)).fetchone()
|
||||
# An unknown user raises AFTER the chat INSERT; transaction context rolls it all back.
|
||||
with conn.cursor() as cur:
|
||||
cur.executemany('INSERT INTO chat_members(chat_id,user_id) VALUES (%s,%s)',
|
||||
[(row['id'], uuid_value(member)) for member in body.member_ids])
|
||||
result = chat_public(conn, row)
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
raise invalid() from None
|
||||
return result
|
||||
|
||||
@app.get('/api/v1/chats')
|
||||
def list_chats(request: Request, user_id=Depends(authenticate)):
|
||||
limit = page_limit(request.query_params.get('limit', '50'))
|
||||
scope = 'chats:' + str(user_id)
|
||||
after = decode_cursor(scope, request.query_params.get('cursor'))
|
||||
where = ' AND (c.created_at,c.id) > (%s,%s)' if after else ''
|
||||
params = (user_id, *after, limit+1) if after else (user_id, limit+1)
|
||||
with request.app.state.db.pool.connection() as conn:
|
||||
rows = conn.execute('SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members m ON m.chat_id=c.id '
|
||||
'WHERE m.user_id=%s'+where+' ORDER BY c.created_at,c.id LIMIT %s', params).fetchall()
|
||||
result = page(scope, rows, limit)
|
||||
result['items'] = [chat_public(conn, row) for row in rows[:limit]]
|
||||
return result
|
||||
|
||||
@app.get('/api/v1/chats/{chat_id}')
|
||||
def get_chat(chat_id: str, request: Request, user_id=Depends(authenticate)):
|
||||
cid = uuid_value(chat_id)
|
||||
with request.app.state.db.pool.connection() as conn:
|
||||
require_member(conn, cid, user_id)
|
||||
row = conn.execute('SELECT id,title,created_at FROM chats WHERE id=%s', (cid,)).fetchone()
|
||||
return chat_public(conn, row)
|
||||
|
||||
@app.post('/api/v1/chats/{chat_id}/messages', status_code=201)
|
||||
def send_message(chat_id: str, body: CreateMessage, request: Request, user_id=Depends(authenticate)):
|
||||
cid = uuid_value(chat_id)
|
||||
key = validate_key(request.headers.get('Idempotency-Key', ''))
|
||||
with request.app.state.db.pool.connection() as conn:
|
||||
require_member(conn, cid, user_id)
|
||||
row = store_message(conn, user_id, cid, body.text, key, body.attachment_ids)
|
||||
return public(row)
|
||||
|
||||
@app.get('/api/v1/chats/{chat_id}/messages')
|
||||
def history(chat_id: str, request: Request, user_id=Depends(authenticate)):
|
||||
cid = uuid_value(chat_id)
|
||||
limit = page_limit(request.query_params.get('limit', '50'))
|
||||
scope = 'messages:' + str(cid)
|
||||
with request.app.state.db.pool.connection() as conn:
|
||||
require_member(conn, cid, user_id)
|
||||
after = decode_cursor(scope, request.query_params.get('cursor'))
|
||||
where = ' AND (m.created_at,m.id) > (%s,%s)' if after else ''
|
||||
params = (cid, *after, limit+1) if after else (cid, limit+1)
|
||||
rows = conn.execute('SELECT '+MESSAGE_FIELDS+' FROM messages m WHERE m.chat_id=%s'+where+
|
||||
' ORDER BY m.created_at,m.id LIMIT %s', params).fetchall()
|
||||
return page(scope, rows, limit)
|
||||
|
||||
@app.post('/api/v1/chats/{chat_id}/attachments',status_code=201)
|
||||
async def upload_attachment(chat_id: str,request: Request,filename: str='',user_id=Depends(authenticate)):
|
||||
cid=uuid_value(chat_id)
|
||||
def access():
|
||||
with request.app.state.db.pool.connection() as conn:
|
||||
require_member(conn,cid,user_id)
|
||||
await run_in_threadpool(access)
|
||||
return await attachments.upload(request,user_id,cid,filename)
|
||||
|
||||
@app.get('/api/v1/attachments/{attachment_id}')
|
||||
def attachment_metadata(attachment_id: str,request: Request,user_id=Depends(authenticate)):
|
||||
aid=uuid_value(attachment_id)
|
||||
with request.app.state.db.pool.connection() as conn:
|
||||
row=attachments.lookup(conn,aid,user_id)
|
||||
return attachments.metadata(row)
|
||||
|
||||
@app.get('/api/v1/attachments/{attachment_id}/content')
|
||||
def attachment_content(attachment_id: str,request: Request,variant: str='original',user_id=Depends(authenticate)):
|
||||
aid=uuid_value(attachment_id)
|
||||
with request.app.state.db.pool.connection() as conn:
|
||||
row=attachments.lookup(conn,aid,user_id)
|
||||
if variant!='original':
|
||||
raise invalid()
|
||||
opened=request.app.state.storage.get(row['object_key'])
|
||||
if opened.length!=row['size_bytes']:
|
||||
opened.close()
|
||||
raise unavailable()
|
||||
return attachments.ObjectResponse(opened,media_type=row['content_type'],headers={
|
||||
'Content-Length':str(row['size_bytes']),
|
||||
'Content-Disposition':"inline; filename*=UTF-8''"+quote(row['filename'],safe='')})
|
||||
|
||||
return app
|
||||
@@ -0,0 +1,176 @@
|
||||
"""Bounded binary upload, image validation and DB/S3 coordination."""
|
||||
import asyncio
|
||||
import hashlib
|
||||
import logging
|
||||
import tempfile
|
||||
import threading
|
||||
import unicodedata
|
||||
import warnings
|
||||
from uuid import uuid4
|
||||
|
||||
import psycopg
|
||||
from PIL import Image, PngImagePlugin, UnidentifiedImageError
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from starlette.requests import ClientDisconnect
|
||||
from starlette.responses import StreamingResponse
|
||||
|
||||
from .errors import ApiError, invalid, not_found
|
||||
from .pagination import public
|
||||
|
||||
MAX_BYTES=10485760
|
||||
MAX_PIXELS=40000000
|
||||
Image.MAX_IMAGE_PIXELS=MAX_PIXELS
|
||||
PngImagePlugin.MAX_TEXT_CHUNK=1048576
|
||||
PngImagePlugin.MAX_TEXT_MEMORY=1048576
|
||||
warnings.filterwarnings('error',category=Image.DecompressionBombWarning)
|
||||
DECODER=threading.BoundedSemaphore(1)
|
||||
LOG=logging.getLogger('messenger')
|
||||
FIELDS='id,chat_id,owner_id,filename,content_type,size_bytes,sha256,created_at,updated_at'
|
||||
|
||||
|
||||
def object_lock(conn,key,wait=True):
|
||||
function='pg_advisory_xact_lock' if wait else 'pg_try_advisory_xact_lock'
|
||||
row=conn.execute('SELECT '+function+'(hashtextextended(%s,0)) AS locked',(key,)).fetchone()
|
||||
return True if wait else row['locked']
|
||||
|
||||
|
||||
def filename_value(value):
|
||||
if not value or not value.strip() or len(value)>255:
|
||||
raise invalid()
|
||||
try:
|
||||
value.encode('utf-8')
|
||||
except UnicodeError:
|
||||
raise invalid() from None
|
||||
if any(c in '/\\' or unicodedata.category(c)=='Cc' for c in value):
|
||||
raise invalid()
|
||||
return value
|
||||
|
||||
|
||||
def metadata(row):
|
||||
result=public({key:value for key,value in row.items() if key!='object_key'})
|
||||
result.update(status='ready',variants=[],error_code=None)
|
||||
return result
|
||||
|
||||
|
||||
def validate_image(file,mime):
|
||||
if not DECODER.acquire(timeout=3):
|
||||
raise ApiError(503,'unavailable','Обработка изображений занята')
|
||||
try:
|
||||
file.seek(0)
|
||||
with Image.open(file) as image:
|
||||
actual={'PNG':'image/png','JPEG':'image/jpeg'}.get(image.format)
|
||||
if actual is None or actual!=mime:
|
||||
raise ApiError(415,'unsupported_media_type','Ожидается PNG или JPEG с правильным MIME')
|
||||
if image.width*image.height>MAX_PIXELS:
|
||||
raise ApiError(413,'payload_too_large','Изображение превышает лимит пикселей')
|
||||
image.verify()
|
||||
file.seek(0)
|
||||
with Image.open(file) as image:
|
||||
image.load()
|
||||
file.seek(0)
|
||||
except (Image.DecompressionBombWarning,Image.DecompressionBombError):
|
||||
raise ApiError(413,'payload_too_large','Изображение превышает лимит пикселей') from None
|
||||
except (UnidentifiedImageError,OSError,SyntaxError,ValueError,EOFError):
|
||||
raise ApiError(415,'unsupported_media_type','Повреждённое или неподдерживаемое изображение') from None
|
||||
finally:
|
||||
DECODER.release()
|
||||
|
||||
|
||||
def compensate(db,store,key):
|
||||
"""A failed/unknown COMMIT is not proof of absence. Recheck under the same lock."""
|
||||
try:
|
||||
with db.pool.connection() as conn:
|
||||
if not object_lock(conn,key,wait=False):
|
||||
return
|
||||
exists=conn.execute('SELECT 1 FROM attachments WHERE object_key=%s',(key,)).fetchone()
|
||||
if not exists:
|
||||
store.delete(key)
|
||||
except Exception as exc:
|
||||
# A periodic, grace-protected janitor will retry after dependency recovery.
|
||||
LOG.warning('attachment_compensation_deferred type=%s',type(exc).__name__)
|
||||
|
||||
|
||||
def persist(db,store,user_id,chat_id,filename,mime,file,length,digest):
|
||||
key='originals/'+uuid4().hex
|
||||
try:
|
||||
with db.pool.connection() as conn:
|
||||
object_lock(conn,key)
|
||||
store.put(key,file,length,mime)
|
||||
row=conn.execute('INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,object_key) '
|
||||
'VALUES (%s,%s,%s,%s,%s,%s,%s,%s) RETURNING '+FIELDS,
|
||||
(uuid4(),chat_id,user_id,filename,mime,length,digest,key)).fetchone()
|
||||
return metadata(row)
|
||||
except ApiError:
|
||||
compensate(db,store,key)
|
||||
raise
|
||||
except psycopg.Error:
|
||||
compensate(db,store,key)
|
||||
raise ApiError(503,'unavailable','Не удалось сохранить вложение') from None
|
||||
except BaseException:
|
||||
compensate(db,store,key)
|
||||
raise
|
||||
|
||||
|
||||
async def upload(request,user_id,chat_id,filename):
|
||||
filename=filename_value(filename)
|
||||
mime=request.headers.get('Content-Type','').split(';')[0].strip().lower()
|
||||
if mime not in ('image/png','image/jpeg'):
|
||||
raise ApiError(415,'unsupported_media_type','Ожидается image/png или image/jpeg')
|
||||
declared=request.headers.get('Content-Length')
|
||||
if declared is not None:
|
||||
try:
|
||||
length=int(declared)
|
||||
if length<0:
|
||||
raise ValueError
|
||||
except ValueError:
|
||||
raise invalid() from None
|
||||
if length>MAX_BYTES:
|
||||
raise ApiError(413,'payload_too_large','Файл превышает 10 MiB')
|
||||
try:
|
||||
await asyncio.wait_for(request.app.state.upload_slots.acquire(),timeout=1)
|
||||
except TimeoutError:
|
||||
raise ApiError(503,'unavailable','Слишком много загрузок') from None
|
||||
try:
|
||||
with tempfile.TemporaryFile(mode='w+b') as file:
|
||||
total=0
|
||||
digest=hashlib.sha256()
|
||||
async def read_body():
|
||||
nonlocal total
|
||||
async for chunk in request.stream():
|
||||
total+=len(chunk)
|
||||
if total>MAX_BYTES:
|
||||
raise ApiError(413,'payload_too_large','Файл превышает 10 MiB')
|
||||
digest.update(chunk)
|
||||
await run_in_threadpool(file.write,chunk)
|
||||
try:
|
||||
await asyncio.wait_for(read_body(),timeout=30)
|
||||
except TimeoutError:
|
||||
raise ApiError(400,'invalid_request','Время загрузки истекло') from None
|
||||
except ClientDisconnect:
|
||||
raise invalid() from None
|
||||
await run_in_threadpool(validate_image,file,mime)
|
||||
return await run_in_threadpool(persist,request.app.state.db,request.app.state.storage,
|
||||
user_id,chat_id,filename,mime,file,total,digest.hexdigest())
|
||||
finally:
|
||||
request.app.state.upload_slots.release()
|
||||
|
||||
|
||||
def lookup(conn,attachment_id,user_id):
|
||||
row=conn.execute('SELECT '+', '.join('a.'+field for field in (FIELDS+',object_key').split(','))+
|
||||
' FROM attachments a JOIN chat_members m ON m.chat_id=a.chat_id '
|
||||
'WHERE a.id=%s AND m.user_id=%s',(attachment_id,user_id)).fetchone()
|
||||
if not row:
|
||||
raise not_found()
|
||||
return row
|
||||
|
||||
|
||||
class ObjectResponse(StreamingResponse):
|
||||
def __init__(self,opened,**kwargs):
|
||||
self.opened=opened
|
||||
super().__init__(opened.chunks(),**kwargs)
|
||||
|
||||
async def __call__(self,scope,receive,send):
|
||||
try:
|
||||
await super().__call__(scope,receive,send)
|
||||
finally:
|
||||
self.opened.close()
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Grace-protected orphan cleanup; absence is verified in the primary DB under lock."""
|
||||
import argparse
|
||||
from datetime import datetime,timezone,timedelta
|
||||
import json
|
||||
from pathlib import Path
|
||||
import time
|
||||
|
||||
from .attachments import object_lock
|
||||
from .db import Database
|
||||
from .object_store import ObjectStore
|
||||
|
||||
|
||||
def sweep(db,store,grace_seconds=300,apply=False):
|
||||
if grace_seconds<60:
|
||||
raise ValueError('Grace must be at least60seconds')
|
||||
cutoff=datetime.now(timezone.utc)-timedelta(seconds=grace_seconds)
|
||||
result={'mode':'apply' if apply else 'dry-run','grace_seconds':grace_seconds,
|
||||
'listed':0,'fresh':0,'tracked':0,'locked':0,'orphans':0,'deleted':0}
|
||||
for page in store.pages():
|
||||
for obj in page.get('Contents',[]):
|
||||
result['listed']+=1
|
||||
if obj['LastModified']>=cutoff:
|
||||
result['fresh']+=1
|
||||
continue
|
||||
with db.pool.connection() as conn:
|
||||
if not object_lock(conn,obj['Key'],wait=False):
|
||||
result['locked']+=1
|
||||
continue
|
||||
if conn.execute('SELECT 1 FROM attachments WHERE object_key=%s',(obj['Key'],)).fetchone():
|
||||
result['tracked']+=1
|
||||
continue
|
||||
result['orphans']+=1
|
||||
if apply:
|
||||
store.delete(obj['Key'])
|
||||
result['deleted']+=1
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser()
|
||||
parser.add_argument('--grace-seconds',type=int,default=300)
|
||||
parser.add_argument('--apply',action='store_true')
|
||||
parser.add_argument('--dry-run',action='store_true')
|
||||
parser.add_argument('--loop',action='store_true')
|
||||
parser.add_argument('--interval',type=int,default=60)
|
||||
args=parser.parse_args()
|
||||
if args.grace_seconds<60 or args.interval<1 or (args.apply and args.dry_run):
|
||||
parser.error('Use grace>=60, interval>=1 and either --apply or --dry-run')
|
||||
db=Database()
|
||||
store=ObjectStore()
|
||||
db.open()
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
result=sweep(db,store,args.grace_seconds,args.apply)
|
||||
print(json.dumps(result),flush=True)
|
||||
except Exception as exc:
|
||||
print(json.dumps({'error':type(exc).__name__,'deleted_unknown':False}),flush=True)
|
||||
if not args.loop:
|
||||
raise
|
||||
finally:
|
||||
Path('/tmp/cleanup-heartbeat').touch()
|
||||
if not args.loop:
|
||||
break
|
||||
time.sleep(args.interval)
|
||||
finally:
|
||||
store.close()
|
||||
db.close()
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Bounded dependencies; PostgreSQL is always the source of truth."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
from redis import Redis
|
||||
from redis.backoff import NoBackoff
|
||||
from redis.retry import Retry
|
||||
|
||||
|
||||
def setting(name, default=None):
|
||||
filename = os.environ.get(name + '_FILE')
|
||||
value = Path(filename).read_text().strip() if filename else os.environ.get(name, default)
|
||||
if value is None:
|
||||
raise RuntimeError(f'Missing configuration: {name}')
|
||||
return value
|
||||
|
||||
|
||||
class Database:
|
||||
def __init__(self):
|
||||
self.session_ttl = int(setting('SESSION_TTL_SECONDS', '3600'))
|
||||
if self.session_ttl < 1:
|
||||
raise ValueError('SESSION_TTL_SECONDS must be positive')
|
||||
self.pool = ConnectionPool(
|
||||
setting('DATABASE_URL'), min_size=1, max_size=int(setting('POOL_MAX_SIZE', '8')),
|
||||
timeout=2, max_waiting=16, open=False,
|
||||
kwargs={'row_factory': dict_row, 'connect_timeout': 3,
|
||||
'options': '-c statement_timeout=3000 -c lock_timeout=2000 -c idle_in_transaction_session_timeout=5000'},
|
||||
)
|
||||
self.cache = Redis.from_url(
|
||||
setting('CACHE_URL', 'redis://redis:6379/0'), decode_responses=True,
|
||||
socket_connect_timeout=0.2, socket_timeout=0.2, max_connections=8,
|
||||
retry=Retry(NoBackoff(), 0),
|
||||
)
|
||||
|
||||
def open(self):
|
||||
self.pool.open(wait=True, timeout=30)
|
||||
|
||||
def close(self):
|
||||
self.pool.close()
|
||||
self.cache.close()
|
||||
@@ -0,0 +1,19 @@
|
||||
class ApiError(Exception):
|
||||
def __init__(self, status, code, message, headers=None):
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.headers = headers or {}
|
||||
|
||||
|
||||
def invalid():
|
||||
return ApiError(400, 'invalid_request', 'Неверный запрос')
|
||||
|
||||
|
||||
def unauthorized(basic=False):
|
||||
scheme = 'Basic realm="messenger", charset="UTF-8"' if basic else 'Bearer realm="messenger"'
|
||||
return ApiError(401, 'unauthorized', 'Требуется аутентификация', {'WWW-Authenticate': scheme})
|
||||
|
||||
|
||||
def not_found():
|
||||
return ApiError(404, 'not_found', 'Объект не найден')
|
||||
@@ -0,0 +1,52 @@
|
||||
"""One PostgreSQL transaction owns both a message and its retry result."""
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from uuid import uuid4
|
||||
|
||||
from .errors import ApiError, invalid, not_found
|
||||
from .models import uuid_value
|
||||
|
||||
|
||||
def validate_key(key):
|
||||
if not re.fullmatch(r'[A-Za-z0-9._:-]{1,128}', key):
|
||||
raise invalid()
|
||||
return key
|
||||
|
||||
|
||||
MESSAGE_FIELDS = 'm.id,m.chat_id,m.sender_id,m.text,m.created_at,ARRAY(SELECT attachment_id FROM message_attachments WHERE message_id=m.id ORDER BY position) AS attachment_ids'
|
||||
|
||||
|
||||
def store_message(conn, user_id, chat_id, text, key, attachment_ids=None):
|
||||
attachment_ids=[] if attachment_ids is None else attachment_ids
|
||||
payload={'text':text}
|
||||
if attachment_ids:
|
||||
payload['attachment_ids']=attachment_ids
|
||||
canonical = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
|
||||
fingerprint = hashlib.sha256(canonical.encode('utf-8')).hexdigest()
|
||||
params = (user_id, chat_id, key)
|
||||
# A competing INSERT waits for the other transaction, then the next statement sees its result.
|
||||
conn.execute("INSERT INTO idempotency_records(user_id,chat_id,key,request_hash,expires_at) "
|
||||
"VALUES (%s,%s,%s,%s,clock_timestamp()+interval '24 hours') ON CONFLICT DO NOTHING",
|
||||
(*params, fingerprint))
|
||||
record = conn.execute('SELECT request_hash,message_id,expires_at > clock_timestamp() AS active '
|
||||
'FROM idempotency_records WHERE user_id=%s AND chat_id=%s AND key=%s FOR UPDATE', params).fetchone()
|
||||
if record['message_id'] is not None and record['active']:
|
||||
if record['request_hash'] != fingerprint:
|
||||
raise ApiError(409, 'conflict', 'Ключ уже использован с другим сообщением')
|
||||
return conn.execute('SELECT '+MESSAGE_FIELDS+' FROM messages m WHERE m.id=%s',
|
||||
(record['message_id'],)).fetchone()
|
||||
ids=[uuid_value(item) for item in attachment_ids]
|
||||
if ids:
|
||||
allowed=conn.execute('SELECT id FROM attachments WHERE chat_id=%s AND id=ANY(%s)',(chat_id,ids)).fetchall()
|
||||
if len(allowed)!=len(ids):
|
||||
raise not_found()
|
||||
row = conn.execute('INSERT INTO messages(id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) '
|
||||
'RETURNING id,chat_id,sender_id,text,created_at', (uuid4(), chat_id, user_id, text)).fetchone()
|
||||
if ids:
|
||||
with conn.cursor() as cur:
|
||||
cur.executemany('INSERT INTO message_attachments(message_id,attachment_id,position) VALUES (%s,%s,%s)',
|
||||
[(row['id'],aid,i) for i,aid in enumerate(ids)])
|
||||
conn.execute("UPDATE idempotency_records SET request_hash=%s,message_id=%s,expires_at=clock_timestamp()+interval '24 hours' "
|
||||
'WHERE user_id=%s AND chat_id=%s AND key=%s', (fingerprint, row['id'], *params))
|
||||
return conn.execute('SELECT '+MESSAGE_FIELDS+' FROM messages m WHERE m.id=%s',(row['id'],)).fetchone()
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Versioned, atomic, repeatable migrations, serialized with an advisory lock."""
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from .db import setting
|
||||
|
||||
|
||||
def main():
|
||||
directory = Path(__file__).resolve().parents[2] / 'migrations'
|
||||
with psycopg.connect(setting('DATABASE_URL'), connect_timeout=3) as conn:
|
||||
conn.execute('SELECT pg_advisory_xact_lock(20261102)')
|
||||
conn.execute('CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY, sha256 text NOT NULL, applied_at timestamptz NOT NULL DEFAULT now())')
|
||||
for path in sorted(directory.glob('*.sql')):
|
||||
sql = path.read_text()
|
||||
checksum = hashlib.sha256(sql.encode()).hexdigest()
|
||||
found = conn.execute('SELECT sha256 FROM schema_migrations WHERE version=%s', (path.name,)).fetchone()
|
||||
if found:
|
||||
if found[0] != checksum:
|
||||
raise RuntimeError('Applied migration checksum changed: ' + path.name)
|
||||
continue
|
||||
conn.execute(sql)
|
||||
conn.execute('INSERT INTO schema_migrations(version,sha256) VALUES (%s,%s)', (path.name, checksum))
|
||||
print('Applied', path.name)
|
||||
print('Migrations up to date')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,75 @@
|
||||
import re
|
||||
from uuid import UUID
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
from .errors import invalid
|
||||
|
||||
|
||||
def uuid_value(value):
|
||||
try:
|
||||
# Require the UUID string representation, not integer/coercible values.
|
||||
if not isinstance(value, str) or len(value) != 36:
|
||||
raise ValueError
|
||||
return UUID(value)
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
raise invalid() from None
|
||||
|
||||
|
||||
class StrictModel(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid', strict=True)
|
||||
|
||||
@field_validator('*')
|
||||
@classmethod
|
||||
def valid_strings(cls, value, info):
|
||||
if isinstance(value, str):
|
||||
if not value.strip() and info.field_name != 'text':
|
||||
raise ValueError('Blank string')
|
||||
# PostgreSQL cannot store NUL or unpaired Unicode surrogates.
|
||||
if '\x00' in value:
|
||||
raise ValueError('NUL is not supported')
|
||||
value.encode('utf-8')
|
||||
return value
|
||||
|
||||
|
||||
class CreateUser(StrictModel):
|
||||
username: str = Field(pattern=r'^[a-z0-9_]{3,32}$')
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
password: str = Field(min_length=12, max_length=128)
|
||||
|
||||
@field_validator('username')
|
||||
@classmethod
|
||||
def username_ascii(cls, value):
|
||||
if not re.fullmatch(r'[a-z0-9_]{3,32}', value):
|
||||
raise ValueError('Invalid username')
|
||||
return value
|
||||
|
||||
|
||||
class CreateChat(StrictModel):
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: list[str] = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator('member_ids')
|
||||
@classmethod
|
||||
def members(cls, value):
|
||||
ids = [uuid_value(item) for item in value]
|
||||
if len(ids) != len(set(ids)):
|
||||
raise ValueError('Duplicate member')
|
||||
return [str(item) for item in ids]
|
||||
|
||||
|
||||
class CreateMessage(StrictModel):
|
||||
text: str = Field(max_length=4000)
|
||||
attachment_ids: list[str] = Field(default_factory=list,max_length=10)
|
||||
|
||||
@field_validator('attachment_ids')
|
||||
@classmethod
|
||||
def attachment_values(cls,value):
|
||||
ids=[uuid_value(item) for item in value]
|
||||
if len(ids)!=len(set(ids)):
|
||||
raise ValueError('Duplicate attachment')
|
||||
return [str(item) for item in ids]
|
||||
|
||||
@model_validator(mode='after')
|
||||
def nonempty_message(self):
|
||||
if not self.text.strip() and not self.attachment_ids:
|
||||
raise ValueError('Message must contain text or attachment')
|
||||
return self
|
||||
@@ -0,0 +1,109 @@
|
||||
"""Small bounded S3 client. API credentials never contain root/admin permissions."""
|
||||
from contextlib import contextmanager
|
||||
import threading
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from .db import setting
|
||||
from .errors import ApiError
|
||||
|
||||
PREFIX = 'originals/'
|
||||
|
||||
|
||||
def unavailable():
|
||||
return ApiError(503,'unavailable','Хранилище файлов временно недоступно')
|
||||
|
||||
|
||||
class OpenObject:
|
||||
def __init__(self,body,release,length):
|
||||
self.body=body
|
||||
self.release=release
|
||||
self.length=length
|
||||
self.closed=False
|
||||
self.close_lock=threading.Lock()
|
||||
|
||||
def chunks(self):
|
||||
try:
|
||||
while True:
|
||||
data=self.body.read(65536)
|
||||
if not data:
|
||||
break
|
||||
yield data
|
||||
finally:
|
||||
self.close()
|
||||
|
||||
def close(self):
|
||||
with self.close_lock:
|
||||
if self.closed:
|
||||
return
|
||||
self.closed=True
|
||||
try:
|
||||
self.body.close()
|
||||
finally:
|
||||
self.release()
|
||||
|
||||
|
||||
class ObjectStore:
|
||||
def __init__(self):
|
||||
self.bucket=setting('S3_BUCKET','messenger-attachments')
|
||||
self.gate=threading.BoundedSemaphore(8)
|
||||
self.client=boto3.client('s3',endpoint_url=setting('S3_ENDPOINT','http://minio:9000'),
|
||||
region_name=setting('S3_REGION','us-east-1'),
|
||||
aws_access_key_id=setting('S3_ACCESS_KEY_ID'),aws_secret_access_key=setting('S3_SECRET_ACCESS_KEY'),
|
||||
config=Config(signature_version='s3v4',connect_timeout=1,read_timeout=3,max_pool_connections=8,
|
||||
retries={'total_max_attempts':1,'mode':'standard'},s3={'addressing_style':'path'},
|
||||
request_checksum_calculation='when_required',response_checksum_validation='when_required'))
|
||||
|
||||
@contextmanager
|
||||
def operation(self):
|
||||
if not self.gate.acquire(timeout=1):
|
||||
raise unavailable()
|
||||
try:
|
||||
yield
|
||||
except (BotoCoreError,ClientError):
|
||||
raise unavailable() from None
|
||||
finally:
|
||||
self.gate.release()
|
||||
|
||||
def check(self):
|
||||
with self.operation():
|
||||
self.client.list_objects_v2(Bucket=self.bucket,Prefix=PREFIX,MaxKeys=1)
|
||||
|
||||
def put(self,key,body,length,mime):
|
||||
with self.operation():
|
||||
body.seek(0)
|
||||
self.client.put_object(Bucket=self.bucket,Key=key,Body=body,ContentLength=length,ContentType=mime)
|
||||
|
||||
def delete(self,key):
|
||||
with self.operation():
|
||||
self.client.delete_object(Bucket=self.bucket,Key=key)
|
||||
|
||||
def get(self,key):
|
||||
if not self.gate.acquire(timeout=1):
|
||||
raise unavailable()
|
||||
try:
|
||||
result=self.client.get_object(Bucket=self.bucket,Key=key)
|
||||
return OpenObject(result['Body'],self.gate.release,result['ContentLength'])
|
||||
except (BotoCoreError,ClientError):
|
||||
self.gate.release()
|
||||
raise unavailable() from None
|
||||
except BaseException:
|
||||
self.gate.release()
|
||||
raise
|
||||
|
||||
def pages(self):
|
||||
token=None
|
||||
while True:
|
||||
params={'Bucket':self.bucket,'Prefix':PREFIX,'MaxKeys':1000}
|
||||
if token:
|
||||
params['ContinuationToken']=token
|
||||
with self.operation():
|
||||
result=self.client.list_objects_v2(**params)
|
||||
yield result
|
||||
if not result.get('IsTruncated'):
|
||||
break
|
||||
token=result['NextContinuationToken']
|
||||
|
||||
def close(self):
|
||||
self.client.close()
|
||||
@@ -0,0 +1,56 @@
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime, timezone
|
||||
from uuid import UUID
|
||||
from .errors import invalid
|
||||
from .models import uuid_value
|
||||
|
||||
|
||||
def stamp(value):
|
||||
return value.astimezone(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
|
||||
|
||||
|
||||
def encode_cursor(scope, row):
|
||||
raw = json.dumps([scope, stamp(row['created_at']), str(row['id'])], separators=(',', ':')).encode()
|
||||
return base64.urlsafe_b64encode(raw).decode().rstrip('=')
|
||||
|
||||
|
||||
def decode_cursor(scope, value):
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if not re.fullmatch(r'[A-Za-z0-9_-]{1,1024}', value):
|
||||
raise ValueError
|
||||
data = json.loads(base64.b64decode(value + '=' * (-len(value) % 4), altchars=b'-_', validate=True))
|
||||
if not isinstance(data, list) or len(data) != 3 or data[0] != scope:
|
||||
raise ValueError
|
||||
ts = datetime.fromisoformat(data[1].replace('Z', '+00:00'))
|
||||
if ts.tzinfo is None:
|
||||
raise ValueError
|
||||
return ts, uuid_value(data[2])
|
||||
except (ValueError, TypeError, AttributeError, OverflowError):
|
||||
raise invalid() from None
|
||||
|
||||
|
||||
def page_limit(value):
|
||||
if not re.fullmatch(r'[0-9]{1,3}', value) or not 1 <= int(value) <= 100:
|
||||
raise invalid()
|
||||
return int(value)
|
||||
|
||||
|
||||
def public(row):
|
||||
def value(item):
|
||||
if isinstance(item,datetime):
|
||||
return stamp(item)
|
||||
if isinstance(item,UUID):
|
||||
return str(item)
|
||||
if isinstance(item,list):
|
||||
return [value(part) for part in item]
|
||||
return item
|
||||
return {key:value(item) for key,item in row.items()}
|
||||
|
||||
|
||||
def page(scope, rows, limit):
|
||||
return {'items': [public(row) for row in rows[:limit]],
|
||||
'next_cursor': encode_cursor(scope, rows[limit-1]) if len(rows) > limit else None}
|
||||
@@ -0,0 +1,49 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import re
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerificationError, InvalidHashError
|
||||
from .errors import unauthorized
|
||||
|
||||
HASHER = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
|
||||
DUMMY_HASH = HASHER.hash('synthetic-dummy-password')
|
||||
|
||||
|
||||
def digest(token):
|
||||
return hashlib.sha256(token.encode()).hexdigest()
|
||||
|
||||
|
||||
def basic_credentials(header):
|
||||
try:
|
||||
scheme, encoded = header.split(' ', 1)
|
||||
if scheme.lower() != 'basic':
|
||||
raise ValueError
|
||||
username, password = base64.b64decode(encoded, validate=True).decode('utf-8').split(':', 1)
|
||||
if not re.fullmatch(r'[a-z0-9_]{3,32}', username) or not 12 <= len(password) <= 128:
|
||||
raise ValueError
|
||||
return username, password
|
||||
except (ValueError, UnicodeError):
|
||||
raise unauthorized(basic=True) from None
|
||||
|
||||
|
||||
def check_password(encoded, password):
|
||||
try:
|
||||
return HASHER.verify(encoded, password)
|
||||
except (VerificationError, InvalidHashError):
|
||||
return False
|
||||
|
||||
|
||||
def bearer(header):
|
||||
try:
|
||||
scheme, token = header.split(' ', 1)
|
||||
if scheme.lower() != 'bearer' or not re.fullmatch(r'[A-Za-z0-9_-]{43}', token):
|
||||
raise ValueError
|
||||
return token
|
||||
except ValueError:
|
||||
raise unauthorized() from None
|
||||
|
||||
|
||||
def new_session(ttl):
|
||||
return secrets.token_urlsafe(32), datetime.now(timezone.utc) + timedelta(seconds=ttl)
|
||||
Reference in New Issue
Block a user