ЛР 5: очередь и асинхронная обработка изображений
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
"""Persistent, confirmed RabbitMQ messages contain identifiers only."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import pika
|
||||
|
||||
QUEUE = 'attachments.v1'
|
||||
|
||||
def connect():
|
||||
url = Path(os.environ['BROKER_URL_FILE']).read_text().strip()
|
||||
params = pika.URLParameters(url)
|
||||
params.heartbeat = 0 # one bounded image at a time; connection failure causes redelivery
|
||||
params.socket_timeout = 5
|
||||
params.blocked_connection_timeout = 10
|
||||
connection = pika.BlockingConnection(params)
|
||||
channel = connection.channel()
|
||||
channel.queue_declare(queue=QUEUE, durable=True)
|
||||
channel.confirm_delivery()
|
||||
return connection, channel
|
||||
@@ -0,0 +1,26 @@
|
||||
import hashlib
|
||||
from fastapi import Header, HTTPException
|
||||
from app.storage import db
|
||||
|
||||
BEARER_CHALLENGE = {"WWW-Authenticate": 'Bearer realm="messenger"'}
|
||||
BASIC_CHALLENGE = {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
|
||||
|
||||
|
||||
def unauthorized(basic=False):
|
||||
raise HTTPException(status_code=401, detail="Unauthorized", headers=BASIC_CHALLENGE if basic else BEARER_CHALLENGE)
|
||||
|
||||
|
||||
def current_user(authorization: str | None = Header(default=None)):
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
unauthorized()
|
||||
token = authorization[7:]
|
||||
if not token or " " in token:
|
||||
unauthorized()
|
||||
with db() as conn:
|
||||
user = conn.execute("""SELECT u.id,u.username,u.display_name,u.created_at FROM sessions s
|
||||
JOIN users u ON u.id=s.user_id
|
||||
WHERE s.token_hash=%s AND s.expires_at > now()""",
|
||||
(hashlib.sha256(token.encode()).hexdigest(),)).fetchone()
|
||||
if user is None:
|
||||
unauthorized()
|
||||
return user
|
||||
@@ -0,0 +1,46 @@
|
||||
"""DB-backed delivery intent, periodically republished until a terminal state.
|
||||
|
||||
Publishing and DB commit are deliberately repeatable: confirmed publish followed
|
||||
by a crash may duplicate a job, never lose an acknowledged upload.
|
||||
"""
|
||||
import json
|
||||
import time
|
||||
import pika
|
||||
from app.broker import connect, QUEUE
|
||||
from app.storage import db
|
||||
from app.models.time_format import utc_z
|
||||
|
||||
def publish_due(channel):
|
||||
with db() as conn:
|
||||
jobs = conn.execute('''SELECT j.* FROM attachment_jobs j
|
||||
JOIN attachments a ON a.id=j.attachment_id
|
||||
WHERE a.status IN ('queued','processing') AND j.next_publish<=now()
|
||||
ORDER BY j.next_publish LIMIT 20 FOR UPDATE OF j SKIP LOCKED''').fetchall()
|
||||
for job in jobs:
|
||||
body = dict(schema_version=1, job_id=str(job['job_id']),
|
||||
type='attachment.process.v1', attachment_id=str(job['attachment_id']),
|
||||
pipeline_version=job['pipeline_version'], attempt=job['attempts']+1,
|
||||
created_at=utc_z(job['created_at']))
|
||||
channel.basic_publish(exchange='', routing_key=QUEUE, body=json.dumps(body),
|
||||
properties=pika.BasicProperties(delivery_mode=2, content_type='application/json',
|
||||
message_id=str(job['job_id'])), mandatory=True)
|
||||
conn.execute("UPDATE attachment_jobs SET next_publish=now()+interval '10 seconds' WHERE job_id=%s",
|
||||
(job['job_id'],))
|
||||
|
||||
def main():
|
||||
while True:
|
||||
connection = None
|
||||
try:
|
||||
connection, channel = connect()
|
||||
while True:
|
||||
publish_due(channel)
|
||||
connection.process_data_events(time_limit=1)
|
||||
except Exception as exc:
|
||||
print('dispatcher reconnect:', type(exc).__name__, flush=True)
|
||||
time.sleep(2)
|
||||
finally:
|
||||
if connection and connection.is_open:
|
||||
connection.close()
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
"""Replicated API. Schema migration is a separate one-shot Compose service."""
|
||||
import os
|
||||
from uuid import uuid4
|
||||
from fastapi import FastAPI, Request, HTTPException
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from psycopg import OperationalError
|
||||
from app.routers import users, chats, messages, attachments
|
||||
from app.s3 import s3_client,bucket
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from app.storage import db
|
||||
|
||||
INSTANCE_ID = os.environ.get('API_INSTANCE_ID') or str(uuid4())
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
def error_code(status):
|
||||
return {400:'invalid_request',401:'unauthorized',404:'not_found',409:'conflict',413:'payload_too_large',415:'unsupported_media_type',429:'rate_limited',503:'unavailable'}.get(status,'internal_error')
|
||||
|
||||
|
||||
def error_response(request,status,message,headers=None):
|
||||
result=JSONResponse(status_code=status,content={'error':{
|
||||
'code':error_code(status),'message':message,'request_id':request.state.request_id}},headers=headers)
|
||||
result.headers['X-Request-Id']=request.state.request_id
|
||||
result.headers['X-Instance-Id']=INSTANCE_ID
|
||||
return result
|
||||
|
||||
|
||||
@app.middleware('http')
|
||||
async def add_request_id(request:Request,call_next):
|
||||
request.state.request_id=str(uuid4())
|
||||
try:
|
||||
response=await call_next(request)
|
||||
except OperationalError:
|
||||
response=error_response(request,503,'Database unavailable')
|
||||
except Exception:
|
||||
response=error_response(request,500,'Internal server error')
|
||||
response.headers['X-Request-Id']=request.state.request_id
|
||||
response.headers['X-Instance-Id']=INSTANCE_ID
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def http_error(request,exc):
|
||||
return error_response(request,exc.status_code,str(exc.detail),exc.headers)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error(request,exc):
|
||||
return error_response(request,400,'Invalid request')
|
||||
|
||||
app.include_router(users.router)
|
||||
app.include_router(chats.router)
|
||||
app.include_router(messages.router)
|
||||
app.include_router(attachments.router)
|
||||
|
||||
@app.get('/health/live')
|
||||
def live():
|
||||
return {'status':'ok'}
|
||||
|
||||
@app.get('/health/ready')
|
||||
def ready():
|
||||
with db() as conn:
|
||||
conn.execute('SELECT 1')
|
||||
try:
|
||||
s3_client().head_bucket(Bucket=bucket())
|
||||
except (ClientError,BotoCoreError,OSError):
|
||||
raise HTTPException(503,'Storage unavailable')
|
||||
return {'status':'ok'}
|
||||
@@ -0,0 +1,5 @@
|
||||
"""One-shot schema migration (never run from individual API replicas)."""
|
||||
from app.storage import migrate
|
||||
if __name__ == '__main__':
|
||||
migrate()
|
||||
print('Migrations completed')
|
||||
@@ -0,0 +1,39 @@
|
||||
from datetime import datetime
|
||||
from app.models.time_format import utc_z
|
||||
from uuid import UUID
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, field_serializer
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: list[UUID] = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator("title")
|
||||
@classmethod
|
||||
def title_must_not_be_blank(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("title must not be blank")
|
||||
return value
|
||||
|
||||
@field_validator("member_ids")
|
||||
@classmethod
|
||||
def member_ids_must_be_unique(cls, value: list[UUID]) -> list[UUID]:
|
||||
if len(value) != len(set(value)):
|
||||
raise ValueError("member_ids must be unique")
|
||||
return value
|
||||
|
||||
class Chat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
id: UUID
|
||||
title: str
|
||||
member_ids: list[UUID]
|
||||
created_at: datetime
|
||||
|
||||
@field_serializer("created_at", when_used="json")
|
||||
def serialize_created_at(self, value: datetime) -> str:
|
||||
return utc_z(value)
|
||||
|
||||
class ChatPage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
items: list[Chat]
|
||||
next_cursor: str | None
|
||||
@@ -0,0 +1,35 @@
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, field_serializer, model_validator
|
||||
from app.models.time_format import utc_z
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
text: str = Field(max_length=4000)
|
||||
attachment_ids: list[UUID] = Field(default_factory=list,max_length=10)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def valid_content(self):
|
||||
if len(set(self.attachment_ids)) != len(self.attachment_ids):
|
||||
raise ValueError('duplicate attachments')
|
||||
if not self.text.strip() and not self.attachment_ids:
|
||||
raise ValueError('message must contain text or attachments')
|
||||
return self
|
||||
|
||||
class Message(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
sender_id: UUID
|
||||
text: str
|
||||
created_at: datetime
|
||||
attachment_ids: list[UUID]
|
||||
|
||||
@field_serializer('created_at', when_used='json')
|
||||
def serialize_created_at(self, value: datetime) -> str:
|
||||
return utc_z(value)
|
||||
|
||||
class MessagePage(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
items: list[Message]
|
||||
next_cursor: str | None
|
||||
@@ -0,0 +1,9 @@
|
||||
"""Contract requires RFC3339 UTC timestamps with a literal Z suffix."""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
def utc_z(value: datetime) -> str:
|
||||
if value.tzinfo is None:
|
||||
# Database columns are TIMESTAMPTZ, but keep the serializer defensive.
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
return value.astimezone(timezone.utc).isoformat().replace('+00:00', 'Z')
|
||||
@@ -0,0 +1,28 @@
|
||||
from datetime import datetime
|
||||
from app.models.time_format import utc_z
|
||||
from uuid import UUID
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, field_serializer
|
||||
|
||||
class CreateUser(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
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("display_name")
|
||||
@classmethod
|
||||
def nonempty(cls, value):
|
||||
if not value.strip():
|
||||
raise ValueError("Blank display name")
|
||||
return value
|
||||
|
||||
class User(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
id: UUID
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: datetime
|
||||
|
||||
@field_serializer("created_at", when_used="json")
|
||||
def serialize_created_at(self, value: datetime) -> str:
|
||||
return utc_z(value)
|
||||
@@ -0,0 +1,177 @@
|
||||
"""Bounded image uploads, authorized streaming downloads and private object storage."""
|
||||
import hashlib
|
||||
import os
|
||||
import tempfile
|
||||
import unicodedata
|
||||
from uuid import UUID, uuid4
|
||||
from io import BytesIO
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Query
|
||||
from fastapi.responses import StreamingResponse
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from PIL import Image, UnidentifiedImageError, ImageFile
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from app.dependencies import current_user
|
||||
from app.routers.chats import get_chat_row
|
||||
from app.storage import db
|
||||
from app.s3 import s3_client, bucket
|
||||
from app.models.time_format import utc_z
|
||||
from pydantic import BaseModel, ConfigDict, field_serializer
|
||||
from datetime import datetime
|
||||
|
||||
router=APIRouter()
|
||||
MAX_BYTES=10*1024*1024
|
||||
MAX_PIXELS=40_000_000
|
||||
CHUNK=64*1024
|
||||
Image.MAX_IMAGE_PIXELS=MAX_PIXELS
|
||||
ImageFile.LOAD_TRUNCATED_IMAGES=False
|
||||
|
||||
class Attachment(BaseModel):
|
||||
model_config=ConfigDict(extra='forbid')
|
||||
id:UUID
|
||||
chat_id:UUID
|
||||
owner_id:UUID
|
||||
filename:str
|
||||
content_type:str
|
||||
size_bytes:int
|
||||
sha256:str
|
||||
status:str
|
||||
variants:list=[]
|
||||
error_code:str|None=None
|
||||
created_at:datetime
|
||||
updated_at:datetime
|
||||
@field_serializer('created_at','updated_at',when_used='json')
|
||||
def as_utc(self,value:datetime)->str:
|
||||
return utc_z(value)
|
||||
|
||||
def public(row):
|
||||
return {k:row[k] for k in ('id','chat_id','owner_id','filename','content_type','size_bytes',
|
||||
'sha256','status','created_at','updated_at')} | {'variants':row.get('variants',[]),'error_code':row.get('error_code')}
|
||||
|
||||
def check_name(name):
|
||||
if not 1<=len(name)<=255 or any(ch in '/\\' or ord(ch)<32 or 127<=ord(ch)<160 or unicodedata.category(ch)=='Cc' for ch in name):
|
||||
raise HTTPException(400,'Invalid filename')
|
||||
|
||||
def inspect_image(file, declared):
|
||||
file.seek(0)
|
||||
try:
|
||||
with Image.open(file) as img:
|
||||
fmt=img.format
|
||||
w,h=img.size
|
||||
if w<=0 or h<=0 or w*h>MAX_PIXELS:
|
||||
raise HTTPException(413,'Image pixel count exceeded')
|
||||
expected={'PNG':'image/png','JPEG':'image/jpeg'}.get(fmt)
|
||||
if not expected or expected!=declared:
|
||||
raise HTTPException(415,'Image content type mismatch')
|
||||
img.verify()
|
||||
file.seek(0)
|
||||
with Image.open(file) as img:
|
||||
img.load() # reject truncated PNG/JPEG and decompression errors
|
||||
except HTTPException:
|
||||
raise
|
||||
except (UnidentifiedImageError, ValueError, OSError, SyntaxError, Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||
raise HTTPException(415,'Invalid image')
|
||||
finally:
|
||||
file.seek(0)
|
||||
|
||||
def put_original(file, key, content_type):
|
||||
client=s3_client()
|
||||
file.seek(0)
|
||||
client.upload_fileobj(file,bucket(),key,ExtraArgs={'ContentType':content_type},
|
||||
Config=__import__('boto3').s3.transfer.TransferConfig(
|
||||
multipart_threshold=16*1024*1024,use_threads=False))
|
||||
|
||||
def delete_original(key):
|
||||
s3_client().delete_object(Bucket=bucket(),Key=key)
|
||||
|
||||
@router.post('/api/v1/chats/{chat_id}/attachments',response_model=Attachment,status_code=202)
|
||||
async def upload(chat_id:UUID,request:Request, filename:str=Query(...),user=Depends(current_user)):
|
||||
check_name(filename)
|
||||
declared=request.headers.get('content-type','').lower()
|
||||
if declared not in ('image/png','image/jpeg'):
|
||||
raise HTTPException(415,'Only PNG and JPEG are supported')
|
||||
with db() as conn:
|
||||
if get_chat_row(conn,chat_id,user['id']) is None:
|
||||
raise HTTPException(404,'Chat not found')
|
||||
length=request.headers.get('content-length')
|
||||
if length is not None:
|
||||
try:
|
||||
if int(length)>MAX_BYTES:raise HTTPException(413,'Upload too large')
|
||||
except ValueError:
|
||||
raise HTTPException(400,'Invalid content length')
|
||||
size=0
|
||||
digest=hashlib.sha256()
|
||||
# Disk-backed temporary spool; no API replica retains permanent content.
|
||||
with tempfile.SpooledTemporaryFile(max_size=1024*1024,mode='w+b') as file:
|
||||
async for part in request.stream():
|
||||
size+=len(part)
|
||||
if size>MAX_BYTES:
|
||||
raise HTTPException(413,'Upload too large')
|
||||
digest.update(part)
|
||||
file.write(part)
|
||||
if not size:raise HTTPException(415,'Empty image')
|
||||
await run_in_threadpool(inspect_image,file,declared)
|
||||
ident=uuid4()
|
||||
key='staging/'+str(ident)
|
||||
try:
|
||||
await run_in_threadpool(put_original,file,key,declared)
|
||||
except (ClientError,BotoCoreError,OSError):
|
||||
# A partially written object is possible after a transport error.
|
||||
try:await run_in_threadpool(delete_original,key)
|
||||
except Exception:pass # periodic reconciler can remove an orphan after grace
|
||||
raise HTTPException(503,'Storage unavailable')
|
||||
try:
|
||||
with db() as conn:
|
||||
if get_chat_row(conn,chat_id,user['id']) is None:
|
||||
raise HTTPException(404,'Chat not found')
|
||||
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 *''',
|
||||
(ident,chat_id,user['id'],filename,declared,size,digest.hexdigest(),key)).fetchone()
|
||||
conn.execute('INSERT INTO attachment_jobs(job_id,attachment_id) VALUES (%s,%s)',
|
||||
(uuid4(),ident))
|
||||
except Exception:
|
||||
try:await run_in_threadpool(delete_original,key)
|
||||
except Exception:pass
|
||||
raise
|
||||
return public(row)
|
||||
|
||||
def authorized(ident,user):
|
||||
with db() as conn:
|
||||
row=conn.execute('''SELECT a.* FROM attachments a
|
||||
JOIN chat_members cm ON cm.chat_id=a.chat_id AND cm.user_id=%s
|
||||
WHERE a.id=%s''',(user['id'],ident)).fetchone()
|
||||
if row is None:raise HTTPException(404,'Attachment not found')
|
||||
return row
|
||||
|
||||
@router.get('/api/v1/attachments/{attachment_id}',response_model=Attachment)
|
||||
def get_attachment(attachment_id:UUID,user=Depends(current_user)):
|
||||
return public(authorized(attachment_id,user))
|
||||
|
||||
@router.get('/api/v1/attachments/{attachment_id}/content')
|
||||
def download(attachment_id:UUID,variant:str='original',user=Depends(current_user)):
|
||||
row=authorized(attachment_id,user)
|
||||
if row['status']!='ready':raise HTTPException(409,'Attachment is not ready')
|
||||
content_type=row['content_type']
|
||||
size=row['size_bytes']
|
||||
key=row['object_key']
|
||||
if variant!='original':
|
||||
found=next((v for v in row['variants'] if v['name']==variant),None)
|
||||
if found is None:raise HTTPException(404,'Variant not found')
|
||||
key=f"results/{attachment_id}/v1/{variant}"
|
||||
content_type=found['content_type']
|
||||
size=found['size_bytes']
|
||||
try:
|
||||
obj=s3_client().get_object(Bucket=bucket(),Key=key)
|
||||
except (ClientError,BotoCoreError,OSError):
|
||||
raise HTTPException(503,'Storage unavailable')
|
||||
body=obj['Body']
|
||||
def chunks():
|
||||
try:
|
||||
for chunk in body.iter_chunks(chunk_size=CHUNK):
|
||||
if chunk:yield chunk
|
||||
finally:
|
||||
body.close()
|
||||
return StreamingResponse(chunks(),media_type=content_type,headers={
|
||||
'Content-Length':str(size),
|
||||
'Content-Disposition':'attachment',
|
||||
'X-Content-Type-Options':'nosniff'})
|
||||
@@ -0,0 +1,52 @@
|
||||
from uuid import UUID, uuid4
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from app.dependencies import current_user
|
||||
from app.models.chats import Chat, ChatPage, CreateChat
|
||||
from app.storage import db
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def get_chat_row(conn, chat_id, user_id):
|
||||
return conn.execute("""SELECT c.id,c.title,c.created_at FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id=c.id WHERE c.id=%s AND cm.user_id=%s""",
|
||||
(chat_id,user_id)).fetchone()
|
||||
|
||||
|
||||
def chat_output(conn,row):
|
||||
members=conn.execute('SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY user_id',(row['id'],)).fetchall()
|
||||
return {**row, 'member_ids':[m['user_id'] for m in members]}
|
||||
|
||||
|
||||
@router.post('/api/v1/chats', response_model=Chat, status_code=201)
|
||||
def create_chat(payload:CreateChat,user=Depends(current_user)):
|
||||
if user['id'] not in payload.member_ids:
|
||||
raise HTTPException(status_code=400,detail='Creator must be a chat member')
|
||||
with db() as conn:
|
||||
rows=conn.execute('SELECT id FROM users WHERE id = ANY(%s)',(payload.member_ids,)).fetchall()
|
||||
if len(rows)!=len(payload.member_ids):
|
||||
raise HTTPException(status_code=400,detail='Unknown member')
|
||||
chat=conn.execute('INSERT INTO chats(id,title) VALUES (%s,%s) RETURNING id,title,created_at',
|
||||
(uuid4(),payload.title)).fetchone()
|
||||
for member in payload.member_ids:
|
||||
conn.execute('INSERT INTO chat_members(chat_id,user_id) VALUES (%s,%s)',(chat['id'],member))
|
||||
return chat_output(conn,chat)
|
||||
|
||||
|
||||
@router.get('/api/v1/chats',response_model=ChatPage)
|
||||
def list_chats(limit:int=Query(default=50,ge=1,le=100),user=Depends(current_user)):
|
||||
with db() 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
|
||||
ORDER BY c.created_at,c.id LIMIT %s""",(user['id'],limit+1)).fetchall()
|
||||
items=[chat_output(conn,row) for row in rows[:limit]]
|
||||
return {'items':items,'next_cursor':None}
|
||||
|
||||
|
||||
@router.get('/api/v1/chats/{chat_id}',response_model=Chat)
|
||||
def get_chat(chat_id:UUID,user=Depends(current_user)):
|
||||
with db() as conn:
|
||||
row=get_chat_row(conn,chat_id,user['id'])
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404,detail='Chat not found')
|
||||
return chat_output(conn,row)
|
||||
@@ -0,0 +1,115 @@
|
||||
import base64
|
||||
import binascii
|
||||
import json
|
||||
import hashlib
|
||||
import re
|
||||
from datetime import datetime
|
||||
from uuid import UUID,uuid4
|
||||
from fastapi import APIRouter,Depends,HTTPException,Query,Header
|
||||
from app.dependencies import current_user
|
||||
from app.models.messages import CreateMessage,Message,MessagePage
|
||||
from app.routers.chats import get_chat_row
|
||||
from app.storage import db
|
||||
|
||||
router=APIRouter()
|
||||
|
||||
MESSAGE_SELECT = """SELECT m.id,m.chat_id,m.sender_id,m.text,m.created_at,
|
||||
COALESCE((SELECT array_agg(ma.attachment_id ORDER BY ma.position)
|
||||
FROM message_attachments ma WHERE ma.message_id=m.id), ARRAY[]::uuid[]) AS attachment_ids
|
||||
FROM messages m"""
|
||||
|
||||
|
||||
|
||||
def encode_cursor(chat_id,row):
|
||||
raw=json.dumps({'chat_id':str(chat_id),'created_at':row['created_at'].isoformat(),'id':str(row['id'])}).encode()
|
||||
return base64.urlsafe_b64encode(raw).decode().rstrip('=')
|
||||
|
||||
|
||||
def decode_cursor(chat_id,cursor):
|
||||
try:
|
||||
raw=base64.b64decode(cursor+'='*(-len(cursor)%4),altchars=b'-_',validate=True)
|
||||
data=json.loads(raw)
|
||||
ts=datetime.fromisoformat(data['created_at'])
|
||||
ident=UUID(data['id'])
|
||||
if data['chat_id']!=str(chat_id) or ts.tzinfo is None:
|
||||
raise ValueError('Wrong cursor')
|
||||
return ts,ident
|
||||
except (ValueError,KeyError,TypeError,UnicodeDecodeError,binascii.Error):
|
||||
raise HTTPException(status_code=400,detail='Invalid cursor')
|
||||
|
||||
|
||||
IDEMPOTENCY_KEY_RE = re.compile(r'^[A-Za-z0-9._:-]{1,128}$', re.ASCII)
|
||||
|
||||
|
||||
def canonical_message_hash(payload):
|
||||
# Canonical semantics, not raw JSON bytes or field order.
|
||||
data = payload.model_dump(mode='json', exclude_none=True)
|
||||
data.setdefault('attachment_ids', [])
|
||||
return hashlib.sha256(json.dumps(data, sort_keys=True, separators=(',', ':'),
|
||||
ensure_ascii=False).encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def advisory_lock_id(user_id,chat_id,key):
|
||||
scope = f'{user_id}:{chat_id}:{key}'.encode('utf-8')
|
||||
return int.from_bytes(hashlib.sha256(scope).digest()[:8], 'big', signed=True)
|
||||
|
||||
|
||||
@router.post('/api/v1/chats/{chat_id}/messages',response_model=Message,status_code=201)
|
||||
def create_message(chat_id:UUID,payload:CreateMessage,user=Depends(current_user),
|
||||
idempotency_key:str|None=Header(default=None,alias='Idempotency-Key')):
|
||||
if idempotency_key is None or not IDEMPOTENCY_KEY_RE.fullmatch(idempotency_key):
|
||||
raise HTTPException(status_code=400,detail='Invalid or missing Idempotency-Key')
|
||||
request_hash=canonical_message_hash(payload)
|
||||
with db() as conn:
|
||||
# Explicit authorization is checked on EVERY replay, not just initial POST.
|
||||
if get_chat_row(conn,chat_id,user['id']) is None:
|
||||
raise HTTPException(status_code=404,detail='Chat not found')
|
||||
# Same key on different processes serializes in PostgreSQL. The message and
|
||||
# key record commit together, so a network timeout cannot create duplicates.
|
||||
conn.execute('SELECT pg_advisory_xact_lock(%s)',
|
||||
(advisory_lock_id(user['id'],chat_id,idempotency_key),))
|
||||
saved=conn.execute("""SELECT request_hash,message_id,created_at FROM message_idempotency
|
||||
WHERE user_id=%s AND chat_id=%s AND idem_key=%s FOR UPDATE""",
|
||||
(user['id'],chat_id,idempotency_key)).fetchone()
|
||||
if saved is not None:
|
||||
# Contract promises a replay window of at least 24 hours; retaining
|
||||
# keys longer is safe and prevents late duplicate deliveries.
|
||||
if saved['request_hash'] != request_hash:
|
||||
raise HTTPException(status_code=409,detail='Idempotency-Key used with another body')
|
||||
return conn.execute(MESSAGE_SELECT + """ WHERE m.id=%s""",(saved['message_id'],)).fetchone()
|
||||
if payload.attachment_ids:
|
||||
authorized=conn.execute("""SELECT id,status FROM attachments
|
||||
WHERE chat_id=%s AND id=ANY(%s) FOR SHARE""",
|
||||
(chat_id,payload.attachment_ids)).fetchall()
|
||||
if len(authorized)!=len(payload.attachment_ids):
|
||||
raise HTTPException(status_code=404,detail='Attachment not found')
|
||||
if any(a['status']=='failed' for a in authorized):
|
||||
raise HTTPException(status_code=409,detail='Attachment failed')
|
||||
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'],payload.text)).fetchone()
|
||||
for pos,attachment_id in enumerate(payload.attachment_ids):
|
||||
conn.execute("""INSERT INTO message_attachments(message_id,attachment_id,position)
|
||||
VALUES (%s,%s,%s)""",(row['id'],attachment_id,pos))
|
||||
row['attachment_ids']=payload.attachment_ids
|
||||
conn.execute("""INSERT INTO message_idempotency(user_id,chat_id,idem_key,request_hash,message_id)
|
||||
VALUES (%s,%s,%s,%s,%s)""",
|
||||
(user['id'],chat_id,idempotency_key,request_hash,row['id']))
|
||||
return row
|
||||
|
||||
|
||||
@router.get('/api/v1/chats/{chat_id}/messages',response_model=MessagePage)
|
||||
def list_messages(chat_id:UUID,limit:int=Query(default=50,ge=1,le=100),
|
||||
cursor:str|None=Query(default=None,min_length=1),user=Depends(current_user)):
|
||||
with db() as conn:
|
||||
if get_chat_row(conn,chat_id,user['id']) is None:
|
||||
raise HTTPException(status_code=404,detail='Chat not found')
|
||||
if cursor is not None:
|
||||
ts,ident=decode_cursor(chat_id,cursor)
|
||||
rows=conn.execute(MESSAGE_SELECT + """ WHERE m.chat_id=%s AND (m.created_at,m.id)>(%s,%s)
|
||||
ORDER BY m.created_at,m.id LIMIT %s""",(chat_id,ts,ident,limit+1)).fetchall()
|
||||
else:
|
||||
rows=conn.execute(MESSAGE_SELECT + """ WHERE m.chat_id=%s ORDER BY m.created_at,m.id LIMIT %s""",(chat_id,limit+1)).fetchall()
|
||||
items=rows[:limit]
|
||||
next_cursor=encode_cursor(chat_id,items[-1]) if len(rows)>limit else None
|
||||
return {'items':items,'next_cursor':next_cursor}
|
||||
@@ -0,0 +1,78 @@
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from uuid import uuid4
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Response
|
||||
from psycopg.errors import UniqueViolation
|
||||
from app.dependencies import current_user, unauthorized
|
||||
from app.models.users import CreateUser, User
|
||||
from app.models.time_format import utc_z
|
||||
from app.storage import db
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def password_hash(password):
|
||||
salt = os.urandom(16)
|
||||
derived = hashlib.scrypt(password.encode('utf-8'), salt=salt, n=2**14, r=8, p=1, dklen=32)
|
||||
return 'scrypt$' + salt.hex() + '$' + derived.hex()
|
||||
|
||||
|
||||
def verify_password(password, encoded):
|
||||
try:
|
||||
_, salt_hex, expected_hex = encoded.split('$')
|
||||
actual = hashlib.scrypt(password.encode('utf-8'),salt=bytes.fromhex(salt_hex),n=2**14,r=8,p=1,dklen=32)
|
||||
return hmac.compare_digest(actual, bytes.fromhex(expected_hex))
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
@router.post('/api/v1/users', response_model=User, status_code=201)
|
||||
def register_user(payload: CreateUser):
|
||||
with db() as conn:
|
||||
try:
|
||||
user = conn.execute("""INSERT INTO users(id,username,display_name,password_hash)
|
||||
VALUES (%s,%s,%s,%s) RETURNING id,username,display_name,created_at""",
|
||||
(uuid4(),payload.username,payload.display_name,password_hash(payload.password))).fetchone()
|
||||
except UniqueViolation:
|
||||
raise HTTPException(status_code=409,detail='Username already exists')
|
||||
return user
|
||||
|
||||
|
||||
@router.get('/api/v1/users/me', response_model=User)
|
||||
def get_current_user(user=Depends(current_user)):
|
||||
return user
|
||||
|
||||
|
||||
@router.post('/api/v1/auth/sessions', status_code=201)
|
||||
def create_session(authorization: str | None = Header(default=None)):
|
||||
if not authorization or not authorization.startswith('Basic '):
|
||||
unauthorized(basic=True)
|
||||
try:
|
||||
raw = base64.b64decode(authorization[6:],validate=True).decode('utf-8')
|
||||
username, password = raw.split(':',1)
|
||||
except (ValueError, UnicodeDecodeError, binascii.Error):
|
||||
unauthorized(basic=True)
|
||||
with db() as conn:
|
||||
row = conn.execute('SELECT * FROM users WHERE username=%s',(username,)).fetchone()
|
||||
if row is None or not verify_password(password,row['password_hash']):
|
||||
unauthorized(basic=True)
|
||||
token = secrets.token_urlsafe(48)
|
||||
ttl = int(os.getenv('SESSION_TTL_SECONDS','3600'))
|
||||
expires = datetime.now(timezone.utc)+timedelta(seconds=ttl)
|
||||
conn.execute('INSERT INTO sessions(token_hash,user_id,expires_at) VALUES (%s,%s,%s)',
|
||||
(hashlib.sha256(token.encode()).hexdigest(),row['id'],expires))
|
||||
return {'token':token,'token_type':'Bearer','expires_at':utc_z(expires),
|
||||
'user':User.model_validate({key:row[key] for key in ('id','username','display_name','created_at')})}
|
||||
|
||||
|
||||
@router.delete('/api/v1/auth/sessions/current',status_code=204)
|
||||
def logout(authorization: str | None = Header(default=None),user=Depends(current_user)):
|
||||
token=authorization[7:]
|
||||
with db() as conn:
|
||||
conn.execute('DELETE FROM sessions WHERE token_hash=%s',(hashlib.sha256(token.encode()).hexdigest(),))
|
||||
return Response(status_code=204)
|
||||
@@ -0,0 +1,19 @@
|
||||
"""S3 access with least-privilege application credentials (never root credentials)."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
|
||||
|
||||
def s3_client():
|
||||
return boto3.client(
|
||||
's3', endpoint_url=os.environ['S3_ENDPOINT'],
|
||||
region_name=os.getenv('S3_REGION','us-east-1'),
|
||||
aws_access_key_id=Path(os.environ['S3_ACCESS_KEY_ID_FILE']).read_text().strip(),
|
||||
aws_secret_access_key=Path(os.environ['S3_SECRET_ACCESS_KEY_FILE']).read_text().strip(),
|
||||
config=Config(connect_timeout=2,read_timeout=15,retries={'max_attempts':2},
|
||||
s3={'addressing_style':'path'}))
|
||||
|
||||
|
||||
def bucket():
|
||||
return os.getenv('S3_BUCKET','messenger-attachments')
|
||||
@@ -0,0 +1,31 @@
|
||||
"""PostgreSQL is the source of truth, including bearer sessions."""
|
||||
import os
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
|
||||
def database_url():
|
||||
secret_file = os.getenv("DATABASE_URL_FILE")
|
||||
if secret_file:
|
||||
return Path(secret_file).read_text().strip()
|
||||
return os.environ["DATABASE_URL"]
|
||||
|
||||
|
||||
@contextmanager
|
||||
def db():
|
||||
with psycopg.connect(database_url(), row_factory=dict_row, connect_timeout=5) as conn:
|
||||
yield conn
|
||||
|
||||
|
||||
def migrate():
|
||||
with db() as conn:
|
||||
# Serialize migration execution even if two operators race to bootstrap.
|
||||
conn.execute("SELECT pg_advisory_xact_lock(83475391)")
|
||||
conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations (version TEXT PRIMARY KEY)")
|
||||
for file in sorted((Path(__file__).parent.parent / "migrations").glob("*.sql")):
|
||||
if conn.execute("SELECT 1 FROM schema_migrations WHERE version=%s", (file.name,)).fetchone():
|
||||
continue
|
||||
conn.execute(file.read_text())
|
||||
conn.execute("INSERT INTO schema_migrations(version) VALUES (%s)", (file.name,))
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
"""At-least-once consumer; PostgreSQL session lock serializes each logical effect."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from io import BytesIO
|
||||
from uuid import UUID
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
from psycopg.types.json import Jsonb
|
||||
from app.broker import connect, QUEUE
|
||||
from app.s3 import s3_client, bucket
|
||||
from app.storage import db
|
||||
|
||||
MAX_ATTEMPTS = int(os.getenv('JOB_MAX_ATTEMPTS', '5'))
|
||||
Image.MAX_IMAGE_PIXELS = 40_000_000
|
||||
|
||||
def render(raw):
|
||||
with Image.open(BytesIO(raw)) as source:
|
||||
if source.width * source.height > 40_000_000:
|
||||
raise ValueError('pixel limit')
|
||||
image = ImageOps.exif_transpose(source).convert('RGBA')
|
||||
scale = min(1, 256/image.width, 256/image.height)
|
||||
dimensions = (max(1, int(image.width*scale)), max(1, int(image.height*scale)))
|
||||
image = image.resize(dimensions, Image.Resampling.LANCZOS)
|
||||
white = Image.new('RGB', dimensions, 'white')
|
||||
white.paste(image, mask=image.getchannel('A'))
|
||||
output = BytesIO()
|
||||
white.save(output, format='JPEG', quality=85)
|
||||
data = output.getvalue()
|
||||
return data, dict(name='thumbnail', content_type='image/jpeg', size_bytes=len(data),
|
||||
width=dimensions[0], height=dimensions[1], sha256=hashlib.sha256(data).hexdigest())
|
||||
|
||||
def process(message):
|
||||
job_id = UUID(message['job_id'])
|
||||
# Stable session advisory lock, released automatically on worker death.
|
||||
lock = int.from_bytes(hashlib.sha256(job_id.bytes).digest()[:8], 'big', signed=True)
|
||||
with db() as conn:
|
||||
if not conn.execute('SELECT pg_try_advisory_lock(%s) AS locked', (lock,)).fetchone()['locked']:
|
||||
return # active owner or DB delivery intent will finish/recover this job
|
||||
conn.commit()
|
||||
row = conn.execute('''SELECT a.*, j.attempts, j.pipeline_version FROM attachment_jobs j
|
||||
JOIN attachments a ON a.id=j.attachment_id WHERE j.job_id=%s''', (job_id,)).fetchone()
|
||||
if not row or row['status'] in ('ready', 'failed'):
|
||||
return
|
||||
if str(row['id']) != message['attachment_id'] or message['pipeline_version'] != row['pipeline_version']:
|
||||
return
|
||||
if row['attempts'] >= MAX_ATTEMPTS:
|
||||
conn.execute("UPDATE attachments SET status='failed',error_code='retry_exhausted',updated_at=now() WHERE id=%s", (row['id'],))
|
||||
return
|
||||
conn.execute('UPDATE attachment_jobs SET attempts=attempts+1 WHERE job_id=%s', (job_id,))
|
||||
conn.execute("UPDATE attachments SET status='processing',updated_at=now() WHERE id=%s", (row['id'],))
|
||||
conn.commit()
|
||||
try:
|
||||
client = s3_client()
|
||||
obj = client.get_object(Bucket=bucket(), Key=row['object_key'])
|
||||
try:
|
||||
raw = obj['Body'].read(10*1024*1024+1)
|
||||
finally:
|
||||
obj['Body'].close()
|
||||
if len(raw) != row['size_bytes'] or hashlib.sha256(raw).hexdigest() != row['sha256']:
|
||||
raise ValueError('checksum mismatch')
|
||||
thumbnail, metadata = render(raw)
|
||||
prefix = f"results/{row['id']}/v1/"
|
||||
client.put_object(Bucket=bucket(), Key=prefix+'original', Body=raw, ContentType=row['content_type'])
|
||||
client.put_object(Bucket=bucket(), Key=prefix+'thumbnail', Body=thumbnail, ContentType='image/jpeg')
|
||||
conn.execute("""UPDATE attachments SET status='ready',object_key=%s,variants=%s,
|
||||
error_code=NULL,updated_at=now() WHERE id=%s""",
|
||||
(prefix+'original', Jsonb([metadata]), row['id']))
|
||||
conn.commit() # consumer ack happens only AFTER this durable result
|
||||
print(f"ready attachment={row['id']} attempt={row['attempts']+1}", flush=True)
|
||||
except Exception as exc:
|
||||
conn.rollback()
|
||||
permanent = isinstance(exc, (ValueError, UnidentifiedImageError, Image.DecompressionBombError))
|
||||
exhausted = row['attempts']+1 >= MAX_ATTEMPTS
|
||||
status = 'failed' if permanent or exhausted else 'queued'
|
||||
code = ('invalid_image' if permanent else 'retry_exhausted') if status=='failed' else None
|
||||
conn.execute('UPDATE attachments SET status=%s,error_code=%s,updated_at=now() WHERE id=%s',
|
||||
(status, code, row['id']))
|
||||
conn.execute("UPDATE attachment_jobs SET next_publish=now()+interval '5 seconds' WHERE job_id=%s", (job_id,))
|
||||
print(f"{status} attachment={row['id']} reason={type(exc).__name__}", flush=True)
|
||||
|
||||
def consume(channel, method, properties, body):
|
||||
try:
|
||||
message = json.loads(body)
|
||||
UUID(message['job_id'])
|
||||
UUID(message['attachment_id'])
|
||||
if message['schema_version'] != 1 or message['type'] != 'attachment.process.v1':
|
||||
raise ValueError('unsupported job')
|
||||
except (ValueError, KeyError, TypeError):
|
||||
channel.basic_reject(method.delivery_tag, requeue=False)
|
||||
return
|
||||
process(message)
|
||||
channel.basic_ack(method.delivery_tag)
|
||||
|
||||
def main():
|
||||
while True:
|
||||
connection = None
|
||||
try:
|
||||
connection, channel = connect()
|
||||
channel.basic_qos(prefetch_count=1)
|
||||
channel.basic_consume(queue=QUEUE, on_message_callback=consume)
|
||||
channel.start_consuming()
|
||||
except Exception as exc:
|
||||
print('worker reconnect:', type(exc).__name__, flush=True)
|
||||
time.sleep(2)
|
||||
finally:
|
||||
if connection and connection.is_open:
|
||||
connection.close()
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user