Реализовать ЛР 7 на оценку 3

This commit is contained in:
2026-12-04 14:27:18 +03:00
parent 31d441184b
commit 7996ebbb48
59 changed files with 2236 additions and 498 deletions
+49 -5
View File
@@ -1,11 +1,10 @@
import logging
import os
import socket
import time
from uuid import uuid4
from opentelemetry import trace
from starlette.datastructures import MutableHeaders
from starlette.datastructures import Headers, MutableHeaders
from ..observability import get_metrics
from ..observability.logging import safe_extra
@@ -15,9 +14,52 @@ logger = logging.getLogger('app')
class RequestContext:
def __init__(self, app) -> None:
def __init__(self, app, request_max_bytes: int, upload_max_bytes: int) -> None:
self.app = app
self.instance_id = os.getenv('INSTANCE_ID') or socket.gethostname()
self.instance_id = os.getenv('INSTANCE_ID') or uuid4().hex
if min(request_max_bytes, upload_max_bytes) <= 0:
raise ValueError('HTTP body limits must be positive')
self.request_max_bytes = request_max_bytes
self.upload_max_bytes = upload_max_bytes
async def _body_receiver(self, scope, receive, send, request_id):
segments = scope['path'].split('/')
upload = (
scope['method'] == 'POST' and len(segments) == 6
and segments[:4] == ['', 'api', 'v1', 'chats'] and segments[-1] == 'attachments'
)
limit = self.upload_max_bytes if upload else self.request_max_bytes
length = Headers(scope=scope).get('content-length')
if length is not None and int(length) > limit:
await error_response(413, 'тело запроса превышает лимит', request_id)(scope, receive, send)
return None
if upload:
# The upload service applies the same cap while consuming chunks.
return receive
body = bytearray()
while True:
message = await receive()
if message['type'] == 'http.disconnect':
return None
chunk = message.get('body', b'')
if len(chunk) > limit - len(body):
await error_response(413, 'тело запроса превышает лимит', request_id)(scope, receive, send)
return None
body.extend(chunk)
if not message.get('more_body', False):
break
pending = True
async def replay():
nonlocal pending
if not pending:
return await receive()
pending = False
return {'type': 'http.request', 'body': bytes(body), 'more_body': False}
return replay
async def __call__(self, scope, receive, send) -> None:
if scope['type'] != 'http':
@@ -42,7 +84,9 @@ class RequestContext:
await send(message)
try:
await self.app(scope, receive, send_wrapper)
body_receiver = await self._body_receiver(scope, receive, send_wrapper, request_id)
if body_receiver is not None:
await self.app(scope, body_receiver, send_wrapper)
except Exception:
logger.exception(
'unhandled HTTP error',
+11 -1
View File
@@ -3,7 +3,7 @@ from __future__ import annotations
import base64
from binascii import Error as Base64Error
from fastapi import APIRouter, Depends, HTTPException, Security, status
from fastapi import APIRouter, Depends, HTTPException, Request, Security, status
from ...auth.tokens import create_token
from ...db.redis import RedisSessionStore
@@ -45,10 +45,20 @@ def _parse_basic(authorization: str | None) -> tuple[str, str]:
@router.post('', status_code=status.HTTP_201_CREATED, response_model=SessionOut)
async def create_session(
request: Request,
authorization: str | None = Security(basic_auth),
users: UserService = Depends(user_service),
sessions: RedisSessionStore = Depends(session_store),
) -> SessionOut:
peer = request.client.host if request.client else 'unknown'
client_ip = request.headers.get('X-Verified-Client-Ip', peer)
retry_after = await request.app.state.login_limiter.reserve(client_ip)
if retry_after:
raise HTTPException(
status_code=429,
detail='слишком много попыток входа',
headers={'Retry-After': str(retry_after)},
)
username, password = _parse_basic(authorization)
user = await users.authenticate(username, password)
if user is None: