File size: 3,979 Bytes
3993434 1a3097b 3993434 1a3097b 3993434 1a3097b 3993434 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | """Admission control before FastAPI parses multipart bodies."""
import asyncio
import json
import tempfile
import threading
from starlette.requests import Request
from starlette.responses import JSONResponse
class RequestAdmission:
def __init__(self, app, authorize, max_upload_bytes=256 * 1024 * 1024,
max_json_bytes=1024 * 1024, max_requests=8):
self.app = app
self.authorize = authorize
self.max_upload_bytes = max_upload_bytes
self.max_json_bytes = max_json_bytes
self.slots = threading.BoundedSemaphore(max_requests)
async def __call__(self, scope, receive, send):
if scope['type'] != 'http' or scope['method'] == 'OPTIONS':
return await self.app(scope, receive, send)
path = scope['path']
protected = (path in ('/transcribe', '/companion/transcribe', '/translate', '/minutes', '/minutes/docx', '/paystack/init', '/paystack/verify', '/donate')
or any(path.startswith(p) for p in ('/result/', '/status/', '/progress/', '/cancel/', '/donate/')))
if protected:
try:
uid = await asyncio.to_thread(self.authorize, Request(scope))
scope.setdefault('state', {})['verified_uid'] = uid
except Exception as e:
status = getattr(e, 'status_code', 503)
detail = getattr(e, 'detail', 'Authentication unavailable')
return await JSONResponse({'detail': detail}, status_code=status)(scope, receive, send)
if scope['method'] not in ('POST', 'PUT', 'PATCH'):
return await self.app(scope, receive, send)
# Audio uploads: transcription and donated recordings.
limit = self.max_upload_bytes if path in ('/transcribe', '/donate') else self.max_json_bytes
headers = dict(scope.get('headers', []))
try:
length = int(headers.get(b'content-length', b'0'))
if length < 0: raise ValueError()
except ValueError:
return await JSONResponse({'detail': 'Invalid Content-Length'}, status_code=400)(scope, receive, send)
if length > limit:
return await JSONResponse({'detail': 'Request too large'}, status_code=413)(scope, receive, send)
if not self.slots.acquire(blocking=False):
return await JSONResponse({'detail': 'Server busy. Retry later.'}, status_code=429,
headers={'Retry-After': '30'})(scope, receive, send)
try:
# Bound memory even for chunked bodies; check bytes before multipart parsing.
with tempfile.SpooledTemporaryFile(max_size=1024 * 1024) as body:
size = 0
async def consume():
nonlocal size
while True:
message = await receive()
if message['type'] == 'http.disconnect': return False
chunk = message.get('body', b'')
size += len(chunk)
if size > limit: return False
body.write(chunk)
if not message.get('more_body', False): return True
try:
ok = await asyncio.wait_for(consume(), timeout=600 if path in ('/transcribe', '/donate') else 30)
except asyncio.TimeoutError:
return await JSONResponse({'detail': 'Upload timed out'}, status_code=408)(scope, receive, send)
if not ok:
return await JSONResponse({'detail': 'Request too large or interrupted'}, status_code=413)(scope, receive, send)
body.seek(0)
async def replay():
chunk = body.read(65536)
return {'type': 'http.request', 'body': chunk, 'more_body': body.tell() < size}
await self.app(scope, replay, send)
finally:
self.slots.release()
|