forked from mtusi2026/mtusi2026lab6
grade3
This commit is contained in:
@@ -8,6 +8,7 @@ import re
|
||||
import struct
|
||||
import hashlib
|
||||
import hmac
|
||||
import logging
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import List, Optional
|
||||
from uuid import UUID
|
||||
@@ -27,35 +28,117 @@ from botocore.client import Config
|
||||
|
||||
import threading
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger — lab5", version="1.5.0")
|
||||
from opentelemetry import metrics, trace
|
||||
from opentelemetry._logs import set_logger_provider
|
||||
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
|
||||
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
|
||||
def outbox_publisher():
|
||||
while True:
|
||||
conn = None
|
||||
try:
|
||||
conn = get_db_connection()
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
SELECT id, stream, payload FROM outbox
|
||||
WHERE published_at IS NULL
|
||||
ORDER BY created_at
|
||||
LIMIT 100
|
||||
FOR UPDATE SKIP LOCKED
|
||||
""")
|
||||
for row in cur.fetchall():
|
||||
redis_client.xadd(row["stream"], {"payload": json.dumps(row["payload"])})
|
||||
cur.execute("UPDATE outbox SET published_at=NOW() WHERE id=%s", (row["id"],))
|
||||
conn.commit()
|
||||
except Exception as e:
|
||||
print(f"OUTBOX PUBLISHER ERROR: {type(e).__name__} - {e}", flush=True)
|
||||
finally:
|
||||
if conn is not None and not conn.closed:
|
||||
conn.close()
|
||||
time.sleep(1)
|
||||
|
||||
@app.on_event("startup")
|
||||
def _start_outbox_publisher():
|
||||
threading.Thread(target=outbox_publisher, daemon=True).start()
|
||||
class JsonLogFormatter(logging.Formatter):
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
span = trace.get_current_span()
|
||||
ctx = span.get_span_context() if span else None
|
||||
trace_id = format(ctx.trace_id, "032x") if ctx and ctx.is_valid else None
|
||||
span_id = format(ctx.span_id, "016x") if ctx and ctx.is_valid else None
|
||||
|
||||
payload = {
|
||||
"ts": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
|
||||
"level": record.levelname,
|
||||
"logger": record.name,
|
||||
"service": os.getenv("OTEL_SERVICE_NAME", "messenger-api"),
|
||||
"msg": record.getMessage(),
|
||||
}
|
||||
if trace_id and span_id:
|
||||
payload["trace_id"] = trace_id
|
||||
payload["span_id"] = span_id
|
||||
|
||||
for attr in ("method", "path", "status_code", "job_id", "attachment_id", "job_status", "attempt", "error_code"):
|
||||
if hasattr(record, attr):
|
||||
payload[attr] = getattr(record, attr)
|
||||
|
||||
if record.exc_info:
|
||||
payload["exception"] = record.exc_info[0].__name__ if record.exc_info[0] else "Exception"
|
||||
|
||||
return json.dumps(payload, ensure_ascii=False)
|
||||
|
||||
|
||||
def setup_api_telemetry():
|
||||
service_name = os.getenv("OTEL_SERVICE_NAME", "messenger-api")
|
||||
endpoint = os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://otel-collector:4318").rstrip("/")
|
||||
env_attrs = os.getenv("OTEL_RESOURCE_ATTRIBUTES", "deployment.environment.name=lab")
|
||||
|
||||
attrs = {"service.name": service_name}
|
||||
for part in env_attrs.split(","):
|
||||
if "=" in part:
|
||||
k, v = part.split("=", 1)
|
||||
attrs[k.strip()] = v.strip()
|
||||
|
||||
resource = Resource.create(attrs)
|
||||
|
||||
tracer_provider = TracerProvider(resource=resource)
|
||||
tracer_provider.add_span_processor(
|
||||
BatchSpanProcessor(OTLPSpanExporter(endpoint=f"{endpoint}/v1/traces"))
|
||||
)
|
||||
trace.set_tracer_provider(tracer_provider)
|
||||
|
||||
metric_reader = PeriodicExportingMetricReader(
|
||||
OTLPMetricExporter(endpoint=f"{endpoint}/v1/metrics"),
|
||||
export_interval_millis=5000,
|
||||
)
|
||||
meter_provider = MeterProvider(resource=resource, metric_readers=[metric_reader])
|
||||
metrics.set_meter_provider(meter_provider)
|
||||
|
||||
logger_provider = LoggerProvider(resource=resource)
|
||||
logger_provider.add_log_record_processor(
|
||||
BatchLogRecordProcessor(OTLPLogExporter(endpoint=f"{endpoint}/v1/logs"))
|
||||
)
|
||||
set_logger_provider(logger_provider)
|
||||
|
||||
root_logger = logging.getLogger()
|
||||
root_logger.setLevel(logging.INFO)
|
||||
root_logger.handlers.clear()
|
||||
|
||||
stream_handler = logging.StreamHandler()
|
||||
stream_handler.setFormatter(JsonLogFormatter())
|
||||
root_logger.addHandler(stream_handler)
|
||||
|
||||
otel_handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider)
|
||||
otel_handler.setFormatter(JsonLogFormatter())
|
||||
root_logger.addHandler(otel_handler)
|
||||
|
||||
return tracer_provider, trace.get_tracer(service_name), metrics.get_meter(service_name)
|
||||
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger — lab6", version="1.6.0")
|
||||
|
||||
_tracer_provider, tracer, meter = setup_api_telemetry()
|
||||
FastAPIInstrumentor.instrument_app(app, tracer_provider=_tracer_provider)
|
||||
api_logger = logging.getLogger("messenger-api")
|
||||
|
||||
api_requests_counter = meter.create_counter(
|
||||
name="http_server_requests_total",
|
||||
description="Total HTTP requests served by API",
|
||||
unit="1",
|
||||
)
|
||||
api_errors_counter = meter.create_counter(
|
||||
name="http_server_errors_total",
|
||||
description="Total HTTP 4xx/5xx responses served by API",
|
||||
unit="1",
|
||||
)
|
||||
api_duration_histogram = meter.create_histogram(
|
||||
name="http_server_request_duration_seconds",
|
||||
description="HTTP request duration in seconds",
|
||||
unit="s",
|
||||
)
|
||||
|
||||
DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://postgres:postgres@postgres:5432/messenger")
|
||||
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
@@ -82,12 +165,77 @@ s3_client = boto3.client(
|
||||
region_name="us-east-1"
|
||||
)
|
||||
|
||||
|
||||
def get_db_connection():
|
||||
return psycopg2.connect(DATABASE_URL, cursor_factory=psycopg2.extras.RealDictCursor)
|
||||
|
||||
|
||||
def outbox_publisher():
|
||||
while True:
|
||||
conn = None
|
||||
try:
|
||||
conn = get_db_connection()
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
SELECT id, stream, payload FROM outbox
|
||||
WHERE published_at IS NULL
|
||||
ORDER BY created_at
|
||||
LIMIT 100
|
||||
FOR UPDATE SKIP LOCKED
|
||||
""")
|
||||
for row in cur.fetchall():
|
||||
redis_client.xadd(row["stream"], {"payload": json.dumps(row["payload"])})
|
||||
cur.execute("UPDATE outbox SET published_at=NOW() WHERE id=%s", (row["id"],))
|
||||
conn.commit()
|
||||
except Exception as e:
|
||||
api_logger.error("Outbox publisher error: %s", type(e).__name__)
|
||||
finally:
|
||||
if conn is not None and not conn.closed:
|
||||
conn.close()
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
def _start_outbox_publisher():
|
||||
threading.Thread(target=outbox_publisher, daemon=True).start()
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def telemetry_middleware(request: Request, call_next):
|
||||
start = time.monotonic()
|
||||
route_obj = request.scope.get("route")
|
||||
route_path = getattr(route_obj, "path", request.url.path)
|
||||
method = request.method
|
||||
status_code = 500
|
||||
try:
|
||||
response = await call_next(request)
|
||||
status_code = response.status_code
|
||||
return response
|
||||
finally:
|
||||
elapsed = time.monotonic() - start
|
||||
low_card_attrs = {
|
||||
"http.method": method,
|
||||
"http.route": route_path,
|
||||
"http.status_code": status_code,
|
||||
}
|
||||
api_requests_counter.add(1, low_card_attrs)
|
||||
api_duration_histogram.record(elapsed, low_card_attrs)
|
||||
if status_code >= 400:
|
||||
api_errors_counter.add(1, low_card_attrs)
|
||||
api_logger.info(
|
||||
"HTTP request completed",
|
||||
extra={
|
||||
"method": method,
|
||||
"path": route_path,
|
||||
"status_code": status_code,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def generate_request_id() -> str:
|
||||
return uuid.uuid4().hex
|
||||
|
||||
|
||||
def make_error_response(
|
||||
status_code: int,
|
||||
code: str,
|
||||
@@ -110,12 +258,14 @@ def make_error_response(
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def encode_cursor(chat_id: str, created_at: str, msg_id: str) -> str:
|
||||
payload = f"{chat_id}|{created_at}|{msg_id}"
|
||||
signature = hmac.new(SECRET_HMAC_KEY.encode(), payload.encode(), hashlib.sha256).hexdigest()[:16]
|
||||
raw = f"{payload}|{signature}"
|
||||
return base64.urlsafe_b64encode(raw.encode()).decode()
|
||||
|
||||
|
||||
def decode_cursor(cursor: str, expected_chat_id: str) -> tuple:
|
||||
try:
|
||||
decoded = base64.urlsafe_b64decode(cursor.encode()).decode()
|
||||
@@ -141,6 +291,7 @@ def decode_cursor(cursor: str, expected_chat_id: str) -> tuple:
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="Invalid cursor format")
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||
req_id = request.headers.get("X-Request-Id") or generate_request_id()
|
||||
@@ -151,6 +302,7 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
|
||||
req_id=req_id
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def http_exception_handler(request: Request, exc: HTTPException):
|
||||
req_id = request.headers.get("X-Request-Id") or generate_request_id()
|
||||
@@ -186,6 +338,7 @@ async def http_exception_handler(request: Request, exc: HTTPException):
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unhandled_exception_handler(request: Request, exc: Exception):
|
||||
req_id = request.headers.get("X-Request-Id") or generate_request_id()
|
||||
@@ -196,6 +349,7 @@ async def unhandled_exception_handler(request: Request, exc: Exception):
|
||||
req_id=req_id,
|
||||
)
|
||||
|
||||
|
||||
class CreateUser(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
username: str = Field(..., pattern=r"^[a-z0-9_]{3,32}$")
|
||||
@@ -208,6 +362,7 @@ class CreateUser(BaseModel):
|
||||
raise ValueError("Must not be blank")
|
||||
return v
|
||||
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
title: str = Field(..., min_length=1, max_length=100)
|
||||
@@ -219,6 +374,7 @@ class CreateChat(BaseModel):
|
||||
raise ValueError("Must not be blank")
|
||||
return v
|
||||
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
text: str = Field(default="", max_length=4000)
|
||||
@@ -230,6 +386,7 @@ class CreateMessage(BaseModel):
|
||||
raise ValueError("Message must contain either text or attachments")
|
||||
return self
|
||||
|
||||
|
||||
@app.get("/health/live")
|
||||
def health_live(response: Response):
|
||||
req_id = generate_request_id()
|
||||
@@ -237,6 +394,7 @@ def health_live(response: Response):
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/health/ready")
|
||||
def health_ready(response: Response):
|
||||
req_id = generate_request_id()
|
||||
@@ -251,6 +409,7 @@ def health_ready(response: Response):
|
||||
raise HTTPException(status_code=503, detail="Database, Redis or S3 unavailable")
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.post("/api/v1/users", status_code=201)
|
||||
def register_user(body: CreateUser, response: Response):
|
||||
req_id = generate_request_id()
|
||||
@@ -285,6 +444,7 @@ def register_user(body: CreateUser, response: Response):
|
||||
"created_at": created_at
|
||||
}
|
||||
|
||||
|
||||
@app.post("/api/v1/auth/sessions", status_code=201)
|
||||
def create_session(authorization: Optional[str] = Header(None), response: Response = None):
|
||||
req_id = generate_request_id()
|
||||
@@ -339,6 +499,7 @@ def create_session(authorization: Optional[str] = Header(None), response: Respon
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def get_current_user_from_token(authorization: Optional[str] = Header(None)) -> dict:
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
raise HTTPException(
|
||||
@@ -380,6 +541,7 @@ def get_current_user_from_token(authorization: Optional[str] = Header(None)) ->
|
||||
"created_at": row['created_at'].isoformat().replace("+00:00", "Z") if isinstance(row['created_at'], datetime) else row['created_at']
|
||||
}
|
||||
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
def revoke_session(authorization: Optional[str] = Header(None)):
|
||||
req_id = generate_request_id()
|
||||
@@ -409,6 +571,7 @@ def revoke_session(authorization: Optional[str] = Header(None)):
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me")
|
||||
def current_user(response: Response, authorization: Optional[str] = Header(None)):
|
||||
req_id = generate_request_id()
|
||||
@@ -416,6 +579,7 @@ def current_user(response: Response, authorization: Optional[str] = Header(None)
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return get_current_user_from_token(authorization)
|
||||
|
||||
|
||||
@app.post("/api/v1/chats", status_code=201)
|
||||
def create_chat(body: CreateChat, response: Response, authorization: Optional[str] = Header(None)):
|
||||
req_id = generate_request_id()
|
||||
@@ -466,6 +630,7 @@ def create_chat(body: CreateChat, response: Response, authorization: Optional[st
|
||||
"created_at": created_at
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/v1/chats")
|
||||
def list_chats(limit: int = 50, cursor: Optional[str] = None, response: Response = None, authorization: Optional[str] = Header(None)):
|
||||
req_id = generate_request_id()
|
||||
@@ -522,6 +687,7 @@ def list_chats(limit: int = 50, cursor: Optional[str] = None, response: Response
|
||||
|
||||
return {"items": page_items, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}")
|
||||
def get_chat(chat_id: UUID, response: Response, authorization: Optional[str] = Header(None)):
|
||||
req_id = generate_request_id()
|
||||
@@ -553,6 +719,7 @@ def get_chat(chat_id: UUID, response: Response, authorization: Optional[str] = H
|
||||
"created_at": chat['created_at'].isoformat().replace("+00:00", "Z") if isinstance(chat['created_at'], datetime) else chat['created_at']
|
||||
}
|
||||
|
||||
|
||||
def validate_image_and_get_dimensions(data: bytes, content_type: str):
|
||||
if len(data) > 10 * 1024 * 1024:
|
||||
raise HTTPException(status_code=413, detail="Payload too large (>10 MiB)")
|
||||
@@ -576,14 +743,14 @@ def validate_image_and_get_dimensions(data: bytes, content_type: str):
|
||||
while i < len(data) - 9:
|
||||
marker = data[i]
|
||||
if marker == 0xff:
|
||||
marker_type = data[i+1]
|
||||
marker_type = data[i + 1]
|
||||
if 0xc0 <= marker_type <= 0xc3:
|
||||
height, width = struct.unpack('>HH', data[i+5:i+9])
|
||||
height, width = struct.unpack('>HH', data[i + 5:i + 9])
|
||||
break
|
||||
if marker_type in {0xd8, 0xd9} or (0xd0 <= marker_type <= 0xd7):
|
||||
i += 2
|
||||
continue
|
||||
seg_len = struct.unpack('>H', data[i+2:i+4])[0]
|
||||
seg_len = struct.unpack('>H', data[i + 2:i + 4])[0]
|
||||
if seg_len < 2:
|
||||
raise HTTPException(status_code=415, detail="Invalid JPEG segment")
|
||||
i += 2 + seg_len
|
||||
@@ -598,6 +765,7 @@ def validate_image_and_get_dimensions(data: bytes, content_type: str):
|
||||
if width * height > 40_000_000:
|
||||
raise HTTPException(status_code=413, detail="Image exceeds 40 million pixels limit")
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=202)
|
||||
async def upload_attachment(
|
||||
chat_id: UUID,
|
||||
@@ -718,6 +886,7 @@ async def upload_attachment(
|
||||
"updated_at": now
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}")
|
||||
def get_attachment(attachment_id: UUID, response: Response, authorization: Optional[str] = Header(None)):
|
||||
req_id = generate_request_id()
|
||||
@@ -754,6 +923,7 @@ def get_attachment(attachment_id: UUID, response: Response, authorization: Optio
|
||||
"updated_at": row['updated_at'].isoformat().replace("+00:00", "Z") if isinstance(row['updated_at'], datetime) else row['updated_at']
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}/content")
|
||||
def download_attachment(
|
||||
attachment_id: UUID,
|
||||
@@ -809,6 +979,7 @@ def download_attachment(
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||||
def create_message(
|
||||
chat_id: UUID,
|
||||
@@ -908,6 +1079,7 @@ def create_message(
|
||||
|
||||
return msg_response
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||
def list_messages(chat_id: UUID, limit: int = 50, cursor: Optional[str] = None,
|
||||
response: Response = None, authorization: Optional[str] = Header(None)):
|
||||
@@ -965,6 +1137,7 @@ def list_messages(chat_id: UUID, limit: int = 50, cursor: Optional[str] = None,
|
||||
|
||||
return {"items": formatted, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
@app.post("/api/v1/attachments/{attachment_id}/replay", status_code=202)
|
||||
def replay_attachment(attachment_id: UUID, response: Response,
|
||||
authorization: Optional[str] = Header(None)):
|
||||
|
||||
Reference in New Issue
Block a user