From cb7824c14ce292b9e7f32a7eec36b381c707d3a7 Mon Sep 17 00:00:00 2001 From: Sergey Lyakhonov Date: Fri, 4 Dec 2026 06:42:43 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=BD=D0=B5=D1=81?= =?UTF-8?q?=D1=82=D0=B8=20=D0=B8=20=D0=B0=D0=B4=D0=B0=D0=BF=D1=82=D0=B8?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=D0=B0=D1=82=D1=8C=20=D0=BE=D0=B1=D1=8F=D0=B7?= =?UTF-8?q?=D0=B0=D1=82=D0=B5=D0=BB=D1=8C=D0=BD=D1=8B=D0=B9=20=D0=BC=D0=B8?= =?UTF-8?q?=D0=BD=D0=B8=D0=BC=D1=83=D0=BC=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80?= =?UTF-8?q?=D0=B0=D1=82=D0=BE=D1=80=D0=BD=D0=BE=D0=B9=206?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Dockerfile | 12 + Dockerfile.s3 | 17 ++ migrations/001_initial.sql | 33 +++ migrations/002_idempotency.sql | 10 + migrations/003_attachments.sql | 17 ++ migrations/004_attachment_pipeline.sql | 49 +++++ migrations/005_versioned_pipeline.sql | 19 ++ migrations/007_trace_context.sql | 1 + migrations/008_login_limit.sql | 5 + requirements.lock.txt | 66 ++++++ requirements.txt | 16 ++ src/__init__.py | 0 src/app.py | 176 +++++++++++++++ src/body_limit.py | 41 ++++ src/broker.py | 38 ++++ src/cache.py | 60 +++++ src/config.py | 46 ++++ src/dispatch.py | 64 ++++++ src/image_pipeline.py | 53 +++++ src/jobs.py | 238 ++++++++++++++++++++ src/migrate.py | 19 ++ src/models.py | 126 +++++++++++ src/objects.py | 36 +++ src/pipeline_versions.py | 2 + src/routes/__init__.py | 0 src/routes/attachments.py | 159 ++++++++++++++ src/routes/chats.py | 79 +++++++ src/routes/common.py | 29 +++ src/routes/health.py | 23 ++ src/routes/messages.py | 85 ++++++++ src/routes/users.py | 52 +++++ src/serve.py | 9 + src/staging.py | 59 +++++ src/storage.py | 289 +++++++++++++++++++++++++ src/telemetry.py | 149 +++++++++++++ src/tls_proxy.py | 52 +++++ src/worker.py | 163 ++++++++++++++ 37 files changed, 2292 insertions(+) create mode 100644 Dockerfile create mode 100644 Dockerfile.s3 create mode 100644 migrations/001_initial.sql create mode 100644 migrations/002_idempotency.sql create mode 100644 migrations/003_attachments.sql create mode 100644 migrations/004_attachment_pipeline.sql create mode 100644 migrations/005_versioned_pipeline.sql create mode 100644 migrations/007_trace_context.sql create mode 100644 migrations/008_login_limit.sql create mode 100644 requirements.lock.txt create mode 100644 requirements.txt create mode 100644 src/__init__.py create mode 100644 src/app.py create mode 100644 src/body_limit.py create mode 100644 src/broker.py create mode 100644 src/cache.py create mode 100644 src/config.py create mode 100644 src/dispatch.py create mode 100644 src/image_pipeline.py create mode 100644 src/jobs.py create mode 100644 src/migrate.py create mode 100644 src/models.py create mode 100644 src/objects.py create mode 100644 src/pipeline_versions.py create mode 100644 src/routes/__init__.py create mode 100644 src/routes/attachments.py create mode 100644 src/routes/chats.py create mode 100644 src/routes/common.py create mode 100644 src/routes/health.py create mode 100644 src/routes/messages.py create mode 100644 src/routes/users.py create mode 100644 src/serve.py create mode 100644 src/staging.py create mode 100644 src/storage.py create mode 100644 src/telemetry.py create mode 100644 src/tls_proxy.py create mode 100644 src/worker.py diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..3bb2cd6d --- /dev/null +++ b/Dockerfile @@ -0,0 +1,12 @@ +FROM python:3.11.10-slim-bookworm@sha256:840e180ebcc6e5c8efab209c43f5e40fd2af98cb49db5c7103c90539c56bb30e +WORKDIR /app +# Приложение работает без прав root. +RUN groupadd -r appuser && useradd -r -g appuser appuser +COPY requirements.lock.txt . +RUN pip install --no-cache-dir -r requirements.lock.txt +COPY src/ src/ +COPY migrations/ migrations/ +USER appuser +HEALTHCHECK --interval=2s --timeout=2s --start-period=10s --retries=3 CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/health/ready',timeout=1)" +EXPOSE 8080 +CMD ["python", "-m", "src.serve"] diff --git a/Dockerfile.s3 b/Dockerfile.s3 new file mode 100644 index 00000000..5ec09f31 --- /dev/null +++ b/Dockerfile.s3 @@ -0,0 +1,17 @@ +# Build pinned upstream releases and verify archive checksums. +FROM golang:1.24.6-bookworm@sha256:ab1d1823abb55a9504d2e3e003b75b36dbeb1cbcc4c92593d85a84ee46becc6c AS build +WORKDIR /build +ADD --checksum=sha256:8819e3e7817e46b7b3798f8f200ead208562e571563c2e040352378031abe9f2 https://github.com/minio/minio/archive/07c3a429bfed433e49018cb0f78a52145d4bedeb.tar.gz /tmp/minio.tar.gz +RUN tar -xzf /tmp/minio.tar.gz --strip-components=1 && CGO_ENABLED=0 go build -trimpath -o /out/minio . +WORKDIR /build-mc +ADD --checksum=sha256:526ec538e7f83e4bfa631788129b08ec85898ca572ce0523ebf9a597946bea27 https://github.com/minio/mc/archive/refs/tags/RELEASE.2025-04-16T18-13-26Z.tar.gz /tmp/mc.tar.gz +RUN tar -xzf /tmp/mc.tar.gz --strip-components=1 && CGO_ENABLED=0 go build -trimpath -o /out/mc . +FROM debian:bookworm-20251020-slim@sha256:78d2f66e0fec9e5a39fb2c72ea5e052b548df75602b5215ed01a17171529f706 +LABEL org.opencontainers.image.source="https://github.com/minio/minio" org.opencontainers.image.revision="07c3a429bfed433e49018cb0f78a52145d4bedeb" +COPY --from=build /build/LICENSE /usr/share/doc/minio/LICENSE +COPY --from=build /build-mc/LICENSE /usr/share/doc/mc/LICENSE +COPY --from=build /out/minio /out/mc /usr/bin/ +COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt +COPY infra/s3-entrypoint.sh /usr/local/bin/s3-entrypoint.sh +ENTRYPOINT ["/bin/sh","/usr/local/bin/s3-entrypoint.sh"] +CMD ["server","/data"] diff --git a/migrations/001_initial.sql b/migrations/001_initial.sql new file mode 100644 index 00000000..2ee14af7 --- /dev/null +++ b/migrations/001_initial.sql @@ -0,0 +1,33 @@ +CREATE TABLE users ( + id uuid PRIMARY KEY, + username varchar(32) NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'), + display_name varchar(100) NOT NULL CHECK (length(btrim(display_name)) > 0), + password_hash text NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title varchar(100) NOT NULL CHECK (length(btrim(title)) > 0), + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats(id), + user_id uuid NOT NULL REFERENCES users(id), + PRIMARY KEY (chat_id, user_id) +); +CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_id); +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats(id), + sender_id uuid NOT NULL REFERENCES users(id), + text varchar(4000) NOT NULL CHECK (length(btrim(text)) > 0), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id) +); +CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id); +CREATE TABLE sessions ( + token_hash char(64) PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users(id), + expires_at timestamptz NOT NULL +); +CREATE INDEX sessions_expiry_idx ON sessions (expires_at); diff --git a/migrations/002_idempotency.sql b/migrations/002_idempotency.sql new file mode 100644 index 00000000..be707c47 --- /dev/null +++ b/migrations/002_idempotency.sql @@ -0,0 +1,10 @@ +CREATE TABLE message_requests ( + user_id uuid NOT NULL REFERENCES users(id), + chat_id uuid NOT NULL REFERENCES chats(id), + key varchar(128) NOT NULL, + body text NOT NULL, + message_id uuid NOT NULL REFERENCES messages(id), + expires_at timestamptz NOT NULL, + PRIMARY KEY (user_id, chat_id, key) +); +CREATE INDEX message_requests_expiry_idx ON message_requests(expires_at); diff --git a/migrations/003_attachments.sql b/migrations/003_attachments.sql new file mode 100644 index 00000000..000a2e80 --- /dev/null +++ b/migrations/003_attachments.sql @@ -0,0 +1,17 @@ +ALTER TABLE messages DROP CONSTRAINT messages_text_check; +ALTER TABLE messages ADD CONSTRAINT messages_text_limit CHECK (length(text)<=4000); +CREATE TABLE attachments ( + id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES chats(id), + owner_id uuid NOT NULL REFERENCES users(id), object_key text NOT NULL UNIQUE, + filename text NOT NULL, content_type text NOT NULL, size_bytes integer NOT NULL, + sha256 char(64) NOT NULL, state text NOT NULL CHECK(state IN ('ready','missing')), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + updated_at timestamptz NOT NULL DEFAULT clock_timestamp(), + FOREIGN KEY(chat_id,owner_id) REFERENCES chat_members(chat_id,user_id) +); +CREATE TABLE message_attachments ( + message_id uuid NOT NULL REFERENCES messages(id), attachment_id uuid NOT NULL REFERENCES attachments(id), + position integer NOT NULL, PRIMARY KEY(message_id,attachment_id), UNIQUE(message_id,position) +); +-- Старые сохранённые ключи теперь сравнивают полное нормализованное тело. +UPDATE message_requests SET body=json_build_object('text',body,'attachment_ids',json_build_array())::text; diff --git a/migrations/004_attachment_pipeline.sql b/migrations/004_attachment_pipeline.sql new file mode 100644 index 00000000..2e2eb707 --- /dev/null +++ b/migrations/004_attachment_pipeline.sql @@ -0,0 +1,49 @@ +ALTER TABLE attachments DROP CONSTRAINT attachments_state_check; +UPDATE attachments SET state = 'failed' WHERE state = 'missing'; +ALTER TABLE attachments ADD COLUMN error_code text; +UPDATE attachments SET error_code = 'original_unavailable' WHERE state = 'failed'; +ALTER TABLE attachments ADD CONSTRAINT attachments_pipeline_state CHECK ( + state IN ('queued', 'processing', 'ready', 'failed') + AND ((state = 'failed') = (error_code IS NOT NULL)) +); + +CREATE TABLE attachment_jobs ( + id uuid PRIMARY KEY, + attachment_id uuid NOT NULL UNIQUE REFERENCES attachments(id), + staging_key text NOT NULL UNIQUE, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + attempt integer NOT NULL DEFAULT 1 CHECK (attempt >= 1), + attempt_limit integer NOT NULL CHECK (attempt_limit >= 1), + state text NOT NULL DEFAULT 'queued' CHECK (state IN ('queued', 'processing', 'ready', 'failed')), + next_publish_at timestamptz, + published_at timestamptz, + publish_failures integer NOT NULL DEFAULT 0, + lease_until timestamptz, + lease_token uuid, + last_error text, + CHECK ((lease_until IS NULL) = (lease_token IS NULL)) +); +CREATE INDEX attachment_jobs_outbox ON attachment_jobs(next_publish_at) + WHERE next_publish_at IS NOT NULL; +CREATE INDEX attachment_jobs_leases ON attachment_jobs(lease_until) + WHERE lease_until IS NOT NULL; + +CREATE TABLE attachment_variants ( + attachment_id uuid NOT NULL REFERENCES attachments(id), + name text NOT NULL CHECK (name IN ('thumbnail', 'crop', 'optimized')), + object_key text NOT NULL UNIQUE, + content_type text NOT NULL, + size_bytes integer NOT NULL CHECK (size_bytes > 0), + sha256 char(64) NOT NULL, + width integer NOT NULL CHECK (width > 0), + height integer NOT NULL CHECK (height > 0), + PRIMARY KEY (attachment_id, name) +); + +CREATE TABLE attachment_replays ( + job_id uuid NOT NULL REFERENCES attachment_jobs(id), + attempt integer NOT NULL, + reason text NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + PRIMARY KEY (job_id, attempt) +); diff --git a/migrations/005_versioned_pipeline.sql b/migrations/005_versioned_pipeline.sql new file mode 100644 index 00000000..760c52b7 --- /dev/null +++ b/migrations/005_versioned_pipeline.sql @@ -0,0 +1,19 @@ +ALTER TABLE attachments + ADD COLUMN target_pipeline_version integer NOT NULL DEFAULT 1 CHECK (target_pipeline_version >= 1), + ADD COLUMN published_pipeline_version integer CHECK (published_pipeline_version >= 1), + ADD CHECK (published_pipeline_version <= target_pipeline_version); +UPDATE attachments SET published_pipeline_version = 1 WHERE state = 'ready'; + +ALTER TABLE attachment_jobs + DROP CONSTRAINT attachment_jobs_attachment_id_key, + DROP CONSTRAINT attachment_jobs_staging_key_key, + DROP CONSTRAINT attachment_jobs_state_check, + ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1 CHECK (pipeline_version >= 1), + ADD COLUMN settled_at timestamptz, + ADD CHECK (state IN ('queued', 'processing', 'ready', 'failed', 'superseded')), + ADD UNIQUE (attachment_id, pipeline_version); +CREATE INDEX attachment_jobs_staging ON attachment_jobs(staging_key); + +ALTER TABLE attachment_variants ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1; +ALTER TABLE attachment_variants DROP CONSTRAINT attachment_variants_pkey; +ALTER TABLE attachment_variants ADD PRIMARY KEY (attachment_id, pipeline_version, name); diff --git a/migrations/007_trace_context.sql b/migrations/007_trace_context.sql new file mode 100644 index 00000000..9256ceb7 --- /dev/null +++ b/migrations/007_trace_context.sql @@ -0,0 +1 @@ +ALTER TABLE attachment_jobs ADD COLUMN trace_context jsonb NOT NULL DEFAULT '{}'::jsonb; diff --git a/migrations/008_login_limit.sql b/migrations/008_login_limit.sql new file mode 100644 index 00000000..32ce764f --- /dev/null +++ b/migrations/008_login_limit.sql @@ -0,0 +1,5 @@ +CREATE TABLE login_limits ( + identity_hash char(64) PRIMARY KEY, + window_start timestamptz NOT NULL, + attempts integer NOT NULL +); diff --git a/requirements.lock.txt b/requirements.lock.txt new file mode 100644 index 00000000..fbbb1359 --- /dev/null +++ b/requirements.lock.txt @@ -0,0 +1,66 @@ +annotated-types==0.8.0 +anyio==4.16.0 +argon2-cffi==23.1.0 +argon2-cffi-bindings==26.2.0 +attrs==26.1.0 +boto3==1.40.61 +botocore==1.40.76 +certifi==2026.11.20 +cffi==2.1.1 +charset-normalizer==3.5.3 +click==8.5.1 +colorama==0.4.6 +fastapi==0.115.0 +googleapis-common-protos==1.76.0 +h11==0.16.0 +httptools==0.9.0 +idna==3.20 +importlib_metadata==8.7.1 +jmespath==1.1.0 +jsonschema==4.26.0 +jsonschema-path==0.3.4 +jsonschema-specifications==2025.9.1 +lazy-object-proxy==1.13.0 +openapi-schema-validator==0.6.3 +openapi-spec-validator==0.7.2 +opentelemetry-api==1.38.0 +opentelemetry-exporter-otlp-proto-common==1.38.0 +opentelemetry-exporter-otlp-proto-http==1.38.0 +opentelemetry-instrumentation==0.59b0 +opentelemetry-instrumentation-botocore==0.59b0 +opentelemetry-instrumentation-dbapi==0.59b0 +opentelemetry-instrumentation-psycopg==0.59b0 +opentelemetry-propagator-aws-xray==1.0.2 +opentelemetry-proto==1.38.0 +opentelemetry-sdk==1.38.0 +opentelemetry-semantic-conventions==0.59b0 +packaging==26.4 +pathable==0.4.4 +pika==1.3.2 +pillow==12.0.0 +protobuf==6.33.6 +psycopg==3.2.3 +psycopg-binary==3.2.3 +psycopg-pool==3.2.4 +pycparser==3.12 +pydantic==2.9.2 +pydantic_core==2.23.4 +python-dateutil==2.9.0.post0 +python-dotenv==1.2.4 +PyYAML==6.0.4 +redis==5.2.0 +referencing==0.36.2 +requests==2.34.2 +rfc3339-validator==0.1.4 +rpds-py==2026.9.1 +s3transfer==0.14.0 +six==1.17.0 +starlette==0.38.6 +typing_extensions==4.16.0 +tzdata==2026.6 +urllib3==2.8.0 +uvicorn==0.32.0 +watchfiles==1.3.0 +websockets==17.4 +wrapt==1.17.3 +zipp==4.1.2 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..9841d5a8 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,16 @@ +fastapi==0.115.0 +uvicorn[standard]==0.32.0 +pydantic==2.9.2 +psycopg[binary]==3.2.3 +psycopg-pool==3.2.4 +argon2-cffi==23.1.0 +redis==5.2.0 + +boto3==1.40.61 +Pillow==12.0.0 +pika==1.3.2 + +opentelemetry-sdk==1.38.0 +opentelemetry-exporter-otlp-proto-http==1.38.0 +opentelemetry-instrumentation-psycopg==0.59b0 +opentelemetry-instrumentation-botocore==0.59b0 diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/app.py b/src/app.py new file mode 100644 index 00000000..3304feb9 --- /dev/null +++ b/src/app.py @@ -0,0 +1,176 @@ +import uuid +import os +import socket +from contextlib import asynccontextmanager +import psycopg +from psycopg_pool import PoolTimeout, TooManyRequests +from starlette.concurrency import run_in_threadpool + +from fastapi import FastAPI, Request +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse +from pydantic import ValidationError as PydanticValidationError +from starlette.exceptions import HTTPException as StarletteHTTPException + +from src.models import ErrorResponse +from src.routes import chats, health, messages, users, attachments +from botocore.exceptions import BotoCoreError, ClientError +from src.storage import storage + + +from src import telemetry +telemetry.setup("messenger-api") +telemetry.register_gauges(storage.pool) + +def create_app() -> FastAPI: + """Создать и настроить приложение FastAPI.""" + @asynccontextmanager + async def lifespan(app): + await run_in_threadpool(storage.pool.open, wait=True) + try: + yield + finally: + await run_in_threadpool(storage.pool.close) + + instance_id = uuid.uuid4().hex + app = FastAPI(title="MTUSI Messenger Lab7", version="1.7.0", lifespan=lifespan) + + @app.exception_handler(BotoCoreError) + @app.exception_handler(ClientError) + @app.exception_handler(psycopg.OperationalError) + @app.exception_handler(psycopg.errors.QueryCanceled) + @app.exception_handler(psycopg.errors.LockNotAvailable) + @app.exception_handler(PoolTimeout) + @app.exception_handler(TooManyRequests) + async def dependency_error(request, exc): + return JSONResponse(status_code=503, content=ErrorResponse(error={ + "code": "unavailable", "message": "хранилище временно недоступно", + "request_id": request.state.request_id}).model_dump(), + headers={"X-Request-Id": request.state.request_id}) + + @app.middleware("http") + async def add_request_id(request: Request, call_next): + """Добавляет идентификаторы запроса и процесса, ограничивает очередь.""" + try: + request_id = str(uuid.UUID(request.headers.get("X-Request-Id", ""))) + except ValueError: + request_id = str(uuid.uuid4()) + request.state.request_id = request_id + + # Ограничение числа обслуживаемых запросов в процессе. + if not storage.acquire_request_slot(): + return JSONResponse( + status_code=503, + content=ErrorResponse( + error={ + "code": "unavailable", + "message": "сервер перегружен, попробуйте позже", + "request_id": request_id, + } + ).model_dump(), + headers={"X-Request-Id": request_id, "X-Instance-Id": instance_id}, + ) + + try: + response = await call_next(request) + response.headers["X-Request-Id"] = request_id + response.headers["X-Instance-Id"] = instance_id + return response + finally: + storage.release_request_slot() + + @app.exception_handler(StarletteHTTPException) + async def http_exception_handler(request: Request, exc: StarletteHTTPException): + """Обработчик HTTPException: возвращает ошибку в формате контракта {"error": ...}.""" + request_id = getattr(request.state, "request_id", str(uuid.uuid4())) + if isinstance(exc.detail, dict) and "error" in exc.detail: + return JSONResponse( + status_code=exc.status_code, + content=exc.detail, + headers={"X-Request-Id": request_id, **(exc.headers or {})}, + ) + return JSONResponse( + status_code=exc.status_code, + content=ErrorResponse( + error={ + "code": "internal_error", + "message": str(exc.detail), + "request_id": request_id, + } + ).model_dump(), + headers={"X-Request-Id": request_id, "X-Instance-Id": instance_id}, + ) + + @app.exception_handler(RequestValidationError) + async def request_validation_handler(request: Request, exc: RequestValidationError): + """Перехватываем ошибки валидации запроса (422 -> 400 по контракту).""" + request_id = getattr(request.state, "request_id", str(uuid.uuid4())) + errors = exc.errors() + messages = [] + for err in errors: + loc = ".".join(str(x) for x in err.get("loc", [])) + messages.append(f"{loc}: {err.get('msg', 'invalid')}") + return JSONResponse( + status_code=400, + content=ErrorResponse( + error={ + "code": "invalid_request", + "message": "; ".join(messages), + "request_id": request_id, + } + ).model_dump(), + headers={"X-Request-Id": request_id, "X-Instance-Id": instance_id}, + ) + + @app.exception_handler(PydanticValidationError) + async def validation_exception_handler(request: Request, exc: PydanticValidationError): + """Перехватываем ошибки Pydantic (422 -> 400 по контракту).""" + request_id = getattr(request.state, "request_id", str(uuid.uuid4())) + errors = exc.errors() + messages = [] + for err in errors: + loc = ".".join(str(x) for x in err.get("loc", [])) + messages.append(f"{loc}: {err.get('msg', 'invalid')}") + return JSONResponse( + status_code=400, + content=ErrorResponse( + error={ + "code": "invalid_request", + "message": "; ".join(messages), + "request_id": request_id, + } + ).model_dump(), + headers={"X-Request-Id": request_id, "X-Instance-Id": instance_id}, + ) + + @app.exception_handler(Exception) + async def generic_exception_handler(request: Request, exc: Exception): + """Обработчик непредвиденных исключений: скрываем детали, возвращаем 500.""" + request_id = getattr(request.state, "request_id", str(uuid.uuid4())) + return JSONResponse( + status_code=500, + content=ErrorResponse( + error={ + "code": "internal_error", + "message": "внутренняя ошибка сервера", + "request_id": request_id, + } + ).model_dump(), + headers={"X-Request-Id": request_id, "X-Instance-Id": instance_id}, + ) + + # Подключаем роуты + app.include_router(health.router) + app.include_router(users.router) + app.include_router(chats.router) + app.include_router(messages.router) + app.include_router(attachments.router) + + app.add_middleware(telemetry.HTTPMiddleware) + from src.body_limit import BodyLimit + app.add_middleware(BodyLimit) + return app + + +# Экземпляр приложения для uvicorn +app = create_app() diff --git a/src/body_limit.py b/src/body_limit.py new file mode 100644 index 00000000..655be3fd --- /dev/null +++ b/src/body_limit.py @@ -0,0 +1,41 @@ +"""Bound the actual ASGI stream, including requests without Content-Length.""" +import json +import uuid + + +class BodyLimit: + def __init__(self, app): + self.app = app + self.instance = uuid.uuid4().hex.encode() + + async def __call__(self, scope, receive, send): + if scope['type'] != 'http': + return await self.app(scope, receive, send) + maximum = 10485760 if scope['path'].endswith('/attachments') else 65536 + parts, size = [], 0 + while True: + message = await receive() + if message['type'] != 'http.request': + return + size += len(message.get('body', b'')) + if size > maximum: + request_id = str(uuid.uuid4()) + import socket + body = json.dumps({'error': {'code':'payload_too_large', 'message':'размер запроса превышен', + 'request_id':request_id}}).encode() + await send({'type':'http.response.start', 'status':413, 'headers':[ + (b'content-type', b'application/json'), (b'x-request-id', request_id.encode()), + (b'x-instance-id', self.instance)]}) + await send({'type':'http.response.body', 'body':body}) + return + parts.append(message.get('body', b'')) + if not message.get('more_body'): + break + consumed = False + async def bounded(): + nonlocal consumed + if not consumed: + consumed = True + return {'type':'http.request', 'body':b''.join(parts), 'more_body':False} + return await receive() + await self.app(scope, bounded, send) diff --git a/src/broker.py b/src/broker.py new file mode 100644 index 00000000..f1b795a0 --- /dev/null +++ b/src/broker.py @@ -0,0 +1,38 @@ +"""RabbitMQ с подтверждаемой публикацией и ручным ack.""" + +import json +import ssl +from contextlib import contextmanager + +import pika + +from src.config import setting + +QUEUE = 'attachment.process.v1' + + +@contextmanager +def channel(heartbeat=90): + params = pika.URLParameters(setting('BROKER_URL')) + params.ssl_options = pika.SSLOptions(ssl.create_default_context(cafile='/tls/ca.crt'), 'broker') + params.heartbeat = heartbeat + params.socket_timeout = 4 + params.stack_timeout = 6 + params.blocked_connection_timeout = 5 + connection = pika.BlockingConnection(params) + try: + result = connection.channel() + result.queue_declare(queue=QUEUE, durable=True) + yield connection, result + finally: + if connection.is_open: + connection.close() + + +def publish(ch, message): + ch.basic_publish( + exchange='', routing_key=QUEUE, body=json.dumps(message, separators=(',', ':')).encode(), + properties=pika.BasicProperties(content_type='application/json', delivery_mode=2, + message_id=message['job_id']), + mandatory=True, + ) diff --git a/src/cache.py b/src/cache.py new file mode 100644 index 00000000..edeb5357 --- /dev/null +++ b/src/cache.py @@ -0,0 +1,60 @@ +"""Необязательный кэш неизменяемого публичного профиля; ошибки обходятся через БД.""" +import logging +import os +from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeout +import threading +from redis import Redis, RedisError +from pydantic import ValidationError +from src.config import setting +from src.models import User + + +class ProfileCache: + def __init__(self): + url = setting('CACHE_URL') + self.client = Redis.from_url(url, decode_responses=True, socket_connect_timeout=0.2, + socket_timeout=0.2, max_connections=16) if url else None + self.ttl = int(os.getenv('PROFILE_CACHE_TTL_SECONDS','60')) + self.hits = self.misses = self.errors = 0 + # DNS может ждать дольше socket timeout; один фоновый вызов ограничивает и время, и очередь. + self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix='profile-cache') + self._pending = None + self._guard = threading.Lock() + + def _bounded(self, action, *args, **kwargs): + with self._guard: + if self._pending is not None and not self._pending.done(): + raise RedisError('кэш занят') + self._pending = self._executor.submit(action, *args, **kwargs) + future = self._pending + try: + return future.result(timeout=0.25) + except FutureTimeout: + raise RedisError('истекло время ожидания кэша') from None + + def get(self, user_id): + if not self.client: + return None + try: + value = self._bounded(self.client.get, 'profile:v1:'+user_id) + if value: + user=User.model_validate_json(value) + if user.id != user_id: + raise ValueError('неверный ключ кэша') + self.hits += 1 + return user + self.misses += 1 + except (RedisError, ValidationError, ValueError): + self.errors += 1 + logging.getLogger(__name__).warning('Кэш профиля недоступен; чтение из PostgreSQL') + return None + + def put(self, user): + if self.client: + try: + self._bounded(self.client.set, 'profile:v1:'+user.id,user.model_dump_json(),ex=self.ttl) + except RedisError: + self.errors += 1 + + +profile_cache = ProfileCache() diff --git a/src/config.py b/src/config.py new file mode 100644 index 00000000..a4a0ec56 --- /dev/null +++ b/src/config.py @@ -0,0 +1,46 @@ +"""Настройки окружения и чтение секретов из файлов.""" +import os +from pathlib import Path +import json +import ssl +import threading +import time +import urllib.request + +_lock = threading.Lock() +_cache = {} +_expires = 0 + + +def service_secrets(): + """Certificate auth; 5-minute token, re-auth and re-read before expiration. + + The process never receives operator credentials. Failure is closed: no + plaintext, root-token, environment-secret or expired-cache fallback. + """ + global _cache, _expires + with _lock: + if time.monotonic() < _expires: + return _cache + ctx = ssl.create_default_context(cafile='/tls/ca.crt') + ctx.load_cert_chain('/tls/cert.crt', '/tls/key.key') + base = os.getenv('BAO_ADDR', 'https://openbao:8200') + name = os.environ['BAO_ROLE'] + req = urllib.request.Request(base+'/v1/auth/cert/login', + data=json.dumps({'name':os.getenv('BAO_AUTH_NAME',name)}).encode(), headers={'Content-Type':'application/json'}) + with urllib.request.urlopen(req, context=ctx, timeout=5) as response: + token = json.load(response)['auth']['client_token'] + req = urllib.request.Request(base+'/v1/secret/data/'+name, headers={'X-Vault-Token':token}) + with urllib.request.urlopen(req, context=ctx, timeout=5) as response: + _cache = json.load(response)['data']['data'] + _expires = time.monotonic()+240 + return _cache + + +def setting(name, default=None): + if os.getenv('BAO_ROLE') and name in ('DATABASE_URL','S3_ACCESS_KEY','S3_SECRET_KEY','BROKER_URL'): + return service_secrets()[name] + path = os.getenv(name + '_FILE') + if path: + return Path(path).read_text(encoding='utf-8').strip() + return os.getenv(name, default) diff --git a/src/dispatch.py b/src/dispatch.py new file mode 100644 index 00000000..0e94c72c --- /dev/null +++ b/src/dispatch.py @@ -0,0 +1,64 @@ +"""Отдельный relay: lease публикации, publisher confirm, восстановление jobs.""" + +import logging +import signal +import threading +import time + +import pika +import psycopg +from psycopg_pool import PoolTimeout + +from src import broker, jobs, telemetry +from opentelemetry.propagate import extract +from opentelemetry.trace import SpanKind +from src.storage import storage + + +def main(): + telemetry.setup("messenger-dispatcher") + telemetry.register_gauges(storage.pool) + logging.basicConfig(level=logging.WARNING) + stopping = threading.Event() + for sig in (signal.SIGINT, signal.SIGTERM): + signal.signal(sig, lambda *_: stopping.set()) + storage.pool.open(wait=True) + next_recovery = 0.0 + try: + while not stopping.is_set(): + reserved = None + try: + with broker.channel(heartbeat=10) as (connection, channel): + channel.confirm_delivery() + while not stopping.is_set(): + if time.monotonic() >= next_recovery: + jobs.recover_expired() + next_recovery = time.monotonic() + 1 + reserved = jobs.reserve_publish() + if reserved: + with telemetry.tracer.start_as_current_span("attachment.publish", + context=extract(reserved["trace_context"]), kind=SpanKind.PRODUCER) as sp: + sp.set_attribute("messaging.system", "rabbitmq") + sp.set_attribute("messaging.destination.name", broker.QUEUE) + sp.set_attribute("job.id", str(reserved["id"])) + message = jobs.envelope(reserved) | telemetry.carrier() + broker.publish(channel, message) + telemetry.event("job.published", job_id=str(reserved["id"]), attempt=reserved["attempt"]) + jobs.confirm_publish(reserved) + reserved = None + else: + connection.process_data_events(time_limit=0.2) + except (pika.exceptions.AMQPError, OSError, psycopg.Error, PoolTimeout) as exc: + logging.warning('dispatch temporarily unavailable: %s', type(exc).__name__) + if reserved: + try: + jobs.publish_failed(reserved) + except (psycopg.Error, PoolTimeout): + pass # expires through the durable publication deadline + stopping.wait(1) + finally: + storage.pool.close() + + +if __name__ == '__main__': + main() diff --git a/src/image_pipeline.py b/src/image_pipeline.py new file mode 100644 index 00000000..0a8396b3 --- /dev/null +++ b/src/image_pipeline.py @@ -0,0 +1,53 @@ +"""Преобразования Pillow в отдельном процессе с жёстким таймаутом родителя.""" + +import json +import sys +from pathlib import Path + +from PIL import Image, ImageOps +from src.pipeline_versions import ENCODING + +Image.MAX_IMAGE_PIXELS = 40_000_000 + + +def fit(image, limit): + width, height = image.size + longest = max(width, height) + if longest <= limit: + return image + size = (max(1, width * limit // longest), max(1, height * limit // longest)) + return image.resize(size, Image.Resampling.LANCZOS) + + +def render(source, target, version=1): + jpeg_quality, webp_quality = ENCODING[version] + with Image.open(source) as opened: + if opened.width * opened.height > Image.MAX_IMAGE_PIXELS: + raise ValueError('pixel limit') + image = ImageOps.exif_transpose(opened) + if 'A' in image.getbands() or 'transparency' in image.info: + rgba = image.convert('RGBA') + rgb = Image.new('RGB', rgba.size, 'white') + rgb.paste(rgba, mask=rgba.getchannel('A')) + else: + rgb = image.convert('RGB') + rgb.info.clear() + del image + thumbnail = fit(rgb, 256) + thumbnail.save(target / 'thumbnail', 'JPEG', quality=jpeg_quality) + return [['thumbnail', 'image/jpeg', *thumbnail.size]] + + + +def main(): + directory = Path(sys.argv[1]) + try: + result = render(directory / 'original', directory, int(sys.argv[2])) + except (OSError, ValueError, SyntaxError, Image.DecompressionBombError): + return 2 + (directory / 'manifest.json').write_text(json.dumps(result), encoding='utf-8') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/src/jobs.py b/src/jobs.py new file mode 100644 index 00000000..e5c9ecc5 --- /dev/null +++ b/src/jobs.py @@ -0,0 +1,238 @@ +"""Устойчивое намерение обработки, lease и атомарная публикация manifest.""" + +import random +import re +from datetime import datetime +from uuid import UUID, uuid4 + +from src.config import setting +from src.objects import BUCKET, client, object_lock +from src.pipeline_versions import ENCODING +from src.storage import storage, timestamp + +JOB_TIMEOUT = int(setting('JOB_TIMEOUT_SECONDS', '60')) +LEASE_SECONDS = max(JOB_TIMEOUT + 5, int(setting('JOB_LEASE_SECONDS', str(JOB_TIMEOUT + 30)))) + + +def envelope(job): + return { + 'schema_version': 1, + 'job_id': str(job['id']), + 'type': 'attachment.process.v1', + 'attachment_id': str(job['attachment_id']), + 'pipeline_version': job['pipeline_version'], + 'attempt': job['attempt'], + 'created_at': timestamp(job['created_at']), + } + + +def validate(message): + required = {'schema_version', 'job_id', 'type', 'attachment_id', 'pipeline_version', 'attempt', 'created_at'} + if not isinstance(message, dict) or not required <= message.keys() <= required | {'traceparent', 'tracestate'}: + raise ValueError('invalid fields') + if (type(message['schema_version']) is not int or message['schema_version'] != 1 + or message['type'] != 'attachment.process.v1' + or type(message['pipeline_version']) is not int or message['pipeline_version'] not in ENCODING + or type(message['attempt']) is not int or message['attempt'] < 1): + raise ValueError('invalid job') + UUID(message['job_id']) + UUID(message['attachment_id']) + if datetime.fromisoformat(message['created_at'].replace('Z', '+00:00')).tzinfo is None: + raise ValueError('missing timezone') + if 'traceparent' in message and not re.fullmatch(r'00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}', + message['traceparent']): + raise ValueError('invalid traceparent') + if 'tracestate' in message and (not isinstance(message['tracestate'], str) or len(message['tracestate']) > 512): + raise ValueError('invalid tracestate') + return {key: message[key] for key in required} + + +def reserve_publish(): + with storage.pool.connection() as conn: + return conn.execute( + """WITH candidate AS ( + SELECT id FROM attachment_jobs WHERE state='queued' + AND next_publish_at <= clock_timestamp() + ORDER BY next_publish_at, id LIMIT 1 FOR UPDATE SKIP LOCKED + ) + UPDATE attachment_jobs j + SET next_publish_at=clock_timestamp()+interval '15 seconds' + FROM candidate WHERE j.id=candidate.id RETURNING j.*""" + ).fetchone() + + +def confirm_publish(job): + with storage.pool.connection() as conn: + conn.execute( + """UPDATE attachment_jobs SET next_publish_at=NULL, published_at=clock_timestamp(), + publish_failures=0 WHERE id=%s AND attempt=%s""", + (job['id'], job['attempt']), + ) + + +def publish_failed(job): + with storage.pool.connection() as conn: + conn.execute( + """UPDATE attachment_jobs SET publish_failures=publish_failures+1, + next_publish_at=clock_timestamp()+%s * interval '1 second' + WHERE id=%s AND attempt=%s AND state='queued' AND next_publish_at IS NOT NULL""", + (delay(job['publish_failures'] + 1), job['id'], job['attempt']), + ) + + +def locked_job(conn, job_id, attachment_id): + attachment = conn.execute('SELECT * FROM attachments WHERE id=%s FOR UPDATE', + (attachment_id,)).fetchone() + if not attachment: + return None, None + job = conn.execute('SELECT * FROM attachment_jobs WHERE id=%s AND attachment_id=%s FOR UPDATE', + (job_id, attachment_id)).fetchone() + return job, attachment + + +def claim(message): + with storage.pool.connection() as conn: + job, attachment = locked_job(conn, message['job_id'], message['attachment_id']) + if (not job or envelope(job) != message or job['state'] != 'queued' + or job['pipeline_version'] != attachment['target_pipeline_version']): + return None + token = uuid4() + conn.execute( + """UPDATE attachment_jobs SET state='processing', lease_token=%s, + lease_until=clock_timestamp()+%s * interval '1 second', next_publish_at=NULL + WHERE id=%s""", (token, LEASE_SECONDS, job['id']), + ) + conn.execute("UPDATE attachments SET state='processing',updated_at=clock_timestamp() " + "WHERE id=%s AND published_pipeline_version IS NULL", + (job['attachment_id'],)) + return job | {'lease_token': token, 'attachment': attachment} + + +def owns(conn, job, claimed): + return ( + job and (job['state'], job['lease_token']) == ('processing', claimed['lease_token']) + and conn.execute('SELECT clock_timestamp() < %s AS active', (job['lease_until'],)).fetchone()['active'] + ) + + +def complete(claimed, variants): + with storage.pool.connection() as conn: + job, attachment = locked_job(conn, claimed['id'], claimed['attachment_id']) + if not owns(conn, job, claimed) or job['pipeline_version'] != attachment['target_pipeline_version']: + return False + for variant in variants: + conn.execute( + """INSERT INTO attachment_variants + (attachment_id,pipeline_version,name,object_key,content_type,size_bytes,sha256,width,height) + VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)""", + (job['attachment_id'], job['pipeline_version'], *variant), + ) + conn.execute("UPDATE attachments SET state='ready',published_pipeline_version=%s," + "updated_at=clock_timestamp(),error_code=NULL WHERE id=%s", + (job['pipeline_version'], job['attachment_id'])) + conn.execute("UPDATE attachment_jobs SET state='ready',lease_token=NULL,lease_until=NULL," + "last_error=NULL,settled_at=clock_timestamp() WHERE id=%s", (job['id'],)) + return True + + +def delay(attempt): + return min(30, 2 ** min(attempt - 1, 5)) * random.uniform(0.75, 1.25) + + +def settle_error(conn, job, code, permanent=False): + exhausted = job['attempt'] >= job['attempt_limit'] + if permanent or exhausted: + error = code if permanent else 'retry_exhausted' + conn.execute("UPDATE attachments SET state='failed',error_code=%s,updated_at=clock_timestamp() " + "WHERE id=%s AND published_pipeline_version IS NULL", (error, job['attachment_id'])) + conn.execute("UPDATE attachment_jobs SET state='failed',lease_token=NULL,lease_until=NULL," + "last_error=%s,next_publish_at=NULL,settled_at=clock_timestamp() WHERE id=%s", + (code, job['id'])) + return + conn.execute("UPDATE attachments SET state='queued',updated_at=clock_timestamp() " + "WHERE id=%s AND published_pipeline_version IS NULL", + (job['attachment_id'],)) + conn.execute("""UPDATE attachment_jobs SET state='queued',lease_token=NULL,lease_until=NULL, + last_error=%s,attempt=attempt+1,published_at=NULL, + next_publish_at=clock_timestamp()+%s*interval '1 second' WHERE id=%s""", + (code, delay(job['attempt']), job['id'])) + + +def fail(claimed, code, permanent=False): + with storage.pool.connection() as conn: + job, _ = locked_job(conn, claimed['id'], claimed['attachment_id']) + if owns(conn, job, claimed): + settle_error(conn, job, code, permanent) + + +def recover_expired(): + with storage.pool.connection() as conn: + expired = conn.execute("SELECT id,attachment_id FROM attachment_jobs " + "WHERE lease_until <= clock_timestamp() ORDER BY lease_until LIMIT 16").fetchall() + for candidate in expired: + with storage.pool.connection() as conn: + job, _ = locked_job(conn, candidate['id'], candidate['attachment_id']) + if (job and job['state'] == 'processing' + and not owns(conn, job, job)): + settle_error(conn, job, 'lease_expired') + + +def replay(attachment_id): + with storage.pool.connection() as conn: + attachment = conn.execute('SELECT * FROM attachments WHERE id=%s FOR UPDATE', + (attachment_id,)).fetchone() + if not attachment: + return None + job = conn.execute('SELECT * FROM attachment_jobs WHERE attachment_id=%s AND pipeline_version=%s FOR UPDATE', + (attachment_id, attachment['target_pipeline_version'])).fetchone() + if not job or job['state'] != 'failed': + return None + source = attachment['object_key'] if attachment['published_pipeline_version'] else job['staging_key'] + object_lock(conn, source) + client().head_object(Bucket=BUCKET, Key=source) + new_attempt = job['attempt'] + 1 + budget = int(setting('JOB_MAX_ATTEMPTS', '5')) + conn.execute( + """UPDATE attachment_jobs SET state='queued', attempt=%s, attempt_limit=%s, + next_publish_at=clock_timestamp(), published_at=NULL, publish_failures=0, settled_at=NULL + WHERE id=%s""", (new_attempt, new_attempt + budget - 1, job['id']), + ) + conn.execute("INSERT INTO attachment_replays(job_id,attempt,reason) VALUES (%s,%s,'operator')", + (job['id'], new_attempt)) + conn.execute("UPDATE attachments SET state='queued',error_code=NULL,updated_at=clock_timestamp() " + "WHERE id=%s AND published_pipeline_version IS NULL", (attachment_id,)) + return job['id'], new_attempt + + +def upgrade(attachment_id, version): + with storage.pool.connection() as conn: + attachment = conn.execute('SELECT * FROM attachments WHERE id=%s FOR UPDATE', (attachment_id,)).fetchone() + if not attachment or version not in ENCODING or version <= attachment['target_pipeline_version']: + return None + previous = conn.execute( + 'SELECT staging_key FROM attachment_jobs WHERE attachment_id=%s AND pipeline_version=%s', + (attachment_id, attachment['target_pipeline_version']), + ).fetchone() + if not previous and not attachment['published_pipeline_version']: + return None + source = attachment['object_key'] if attachment['published_pipeline_version'] else previous['staging_key'] + object_lock(conn, source) + client().head_object(Bucket=BUCKET, Key=source) + conn.execute( + """UPDATE attachment_jobs SET state='superseded', lease_token=NULL, lease_until=NULL, + next_publish_at=NULL, settled_at=clock_timestamp() + WHERE attachment_id=%s AND state IN ('queued','processing')""", (attachment_id,), + ) + conn.execute( + """UPDATE attachments SET target_pipeline_version=%s, + state=CASE WHEN published_pipeline_version IS NULL THEN 'queued' ELSE 'ready' END, + error_code=NULL,updated_at=clock_timestamp() WHERE id=%s""", + (version, attachment_id), + ) + job_id = uuid4() + conn.execute( + """INSERT INTO attachment_jobs(id,attachment_id,staging_key,attempt_limit,next_publish_at,pipeline_version) + VALUES (%s,%s,%s,%s,clock_timestamp(),%s)""", + (job_id, attachment_id, f'staging/{attachment_id}', int(setting('JOB_MAX_ATTEMPTS', '5')), version), + ) + return job_id diff --git a/src/migrate.py b/src/migrate.py new file mode 100644 index 00000000..69dacbfe --- /dev/null +++ b/src/migrate.py @@ -0,0 +1,19 @@ +"""Версионируемые миграции: одна транзакция, блокировка от параллельного запуска.""" +from pathlib import Path +import psycopg +from src.config import setting + + +def main(): + with psycopg.connect(setting('DATABASE_URL'), connect_timeout=5) as conn: + conn.execute('SELECT pg_advisory_xact_lock(2301002)') + conn.execute('CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY)') + for path in sorted(Path('/app/migrations' if Path('/app/migrations').exists() else 'migrations').glob('*.sql')): + if not conn.execute('SELECT 1 FROM schema_migrations WHERE version=%s', (path.name,)).fetchone(): + conn.execute(path.read_text(encoding='utf-8')) + conn.execute('INSERT INTO schema_migrations VALUES (%s)', (path.name,)) + print('Применена миграция:', path.name) + + +if __name__ == '__main__': + main() diff --git a/src/models.py b/src/models.py new file mode 100644 index 00000000..dc507cce --- /dev/null +++ b/src/models.py @@ -0,0 +1,126 @@ +from datetime import datetime, timezone +from typing import Optional +import uuid + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator + + +def utc_now() -> str: + """Возвращает текущее время в формате RFC 3339 UTC с суффиксом Z.""" + return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +class ErrorDetail(BaseModel): + """Детали ошибки API.""" + code: str + message: str + request_id: str + + +class ErrorResponse(BaseModel): + """Стандартный ответ об ошибке.""" + error: ErrorDetail + + +class Health(BaseModel): + """Ответ проверки работоспособности.""" + status: str = "ok" + + +class User(BaseModel): + """Модель пользователя.""" + id: str + username: str + display_name: str + created_at: str + + +class CreateUser(BaseModel): + """Данные для создания пользователя.""" + model_config = ConfigDict(extra="forbid", strict=True) + + password: str = Field(..., min_length=12, max_length=128) + username: str = Field(..., pattern=r"^[a-z0-9_]{3,32}$") + display_name: str = Field(..., min_length=1, max_length=100) + + @field_validator("display_name") + @classmethod + def display_name_not_whitespace_only(cls, v: str) -> str: + """Запрещаем display_name, состоящий только из пробельных символов.""" + if v.strip() == "": + raise ValueError("display_name не может состоять только из пробелов") + return v + + +class Chat(BaseModel): + """Модель чата.""" + id: str + title: str + member_ids: list[str] + created_at: str + + +class CreateChat(BaseModel): + """Данные для создания чата.""" + model_config = ConfigDict(extra="forbid", strict=True) + + 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 valid_members(cls, values): + """Проверить UUID и привести их к единому представлению.""" + return [str(uuid.UUID(value)) for value in values] + + @field_validator("title") + @classmethod + def title_not_whitespace_only(cls, v: str) -> str: + """Запрещаем title, состоящий только из пробельных символов.""" + if v.strip() == "": + raise ValueError("title не может состоять только из пробелов") + return v + + +class Message(BaseModel): + """Модель сообщения.""" + id: str + chat_id: str + sender_id: str + text: str + created_at: str + attachment_ids: list[str] = Field(default_factory=list) + + +class CreateMessage(BaseModel): + """Данные для отправки сообщения.""" + model_config = ConfigDict(extra="forbid", strict=True) + + text: str = Field(..., max_length=4000) + attachment_ids: list[str] = Field(default_factory=list, max_length=10) + + @field_validator('attachment_ids') + @classmethod + def valid_attachments(cls, values): + ids = [str(uuid.UUID(v)) for v in values] + if len(set(ids)) != len(ids): + raise ValueError('duplicate attachment_id') + return ids + + @model_validator(mode='after') + def valid_content(self): + if not self.text.strip() and not self.attachment_ids: + raise ValueError('empty message') + return self + + +class ChatPage(BaseModel): + """Страница списка чатов с курсорной пагинацией.""" + items: list[Chat] + next_cursor: Optional[str] = None + + +class MessagePage(BaseModel): + """Страница истории сообщений с курсорной пагинацией.""" + items: list[Message] + next_cursor: Optional[str] = None diff --git a/src/objects.py b/src/objects.py new file mode 100644 index 00000000..8c036e57 --- /dev/null +++ b/src/objects.py @@ -0,0 +1,36 @@ +"""S3 operations with bounded timeouts and immutable server-generated keys.""" +import boto3 +from botocore.config import Config +from botocore.exceptions import ClientError +from src.config import setting + +def client(): + return boto3.client('s3', endpoint_url=setting('S3_ENDPOINT','https://s3:9000'), verify='/tls/ca.crt', + aws_access_key_id=setting('S3_ACCESS_KEY'), aws_secret_access_key=setting('S3_SECRET_KEY'), + region_name='us-east-1', config=Config(connect_timeout=2,read_timeout=5, + retries={'total_max_attempts':1},s3={'addressing_style':'path'})) + +BUCKET = setting('S3_BUCKET','attachments') + + +class ObjectConflict(Exception): + """Неизменяемый ключ уже содержит другие данные.""" + + +def put_immutable(s3, key, stream, size, content_type, digest): + try: + s3.put_object(Bucket=BUCKET, Key=key, Body=stream, ContentLength=size, + ContentType=content_type, Metadata={'sha256': digest}, IfNoneMatch='*') + except ClientError as exc: + if exc.response['ResponseMetadata']['HTTPStatusCode'] != 412: + raise + existing = s3.head_object(Bucket=BUCKET, Key=key) + if (existing['ContentLength'], existing['ContentType'], existing['Metadata'].get('sha256')) != ( + size, content_type, digest): + raise ObjectConflict(key) from None + + +def object_lock(conn, key, wait=True): + fn = 'pg_advisory_xact_lock' if wait else 'pg_try_advisory_xact_lock' + row = conn.execute('SELECT '+fn+'(hashtextextended(%s,42)) AS locked',(key,)).fetchone() + return wait or row['locked'] diff --git a/src/pipeline_versions.py b/src/pipeline_versions.py new file mode 100644 index 00000000..5181955a --- /dev/null +++ b/src/pipeline_versions.py @@ -0,0 +1,2 @@ +"""Åäèíñòâåííûé îáÿçàòåëüíûé pipeline.""" +ENCODING = {1: (85, 82)} diff --git a/src/routes/__init__.py b/src/routes/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/routes/attachments.py b/src/routes/attachments.py new file mode 100644 index 00000000..157ca19d --- /dev/null +++ b/src/routes/attachments.py @@ -0,0 +1,159 @@ +"""Bounded synchronous image uploads; one decode per process.""" +import asyncio +import hashlib +import tempfile +import unicodedata +import uuid +import warnings +from PIL import Image, UnidentifiedImageError +from fastapi import APIRouter, Depends, HTTPException, Request +from starlette.concurrency import run_in_threadpool +from starlette.responses import StreamingResponse +from starlette.requests import ClientDisconnect +from src.routes.common import require_user, make_error, get_request_id +from src.storage import storage, timestamp +from src.objects import client, BUCKET, object_lock, put_immutable +from src.config import setting +from src import telemetry +import json + +router = APIRouter() +slots = asyncio.Semaphore(1) +MAX_BYTES=10*1024*1024 +Image.MAX_IMAGE_PIXELS=40_000_000 + +class InvalidImage(Exception): + def __init__(self,status): + self.status=status + +def error(request, status, code, message): + return HTTPException(status, detail=make_error(code,message,get_request_id(request)).model_dump()) + +def inspect_image(stream, declared): + try: + with warnings.catch_warnings(): + warnings.simplefilter('error', Image.DecompressionBombWarning) + with Image.open(stream) as image: + if image.width*image.height>40_000_000: + raise InvalidImage(413) + actual={'PNG':'image/png','JPEG':'image/jpeg'}.get(image.format) + if not actual or actual != declared: + raise InvalidImage(415) + image.verify() + stream.seek(0) + with Image.open(stream) as image: + image.load() + except (Image.DecompressionBombError,Image.DecompressionBombWarning): + raise InvalidImage(413) from None + except (UnidentifiedImageError,OSError,SyntaxError,ValueError): + raise InvalidImage(415) from None + finally: + stream.seek(0) + +def metadata(row, variants=()): + return {k: str(row[k]) for k in ('id','chat_id','owner_id')} | { + k:row[k] for k in ('filename','content_type','size_bytes','sha256')} | { + 'status':row['state'],'variants':list(variants),'error_code':row['error_code'], + 'created_at':timestamp(row['created_at']),'updated_at':timestamp(row['updated_at'])} + +def save(stream, chat_id, owner, filename, content_type, size, digest): + attachment_id=uuid.uuid4() + key=f'originals/{attachment_id}' + staging_key=f'staging/{attachment_id}' + with storage.pool.connection() as conn: + object_lock(conn, staging_key) + put_immutable(client(), staging_key, stream, size, content_type, digest) + row=conn.execute("INSERT INTO attachments(id,chat_id,owner_id,object_key,filename,content_type,size_bytes,sha256,state) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,'queued') RETURNING *", + (attachment_id,chat_id,owner,key,filename,content_type,size,digest)).fetchone() + conn.execute( + "INSERT INTO attachment_jobs(id,attachment_id,staging_key,attempt_limit,next_publish_at,trace_context) " + "VALUES (%s,%s,%s,%s,clock_timestamp(),%s)", + (uuid.uuid4(), attachment_id, staging_key, int(setting('JOB_MAX_ATTEMPTS', '5')),json.dumps(telemetry.carrier())), + ) + return metadata(row) + +@router.post('/api/v1/chats/{chat_id}/attachments',status_code=202) +async def upload(request:Request,chat_id:uuid.UUID,filename:str='',actor:str=Depends(require_user)): + if not await run_in_threadpool(storage.is_chat_member,str(chat_id),actor): + raise error(request,404,'not_found','chat not found') + if not 1<=len(filename)<=255 or any(c in '/\\' or unicodedata.category(c)=='Cc' for c in filename): + raise error(request,400,'invalid_request','invalid filename') + mime=request.headers.get('content-type','').lower() + if mime not in ('image/png','image/jpeg'): + raise error(request,415,'unsupported_media_type','PNG/JPEG required') + length=request.headers.get('content-length') + if length is not None: + if not length.isdecimal(): + raise error(request,400,'invalid_request','invalid length') + if int(length)>MAX_BYTES: + raise error(request,413,'payload_too_large','limit 10 MiB') + try: + await asyncio.wait_for(slots.acquire(),timeout=25) + except asyncio.TimeoutError: + raise error(request,503,'unavailable','upload queue busy') from None + try: + with tempfile.TemporaryFile() as stream: + size=0; digest=hashlib.sha256() + async def receive(): + nonlocal size + async for chunk in request.stream(): + size+=len(chunk) + if size>MAX_BYTES: + raise error(request,413,'payload_too_large','limit 10 MiB') + digest.update(chunk) + await run_in_threadpool(stream.write,chunk) + try: + await asyncio.wait_for(receive(),timeout=20) + await run_in_threadpool(stream.seek,0) + await run_in_threadpool(inspect_image,stream,mime) + except ClientDisconnect: + raise error(request,400,'invalid_request','upload disconnected') from None + except asyncio.TimeoutError: + raise error(request,400,'invalid_request','upload timed out') from None + except InvalidImage as exc: + raise error(request,exc.status,'payload_too_large' if exc.status==413 else 'unsupported_media_type','invalid image') from None + return await run_in_threadpool(save,stream,str(chat_id),actor,filename,mime,size,digest.hexdigest()) + finally: + slots.release() + +def accessible(conn, request, attachment_id, actor): + # One consistent manifest for all reads in the enclosing transaction. + row=conn.execute('SELECT a.* FROM attachments a JOIN chat_members m ON a.chat_id=m.chat_id ' + 'WHERE a.id=%s AND m.user_id=%s FOR SHARE OF a',(attachment_id,actor)).fetchone() + if not row: + raise error(request,404,'not_found','attachment not found') + return row + +@router.get('/api/v1/attachments/{attachment_id}') +def get_attachment(request:Request,attachment_id:uuid.UUID,actor:str=Depends(require_user)): + with storage.pool.connection() as conn: + row = accessible(conn, request, attachment_id, actor) + variants = conn.execute( + 'SELECT name,content_type,size_bytes,sha256,width,height FROM attachment_variants ' + 'WHERE attachment_id=%s AND pipeline_version=%s ORDER BY name', + (attachment_id, row['published_pipeline_version']), + ).fetchall() + return metadata(row, variants) + +@router.get('/api/v1/attachments/{attachment_id}/content') +def content(request:Request,attachment_id:uuid.UUID,variant:str='original',actor:str=Depends(require_user)): + with storage.pool.connection() as conn: + row = accessible(conn, request, attachment_id, actor) + if variant not in ('original','thumbnail','crop','optimized'): + raise error(request,400,'invalid_request','invalid variant') + if row['state'] != 'ready': + raise error(request,409,'conflict','attachment not ready') + if variant != 'original': + row = conn.execute( + 'SELECT * FROM attachment_variants WHERE attachment_id=%s AND pipeline_version=%s AND name=%s', + (attachment_id, row['published_pipeline_version'], variant), + ).fetchone() + if not row: + raise error(request,404,'not_found','variant not found') + obj=client().get_object(Bucket=BUCKET,Key=row['object_key']) + def chunks(): + try: + yield from obj['Body'].iter_chunks(chunk_size=64*1024) + finally: + obj['Body'].close() + return StreamingResponse(chunks(),media_type=row['content_type'],headers={'Content-Length':str(row['size_bytes'])}) diff --git a/src/routes/chats.py b/src/routes/chats.py new file mode 100644 index 00000000..1324eca1 --- /dev/null +++ b/src/routes/chats.py @@ -0,0 +1,79 @@ +from uuid import UUID + +from fastapi import APIRouter, Depends, HTTPException, Request + +from src.models import Chat, ChatPage, CreateChat +from src.routes.common import get_request_id, make_error, require_user +from src.storage import LimitExceeded, ValidationError, storage + +router = APIRouter() + + +@router.post("/api/v1/chats", response_model=Chat, status_code=201) +def create_chat( + request: Request, + body: CreateChat, + x_user_id: str = Depends(require_user), +): + """Создать чат. Создатель обязательно должен входить в member_ids.""" + request_id = get_request_id(request) + + try: + chat = storage.create_chat(body.title, body.member_ids, x_user_id) + return chat + except ValidationError as e: + raise HTTPException( + status_code=400, + detail=make_error("invalid_request", str(e), request_id).model_dump(), + ) + except LimitExceeded as e: + raise HTTPException( + status_code=429, + detail=make_error("rate_limited", str(e), request_id).model_dump(), + ) + + +@router.get("/api/v1/chats", response_model=ChatPage) +def list_chats( + request: Request, + x_user_id: str = Depends(require_user), + limit: int = 50, + cursor: str | None = None, +): + """Список чатов текущего пользователя с курсорной пагинацией.""" + request_id = get_request_id(request) + + if limit < 1 or limit > 100: + raise HTTPException( + status_code=400, + detail=make_error("invalid_request", "limit должен быть от 1 до 100", request_id).model_dump(), + ) + + try: + items, next_cursor = storage.list_chats_for_user(x_user_id, cursor, limit) + return ChatPage(items=items, next_cursor=next_cursor) + except ValidationError as e: + raise HTTPException( + status_code=400, + detail=make_error("invalid_request", str(e), request_id).model_dump(), + ) + + +@router.get("/api/v1/chats/{chat_id}", response_model=Chat) +def get_chat( + request: Request, + chat_id: UUID, + x_user_id: str = Depends(require_user), +): + """Получить чат по id. Доступен только участникам чата (чужой — 404).""" + request_id = get_request_id(request) + + chat_id_str = str(chat_id) + chat = storage.get_chat(chat_id_str) + if not chat or x_user_id not in chat.member_ids: + raise HTTPException( + status_code=404, + detail=make_error("not_found", "чат не найден", request_id).model_dump(), + ) + + return chat diff --git a/src/routes/common.py b/src/routes/common.py new file mode 100644 index 00000000..628e51e6 --- /dev/null +++ b/src/routes/common.py @@ -0,0 +1,29 @@ +"""Общие ошибки и проверка Bearer-сессии; X-User-Id не используется.""" +from fastapi import HTTPException, Request +from src.models import ErrorResponse +from src.storage import storage + + +def make_error(code, message, request_id): + return ErrorResponse(error={'code': code, 'message': message, 'request_id': request_id}) + + +def get_request_id(request): + return request.state.request_id + + +def unauthorized(request, basic=False): + challenge = 'Basic realm="messenger", charset="UTF-8"' if basic else 'Bearer realm="messenger"' + raise HTTPException(401, detail=make_error('unauthorized', 'неверные учётные данные', get_request_id(request)).model_dump(), headers={'WWW-Authenticate': challenge}) + + +def require_user(request: Request): + authorization = request.headers.get('Authorization', '') + parts = authorization.split() + if len(parts) != 2 or parts[0].lower() != 'bearer': + unauthorized(request) + user_id = storage.session_user(parts[1]) + if not user_id: + unauthorized(request) + request.state.token = parts[1] + return user_id diff --git a/src/routes/health.py b/src/routes/health.py new file mode 100644 index 00000000..9e45f954 --- /dev/null +++ b/src/routes/health.py @@ -0,0 +1,23 @@ +"""Жизнь процесса и готовность критичного хранилища проверяются отдельно.""" +from fastapi import APIRouter +from src.models import Health +from src.storage import storage +router = APIRouter() + + +@router.get('/health/live') +def liveness(): + return Health() + + +@router.get('/health/ready') +def readiness(): + storage.ready() + from src.objects import client, BUCKET + client().list_objects_v2(Bucket=BUCKET, Prefix="staging/", MaxKeys=1) + return Health() + + +@router.get('/stats') +def stats(): + return storage.get_stats() diff --git a/src/routes/messages.py b/src/routes/messages.py new file mode 100644 index 00000000..1045e5dc --- /dev/null +++ b/src/routes/messages.py @@ -0,0 +1,85 @@ +from uuid import UUID +import re +import os + +from fastapi import APIRouter, Depends, HTTPException, Request + +from src.models import CreateMessage, Message, MessagePage +from src.routes.common import get_request_id, make_error, require_user +from src.storage import NotFoundError, ConflictError, LimitExceeded, ValidationError, storage + +router = APIRouter() + + +@router.post("/api/v1/chats/{chat_id}/messages", response_model=Message, status_code=201) +def create_message( + request: Request, + chat_id: UUID, + body: CreateMessage, + x_user_id: str = Depends(require_user), +): + """Отправить сообщение от владельца Bearer-сессии с общей защитой повторов.""" + request_id = get_request_id(request) + + chat_id_str = str(chat_id) + if os.getenv('OPTIMIZED_WRITES','1') == '1': + allowed = storage.is_chat_member(chat_id_str, x_user_id) + else: + chat = storage.get_chat(chat_id_str) + allowed = bool(chat and x_user_id in chat.member_ids) + if not allowed: + raise HTTPException( + status_code=404, + detail=make_error("not_found", "чат не найден", request_id).model_dump(), + ) + + try: + key = request.headers.get('Idempotency-Key', '') + if not re.fullmatch(r'[A-Za-z0-9._:-]{1,128}', key): + raise HTTPException(400, detail=make_error('invalid_request', 'неверный Idempotency-Key', request_id).model_dump()) + msg = storage.create_message(chat_id_str, x_user_id, body.text, key, body.attachment_ids) + return msg + except NotFoundError as e: + raise HTTPException(404, detail=make_error('not_found', str(e), request_id).model_dump()) + except ConflictError as e: + raise HTTPException(409, detail=make_error('conflict', str(e), request_id).model_dump()) + except LimitExceeded as e: + raise HTTPException( + status_code=429, + detail=make_error("rate_limited", str(e), request_id).model_dump(), + ) + + +@router.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage) +def list_messages( + request: Request, + chat_id: UUID, + x_user_id: str = Depends(require_user), + limit: int = 50, + cursor: str | None = None, +): + """История сообщений чата с курсорной пагинацией. Доступно только участникам.""" + request_id = get_request_id(request) + + chat_id_str = str(chat_id) + chat = storage.get_chat(chat_id_str) + if not chat or x_user_id not in chat.member_ids: + raise HTTPException( + status_code=404, + detail=make_error("not_found", "чат не найден", request_id).model_dump(), + ) + + if limit < 1 or limit > 100: + raise HTTPException( + status_code=400, + detail=make_error("invalid_request", "limit должен быть от 1 до 100", request_id).model_dump(), + ) + + try: + items, next_cursor = storage.list_messages(chat_id_str, cursor, limit) + return MessagePage(items=items, next_cursor=next_cursor) + except ValidationError as e: + raise HTTPException( + status_code=400, + detail=make_error("invalid_request", str(e), request_id).model_dump(), + ) diff --git a/src/routes/users.py b/src/routes/users.py new file mode 100644 index 00000000..64aeda44 --- /dev/null +++ b/src/routes/users.py @@ -0,0 +1,52 @@ +"""Регистрация, вход, текущий пользователь и отзыв сессии.""" +import base64 +import binascii +from fastapi import APIRouter, Request, Response, HTTPException +from src.models import CreateUser, User +from src.routes.common import get_request_id, make_error, require_user, unauthorized +from src.storage import ConflictError, storage + +router = APIRouter() + + +@router.post('/api/v1/users', response_model=User, status_code=201) +def register_user(request: Request, body: CreateUser): + try: + return storage.create_user(body.username,body.display_name,body.password) + except ConflictError as exc: + raise HTTPException(409,detail=make_error('conflict',str(exc),get_request_id(request)).model_dump()) + + +@router.post('/api/v1/auth/sessions', status_code=201) +async def login(request: Request): + if await request.body(): + raise HTTPException(400, detail=make_error('invalid_request','тело запроса не допускается',get_request_id(request)).model_dump()) + parts = request.headers.get('Authorization','').split() + try: + if len(parts) != 2 or parts[0].lower() != 'basic': + unauthorized(request, basic=True) + username,password = base64.b64decode(parts[1],validate=True).decode('utf-8').split(':',1) + username.encode('ascii') + except (ValueError, UnicodeError, binascii.Error): + unauthorized(request,basic=True) + # Вычисление KDF и синхронные запросы выполняются вне цикла событий. + from starlette.concurrency import run_in_threadpool + if not await run_in_threadpool(storage.login_allowed, username): + raise HTTPException(429, detail=make_error('rate_limited','повторите вход позже',get_request_id(request)).model_dump(), + headers={'Retry-After':'60'}) + result = await run_in_threadpool(storage.login,username,password) + if not result: + unauthorized(request,basic=True) + return result + + +@router.get('/api/v1/users/me',response_model=User) +def current_user(request: Request): + return storage.get_user(require_user(request)) + + +@router.delete('/api/v1/auth/sessions/current',status_code=204) +def logout(request: Request): + require_user(request) + storage.logout(request.state.token) + return Response(status_code=204) diff --git a/src/serve.py b/src/serve.py new file mode 100644 index 00000000..84393913 --- /dev/null +++ b/src/serve.py @@ -0,0 +1,9 @@ +"""API has no reachable plaintext business port.""" +import threading +import uvicorn +from src.tls_proxy import serve + +if __name__ == '__main__': + threading.Thread(target=serve, args=(8443, 8080, 'lb'), daemon=True).start() + uvicorn.run('src.app:app', host='127.0.0.1', port=8080, access_log=False, + timeout_graceful_shutdown=8, timeout_keep_alive=2) diff --git a/src/staging.py b/src/staging.py new file mode 100644 index 00000000..26ec0ad9 --- /dev/null +++ b/src/staging.py @@ -0,0 +1,59 @@ +"""Очистка staging с блокировкой, общей с HTTP upload и replay.""" + +import logging +import signal +import threading +from datetime import datetime, timezone + +import psycopg +from botocore.exceptions import BotoCoreError, ClientError +from psycopg_pool import PoolTimeout + +from src.config import setting +from src.objects import BUCKET, client, object_lock +from src.storage import storage + + +def cleanup(s3, retention): + count = 0 + now = datetime.now(timezone.utc) + pages = s3.get_paginator('list_objects_v2') + for page in pages.paginate(Bucket=BUCKET, Prefix='staging/'): + for item in page.get('Contents', []): + key = item['Key'] + with storage.pool.connection() as conn: + if not object_lock(conn, key, wait=False): + continue + job = conn.execute( + 'SELECT state,settled_at FROM attachment_jobs WHERE staging_key=%s ' + 'ORDER BY pipeline_version DESC LIMIT 1', (key,), + ).fetchone() + retention_start = (job['settled_at'] if job else None) or item['LastModified'] + age = (now - retention_start).total_seconds() + if job and job['state'] in ('queued', 'processing'): + continue + if (job and job['state'] == 'ready') or age >= retention: + s3.delete_object(Bucket=BUCKET, Key=key) + count += 1 + return count + + +def main(): + stop = threading.Event() + for sig in (signal.SIGTERM, signal.SIGINT): + signal.signal(sig, lambda *_: stop.set()) + retention = max(60, int(setting('STAGING_RETENTION_SECONDS', '86400'))) + storage.pool.open(wait=True) + try: + while not stop.is_set(): + try: + cleanup(client(), retention) + except (BotoCoreError, ClientError, OSError, psycopg.Error, PoolTimeout) as exc: + logging.warning('staging cleanup temporarily unavailable: %s', type(exc).__name__) + stop.wait(30) + finally: + storage.pool.close() + + +if __name__ == '__main__': + main() diff --git a/src/storage.py b/src/storage.py new file mode 100644 index 00000000..6404b17c --- /dev/null +++ b/src/storage.py @@ -0,0 +1,289 @@ +"""PostgreSQL — источник истины; каждый контекст подключения завершает транзакцию.""" +import base64 +import binascii +from datetime import datetime, timezone +import hashlib +import json +import os +import secrets +import threading +import uuid + +from argon2 import PasswordHasher +from argon2.exceptions import VerifyMismatchError, VerificationError, InvalidHashError +from psycopg.errors import UniqueViolation, ForeignKeyViolation +from psycopg.rows import dict_row +from psycopg_pool import ConnectionPool +from src.config import setting +from src.cache import profile_cache +from src.models import User, Chat, Message + +_CURSOR_FIELDS = {"scope", "resource_id", "created_at", "id"} +PASSWORDS = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1) +DUMMY_HASH = PASSWORDS.hash('synthetic-dummy-password') + + +class ValidationError(Exception): + """Неверный запрос.""" + + +class ConflictError(Exception): + """Имя уже занято.""" + + +class LimitExceeded(Exception): + """Перегрузка сервера.""" + + +class NotFoundError(Exception): + """Объект отсутствует или недоступен.""" + + +def timestamp(value): + return value.astimezone(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z') + + +def public_row(row): + return {k: timestamp(v) if isinstance(v, datetime) else str(v) if isinstance(v, uuid.UUID) else v + for k, v in row.items() if k != 'password_hash'} + + +class PostgresStorage: + def __init__(self): + self.pool = ConnectionPool(setting('DATABASE_URL', ''), min_size=1, max_size=int(os.getenv("POOL_SIZE", "10")), + timeout=3, max_waiting=32, open=False, check=ConnectionPool.check_connection, + kwargs={'row_factory': dict_row, 'connect_timeout': 3, + 'options': '-c statement_timeout=3000 -c lock_timeout=2000'}) + self._lock = threading.Lock() + self._requests = 0 + + @staticmethod + def _encode_cursor(scope: str, resource_id: str, created_at: str, item_id: str) -> str: + """Собрать непрозрачный курсор, привязанный к конкретному ресурсу.""" + payload = { + "scope": scope, + "resource_id": resource_id, + "created_at": created_at, + "id": item_id, + } + raw = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8") + return base64.urlsafe_b64encode(raw).decode("ascii") + + @staticmethod + def _decode_cursor(cursor: str, expected_scope: str, expected_resource_id: str) -> tuple[str, str]: + """Разобрать и проверить курсор. + + Клиент видит курсор как непрозрачную строку, поэтому любые пустые, + повреждённые или относящиеся к другому ресурсу значения отклоняем. + """ + if cursor == "": + raise ValidationError("некорректный cursor") + + allowed_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=" + if any(char not in allowed_chars for char in cursor) or "=" in cursor.rstrip("="): + raise ValidationError("некорректный cursor") + + try: + raw = base64.b64decode(cursor.encode("ascii"), altchars=b"-_", validate=True) + payload = json.loads(raw.decode("utf-8")) + except (UnicodeEncodeError, UnicodeDecodeError, binascii.Error, json.JSONDecodeError): + raise ValidationError("некорректный cursor") + + if not isinstance(payload, dict) or set(payload) != _CURSOR_FIELDS: + raise ValidationError("некорректный cursor") + + if not all(isinstance(payload[field], str) for field in _CURSOR_FIELDS): + raise ValidationError("некорректный cursor") + + if payload["scope"] != expected_scope or payload["resource_id"] != expected_resource_id: + raise ValidationError("некорректный cursor") + + try: + uuid.UUID(payload["resource_id"]) + uuid.UUID(payload["id"]) + datetime.fromisoformat(payload["created_at"].replace("Z", "+00:00")) + except ValueError: + raise ValidationError("некорректный cursor") + + return payload["created_at"], payload["id"] + + + def create_user(self, username, display_name, password): + password_hash = PASSWORDS.hash(password) + try: + with self.pool.connection() as conn: + row = conn.execute('INSERT INTO users (id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) RETURNING id,username,display_name,created_at', + (uuid.uuid4(), username, display_name, password_hash)).fetchone() + return User(**public_row(row)) + except UniqueViolation: + raise ConflictError('имя пользователя уже занято') from None + + def get_user(self, user_id): + cached = profile_cache.get(user_id) + if cached: + return cached + with self.pool.connection() as conn: + row = conn.execute('SELECT id,username,display_name,created_at FROM users WHERE id=%s', (user_id,)).fetchone() + user = User(**public_row(row)) if row else None + if user: + profile_cache.put(user) + return user + + def login(self, username, password): + with self.pool.connection() as conn: + row = conn.execute('SELECT * FROM users WHERE username=%s', (username,)).fetchone() + try: + PASSWORDS.verify(row['password_hash'] if row else DUMMY_HASH, password) + except (VerifyMismatchError, VerificationError, InvalidHashError): + return None + if not row: + return None + token = secrets.token_urlsafe(32) + with self.pool.connection() as conn: + session = conn.execute("INSERT INTO sessions VALUES (%s,%s,clock_timestamp() + %s * interval '1 second') RETURNING expires_at", + (self.token_hash(token), row['id'], int(os.getenv('SESSION_TTL_SECONDS', '3600')))).fetchone() + return {'token': token, 'token_type': 'Bearer', 'expires_at': timestamp(session['expires_at']), 'user': User(**public_row(row)).model_dump()} + + def login_allowed(self, username): + # A bounded, shared per-account window; arbitrary proxy headers are ignored. + identity = hashlib.sha256(username.lower().encode()).hexdigest() + with self.pool.connection() as conn: + row = conn.execute("""INSERT INTO login_limits VALUES (%s,clock_timestamp(),1) + ON CONFLICT(identity_hash) DO UPDATE SET + attempts=CASE WHEN login_limits.window_start < clock_timestamp()-interval '60 seconds' + THEN 1 ELSE login_limits.attempts+1 END, + window_start=CASE WHEN login_limits.window_start < clock_timestamp()-interval '60 seconds' + THEN clock_timestamp() ELSE login_limits.window_start END RETURNING attempts""", (identity,)).fetchone() + conn.execute("DELETE FROM login_limits WHERE window_start < clock_timestamp()-interval '1 hour'") + return row['attempts'] <= 10 + + @staticmethod + def token_hash(token): + return hashlib.sha256(token.encode()).hexdigest() + + def session_user(self, token): + with self.pool.connection() as conn: + row = conn.execute('SELECT user_id FROM sessions WHERE token_hash=%s AND expires_at > clock_timestamp()', (self.token_hash(token),)).fetchone() + return str(row['user_id']) if row else None + + def logout(self, token): + with self.pool.connection() as conn: + conn.execute('DELETE FROM sessions WHERE token_hash=%s', (self.token_hash(token),)) + + def create_chat(self, title, member_ids, creator_id): + if len(set(member_ids)) != len(member_ids) or creator_id not in member_ids: + raise ValidationError('неверный список участников') + chat_id = uuid.uuid4() + try: + with self.pool.connection() as conn: + row = conn.execute('INSERT INTO chats (id,title) VALUES (%s,%s) RETURNING *', (chat_id,title)).fetchone() + for member in member_ids: + conn.execute('INSERT INTO chat_members VALUES (%s,%s)', (chat_id,member)) + return Chat(**public_row(row), member_ids=sorted(member_ids)) + except ForeignKeyViolation: + raise ValidationError('участник не существует') from None + + def get_chat(self, chat_id): + with self.pool.connection() as conn: + row = conn.execute('SELECT * FROM chats WHERE id=%s', (chat_id,)).fetchone() + if not row: + return None + members = conn.execute('SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY user_id', (chat_id,)).fetchall() + return Chat(**public_row(row), member_ids=[str(x['user_id']) for x in members]) + + def is_chat_member(self, chat_id, user_id): + """Проверить доступ без загрузки всего чата и списка участников.""" + with self.pool.connection() as conn: + return conn.execute('SELECT 1 FROM chat_members WHERE chat_id=%s AND user_id=%s', (chat_id,user_id)).fetchone() is not None + + def list_chats_for_user(self, user_id, cursor, limit): + with self.pool.connection() as conn: + params = [user_id] + boundary = '' + if cursor is not None: + when, item = self._decode_cursor(cursor, 'chats', user_id) + marker = conn.execute('SELECT c.created_at FROM chats c JOIN chat_members m ON m.chat_id=c.id WHERE c.id=%s AND m.user_id=%s', (item,user_id)).fetchone() + if not marker or timestamp(marker['created_at']) != when: + raise ValidationError('некорректный cursor') + boundary = ' AND (c.created_at,c.id) > (%s,%s)' + params += [when,item] + rows = conn.execute('SELECT c.* FROM chats c JOIN chat_members m ON m.chat_id=c.id WHERE m.user_id=%s' + boundary + ' ORDER BY c.created_at,c.id LIMIT %s', params+[limit+1]).fetchall() + page = [self.get_chat(str(row['id'])) for row in rows[:limit]] + next_cursor = self._encode_cursor('chats',user_id,page[-1].created_at,page[-1].id) if len(rows)>limit else None + return page,next_cursor + + def create_message(self, chat_id, sender_id, text, key, attachment_ids=None): + attachment_ids = attachment_ids or [] + normalized = {'text': text, 'attachment_ids': attachment_ids} + # Блокировка сериализует один ключ на всех репликах; результат и сообщение атомарны. + with self.pool.connection() as conn: + scope = json.dumps([sender_id, chat_id, key]) + conn.execute('SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))', (scope,)) + old = conn.execute('SELECT * FROM message_requests WHERE user_id=%s AND chat_id=%s AND key=%s AND expires_at>clock_timestamp()', (sender_id,chat_id,key)).fetchone() + if old: + if json.loads(old['body']) != normalized: + raise ConflictError('ключ уже использован с другим сообщением') + row = conn.execute('SELECT * FROM messages WHERE id=%s', (old['message_id'],)).fetchone() + return self.message_model(conn, row) + for attachment_id in sorted(attachment_ids): + attachment = conn.execute('SELECT state FROM attachments WHERE id=%s AND chat_id=%s FOR SHARE', (attachment_id,chat_id)).fetchone() + if not attachment: + raise NotFoundError('вложение не найдено') + if attachment['state'] == 'failed': + raise ConflictError('вложение недоступно') + optimized = os.getenv('OPTIMIZED_WRITES','1') == '1' + if not optimized: + conn.execute('DELETE FROM message_requests WHERE user_id=%s AND chat_id=%s AND key=%s', (sender_id,chat_id,key)) + row = conn.execute('INSERT INTO messages (id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) RETURNING *', (uuid.uuid4(),chat_id,sender_id,text)).fetchone() + # Под той же блокировкой UPSERT заменяет просроченный результат без отдельного DELETE. + suffix = ' ON CONFLICT (user_id,chat_id,key) DO UPDATE SET body=EXCLUDED.body,message_id=EXCLUDED.message_id,expires_at=EXCLUDED.expires_at' if optimized else '' + conn.execute("INSERT INTO message_requests VALUES (%s,%s,%s,%s,%s,clock_timestamp()+interval '24 hours')"+suffix, (sender_id,chat_id,key,json.dumps(normalized,ensure_ascii=False),row['id'])) + for position, attachment_id in enumerate(attachment_ids): + conn.execute('INSERT INTO message_attachments VALUES (%s,%s,%s)', (row['id'],attachment_id,position)) + result = self.message_model(conn,row) + return result + + @staticmethod + def message_model(conn, row): + ids = conn.execute('SELECT attachment_id FROM message_attachments WHERE message_id=%s ORDER BY position', (row['id'],)).fetchall() + return Message(**public_row(row), attachment_ids=[str(x['attachment_id']) for x in ids]) + + def list_messages(self, chat_id, cursor, limit): + with self.pool.connection() as conn: + params = [chat_id] + boundary = '' + if cursor is not None: + when,item = self._decode_cursor(cursor,'messages',chat_id) + marker = conn.execute('SELECT created_at FROM messages WHERE id=%s AND chat_id=%s', (item,chat_id)).fetchone() + if not marker or timestamp(marker['created_at']) != when: + raise ValidationError('некорректный cursor') + boundary = ' AND (created_at,id) > (%s,%s)' + params += [when,item] + rows = conn.execute('SELECT * FROM messages WHERE chat_id=%s' + boundary + ' ORDER BY created_at,id LIMIT %s', params+[limit+1]).fetchall() + page = [self.message_model(conn,row) for row in rows[:limit]] + next_cursor = self._encode_cursor('messages',chat_id,page[-1].created_at,page[-1].id) if len(rows)>limit else None + return page,next_cursor + + def ready(self): + with self.pool.connection() as conn: + conn.execute('SELECT 1 FROM schema_migrations LIMIT 1') + + def acquire_request_slot(self): + with self._lock: + if self._requests >= 100: + return False + self._requests += 1 + return True + + def release_request_slot(self): + with self._lock: + self._requests -= 1 + + def get_stats(self): + with self.pool.connection() as conn: + result = {table: conn.execute('SELECT count(*) AS n FROM '+table).fetchone()['n'] for table in ('users','chats','messages')} + result['profile_cache'] = {'hits': profile_cache.hits, 'misses': profile_cache.misses, 'errors': profile_cache.errors, 'ttl_seconds': profile_cache.ttl} + return result + + +storage = PostgresStorage() diff --git a/src/telemetry.py b/src/telemetry.py new file mode 100644 index 00000000..31ae8073 --- /dev/null +++ b/src/telemetry.py @@ -0,0 +1,149 @@ +"""Bounded OTLP pipelines; explicit, low-cardinality application signals.""" +import atexit +import json +import logging +import os +import socket +import time +from contextlib import contextmanager + +from opentelemetry import trace, metrics +from opentelemetry.context import attach, detach +from opentelemetry.propagate import extract, inject +from opentelemetry.sdk.resources import Resource +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import BatchSpanProcessor +from opentelemetry.sdk.trace.sampling import ParentBased, TraceIdRatioBased +from opentelemetry.sdk.metrics import MeterProvider +from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader +from opentelemetry.sdk.metrics.view import View, ExplicitBucketHistogramAggregation +from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler +from opentelemetry.sdk._logs.export import BatchLogRecordProcessor +from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter +from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter +from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter +from opentelemetry.trace import SpanKind, Status, StatusCode + +_initialized = False +logger = logging.getLogger('messenger.events') +logger.propagate = False +logger.setLevel(logging.INFO) +busy = 0 +tracer = trace.get_tracer('messenger', '1.7.0') +meter = metrics.get_meter('messenger', '1.7.0') +http_count = meter.create_counter('messenger.http.requests') +http_duration = meter.create_histogram('messenger.http.duration', unit='s') +job_count = meter.create_counter('messenger.jobs') +job_duration = meter.create_histogram('messenger.job.duration', unit='s') +ready_duration = meter.create_histogram('messenger.ready.duration', unit='s') + + +def setup(service): + global _initialized + if _initialized or os.getenv('TELEMETRY_ENABLED', '1') == '0': + return + _initialized = True + resource = Resource.create({'service.name': service, 'service.version': '1.7.0', + 'service.instance.id': socket.gethostname(), 'deployment.environment.name': 'lab'}) + endpoint = os.getenv('OTEL_EXPORTER_OTLP_ENDPOINT', 'https://otel-collector:4318') + import requests + session = requests.Session() + session.verify = '/tls/ca.crt' + session.cert = ('/tls/cert.crt', '/tls/key.key') + tp = TracerProvider(resource=resource, sampler=ParentBased(TraceIdRatioBased( + float(os.getenv('TRACE_SAMPLE_RATIO', '1'))))) + tp.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint=endpoint+'/v1/traces', timeout=2, session=session), + max_queue_size=256, max_export_batch_size=64, schedule_delay_millis=1000)) + trace.set_tracer_provider(tp) + mp = MeterProvider(resource=resource, metric_readers=[PeriodicExportingMetricReader( + OTLPMetricExporter(endpoint=endpoint+'/v1/metrics', timeout=2, session=session), export_interval_millis=5000)], + views=[View(instrument_type=metrics.Histogram, + aggregation=ExplicitBucketHistogramAggregation([.005,.01,.025,.05,.1,.25,.5,1,2,5,10,20,30,60,120]))]) + metrics.set_meter_provider(mp) + lp = LoggerProvider(resource=resource) + lp.add_log_record_processor(BatchLogRecordProcessor(OTLPLogExporter(endpoint=endpoint+'/v1/logs', timeout=2, session=session), + max_queue_size=256, max_export_batch_size=64, schedule_delay_millis=1000)) + logger.addHandler(LoggingHandler(level=logging.INFO, logger_provider=lp)) + from opentelemetry.instrumentation.psycopg import PsycopgInstrumentor + from opentelemetry.instrumentation.botocore import BotocoreInstrumentor + # DB statements have placeholders; parameters and credentials are never captured. + PsycopgInstrumentor().instrument(skip_dep_check=True) + BotocoreInstrumentor().instrument() + atexit.register(lp.shutdown) + + +def event(name, **fields): + context = trace.get_current_span().get_span_context() + logger.info(json.dumps({'event': name, 'trace_id': format(context.trace_id, '032x'), + 'span_id': format(context.span_id, '016x'), **fields}, separators=(',', ':'))) + + +def carrier(): + result = {} + inject(result) + return result + + +@contextmanager +def span(name, **attrs): + with tracer.start_as_current_span(name, attributes=attrs, record_exception=False, + set_status_on_exception=False) as current: + try: + yield current + except Exception as exc: + current.set_status(Status(StatusCode.ERROR, type(exc).__name__)) + current.set_attribute('error.type', type(exc).__name__) + raise + + +class HTTPMiddleware: + """No bodies, raw URLs, query strings or incoming arbitrary headers are exported.""" + def __init__(self, app): + self.app = app + + async def __call__(self, scope, receive, send): + if scope['type'] != 'http' or scope['path'].startswith('/health/'): + return await self.app(scope, receive, send) + start = time.monotonic() + status = 500 + method = scope['method'] if scope['method'] in ('GET','POST','PUT','DELETE','PATCH','HEAD','OPTIONS') else 'OTHER' + headers = {k.decode('latin1'): v.decode('latin1') for k,v in scope['headers'] if k in (b'traceparent',b'tracestate')} + with tracer.start_as_current_span('HTTP request', context=extract(headers), kind=SpanKind.SERVER, + record_exception=False, set_status_on_exception=False) as current: + async def wrapped(message): + nonlocal status + if message['type'] == 'http.response.start': + status = message['status'] + message['headers'].append((b'x-trace-id', format(current.get_span_context().trace_id, '032x').encode())) + await send(message) + try: + await self.app(scope, receive, wrapped) + finally: + route = getattr(scope.get('route'), 'path', 'unmatched') + attrs = {'method': method, 'route': route, 'status_class': str(status//100)+'xx'} + current.update_name(method+' '+route) + current.set_attributes({'http.request.method': method, 'http.route': route, 'http.response.status_code': status}) + if status >= 500: + current.set_status(Status(StatusCode.ERROR)) + http_count.add(1, attrs) + http_duration.record(time.monotonic()-start, attrs) + event('http.completed', method=method, route=route, status=status, + request_id=scope.get('state', {}).get('request_id', '')) + + +def register_gauges(pool, worker=False): + from opentelemetry.metrics import Observation + def pool_values(key): + return lambda options: [Observation(pool.get_stats().get(key, 0))] + meter.create_observable_gauge('messenger.db.pool.used', callbacks=[lambda _: [Observation( + pool.get_stats().get('pool_size',0)-pool.get_stats().get('pool_available',0))]]) + meter.create_observable_gauge('messenger.db.pool.waiting', callbacks=[pool_values('requests_waiting')]) + if worker: + meter.create_observable_gauge('messenger.worker.busy', callbacks=[lambda _: [Observation(busy)]]) + meter.create_observable_gauge('messenger.worker.capacity', callbacks=[lambda _: [Observation(1)]]) + def process_stats(options): + import resource + return [Observation(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss*1024)] + meter.create_observable_gauge('messenger.process.maxrss', unit='By', callbacks=[process_stats]) + meter.create_observable_counter('messenger.process.cpu', unit='s', callbacks=[lambda _: [Observation( + sum(os.times()[:2]))]]) diff --git a/src/tls_proxy.py b/src/tls_proxy.py new file mode 100644 index 00000000..bd1a5d9a --- /dev/null +++ b/src/tls_proxy.py @@ -0,0 +1,52 @@ +"""TLS boundary: CA validation followed by an explicit client CN allowlist. + +Upstream is always loopback in the SAME network namespace. No plaintext listener +is reachable on the Compose network. Each connection has bounded idle time. +""" +import os +import select +import socket +import socketserver +import ssl +import threading + + +def serve(port, upstream, identities, directory='/tls'): + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.minimum_version = ssl.TLSVersion.TLSv1_2 + context.load_cert_chain(directory+'/cert.crt', directory+'/key.key') + context.load_verify_locations(directory+'/ca.crt') + context.verify_mode = ssl.CERT_REQUIRED + allowed = set(identities.split(',')) + + class Handler(socketserver.BaseRequestHandler): + def handle(self): + try: + self.request.settimeout(5) + with context.wrap_socket(self.request, server_side=True) as client: + cn = [v for part in client.getpeercert()['subject'] for k,v in part if k == 'commonName'] + if len(cn) != 1 or cn[0] not in allowed: + return + with socket.create_connection(('127.0.0.1', upstream), timeout=5) as target: + client.settimeout(30) + target.settimeout(30) + while True: + readable, _, _ = select.select([client, target], [], [], 30) + if not readable: + return + for source in readable: + data = source.recv(65536) + if not data: + return + (target if source is client else client).sendall(data) + except (OSError, ssl.SSLError): + pass # Never log certificates, payloads, headers or credentials. + + class Server(socketserver.ThreadingTCPServer): + allow_reuse_address = True + daemon_threads = True + Server(('0.0.0.0', port), Handler).serve_forever() + + +if __name__ == '__main__': + serve(int(os.getenv('TLS_PORT', '9443')), int(os.environ['UPSTREAM_PORT']), os.environ['ALLOW_CN']) diff --git a/src/worker.py b/src/worker.py new file mode 100644 index 00000000..aaadf991 --- /dev/null +++ b/src/worker.py @@ -0,0 +1,163 @@ +"""Worker обрабатывает одну доставку за раз и подтверждает после COMMIT.""" + +import hashlib +import json +import logging +import signal +import subprocess +import sys +import tempfile +import threading +import time +from datetime import datetime, timezone +from contextlib import closing +from pathlib import Path + +import pika +import psycopg +from botocore.exceptions import BotoCoreError, ClientError +from psycopg_pool import PoolTimeout + +from src import broker, jobs, telemetry +from opentelemetry.propagate import extract +from opentelemetry.trace import SpanKind, Status, StatusCode +from src.objects import BUCKET, ObjectConflict, client, put_immutable +from src.storage import storage + + +class PermanentError(Exception): + pass + + +def fetch(s3, key, attachment, destination): + digest = hashlib.sha256() + size = 0 + obj = s3.get_object(Bucket=BUCKET, Key=key) + with closing(obj['Body']) as stream, destination.open('wb') as output: + for chunk in stream.iter_chunks(chunk_size=64 * 1024): + size += len(chunk) + if size > attachment['size_bytes']: + raise PermanentError('staging_integrity') + digest.update(chunk) + output.write(chunk) + if (size, digest.hexdigest()) != (attachment['size_bytes'], attachment['sha256']): + raise PermanentError('staging_integrity') + + +def process(job): + attachment = job['attachment'] + s3 = client() + with tempfile.TemporaryDirectory() as temp: + directory = Path(temp) + original = directory / 'original' + source = attachment['object_key'] if attachment['published_pipeline_version'] else job['staging_key'] + fetch(s3, source, attachment, original) + result = subprocess.run([sys.executable, '-m', 'src.image_pipeline', temp, str(job['pipeline_version'])], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + timeout=jobs.JOB_TIMEOUT, check=False) + if result.returncode == 2: + raise PermanentError('invalid_image') + result.check_returncode() + with original.open('rb') as stream: + put_immutable(s3, attachment['object_key'], stream, attachment['size_bytes'], + attachment['content_type'], attachment['sha256']) + variants = [] + for name, mime, width, height in json.loads((directory / 'manifest.json').read_text()): + key = f"variants/{attachment['id']}/v{job['pipeline_version']}/{name}" + output = directory / name + size = output.stat().st_size + with output.open('rb') as stream: + digest = hashlib.file_digest(stream, 'sha256').hexdigest() + stream.seek(0) + put_immutable(s3, key, stream, size, mime, digest) + variants.append((name, key, mime, size, digest, width, height)) + published = jobs.complete(job, variants) + if published: + telemetry.ready_duration.record((datetime.now(timezone.utc)-job["attachment"]["created_at"]).total_seconds(), {"job_type":"attachment"}) + + +def handle_inner(channel, delivery, body): + try: + message = jobs.validate(json.loads(body)) + except (ValueError, TypeError, AttributeError): + logging.warning('invalid broker job') + channel.basic_reject(delivery.delivery_tag, requeue=False) + return + + job = jobs.claim(message) + if job: + telemetry.busy = 1 + started = time.monotonic() + outcome = "success" + try: + with telemetry.span("attachment.transform_and_publish"): + process(job) + except PermanentError as exc: + outcome = "failed" + jobs.fail(job, str(exc), permanent=True) + except ObjectConflict: + outcome = "failed" + jobs.fail(job, 'object_conflict', permanent=True) + except (BotoCoreError, ClientError, OSError, subprocess.SubprocessError) as exc: + outcome = "retry" + logging.warning('processing retry job=%s cause=%s', job['id'], type(exc).__name__) + jobs.fail(job, 'processing_timeout' if isinstance(exc, subprocess.TimeoutExpired) else 'processing_failed') + except (psycopg.Error, PoolTimeout): + # No ack: reconnect and durable lease recovery handle this attempt. + outcome = "retry" + raise + finally: + telemetry.busy = 0 + attrs = {"job_type":"attachment", "outcome":outcome} + telemetry.job_count.add(1, attrs) + telemetry.job_duration.record(time.monotonic()-started, attrs) + if outcome != "success": + telemetry.trace.get_current_span().set_status(Status(StatusCode.ERROR)) + telemetry.event("job.processed", job_id=str(job["id"]), attempt=job["attempt"], outcome=outcome) + else: + telemetry.event("job.duplicate") + channel.basic_ack(delivery.delivery_tag) + + + +def handle(channel, delivery, body): + try: + raw = json.loads(body) + carrier = {k:raw[k] for k in ('traceparent','tracestate') if k in raw} + except (ValueError, TypeError): + carrier = {} + with telemetry.tracer.start_as_current_span('attachment.consume', context=extract(carrier), + kind=SpanKind.CONSUMER, record_exception=False, set_status_on_exception=False) as sp: + sp.set_attribute('messaging.system', 'rabbitmq') + sp.set_attribute('messaging.destination.name', broker.QUEUE) + sp.set_attribute('messaging.message.redelivered', delivery.redelivered) + handle_inner(channel, delivery, body) + + +def main(): + telemetry.setup("messenger-worker") + telemetry.register_gauges(storage.pool, worker=True) + logging.basicConfig(level=logging.WARNING) + stopping = threading.Event() + for sig in (signal.SIGINT, signal.SIGTERM): + signal.signal(sig, lambda *_: stopping.set()) + storage.pool.open(wait=True) + try: + while not stopping.is_set(): + try: + with broker.channel(heartbeat=jobs.LEASE_SECONDS + 15) as (_, channel): + channel.basic_qos(prefetch_count=1) + for delivery, _, body in channel.consume(broker.QUEUE, inactivity_timeout=0.5): + if stopping.is_set(): + break + if delivery: + handle(channel, delivery, body) + except (pika.exceptions.AMQPError, OSError, psycopg.Error, PoolTimeout) as exc: + logging.warning('worker temporarily unavailable: %s', type(exc).__name__) + stopping.wait(1) + finally: + storage.pool.close() + + +if __name__ == '__main__': + main()