diff --git a/.dockerignore b/.dockerignore index bc16e55..0fbb212 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,20 +1,9 @@ -.git -.github -.env -.env.* -!.env.example -secrets -certs -volumes -data -backups -*.key -*.pem -*.p12 -*.pfx -*.jks .venv -__pycache__ -node_modules +secrets +.env +.git +**/__pycache__ +**/*.pyc evidence -.DS_Store +*.md +!src/**/* diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..a279135 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +*.sh text eol=lf +*.cfg text eol=lf +*.conf text eol=lf +*.hcl text eol=lf +infra/** text eol=lf diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..69e5f86 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,29 @@ +FROM python:3.13.16-slim-bookworm@sha256:a1165e272e578941b84abc79e4ab38a0305cd12803a5c4247979ac7655f4d641 + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + PIP_DEFAULT_TIMEOUT=120 \ + PYTHONPATH=/app/src \ + APP_HOST=0.0.0.0 \ + APP_PORT=8080 \ + APP_ENV=lab + +WORKDIR /app + +RUN useradd --create-home --uid 10001 --shell /usr/sbin/nologin appuser + +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt + +COPY src /app/src +COPY migrations /app/migrations + +USER appuser + +EXPOSE 8080 8443 + +HEALTHCHECK --interval=5s --timeout=3s --start-period=60s --retries=20 \ + CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2).read()"] + +CMD ["python", "-m", "app"] diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..fbe09f8 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,494 @@ +name: lab7 + +networks: + lab: + telemetry: + internal: true + +volumes: + postgres-data: + redis-data: + minio-data: + rabbit-data: + openbao-data: + tempo-data: + loki-data: + prometheus-data: + +services: + postgres: + image: postgres:16.8-bookworm + user: "0:0" + restart: unless-stopped + mem_limit: 512m + cpus: "1.0" + environment: + POSTGRES_USER: messenger + POSTGRES_DB: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/db_migrator_password + volumes: + - postgres-data:/var/lib/postgresql/data + - ./infra/postgres/entry.sh:/entry.sh:ro + - ./infra/postgres/init-roles.sh:/docker-entrypoint-initdb.d/10-roles.sh:ro + - ./infra/postgres/pg_hba.conf:/etc/pg/pg_hba.conf:ro + - ./secrets/certs/postgres.crt:/certs/postgres.crt:ro + - ./secrets/certs/postgres.key:/certs/postgres.key:ro + - ./secrets/passwords/db_migrator:/run/secrets/db_migrator_password:ro + - ./secrets/passwords/db_api:/run/secrets/db_api_password:ro + - ./secrets/passwords/db_worker:/run/secrets/db_worker_password:ro + - ./secrets/passwords/db_relay:/run/secrets/db_relay_password:ro + - ./secrets/passwords/db_gc:/run/secrets/db_gc_password:ro + entrypoint: ["/bin/sh", "/entry.sh"] + networks: [lab] + healthcheck: + test: ["CMD-SHELL", "pg_isready -U messenger -d messenger && test -f /var/lib/postgresql/data/.roles-ready"] + interval: 5s + timeout: 3s + retries: 30 + start_period: 20s + + redis: + image: redis:7.4.2-bookworm + user: "0:0" + restart: unless-stopped + mem_limit: 256m + cpus: "0.50" + volumes: + - redis-data:/data + - ./infra/redis/entry.sh:/entry.sh:ro + - ./secrets/certs/redis.crt:/certs/redis.crt:ro + - ./secrets/certs/redis.key:/certs/redis.key:ro + - ./secrets/certs/ca.crt:/certs/ca.crt:ro + - ./secrets/passwords/redis:/run/secrets/redis_password:ro + entrypoint: ["/bin/sh", "/entry.sh"] + networks: [lab] + healthcheck: + test: ["CMD-SHELL", "redis-cli --tls --cacert /certs/ca.crt -h redis -p 6379 -a \"$$(cat /run/secrets/redis_password)\" ping | grep -q PONG"] + interval: 5s + timeout: 3s + retries: 30 + start_period: 10s + + minio: + image: minio/minio:RELEASE.2024-10-02T17-50-41Z + restart: unless-stopped + mem_limit: 512m + cpus: "0.50" + command: ["server", "/data", "--address", "127.0.0.1:9000", "--console-address", "127.0.0.1:9001"] + env_file: + - ./secrets/minio.env + volumes: + - minio-data:/data + networks: [lab] + + minio-tls: + image: nginx:1.27.4-alpine + restart: unless-stopped + network_mode: "service:minio" + depends_on: + - minio + volumes: + - ./infra/nginx/minio.conf:/etc/nginx/conf.d/default.conf:ro + - ./secrets/certs/minio.crt:/certs/minio.crt:ro + - ./secrets/certs/minio.key:/certs/minio.key:ro + + minio-init: + image: minio/mc:RELEASE.2024-10-02T08-27-28Z + restart: "no" + entrypoint: ["/bin/sh", "/opt/minio-bootstrap.sh"] + volumes: + - ./infra/minio-bootstrap.sh:/opt/minio-bootstrap.sh:ro + - ./infra/minio:/policies:ro + - ./secrets:/secrets:ro + - ./secrets/certs/ca.crt:/certs/ca.crt:ro + networks: [lab] + depends_on: + - minio + - minio-tls + + rabbitmq: + image: rabbitmq:3.13.7-management-alpine + user: "0:0" + restart: unless-stopped + mem_limit: 512m + cpus: "0.50" + entrypoint: ["/bin/sh", "/entry.sh"] + volumes: + - rabbit-data:/var/lib/rabbitmq + - ./infra/rabbit-entry.sh:/entry.sh:ro + - ./infra/rabbitmq/rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf:ro + - ./secrets/rabbit-definitions.json:/run/secrets/definitions.json:ro + - ./secrets/certs/ca.crt:/certs/ca.crt:ro + - ./secrets/certs/rabbitmq.crt:/certs/rabbitmq.crt:ro + - ./secrets/certs/rabbitmq.key:/certs/rabbitmq.key:ro + - ./secrets/passwords/rabbit_operator_name:/run/secrets/rabbitmq_user:ro + - ./secrets/passwords/rabbit_operator:/run/secrets/rabbitmq_password:ro + networks: [lab] + healthcheck: + test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"] + interval: 5s + timeout: 5s + retries: 30 + start_period: 20s + + openbao: + image: openbao/openbao:2.1.0 + user: "0:0" + restart: unless-stopped + mem_limit: 256m + cpus: "0.50" + entrypoint: ["/bin/sh", "/entry.sh"] + cap_add: + - IPC_LOCK + volumes: + - openbao-data:/openbao/data + - ./infra/openbao/entry.sh:/entry.sh:ro + - ./infra/openbao/config.hcl:/openbao/config/config.hcl:ro + - ./secrets/certs/openbao.crt:/certs/openbao.crt:ro + - ./secrets/certs/openbao.key:/certs/openbao.key:ro + ports: + - "127.0.0.1:8200:8200" + networks: [lab] + + openbao-init: + image: python:3.13.16-slim-bookworm@sha256:a1165e272e578941b84abc79e4ab38a0305cd12803a5c4247979ac7655f4d641 + user: "0:0" + restart: "no" + entrypoint: ["python", "/opt/openbao_bootstrap.py"] + environment: + BAO_ADDR: https://openbao:8200 + BAO_CACERT: /secrets/certs/ca.crt + SECRETS_DIR: /secrets + POLICIES_DIR: /policies + volumes: + - ./scripts/openbao_bootstrap.py:/opt/openbao_bootstrap.py:ro + - ./secrets:/secrets + - ./infra/openbao/policies:/policies:ro + networks: [lab] + depends_on: + - openbao + + tempo: + image: grafana/tempo:2.6.1 + restart: unless-stopped + mem_limit: 256m + cpus: "0.50" + command: ["-config.file=/etc/tempo/tempo.yml"] + volumes: + - tempo-data:/var/tempo + - ./infra/tempo/tempo.yml:/etc/tempo/tempo.yml:ro + networks: [telemetry] + + loki: + image: grafana/loki:3.3.2 + restart: unless-stopped + mem_limit: 256m + cpus: "0.50" + command: ["-config.file=/etc/loki/loki.yml"] + volumes: + - loki-data:/loki + - ./infra/loki/loki.yml:/etc/loki/loki.yml:ro + networks: [telemetry] + + telemetry-proxy: + image: nginx:1.27.4-alpine + restart: unless-stopped + mem_limit: 128m + cpus: "0.25" + volumes: + - ./infra/nginx/telemetry.conf:/etc/nginx/conf.d/default.conf:ro + - ./secrets/certs/telemetry.crt:/certs/telemetry.crt:ro + - ./secrets/certs/telemetry.key:/certs/telemetry.key:ro + - ./secrets/certs/ca.crt:/certs/ca.crt:ro + networks: + telemetry: {} + lab: + aliases: + - tempo.lab.internal + - loki.lab.internal + depends_on: + - tempo + - loki + + otel-collector: + image: otel/opentelemetry-collector-contrib:0.115.0 + restart: unless-stopped + mem_limit: 384m + cpus: "0.50" + command: ["--config=/etc/otel/collector.yaml"] + env_file: + - ./secrets/otel.env + volumes: + - ./infra/otel/collector.yaml:/etc/otel/collector.yaml:ro + - ./secrets/certs/ca.crt:/certs/ca.crt:ro + - ./secrets/certs/otel.crt:/certs/otel.crt:ro + - ./secrets/certs/otel.key:/certs/otel.key:ro + networks: [lab] + depends_on: + - telemetry-proxy + + prometheus: + image: prom/prometheus:v2.55.1 + restart: unless-stopped + mem_limit: 384m + cpus: "0.50" + command: + - --config.file=/etc/prometheus/prometheus.yml + - --web.config.file=/etc/prometheus/web.yml + - --storage.tsdb.path=/prometheus + - --storage.tsdb.retention.time=7d + - --web.listen-address=:9090 + volumes: + - prometheus-data:/prometheus + - ./infra/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro + - ./infra/prometheus/alerts.yml:/etc/prometheus/alerts.yml:ro + - ./secrets/prometheus/web.yml:/etc/prometheus/web.yml:ro + - ./secrets/certs/ca.crt:/certs/ca.crt:ro + - ./secrets/certs/prometheus.crt:/certs/prometheus.crt:ro + - ./secrets/certs/prometheus.key:/certs/prometheus.key:ro + networks: [lab] + depends_on: + - otel-collector + + grafana: + image: grafana/grafana:11.4.0 + restart: unless-stopped + mem_limit: 384m + cpus: "0.50" + entrypoint: ["/bin/sh", "/opt/entry.sh"] + environment: + GF_SERVER_PROTOCOL: https + GF_SERVER_CERT_FILE: /certs/grafana.crt + GF_SERVER_CERT_KEY: /certs/grafana.key + GF_SERVER_HTTP_PORT: "3000" + ports: + - "127.0.0.1:3000:3000" + volumes: + - ./infra/grafana/entry.sh:/opt/entry.sh:ro + - ./secrets/passwords/grafana_admin:/run/secrets/grafana_admin_password:ro + - ./secrets/certs/grafana.crt:/certs/grafana.crt:ro + - ./secrets/certs/grafana.key:/certs/grafana.key:ro + - ./secrets/grafana/datasources.yml:/etc/grafana/provisioning/datasources/datasources.yml:ro + - ./infra/grafana/provisioning/dashboards:/etc/grafana/provisioning/dashboards:ro + - ./infra/grafana/provisioning/alerting:/etc/grafana/provisioning/alerting:ro + - ./infra/grafana/dashboards:/etc/grafana/dashboards:ro + networks: [lab] + depends_on: + - prometheus + - telemetry-proxy + + haproxy: + image: haproxy:2.8.14 + restart: unless-stopped + mem_limit: 256m + cpus: "0.50" + ports: + - "127.0.0.1:8443:8443" + volumes: + - ./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + - ./secrets/haproxy:/certs:ro + networks: [lab] + depends_on: + - api + + migrate: + build: . + image: lab7-messenger:1 + restart: "no" + user: "10001:10001" + mem_limit: 512m + cap_drop: ["ALL"] + security_opt: ["no-new-privileges:true"] + command: ["python", "-m", "app.migrate"] + environment: &migrate-env + APP_ROLE: migrate + RUN_MIGRATIONS: "1" + MTLS_ENABLED: "0" + OTEL_SDK_DISABLED: "1" + BAO_ADDR: https://openbao:8200 + BAO_CACERT: /run/app/ca.crt + BAO_ROLE_ID_FILE: /run/app/role_id + BAO_SECRET_ID_FILE: /run/app/secret_id + BAO_KV_PATH: secret/data/messenger/migrate + TLS_CA_FILE: /run/app/ca.crt + DB_CONNECT_TIMEOUT_SECONDS: "5" + volumes: + - ./secrets/runtime/migrate:/run/app:ro + networks: [lab] + depends_on: + postgres: + condition: service_healthy + openbao-init: + condition: service_completed_successfully + + api: + build: . + image: lab7-messenger:1 + restart: unless-stopped + init: true + mem_limit: 768m + cpus: "1.0" + cap_drop: ["ALL"] + security_opt: ["no-new-privileges:true"] + deploy: + replicas: 2 + environment: + APP_ROLE: api + APP_HOST: 0.0.0.0 + APP_PORT: "8443" + INTERNAL_PORT: "8080" + MTLS_ENABLED: "1" + MTLS_ALLOWED_DNS: lb.lab.internal + RUN_MIGRATIONS: "0" + BAO_ADDR: https://openbao:8200 + BAO_CACERT: /run/app/ca.crt + BAO_ROLE_ID_FILE: /run/app/role_id + BAO_SECRET_ID_FILE: /run/app/secret_id + BAO_KV_PATH: secret/data/messenger/api + TLS_CA_FILE: /run/app/ca.crt + TLS_CERT_FILE: /run/app/server.crt + TLS_KEY_FILE: /run/app/server.key + OTEL_SERVICE_NAME: messenger-api + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318 + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_EXPORTER_OTLP_CERTIFICATE: /run/app/ca.crt + S3_ENDPOINT: https://minio:9000 + S3_BUCKET: messenger-attachments + ARGON2_MEMORY_KIB: "19456" + ARGON2_ITERATIONS: "2" + ARGON2_PARALLELISM: "1" + LOGIN_RATE_LIMIT: "10" + LOGIN_RATE_WINDOW_SECONDS: "60" + MAX_JSON_BYTES: "65536" + SESSION_TTL_SECONDS: "3600" + DB_CONNECT_TIMEOUT_SECONDS: "5" + REDIS_SOCKET_TIMEOUT_SECONDS: "3" + volumes: + - ./secrets/runtime/api:/run/app:ro + networks: [lab] + depends_on: + migrate: + condition: service_completed_successfully + minio-init: + condition: service_completed_successfully + redis: + condition: service_healthy + healthcheck: + test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=3).read()"] + interval: 5s + timeout: 5s + retries: 24 + start_period: 40s + + worker: + build: . + image: lab7-messenger:1 + restart: unless-stopped + init: true + mem_limit: 768m + cpus: "1.0" + cap_drop: ["ALL"] + security_opt: ["no-new-privileges:true"] + command: ["python", "-m", "app.worker"] + environment: + APP_ROLE: worker + MTLS_ENABLED: "0" + RUN_MIGRATIONS: "0" + OTEL_SERVICE_NAME: messenger-worker + BAO_ADDR: https://openbao:8200 + BAO_CACERT: /run/app/ca.crt + BAO_ROLE_ID_FILE: /run/app/role_id + BAO_SECRET_ID_FILE: /run/app/secret_id + BAO_KV_PATH: secret/data/messenger/worker + TLS_CA_FILE: /run/app/ca.crt + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318 + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_EXPORTER_OTLP_CERTIFICATE: /run/app/ca.crt + S3_ENDPOINT: https://minio:9000 + S3_BUCKET: messenger-attachments + DB_CONNECT_TIMEOUT_SECONDS: "5" + volumes: + - ./secrets/runtime/worker:/run/app:ro + networks: [lab] + depends_on: + migrate: + condition: service_completed_successfully + minio-init: + condition: service_completed_successfully + rabbitmq: + condition: service_healthy + healthcheck: + test: ["CMD", "python", "-c", "import pathlib; assert pathlib.Path('/tmp/worker-heartbeat').read_text().strip()=='ok'"] + interval: 5s + timeout: 3s + retries: 20 + start_period: 40s + + relay: + build: . + image: lab7-messenger:1 + restart: unless-stopped + init: true + mem_limit: 384m + cpus: "0.50" + cap_drop: ["ALL"] + security_opt: ["no-new-privileges:true"] + command: ["python", "-m", "app.relay"] + environment: + APP_ROLE: relay + MTLS_ENABLED: "0" + RUN_MIGRATIONS: "0" + OTEL_SERVICE_NAME: messenger-relay + BAO_ADDR: https://openbao:8200 + BAO_CACERT: /run/app/ca.crt + BAO_ROLE_ID_FILE: /run/app/role_id + BAO_SECRET_ID_FILE: /run/app/secret_id + BAO_KV_PATH: secret/data/messenger/relay + TLS_CA_FILE: /run/app/ca.crt + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318 + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_EXPORTER_OTLP_CERTIFICATE: /run/app/ca.crt + DB_CONNECT_TIMEOUT_SECONDS: "5" + volumes: + - ./secrets/runtime/relay:/run/app:ro + networks: [lab] + depends_on: + migrate: + condition: service_completed_successfully + rabbitmq: + condition: service_healthy + + gc: + build: . + image: lab7-messenger:1 + restart: unless-stopped + mem_limit: 384m + cpus: "0.50" + cap_drop: ["ALL"] + security_opt: ["no-new-privileges:true"] + command: ["python", "-m", "app.gc"] + environment: + APP_ROLE: gc + MTLS_ENABLED: "0" + RUN_MIGRATIONS: "0" + OTEL_SERVICE_NAME: messenger-gc + BAO_ADDR: https://openbao:8200 + BAO_CACERT: /run/app/ca.crt + BAO_ROLE_ID_FILE: /run/app/role_id + BAO_SECRET_ID_FILE: /run/app/secret_id + BAO_KV_PATH: secret/data/messenger/gc + TLS_CA_FILE: /run/app/ca.crt + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318 + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_EXPORTER_OTLP_CERTIFICATE: /run/app/ca.crt + S3_ENDPOINT: https://minio:9000 + S3_BUCKET: messenger-attachments + DB_CONNECT_TIMEOUT_SECONDS: "5" + volumes: + - ./secrets/runtime/gc:/run/app:ro + networks: [lab] + depends_on: + migrate: + condition: service_completed_successfully + minio-init: + condition: service_completed_successfully diff --git a/infra/faults.json b/infra/faults.json new file mode 100644 index 0000000..1e00abc --- /dev/null +++ b/infra/faults.json @@ -0,0 +1 @@ +{"inject_transient": false, "crash_after_s3": false, "relay_exit_before_publish": false, "stall_seconds": 0, "timeout_seconds": 0} \ No newline at end of file diff --git a/infra/grafana/dashboards/messenger.json b/infra/grafana/dashboards/messenger.json new file mode 100644 index 0000000..b02172a --- /dev/null +++ b/infra/grafana/dashboards/messenger.json @@ -0,0 +1,212 @@ +{ + "annotations": {"list": []}, + "editable": true, + "fiscalYearStartMonth": 0, + "graphTooltip": 1, + "links": [], + "refresh": "10s", + "schemaVersion": 39, + "tags": ["messenger", "lab6"], + "time": {"from": "now-1h", "to": "now"}, + "timezone": "browser", + "title": "Messenger observability", + "uid": "messenger-lab6", + "version": 1, + "panels": [ + { + "type": "text", + "id": 1, + "title": "SLI и единицы", + "gridPos": {"h": 5, "w": 24, "x": 0, "y": 0}, + "options": { + "mode": "markdown", + "content": "**API availability.** SLI = бизнес-ответы 5xx / все бизнес-запросы, без `/health`. SLO = 99% успеха на окне 5 минут. Алерт смотрит окно 1 минута и порог 5%.\n\n**Time to ready.** SLI = гистограмма секунд от записи вложения до `ready`. SLO = p95 не выше 60 с. Алерт смотрит возраст старейшей queued/processing задачи и порог 30 с. Это backlog, не среднее время обработки.\n\nПроцентили считаются `histogram_quantile` по сумме bucket всех реплик (`sum by (le)`), а не как среднее готовых p95. Единицы: RPS — запросы/с, длительность и возраст — секунды, пул и worker — штуки, память — байты, CPU — ядра." + } + }, + { + "type": "timeseries", + "id": 2, + "title": "API RPS", + "description": "Запросы в секунду, только sli=business. Единица req/s.", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "gridPos": {"h": 8, "w": 8, "x": 0, "y": 5}, + "fieldConfig": {"defaults": {"unit": "reqps", "custom": {"drawStyle": "line", "fillOpacity": 15}}, "overrides": []}, + "options": {"legend": {"displayMode": "list", "placement": "bottom"}}, + "targets": [ + { + "refId": "A", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "expr": "sum by (status_class) (rate(http_server_requests_total{service_name=\"messenger-api\",sli=\"business\"}[1m]))", + "legendFormat": "{{status_class}}" + } + ] + }, + { + "type": "timeseries", + "id": 3, + "title": "Ошибки API", + "description": "Сколько бизнес-ответов 4xx и 5xx накоплено. 4xx — ошибка запроса, 5xx — сбой сервера. Алерт и SLO по-прежнему только про 5xx.", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "gridPos": {"h": 8, "w": 8, "x": 8, "y": 5}, + "fieldConfig": {"defaults": {"unit": "short", "min": 0, "custom": {"drawStyle": "line", "fillOpacity": 10}}, "overrides": []}, + "options": {"legend": {"displayMode": "list", "placement": "bottom"}}, + "targets": [ + { + "refId": "A", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "expr": "sum by (status_class) (http_server_requests_total{service_name=\"messenger-api\",sli=\"business\",status_class=~\"4xx|5xx\"}) or label_replace(vector(0), \"status_class\", \"4xx\", \"\", \"\") or label_replace(vector(0), \"status_class\", \"5xx\", \"\", \"\")", + "legendFormat": "{{status_class}}" + } + ] + }, + { + "type": "timeseries", + "id": 4, + "title": "API duration", + "description": "Секунды. histogram_quantile от суммы bucket всех реплик API.", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "gridPos": {"h": 8, "w": 8, "x": 16, "y": 5}, + "fieldConfig": {"defaults": {"unit": "s", "custom": {"drawStyle": "line", "fillOpacity": 10}}, "overrides": []}, + "options": {"legend": {"displayMode": "list", "placement": "bottom"}}, + "targets": [ + {"refId": "A", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "histogram_quantile(0.50, sum by (le) (rate(http_server_duration_seconds_bucket{service_name=\"messenger-api\",sli=\"business\"}[5m])))", "legendFormat": "p50"}, + {"refId": "B", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_duration_seconds_bucket{service_name=\"messenger-api\",sli=\"business\"}[5m])))", "legendFormat": "p95"}, + {"refId": "C", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_duration_seconds_bucket{service_name=\"messenger-api\",sli=\"business\"}[5m])))", "legendFormat": "p99"} + ] + }, + { + "type": "timeseries", + "id": 5, + "title": "Jobs", + "description": "Задачи в секунду по outcome. Единица jobs/s.", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "gridPos": {"h": 8, "w": 8, "x": 0, "y": 13}, + "fieldConfig": {"defaults": {"unit": "ops", "custom": {"drawStyle": "line", "fillOpacity": 15}}, "overrides": []}, + "options": {"legend": {"displayMode": "list", "placement": "bottom"}}, + "targets": [ + {"refId": "A", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "sum by (outcome) (rate(jobs_processed_total{job_type=\"attachment.process.v1\",outcome=~\"ready|failed|retry\"}[5m]))", "legendFormat": "{{outcome}}"} + ] + }, + { + "type": "timeseries", + "id": 6, + "title": "Job duration", + "description": "Секунды обработки. p95 из гистограммы, отдельно для ready и failed.", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "gridPos": {"h": 8, "w": 8, "x": 8, "y": 13}, + "fieldConfig": {"defaults": {"unit": "s", "custom": {"drawStyle": "line", "fillOpacity": 10}}, "overrides": []}, + "options": {"legend": {"displayMode": "list", "placement": "bottom"}}, + "targets": [ + {"refId": "A", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "histogram_quantile(0.50, sum by (le) (rate(jobs_duration_seconds_bucket{outcome=~\"ready|failed|retry\"}[5m])))", "legendFormat": "p50"}, + {"refId": "B", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "histogram_quantile(0.95, sum by (le) (rate(jobs_duration_seconds_bucket{outcome=~\"ready|failed|retry\"}[5m])))", "legendFormat": "p95"}, + {"refId": "C", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "histogram_quantile(0.99, sum by (le) (rate(jobs_duration_seconds_bucket{outcome=~\"ready|failed|retry\"}[5m])))", "legendFormat": "p99"} + ] + }, + { + "type": "timeseries", + "id": 7, + "title": "Time to ready", + "description": "Секунды от принятия вложения до ready. p95 — SLO 60 с.", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "gridPos": {"h": 8, "w": 8, "x": 16, "y": 13}, + "fieldConfig": {"defaults": {"unit": "s", "custom": {"drawStyle": "line", "fillOpacity": 10}}, "overrides": []}, + "options": {"legend": {"displayMode": "list", "placement": "bottom"}}, + "targets": [ + {"refId": "A", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "histogram_quantile(0.50, sum by (le) (rate(attachment_time_to_ready_seconds_bucket[5m])))", "legendFormat": "p50"}, + {"refId": "B", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "histogram_quantile(0.95, sum by (le) (rate(attachment_time_to_ready_seconds_bucket[5m])))", "legendFormat": "p95"}, + {"refId": "C", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "histogram_quantile(0.99, sum by (le) (rate(attachment_time_to_ready_seconds_bucket[5m])))", "legendFormat": "p99"} + ] + }, + { + "type": "timeseries", + "id": 8, + "title": "Queue depth", + "description": "Число задач queued или processing. max, чтобы две реплики API не удваивали одно наблюдение.", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "gridPos": {"h": 8, "w": 8, "x": 0, "y": 21}, + "fieldConfig": {"defaults": {"unit": "short", "custom": {"drawStyle": "line", "fillOpacity": 15}}, "overrides": []}, + "options": {"legend": {"displayMode": "list", "placement": "bottom"}}, + "targets": [ + {"refId": "A", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "max(queue_depth_ratio{queue=\"attachment.jobs\"})", "legendFormat": "attachment.jobs"} + ] + }, + { + "type": "timeseries", + "id": 9, + "title": "Oldest job age", + "description": "Секунды. Порог алерта 30 с отмечен как backlog, не как latency worker.", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "gridPos": {"h": 8, "w": 8, "x": 8, "y": 21}, + "fieldConfig": {"defaults": {"unit": "s", "custom": {"drawStyle": "line", "fillOpacity": 10}}, "overrides": []}, + "options": {"legend": {"displayMode": "list", "placement": "bottom"}}, + "targets": [ + {"refId": "A", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "max(queue_oldest_age_seconds{queue=\"attachment.jobs\"})", "legendFormat": "oldest"} + ] + }, + { + "type": "timeseries", + "id": 10, + "title": "DB pool", + "description": "Соединения: used — занятые, waiting — ждущие checkout, capacity — размер пула с overflow. Сумма по репликам API.", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "gridPos": {"h": 8, "w": 8, "x": 16, "y": 21}, + "fieldConfig": {"defaults": {"unit": "short", "custom": {"drawStyle": "line", "fillOpacity": 10}}, "overrides": []}, + "options": {"legend": {"displayMode": "list", "placement": "bottom"}}, + "targets": [ + {"refId": "A", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "sum by (state) (db_pool_connections_ratio{service_name=\"messenger-api\"})", "legendFormat": "{{state}}"} + ] + }, + { + "type": "timeseries", + "id": 11, + "title": "Worker saturation", + "description": "busy — занятые слоты, capacity — WORKER_CONCURRENCY.", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "gridPos": {"h": 8, "w": 8, "x": 0, "y": 29}, + "fieldConfig": {"defaults": {"unit": "short", "custom": {"drawStyle": "line", "fillOpacity": 10}}, "overrides": []}, + "options": {"legend": {"displayMode": "list", "placement": "bottom"}}, + "targets": [ + {"refId": "A", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "max by (state) (worker_slots_ratio{service_name=\"messenger-worker\"})", "legendFormat": "{{state}}"} + ] + }, + { + "type": "timeseries", + "id": 12, + "title": "Process CPU", + "description": "Секунды CPU на секунду стены, сумма процессов сервиса. Единица — ядра.", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "gridPos": {"h": 8, "w": 8, "x": 8, "y": 29}, + "fieldConfig": {"defaults": {"unit": "short", "custom": {"drawStyle": "line", "fillOpacity": 10}}, "overrides": []}, + "options": {"legend": {"displayMode": "list", "placement": "bottom"}}, + "targets": [ + {"refId": "A", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "sum by (service_name) (process_cpu_utilization_ratio)", "legendFormat": "{{service_name}}"} + ] + }, + { + "type": "timeseries", + "id": 13, + "title": "Process memory", + "description": "RSS процессов, байты.", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "gridPos": {"h": 8, "w": 8, "x": 16, "y": 29}, + "fieldConfig": {"defaults": {"unit": "bytes", "custom": {"drawStyle": "line", "fillOpacity": 10}}, "overrides": []}, + "options": {"legend": {"displayMode": "list", "placement": "bottom"}}, + "targets": [ + {"refId": "A", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "sum by (service_name) (process_memory_usage_bytes)", "legendFormat": "{{service_name}}"} + ] + }, + { + "type": "timeseries", + "id": 14, + "title": "Prometheus alert state", + "description": "1 — firing. Пропавший ряд — resolved/inactive. Имена HighApiErrorRate и QueueLagHigh.", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "gridPos": {"h": 8, "w": 24, "x": 0, "y": 37}, + "fieldConfig": {"defaults": {"unit": "short", "min": 0, "max": 1, "custom": {"drawStyle": "line", "fillOpacity": 10}}, "overrides": []}, + "options": {"legend": {"displayMode": "list", "placement": "bottom"}}, + "targets": [ + {"refId": "A", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "ALERTS{alertname=~\"HighApiErrorRate|QueueLagHigh\"}", "legendFormat": "{{alertname}} {{alertstate}}"} + ] + } + ] +} diff --git a/infra/grafana/entry.sh b/infra/grafana/entry.sh new file mode 100644 index 0000000..7957dcf --- /dev/null +++ b/infra/grafana/entry.sh @@ -0,0 +1,9 @@ +#!/bin/sh +set -eu +export GF_SECURITY_ADMIN_USER=admin +export GF_SECURITY_ADMIN_PASSWORD="$(cat /run/secrets/grafana_admin_password)" +export GF_AUTH_ANONYMOUS_ENABLED=false +export GF_USERS_ALLOW_SIGN_UP=false +export GF_ANALYTICS_REPORTING_ENABLED=false +export GF_ANALYTICS_CHECK_FOR_UPDATES=false +exec /run.sh diff --git a/infra/grafana/provisioning/alerting/contact_points.yml b/infra/grafana/provisioning/alerting/contact_points.yml new file mode 100644 index 0000000..1cd3147 --- /dev/null +++ b/infra/grafana/provisioning/alerting/contact_points.yml @@ -0,0 +1,12 @@ +apiVersion: 1 + +contactPoints: + - orgId: 1 + name: messenger-local + receivers: + - uid: messenger-local-none + type: webhook + settings: + url: http://127.0.0.1:9/unused + httpMethod: POST + disableResolveMessage: false diff --git a/infra/grafana/provisioning/alerting/policies.yml b/infra/grafana/provisioning/alerting/policies.yml new file mode 100644 index 0000000..1308c83 --- /dev/null +++ b/infra/grafana/provisioning/alerting/policies.yml @@ -0,0 +1,8 @@ +apiVersion: 1 + +policies: + - orgId: 1 + receiver: messenger-local + group_by: + - grafana_folder + - alertname diff --git a/infra/grafana/provisioning/alerting/rules.yml b/infra/grafana/provisioning/alerting/rules.yml new file mode 100644 index 0000000..66c5bfa --- /dev/null +++ b/infra/grafana/provisioning/alerting/rules.yml @@ -0,0 +1,120 @@ +apiVersion: 1 + +groups: + - orgId: 1 + name: messenger-slo + folder: Messenger + interval: 30s + rules: + - uid: high-api-error-rate + title: High API error rate + condition: B + data: + - refId: A + relativeTimeRange: + from: 300 + to: 0 + datasourceUid: prometheus + model: + datasource: + type: prometheus + uid: prometheus + editorMode: code + expr: sum(rate(http_server_requests_total{service_name="messenger-api",sli="business",status_class="5xx"}[1m])) / clamp_min(sum(rate(http_server_requests_total{service_name="messenger-api",sli="business"}[1m])), 1e-9) + instant: true + intervalMs: 1000 + maxDataPoints: 43200 + refId: A + - refId: B + relativeTimeRange: + from: 0 + to: 0 + datasourceUid: __expr__ + model: + conditions: + - evaluator: + params: + - 0.05 + type: gt + operator: + type: and + query: + params: + - B + reducer: + params: [] + type: last + type: query + datasource: + type: __expr__ + uid: __expr__ + expression: A + intervalMs: 1000 + maxDataPoints: 43200 + refId: B + type: threshold + noDataState: OK + execErrState: Error + for: 1m + annotations: + summary: Доля бизнес 5xx выше 5% на окне 1 минута. + description: SLI исключает /health. SLO — 99% успеха на окне 5 минут. Runbook — infra/grafana/runbooks/high-error-rate.md. + labels: + severity: warning + isPaused: false + - uid: queue-lag-high + title: Queue lag high + condition: B + data: + - refId: A + relativeTimeRange: + from: 300 + to: 0 + datasourceUid: prometheus + model: + datasource: + type: prometheus + uid: prometheus + editorMode: code + expr: max(queue_oldest_age_seconds{queue="attachment.jobs"}) + instant: true + intervalMs: 1000 + maxDataPoints: 43200 + refId: A + - refId: B + relativeTimeRange: + from: 0 + to: 0 + datasourceUid: __expr__ + model: + conditions: + - evaluator: + params: + - 30 + type: gt + operator: + type: and + query: + params: + - B + reducer: + params: [] + type: last + type: query + datasource: + type: __expr__ + uid: __expr__ + expression: A + intervalMs: 1000 + maxDataPoints: 43200 + refId: B + type: threshold + noDataState: OK + execErrState: Error + for: 1m + annotations: + summary: Возраст старейшей задачи больше 30 секунд. + description: Backlog, не latency обработки. SLO p95 time-to-ready — 60 секунд. Runbook — infra/grafana/runbooks/queue-lag.md. + labels: + severity: warning + isPaused: false diff --git a/infra/grafana/provisioning/dashboards/dashboards.yml b/infra/grafana/provisioning/dashboards/dashboards.yml new file mode 100644 index 0000000..3e39120 --- /dev/null +++ b/infra/grafana/provisioning/dashboards/dashboards.yml @@ -0,0 +1,11 @@ +apiVersion: 1 + +providers: + - name: Messenger + orgId: 1 + folder: Messenger + type: file + disableDeletion: false + updateIntervalSeconds: 30 + options: + path: /etc/grafana/dashboards diff --git a/infra/grafana/provisioning/datasources/datasources.yml b/infra/grafana/provisioning/datasources/datasources.yml new file mode 100644 index 0000000..b04d93c --- /dev/null +++ b/infra/grafana/provisioning/datasources/datasources.yml @@ -0,0 +1,45 @@ +apiVersion: 1 + +datasources: + - name: Prometheus + uid: prometheus + type: prometheus + access: proxy + url: http://prometheus:9090 + isDefault: true + editable: false + jsonData: + timeInterval: 10s + - name: Loki + uid: loki + type: loki + access: proxy + url: http://loki:3100 + editable: false + jsonData: + derivedFields: + - name: trace_id + matcherRegex: "\"trace_id\":\"([0-9a-f]+)\"" + url: "$${__value.raw}" + datasourceUid: tempo + urlDisplayLabel: Открыть трассу + - name: Tempo + uid: tempo + type: tempo + access: proxy + url: http://tempo:3200 + editable: false + jsonData: + tracesToLogsV2: + datasourceUid: loki + filterByTraceID: false + customQuery: true + query: '{service_name=~"messenger-.+"} | trace_id="$${__trace.traceId}"' + tracesToMetrics: + datasourceUid: prometheus + serviceMap: + datasourceUid: prometheus + nodeGraph: + enabled: true + lokiSearch: + datasourceUid: loki diff --git a/infra/grafana/runbooks/high-error-rate.md b/infra/grafana/runbooks/high-error-rate.md new file mode 100644 index 0000000..6888bab --- /dev/null +++ b/infra/grafana/runbooks/high-error-rate.md @@ -0,0 +1,13 @@ +# High API error rate + +SLI: доля ответов 5xx среди бизнес-запросов (`sli="business"`). Проверки `/health/*` в числитель и знаменатель не входят: отказ клиента с неверным паролем — это 401, а не отказ базы. + +SLO: не меньше 99% успешных бизнес-запросов на скользящем окне 5 минут. + +Алерт: та же доля на окне 1 минута выше 5% в течение 1 минуты. Окно короче SLO, чтобы короткий отказ успел зажечься и погаснуть на защите. + +1. На дашборде Messenger сравнить панель доли ошибок и p95 длительности. +2. Открыть трассу запроса со статусом 5xx. Если время в `db.finalize` или запрос оборвался таймаутом пула, это база. Если span handler длинный без дочернего db/s3, это код обработчика. +3. Сверить `db.pool.connections` со `state=used` и `state=waiting`. Рост waiting при полном used — насыщение пула, а не медленный Python. +4. Вернуть Postgres (`docker compose unpause postgres` или `start`). +5. Убедиться, что алерт перешёл из firing в inactive. Доставка уведомлений наружу не используется. diff --git a/infra/grafana/runbooks/queue-lag.md b/infra/grafana/runbooks/queue-lag.md new file mode 100644 index 0000000..c1546d5 --- /dev/null +++ b/infra/grafana/runbooks/queue-lag.md @@ -0,0 +1,12 @@ +# Queue lag + +Backlog — число задач `attachment.jobs` в статусе queued или processing и возраст старейшей из них. Это не latency успешной обработки: её показывает гистограмма `attachment.time_to_ready`. + +SLO: p95 времени от принятой загрузки до `ready` не выше 60 секунд. + +Алерт: возраст старейшей задачи больше 30 секунд в течение 1 минуты. + +1. Сравнить queue depth / oldest age с `worker.slots`. Если capacity пропала, контейнер worker остановлен. +2. По trace id загрузки найти server span API, producer span relay (`publish attachment.jobs`) и consumer span worker. Разрыв после producer при живом API означает, что consumer не забирает сообщения. +3. В логах Loki по тому же trace id проверить `outbox published` и отсутствие `job ready`. +4. Запустить worker. Глубина и возраст должны уменьшиться, алерт стать inactive. diff --git a/infra/haproxy.cfg b/infra/haproxy.cfg new file mode 100644 index 0000000..63eef5a --- /dev/null +++ b/infra/haproxy.cfg @@ -0,0 +1,41 @@ +global + log stdout format raw local0 + maxconn 256 + ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets + +defaults + log global + mode http + option httplog + option dontlognull + option redispatch + timeout connect 3s + timeout client 120s + timeout server 120s + timeout http-request 30s + retries 2 + +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + hold other 5s + hold refused 5s + hold nx 5s + hold timeout 5s + hold obsolete 5s + +frontend public + bind :8443 ssl crt /certs/lb-server.pem alpn http/1.1 + http-request set-header X-Forwarded-Proto https + default_backend api + +backend api + balance roundrobin + option httpchk + http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host api + http-check expect status 200 + default-server inter 2s fall 2 rise 2 resolvers docker init-addr last,libc,none resolve-prefer ipv4 ssl verify required ca-file /certs/ca.crt crt /certs/lb-client.pem verifyhost api alpn http/1.1 + server-template api 8 api:8443 check diff --git a/infra/loki/loki.yml b/infra/loki/loki.yml new file mode 100644 index 0000000..b518bea --- /dev/null +++ b/infra/loki/loki.yml @@ -0,0 +1,37 @@ +auth_enabled: false + +server: + http_listen_port: 3100 + log_level: warn + +common: + path_prefix: /loki + storage: + filesystem: + chunks_directory: /loki/chunks + rules_directory: /loki/rules + replication_factor: 1 + ring: + instance_addr: 127.0.0.1 + kvstore: + store: inmemory + +schema_config: + configs: + - from: 2024-01-01 + store: tsdb + object_store: filesystem + schema: v13 + index: + prefix: index_ + period: 24h + +limits_config: + allow_structured_metadata: true + volume_enabled: true + retention_period: 168h + reject_old_samples: true + reject_old_samples_max_age: 168h + ingestion_rate_mb: 8 + ingestion_burst_size_mb: 16 + max_streams_per_user: 10000 diff --git a/infra/minio-bootstrap.sh b/infra/minio-bootstrap.sh new file mode 100644 index 0000000..4e03f87 --- /dev/null +++ b/infra/minio-bootstrap.sh @@ -0,0 +1,38 @@ +#!/bin/sh +set -eu +ROOT_USER=$(cat /secrets/passwords/minio_root_user) +ROOT_PASS=$(cat /secrets/passwords/minio_root_password) +API_KEY=$(cat /secrets/passwords/s3_api_key) +API_SECRET=$(cat /secrets/passwords/s3_api_secret) +WORKER_KEY=$(cat /secrets/passwords/s3_worker_key) +WORKER_SECRET=$(cat /secrets/passwords/s3_worker_secret) +GC_KEY=$(cat /secrets/passwords/s3_gc_key) +GC_SECRET=$(cat /secrets/passwords/s3_gc_secret) +export SSL_CERT_FILE=/certs/ca.crt + +i=0 +while [ "$i" -lt 40 ]; do + if mc alias set local https://minio:9000 "$ROOT_USER" "$ROOT_PASS" >/dev/null 2>&1; then + break + fi + i=$((i + 1)) + sleep 1 +done +mc alias set local https://minio:9000 "$ROOT_USER" "$ROOT_PASS" +mc mb --ignore-existing local/messenger-attachments +mc anonymous set none local/messenger-attachments + +add_user() { + key=$1 + secret=$2 + policy=$3 + file=$4 + mc admin user add local "$key" "$secret" >/dev/null 2>&1 || mc admin user add local "$key" "$secret" + mc admin policy create local "$policy" "$file" >/dev/null 2>&1 || true + mc admin policy attach local "$policy" --user "$key" >/dev/null 2>&1 || mc admin policy set local "$policy" user="$key" +} + +add_user "$API_KEY" "$API_SECRET" api-objects /policies/api-policy.json +add_user "$WORKER_KEY" "$WORKER_SECRET" worker-objects /policies/worker-policy.json +add_user "$GC_KEY" "$GC_SECRET" gc-objects /policies/gc-policy.json +echo "minio bootstrap complete" diff --git a/infra/minio-entry.sh b/infra/minio-entry.sh new file mode 100644 index 0000000..bbfc649 --- /dev/null +++ b/infra/minio-entry.sh @@ -0,0 +1,5 @@ +#!/bin/sh +set -eu +export MINIO_ROOT_USER="$(cat /run/secrets/minio_root_user)" +export MINIO_ROOT_PASSWORD="$(cat /run/secrets/minio_root_password)" +exec /usr/bin/docker-entrypoint.sh server /data --address :9000 --console-address :9001 diff --git a/infra/minio-policy.json b/infra/minio-policy.json new file mode 100644 index 0000000..2d45154 --- /dev/null +++ b/infra/minio-policy.json @@ -0,0 +1,21 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "ApiObjectAccess", + "Effect": "Allow", + "Action": [ + "s3:GetObject", + "s3:PutObject", + "s3:DeleteObject", + "s3:AbortMultipartUpload", + "s3:ListBucket", + "s3:GetBucketLocation" + ], + "Resource": [ + "arn:aws:s3:::messenger-attachments", + "arn:aws:s3:::messenger-attachments/*" + ] + } + ] +} diff --git a/infra/minio/api-policy.json b/infra/minio/api-policy.json new file mode 100644 index 0000000..506c1fc --- /dev/null +++ b/infra/minio/api-policy.json @@ -0,0 +1,20 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": ["s3:GetBucketLocation", "s3:ListBucket", "s3:HeadBucket"], + "Resource": ["arn:aws:s3:::messenger-attachments"] + }, + { + "Effect": "Allow", + "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"], + "Resource": ["arn:aws:s3:::messenger-attachments/staging/*"] + }, + { + "Effect": "Allow", + "Action": ["s3:GetObject"], + "Resource": ["arn:aws:s3:::messenger-attachments/att/*"] + } + ] +} diff --git a/infra/minio/gc-policy.json b/infra/minio/gc-policy.json new file mode 100644 index 0000000..1603dbb --- /dev/null +++ b/infra/minio/gc-policy.json @@ -0,0 +1,18 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": ["s3:GetBucketLocation", "s3:ListBucket", "s3:HeadBucket"], + "Resource": ["arn:aws:s3:::messenger-attachments"] + }, + { + "Effect": "Allow", + "Action": ["s3:GetObject", "s3:DeleteObject"], + "Resource": [ + "arn:aws:s3:::messenger-attachments/staging/*", + "arn:aws:s3:::messenger-attachments/att/*" + ] + } + ] +} diff --git a/infra/minio/worker-policy.json b/infra/minio/worker-policy.json new file mode 100644 index 0000000..a15c191 --- /dev/null +++ b/infra/minio/worker-policy.json @@ -0,0 +1,20 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": ["s3:GetBucketLocation", "s3:ListBucket", "s3:HeadBucket"], + "Resource": ["arn:aws:s3:::messenger-attachments"] + }, + { + "Effect": "Allow", + "Action": ["s3:GetObject", "s3:DeleteObject"], + "Resource": ["arn:aws:s3:::messenger-attachments/staging/*"] + }, + { + "Effect": "Allow", + "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"], + "Resource": ["arn:aws:s3:::messenger-attachments/att/*"] + } + ] +} diff --git a/infra/nginx/minio.conf b/infra/nginx/minio.conf new file mode 100644 index 0000000..554c7c8 --- /dev/null +++ b/infra/nginx/minio.conf @@ -0,0 +1,20 @@ +server { + listen 9000 ssl; + server_name minio; + server_tokens off; + ssl_certificate /certs/minio.crt; + ssl_certificate_key /certs/minio.key; + ssl_protocols TLSv1.2 TLSv1.3; + client_max_body_size 20m; + access_log off; + + location / { + proxy_pass http://127.0.0.1:9000; + proxy_http_version 1.1; + proxy_set_header Host $http_host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header Connection ""; + proxy_buffering off; + proxy_request_buffering off; + } +} diff --git a/infra/nginx/telemetry.conf b/infra/nginx/telemetry.conf new file mode 100644 index 0000000..4a6d75d --- /dev/null +++ b/infra/nginx/telemetry.conf @@ -0,0 +1,72 @@ +resolver 127.0.0.11 valid=10s ipv6=off; + +map $ssl_client_s_dn $telemetry_client_ok { + default 0; + "~CN=otel-collector(,|$)" 1; + "~CN=grafana(,|$)" 1; +} + +server { + listen 4318 ssl; + server_name tempo.lab.internal; + server_tokens off; + ssl_certificate /certs/telemetry.crt; + ssl_certificate_key /certs/telemetry.key; + ssl_client_certificate /certs/ca.crt; + ssl_verify_client on; + ssl_protocols TLSv1.2 TLSv1.3; + client_max_body_size 20m; + access_log off; + if ($telemetry_client_ok = 0) { return 403; } + location / { + set $upstream tempo:4318; + proxy_pass http://$upstream; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header Content-Type $content_type; + proxy_set_header Connection ""; + } +} + +server { + listen 3200 ssl; + server_name tempo.lab.internal; + server_tokens off; + ssl_certificate /certs/telemetry.crt; + ssl_certificate_key /certs/telemetry.key; + ssl_client_certificate /certs/ca.crt; + ssl_verify_client on; + ssl_protocols TLSv1.2 TLSv1.3; + client_max_body_size 20m; + access_log off; + if ($telemetry_client_ok = 0) { return 403; } + location / { + set $upstream tempo:3200; + proxy_pass http://$upstream; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header Connection ""; + } +} + +server { + listen 3100 ssl; + server_name loki.lab.internal; + server_tokens off; + ssl_certificate /certs/telemetry.crt; + ssl_certificate_key /certs/telemetry.key; + ssl_client_certificate /certs/ca.crt; + ssl_verify_client on; + ssl_protocols TLSv1.2 TLSv1.3; + client_max_body_size 20m; + access_log off; + if ($telemetry_client_ok = 0) { return 403; } + location / { + set $upstream loki:3100; + proxy_pass http://$upstream; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header Content-Type $content_type; + proxy_set_header Connection ""; + } +} diff --git a/infra/openbao/config.hcl b/infra/openbao/config.hcl new file mode 100644 index 0000000..a9cfce7 --- /dev/null +++ b/infra/openbao/config.hcl @@ -0,0 +1,17 @@ +ui = false +disable_mlock = true + +storage "file" { + path = "/openbao/data" +} + +listener "tcp" { + address = "0.0.0.0:8200" + cluster_address = "0.0.0.0:8201" + tls_cert_file = "/tmp/tls/server.crt" + tls_key_file = "/tmp/tls/server.key" + tls_min_version = "tls12" +} + +api_addr = "https://openbao:8200" +cluster_addr = "https://openbao:8201" diff --git a/infra/openbao/entry.sh b/infra/openbao/entry.sh new file mode 100644 index 0000000..0e2ecf5 --- /dev/null +++ b/infra/openbao/entry.sh @@ -0,0 +1,17 @@ +#!/bin/sh +set -eu +mkdir -p /tmp/tls /openbao/data +cp /certs/openbao.crt /tmp/tls/server.crt +cp /certs/openbao.key /tmp/tls/server.key +chmod 644 /tmp/tls/server.crt +chmod 600 /tmp/tls/server.key +if id openbao >/dev/null 2>&1; then + chown -R openbao:openbao /tmp/tls /openbao/data + if command -v su-exec >/dev/null 2>&1; then + exec su-exec openbao bao server -config=/openbao/config/config.hcl + fi + if command -v gosu >/dev/null 2>&1; then + exec gosu openbao bao server -config=/openbao/config/config.hcl + fi +fi +exec bao server -config=/openbao/config/config.hcl diff --git a/infra/openbao/policies/messenger-api.hcl b/infra/openbao/policies/messenger-api.hcl new file mode 100644 index 0000000..190c529 --- /dev/null +++ b/infra/openbao/policies/messenger-api.hcl @@ -0,0 +1,3 @@ +path "secret/data/messenger/api" { + capabilities = ["read"] +} diff --git a/infra/openbao/policies/messenger-gc.hcl b/infra/openbao/policies/messenger-gc.hcl new file mode 100644 index 0000000..f826366 --- /dev/null +++ b/infra/openbao/policies/messenger-gc.hcl @@ -0,0 +1,3 @@ +path "secret/data/messenger/gc" { + capabilities = ["read"] +} diff --git a/infra/openbao/policies/messenger-migrate.hcl b/infra/openbao/policies/messenger-migrate.hcl new file mode 100644 index 0000000..0d8a415 --- /dev/null +++ b/infra/openbao/policies/messenger-migrate.hcl @@ -0,0 +1,3 @@ +path "secret/data/messenger/migrate" { + capabilities = ["read"] +} diff --git a/infra/openbao/policies/messenger-relay.hcl b/infra/openbao/policies/messenger-relay.hcl new file mode 100644 index 0000000..923b16a --- /dev/null +++ b/infra/openbao/policies/messenger-relay.hcl @@ -0,0 +1,3 @@ +path "secret/data/messenger/relay" { + capabilities = ["read"] +} diff --git a/infra/openbao/policies/messenger-worker.hcl b/infra/openbao/policies/messenger-worker.hcl new file mode 100644 index 0000000..6c67e26 --- /dev/null +++ b/infra/openbao/policies/messenger-worker.hcl @@ -0,0 +1,3 @@ +path "secret/data/messenger/worker" { + capabilities = ["read"] +} diff --git a/infra/otel/collector.yaml b/infra/otel/collector.yaml new file mode 100644 index 0000000..eedf662 --- /dev/null +++ b/infra/otel/collector.yaml @@ -0,0 +1,97 @@ +receivers: + otlp: + protocols: + grpc: + endpoint: 127.0.0.1:4317 + http: + endpoint: 0.0.0.0:4318 + tls: + cert_file: /certs/otel.crt + key_file: /certs/otel.key + auth: + authenticator: bearertokenauth + +processors: + memory_limiter: + check_interval: 1s + limit_mib: 256 + spike_limit_mib: 64 + batch: + timeout: 5s + send_batch_size: 512 + send_batch_max_size: 1024 + +exporters: + otlphttp/tempo: + endpoint: https://tempo.lab.internal:4318 + timeout: 5s + tls: + ca_file: /certs/ca.crt + cert_file: /certs/otel.crt + key_file: /certs/otel.key + retry_on_failure: + enabled: true + initial_interval: 1s + max_interval: 10s + max_elapsed_time: 30s + sending_queue: + enabled: true + num_consumers: 2 + queue_size: 200 + otlphttp/loki: + endpoint: https://loki.lab.internal:3100/otlp + timeout: 5s + tls: + ca_file: /certs/ca.crt + cert_file: /certs/otel.crt + key_file: /certs/otel.key + retry_on_failure: + enabled: true + initial_interval: 1s + max_interval: 10s + max_elapsed_time: 30s + sending_queue: + enabled: true + num_consumers: 2 + queue_size: 200 + prometheus: + endpoint: 0.0.0.0:8889 + tls: + cert_file: /certs/otel.crt + key_file: /certs/otel.key + resource_to_telemetry_conversion: + enabled: true + metric_expiration: 5m + +extensions: + health_check: + endpoint: 127.0.0.1:13133 + bearertokenauth: + scheme: Bearer + token: ${env:OTEL_INGEST_TOKEN} + +service: + extensions: [health_check, bearertokenauth] + telemetry: + logs: + level: info + metrics: + readers: + - pull: + exporter: + prometheus: + host: 127.0.0.1 + port: 8888 + pipelines: + traces: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlphttp/tempo] + metrics: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [prometheus] + logs: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlphttp/loki] diff --git a/infra/postgres/entry.sh b/infra/postgres/entry.sh new file mode 100644 index 0000000..de501af --- /dev/null +++ b/infra/postgres/entry.sh @@ -0,0 +1,13 @@ +#!/bin/sh +set -eu +mkdir -p /var/lib/postgresql/tls +cp /certs/postgres.crt /var/lib/postgresql/tls/server.crt +cp /certs/postgres.key /var/lib/postgresql/tls/server.key +chown postgres:postgres /var/lib/postgresql/tls/server.crt /var/lib/postgresql/tls/server.key +chmod 644 /var/lib/postgresql/tls/server.crt +chmod 600 /var/lib/postgresql/tls/server.key +exec docker-entrypoint.sh postgres \ + -c ssl=on \ + -c ssl_cert_file=/var/lib/postgresql/tls/server.crt \ + -c ssl_key_file=/var/lib/postgresql/tls/server.key \ + -c hba_file=/etc/pg/pg_hba.conf diff --git a/infra/postgres/init-roles.sh b/infra/postgres/init-roles.sh new file mode 100644 index 0000000..30281c1 --- /dev/null +++ b/infra/postgres/init-roles.sh @@ -0,0 +1,14 @@ +#!/bin/sh +set -eu +psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" \ + -v api_pass="$(cat /run/secrets/db_api_password)" \ + -v worker_pass="$(cat /run/secrets/db_worker_password)" \ + -v relay_pass="$(cat /run/secrets/db_relay_password)" \ + -v gc_pass="$(cat /run/secrets/db_gc_password)" <<'SQL' +SELECT format('CREATE ROLE api_user LOGIN PASSWORD %L NOSUPERUSER NOCREATEDB NOCREATEROLE', :'api_pass') \gexec +SELECT format('CREATE ROLE worker_user LOGIN PASSWORD %L NOSUPERUSER NOCREATEDB NOCREATEROLE', :'worker_pass') \gexec +SELECT format('CREATE ROLE relay_user LOGIN PASSWORD %L NOSUPERUSER NOCREATEDB NOCREATEROLE', :'relay_pass') \gexec +SELECT format('CREATE ROLE gc_user LOGIN PASSWORD %L NOSUPERUSER NOCREATEDB NOCREATEROLE', :'gc_pass') \gexec +GRANT CONNECT ON DATABASE messenger TO api_user, worker_user, relay_user, gc_user; +SQL +touch /var/lib/postgresql/data/.roles-ready diff --git a/infra/postgres/pg_hba.conf b/infra/postgres/pg_hba.conf new file mode 100644 index 0000000..677a114 --- /dev/null +++ b/infra/postgres/pg_hba.conf @@ -0,0 +1,3 @@ +local all all trust +hostssl all all all scram-sha-256 +hostnossl all all all reject diff --git a/infra/prometheus/alerts.yml b/infra/prometheus/alerts.yml new file mode 100644 index 0000000..199435b --- /dev/null +++ b/infra/prometheus/alerts.yml @@ -0,0 +1,29 @@ +groups: + - name: messenger-slo + interval: 15s + rules: + - alert: HighApiErrorRate + expr: | + ( + sum(rate(http_server_requests_total{service_name="messenger-api",sli="business",status_class="5xx"}[1m])) + / + clamp_min(sum(rate(http_server_requests_total{service_name="messenger-api",sli="business"}[1m])), 1e-9) + ) > 0.05 + for: 1m + labels: + severity: warning + slo: api-availability + annotations: + summary: Доля бизнес-запросов с ответом 5xx выше 5% за 1 минуту. + description: SLI — 5xx среди запросов sli=business, без /health. SLO — не меньше 99% успешных бизнес-запросов на окне 5 минут. Этот алерт короче SLO, чтобы короткий отказ был виден и снялся после восстановления. + runbook: Открыть дашборд Messenger. Сравнить долю 5xx и p95. В трассе ошибочного запроса посмотреть, сидит ли время в db.finalize или это сам handler. Сверить db.pool.connections state=used и state=waiting. Вернуть Postgres. Дождаться, пока ряд алерта исчезнет. + - alert: QueueLagHigh + expr: max(queue_oldest_age_seconds{queue="attachment.jobs"}) > 30 + for: 1m + labels: + severity: warning + slo: time-to-ready + annotations: + summary: Возраст старейшей задачи attachment.jobs больше 30 секунд. + description: Backlog — это число и возраст задач в статусе queued или processing, а не длительность успешной обработки. SLO времени до ready — p95 гистограммы attachment_time_to_ready_seconds не выше 60 секунд. + runbook: На дашборде сравнить queue depth и oldest age с worker.slots. Если busy=0 и capacity пропала, worker остановлен. Проверить трассу upload и лог relay на publish. Запустить worker. Возраст должен упасть, алерт перейти в inactive. diff --git a/infra/prometheus/prometheus.yml b/infra/prometheus/prometheus.yml new file mode 100644 index 0000000..be52f77 --- /dev/null +++ b/infra/prometheus/prometheus.yml @@ -0,0 +1,15 @@ +global: + scrape_interval: 10s + evaluation_interval: 15s + +rule_files: + - /etc/prometheus/alerts.yml + +scrape_configs: + - job_name: otel-collector + scheme: https + tls_config: + ca_file: /certs/ca.crt + server_name: otel-collector + static_configs: + - targets: ["otel-collector:8889"] diff --git a/infra/rabbit-entry.sh b/infra/rabbit-entry.sh new file mode 100644 index 0000000..c906c2c --- /dev/null +++ b/infra/rabbit-entry.sh @@ -0,0 +1,12 @@ +#!/bin/sh +set -eu +mkdir -p /var/lib/rabbitmq/tls +cp /certs/ca.crt /var/lib/rabbitmq/tls/ca.crt +cp /certs/rabbitmq.crt /var/lib/rabbitmq/tls/server.crt +cp /certs/rabbitmq.key /var/lib/rabbitmq/tls/server.key +chown -R rabbitmq:rabbitmq /var/lib/rabbitmq/tls +chmod 644 /var/lib/rabbitmq/tls/ca.crt /var/lib/rabbitmq/tls/server.crt +chmod 600 /var/lib/rabbitmq/tls/server.key +export RABBITMQ_DEFAULT_USER="$(cat /run/secrets/rabbitmq_user)" +export RABBITMQ_DEFAULT_PASS="$(cat /run/secrets/rabbitmq_password)" +exec docker-entrypoint.sh rabbitmq-server diff --git a/infra/rabbitmq/rabbitmq.conf b/infra/rabbitmq/rabbitmq.conf new file mode 100644 index 0000000..381befc --- /dev/null +++ b/infra/rabbitmq/rabbitmq.conf @@ -0,0 +1,12 @@ +listeners.tcp = none +listeners.ssl.default = 5671 +ssl_options.cacertfile = /var/lib/rabbitmq/tls/ca.crt +ssl_options.certfile = /var/lib/rabbitmq/tls/server.crt +ssl_options.keyfile = /var/lib/rabbitmq/tls/server.key +ssl_options.verify = verify_none +ssl_options.fail_if_no_peer_cert = false +ssl_options.versions.1 = tlsv1.2 +ssl_options.versions.2 = tlsv1.3 +management.tcp.ip = 127.0.0.1 +management.tcp.port = 15672 +load_definitions = /run/secrets/definitions.json diff --git a/infra/redis/entry.sh b/infra/redis/entry.sh new file mode 100644 index 0000000..7055bc8 --- /dev/null +++ b/infra/redis/entry.sh @@ -0,0 +1,19 @@ +#!/bin/sh +set -eu +mkdir -p /tmp/tls /data +cp /certs/redis.crt /tmp/tls/server.crt +cp /certs/redis.key /tmp/tls/server.key +chown redis:redis /tmp/tls/server.crt /tmp/tls/server.key /data +chmod 644 /tmp/tls/server.crt +chmod 600 /tmp/tls/server.key +exec gosu redis redis-server \ + --tls-port 6379 \ + --port 0 \ + --tls-cert-file /tmp/tls/server.crt \ + --tls-key-file /tmp/tls/server.key \ + --tls-ca-cert-file /certs/ca.crt \ + --requirepass "$(cat /run/secrets/redis_password)" \ + --appendonly yes \ + --appendfsync always \ + --dir /data \ + --protected-mode yes diff --git a/infra/tempo/tempo.yml b/infra/tempo/tempo.yml new file mode 100644 index 0000000..e136b8d --- /dev/null +++ b/infra/tempo/tempo.yml @@ -0,0 +1,28 @@ +server: + http_listen_port: 3200 + log_level: warn + +distributor: + receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + http: + endpoint: 0.0.0.0:4318 + +ingester: + trace_idle_period: 10s + max_block_duration: 5m + +compactor: + compaction: + block_retention: 168h + +storage: + trace: + backend: local + wal: + path: /var/tempo/wal + local: + path: /var/tempo/blocks diff --git a/migrations/001_initial.sql b/migrations/001_initial.sql new file mode 100644 index 0000000..b9e0369 --- /dev/null +++ b/migrations/001_initial.sql @@ -0,0 +1,52 @@ +-- Пользователи, чаты, состав и сообщения. Пароли и тексты сообщений +-- не пишутся приложением в логи. password_hash — только Argon2id. +-- Сессии в этой схеме нет: их источник истины — Redis (см. compose.yaml). + +CREATE TABLE users ( + id UUID PRIMARY KEY, + username TEXT NOT NULL, + display_name TEXT NOT NULL, + password_hash TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + CONSTRAINT uq_users_username UNIQUE (username), + CONSTRAINT ck_users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'), + CONSTRAINT ck_users_display_name_len CHECK ( + char_length(btrim(display_name)) >= 1 AND char_length(display_name) <= 100 + ), + CONSTRAINT ck_users_password_hash_len CHECK (char_length(password_hash) >= 20) +); + +CREATE TABLE chats ( + id UUID PRIMARY KEY, + title TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + CONSTRAINT ck_chats_title CHECK (char_length(btrim(title)) >= 1 AND char_length(title) <= 100) +); + +-- Состав чата пишется в той же транзакции, что и строка chats. +-- Откат до COMMIT не оставляет чат без участников. +CREATE TABLE chat_members ( + chat_id UUID NOT NULL REFERENCES chats (id), + user_id UUID NOT NULL REFERENCES users (id), + ordinal SMALLINT NOT NULL, + PRIMARY KEY (chat_id, user_id), + CONSTRAINT ck_chat_members_ordinal CHECK (ordinal >= 0 AND ordinal < 100) +); + +-- Список чатов пользователя: фильтр по user_id, затем порядок (created_at, id) чата. +CREATE INDEX ix_chat_members_user 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), + body TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + CONSTRAINT ck_messages_text CHECK (char_length(btrim(body)) >= 1 AND char_length(body) <= 4000) +); + +-- История: WHERE chat_id = $1 AND (created_at, id) > ($2, $3) +-- ORDER BY created_at, id LIMIT $4. +-- Ведущий chat_id отсекает чужие чаты, пара (created_at, id) продолжает +-- keyset с cursor и не читает предыдущие строки этой истории. +CREATE INDEX ix_messages_history ON messages (chat_id, created_at, id); diff --git a/migrations/002_idempotency.sql b/migrations/002_idempotency.sql new file mode 100644 index 0000000..f7cbcf5 --- /dev/null +++ b/migrations/002_idempotency.sql @@ -0,0 +1,22 @@ +-- Общая идемпотентность POST сообщения для всех API-реплик. +-- Результат пишется в той же транзакции, что и messages: 5xx не сохраняется. + +CREATE TABLE idempotency_records ( + user_id UUID NOT NULL REFERENCES users (id), + method TEXT NOT NULL, + request_path TEXT NOT NULL, + idempotency_key TEXT NOT NULL, + request_hash TEXT NOT NULL, + status_code SMALLINT NOT NULL, + message_id UUID NOT NULL REFERENCES messages (id), + created_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (user_id, method, request_path, idempotency_key), + CONSTRAINT ck_idem_method CHECK (method = 'POST'), + CONSTRAINT ck_idem_status CHECK (status_code = 201), + CONSTRAINT ck_idem_key CHECK (idempotency_key ~ '^[A-Za-z0-9._:-]{1,128}$'), + CONSTRAINT ck_idem_path CHECK (char_length(request_path) BETWEEN 1 AND 300), + CONSTRAINT ck_idem_hash CHECK (char_length(request_hash) = 64) +); + +CREATE INDEX ix_idempotency_message ON idempotency_records (message_id); +CREATE INDEX ix_idempotency_created ON idempotency_records (created_at); diff --git a/migrations/003_attachments.sql b/migrations/003_attachments.sql new file mode 100644 index 0000000..41ef516 --- /dev/null +++ b/migrations/003_attachments.sql @@ -0,0 +1,39 @@ +-- Вложения: метаданные в PostgreSQL, байты в S3. Пустой text сообщения +-- допускается только вместе с attachment_ids (проверяет приложение). + +ALTER TABLE messages DROP CONSTRAINT ck_messages_text; +ALTER TABLE messages ADD CONSTRAINT ck_messages_text CHECK (char_length(body) <= 4000); + +CREATE TABLE attachments ( + id UUID PRIMARY KEY, + chat_id UUID NOT NULL REFERENCES chats (id), + owner_id UUID NOT NULL REFERENCES users (id), + filename TEXT NOT NULL, + content_type TEXT NOT NULL, + size_bytes INTEGER NOT NULL, + sha256 TEXT NOT NULL, + object_key TEXT NOT NULL, + status TEXT NOT NULL, + error_code TEXT, + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + CONSTRAINT uq_attachments_object_key UNIQUE (object_key), + CONSTRAINT ck_attachments_filename CHECK (char_length(filename) BETWEEN 1 AND 255), + CONSTRAINT ck_attachments_content_type CHECK (content_type IN ('image/png', 'image/jpeg')), + CONSTRAINT ck_attachments_size CHECK (size_bytes >= 1 AND size_bytes <= 10485760), + CONSTRAINT ck_attachments_sha256 CHECK (sha256 ~ '^[a-f0-9]{64}$'), + CONSTRAINT ck_attachments_status CHECK (status = 'ready'), + CONSTRAINT ck_attachments_error CHECK (error_code IS NULL) +); + +CREATE INDEX ix_attachments_chat ON attachments (chat_id, created_at, id); + +CREATE TABLE message_attachments ( + message_id UUID NOT NULL REFERENCES messages (id), + attachment_id UUID NOT NULL REFERENCES attachments (id), + ordinal SMALLINT NOT NULL, + PRIMARY KEY (message_id, attachment_id), + CONSTRAINT ck_message_attachments_ordinal CHECK (ordinal >= 0 AND ordinal < 10) +); + +CREATE INDEX ix_message_attachments_attachment ON message_attachments (attachment_id); diff --git a/migrations/004_jobs.sql b/migrations/004_jobs.sql new file mode 100644 index 0000000..53e4661 --- /dev/null +++ b/migrations/004_jobs.sql @@ -0,0 +1,94 @@ +-- Lab5: асинхронные состояния, варианты, transactional outbox и реестр отказов. +-- Сообщение брокера хранит только идентификаторы. Байты остаются в S3. + +ALTER TABLE attachments DROP CONSTRAINT ck_attachments_status; + +ALTER TABLE attachments ADD CONSTRAINT ck_attachments_status CHECK (status IN ('queued', 'processing', 'ready', 'failed')); + +ALTER TABLE attachments DROP CONSTRAINT ck_attachments_error; + +ALTER TABLE attachments ADD CONSTRAINT ck_attachments_error CHECK ((status = 'failed' AND error_code IS NOT NULL AND char_length(error_code) BETWEEN 1 AND 64) OR (status <> 'failed' AND error_code IS NULL)); + +ALTER TABLE attachments ADD COLUMN staging_key TEXT; + +ALTER TABLE attachments ADD CONSTRAINT ck_attachments_staging CHECK (staging_key IS NULL OR char_length(staging_key) BETWEEN 8 AND 300); + +CREATE TABLE attachment_variants ( + attachment_id UUID NOT NULL REFERENCES attachments (id), + name TEXT NOT NULL, + content_type TEXT NOT NULL, + size_bytes INTEGER NOT NULL, + width INTEGER NOT NULL, + height INTEGER NOT NULL, + sha256 TEXT NOT NULL, + object_key TEXT NOT NULL, + pipeline_version INTEGER NOT NULL, + PRIMARY KEY (attachment_id, name), + CONSTRAINT uq_attachment_variants_object_key UNIQUE (object_key), + CONSTRAINT ck_variants_name CHECK (name IN ('thumbnail', 'crop', 'optimized')), + CONSTRAINT ck_variants_type CHECK (content_type IN ('image/jpeg', 'image/png', 'image/webp')), + CONSTRAINT ck_variants_size CHECK (size_bytes >= 1), + CONSTRAINT ck_variants_dim CHECK (width >= 1 AND height >= 1), + CONSTRAINT ck_variants_sha CHECK (sha256 ~ '^[a-f0-9]{64}$'), + CONSTRAINT ck_variants_pipeline CHECK (pipeline_version >= 1) +); + +CREATE TABLE attachment_jobs ( + job_id UUID PRIMARY KEY, + attachment_id UUID NOT NULL REFERENCES attachments (id), + pipeline_version INTEGER NOT NULL, + status TEXT NOT NULL, + attempt INTEGER NOT NULL, + max_attempts INTEGER NOT NULL, + lease_until TIMESTAMPTZ, + lease_owner TEXT, + next_attempt_at TIMESTAMPTZ, + error_code TEXT, + staging_key TEXT NOT NULL, + objects_written_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + CONSTRAINT uq_attachment_jobs_effect UNIQUE (attachment_id, pipeline_version), + CONSTRAINT ck_jobs_status CHECK (status IN ('queued', 'processing', 'ready', 'failed')), + CONSTRAINT ck_jobs_attempt CHECK (attempt >= 0 AND attempt <= max_attempts), + CONSTRAINT ck_jobs_max CHECK (max_attempts BETWEEN 1 AND 20), + CONSTRAINT ck_jobs_pipeline CHECK (pipeline_version >= 1), + CONSTRAINT ck_jobs_staging CHECK (char_length(staging_key) BETWEEN 8 AND 300) +); + +CREATE INDEX ix_jobs_lease ON attachment_jobs (status, lease_until); + +CREATE TABLE job_outbox ( + id UUID PRIMARY KEY, + job_id UUID NOT NULL REFERENCES attachment_jobs (job_id), + payload TEXT NOT NULL, + available_at TIMESTAMPTZ NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + published_at TIMESTAMPTZ, + publish_attempts INTEGER NOT NULL, + gap_injected BOOLEAN NOT NULL DEFAULT FALSE, + CONSTRAINT ck_outbox_attempts CHECK (publish_attempts >= 0) +); + +CREATE INDEX ix_outbox_pending ON job_outbox (available_at, created_at); + +CREATE TABLE job_failures ( + id UUID PRIMARY KEY, + job_id UUID NOT NULL REFERENCES attachment_jobs (job_id), + attachment_id UUID NOT NULL, + attempt INTEGER NOT NULL, + error_code TEXT NOT NULL, + permanent BOOLEAN NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + CONSTRAINT ck_job_failures_code CHECK (char_length(error_code) BETWEEN 1 AND 64) +); + +CREATE INDEX ix_job_failures_job ON job_failures (job_id, created_at); + +CREATE TABLE job_replays ( + id UUID PRIMARY KEY, + job_id UUID NOT NULL REFERENCES attachment_jobs (job_id), + outcome TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + CONSTRAINT ck_replays_outcome CHECK (outcome IN ('enqueued', 'already_ready', 'in_progress')) +); diff --git a/migrations/005_grants.sql b/migrations/005_grants.sql new file mode 100644 index 0000000..504ca53 --- /dev/null +++ b/migrations/005_grants.sql @@ -0,0 +1,8 @@ +-- Отдельные роли логина уже созданы оператором. DDL остаётся у роли миграции. +-- DML на таблицы приложения общий: это учебное упрощение уровня 3. +GRANT USAGE ON SCHEMA public TO api_user, worker_user, relay_user, gc_user; + +GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO api_user, worker_user, relay_user, gc_user; + +ALTER DEFAULT PRIVILEGES IN SCHEMA public + GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO api_user, worker_user, relay_user, gc_user; diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..c6af436 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,14 @@ +fastapi==0.115.6 +uvicorn==0.34.0 +pydantic==2.10.6 +SQLAlchemy[asyncio]==2.0.38 +greenlet==3.1.1 +asyncpg==0.30.0 +redis==5.2.1 +argon2-cffi==23.1.0 +boto3==1.36.11 +pillow==11.1.0 +aio-pika==9.5.5 +opentelemetry-api==1.29.0 +opentelemetry-sdk==1.29.0 +opentelemetry-exporter-otlp-proto-http==1.29.0 diff --git a/scripts/bootstrap.py b/scripts/bootstrap.py new file mode 100644 index 0000000..8d862a8 --- /dev/null +++ b/scripts/bootstrap.py @@ -0,0 +1,332 @@ +#!/usr/bin/env python3 +"""Create local CA, service certificates and passwords. Nothing here is committed.""" +import os +import shutil +import stat +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SECRETS = ROOT / "secrets" +CERTS = SECRETS / "certs" +PASSWORDS = SECRETS / "passwords" +OPENSSL_IMAGE = "alpine/openssl:3.3.3" +HTTPD_IMAGE = "httpd:2.4.62-alpine" + +SERVICES = [ + ("api", "api", ["api", "localhost"], ["127.0.0.1"], "serverAuth"), + ("postgres", "postgres", ["postgres", "localhost"], ["127.0.0.1"], "serverAuth"), + ("redis", "redis", ["redis", "localhost"], ["127.0.0.1"], "serverAuth"), + ("minio", "minio", ["minio", "localhost"], ["127.0.0.1"], "serverAuth"), + ("rabbitmq", "rabbitmq", ["rabbitmq", "localhost"], ["127.0.0.1"], "serverAuth"), + ("openbao", "openbao", ["openbao", "localhost"], ["127.0.0.1"], "serverAuth"), + ("otel", "otel-collector", ["otel-collector", "localhost"], ["127.0.0.1"], "serverAuth, clientAuth"), + ("grafana", "grafana", ["grafana", "localhost"], ["127.0.0.1"], "serverAuth, clientAuth"), + ("prometheus", "prometheus", ["prometheus", "localhost"], ["127.0.0.1"], "serverAuth, clientAuth"), + ( + "telemetry", + "telemetry.lab.internal", + ["telemetry.lab.internal", "tempo.lab.internal", "loki.lab.internal"], + [], + "serverAuth", + ), + ("lb-server", "localhost", ["localhost"], ["127.0.0.1"], "serverAuth"), + ("lb-client", "lb.lab.internal", ["lb.lab.internal"], [], "clientAuth"), + ("intruder", "intruder.lab.internal", ["intruder.lab.internal"], [], "clientAuth"), +] + + +def docker(*args): + subprocess.check_call(["docker", *args]) + + +def password(name: str) -> str: + path = PASSWORDS / name + if path.is_file() and path.read_text(encoding="utf-8").strip(): + return path.read_text(encoding="utf-8").strip() + import secrets + + value = secrets.token_hex(24) + path.write_text(value + "\n", encoding="utf-8", newline="\n") + os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH) + return value + + +def write(path: Path, text: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8", newline="\n") + os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH) + + +def place(src: Path, dst: Path) -> None: + dst.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(src, dst) + os.chmod(dst, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH) + + +def cnf(cn: str, dns_names: list[str], ips: list[str], eku: str) -> str: + san = [] + for index, name in enumerate(dns_names, start=1): + san.append("DNS.%s = %s" % (index, name)) + for index, ip in enumerate(ips, start=1): + san.append("IP.%s = %s" % (index, ip)) + return ( + "[req]\n" + "distinguished_name = dn\n" + "prompt = no\n" + "[dn]\n" + "CN = %s\n" + "[ext]\n" + "subjectAltName = @san\n" + "keyUsage = digitalSignature, keyEncipherment\n" + "extendedKeyUsage = %s\n" + "basicConstraints = CA:FALSE\n" + "[san]\n%s\n" % (cn, eku, "\n".join(san)) + ) + + +def issue_certificates() -> None: + if (CERTS / "ca.crt").is_file() and (CERTS / "api.crt").is_file() and (CERTS / "lb-client.crt").is_file(): + print("certificates already exist") + return + CERTS.mkdir(parents=True, exist_ok=True) + script = ["#!/bin/sh", "set -eu", "cd /work"] + script.append("openssl genrsa -out ca.key 4096") + script.append('openssl req -x509 -new -nodes -key ca.key -sha256 -days 825 -out ca.crt -subj "/CN=lab7-local-ca"') + script.append("openssl genrsa -out foreign-ca.key 4096") + script.append( + 'openssl req -x509 -new -nodes -key foreign-ca.key -sha256 -days 825 -out foreign-ca.crt -subj "/CN=lab7-foreign-ca"' + ) + script.append("issue() {") + script.append(' name="$1"; cnf="$2"; ca_cert="$3"; ca_key="$4"') + script.append(' openssl genrsa -out "$name.key" 2048') + script.append(' openssl req -new -key "$name.key" -out "$name.csr" -config "$cnf"') + script.append( + ' openssl x509 -req -in "$name.csr" -CA "$ca_cert" -CAkey "$ca_key" -CAcreateserial -out "$name.crt" -days 825 -sha256 -extfile "$cnf" -extensions ext' + ) + script.append(' rm -f "$name.csr"') + script.append("}") + for name, cn, dns_names, ips, eku in SERVICES: + write(CERTS / ("%s.cnf" % name), cnf(cn, dns_names, ips, eku)) + script.append('issue %s %s.cnf ca.crt ca.key' % (name, name)) + write(CERTS / "foreign-client.cnf", cnf("lb.lab.internal", ["lb.lab.internal"], [], "clientAuth")) + script.append("issue foreign-client foreign-client.cnf foreign-ca.crt foreign-ca.key") + write(CERTS / "issue.sh", "\n".join(script) + "\n") + docker( + "run", + "--rm", + "--entrypoint", + "/bin/sh", + "-v", + "%s:/work" % CERTS, + "-w", + "/work", + OPENSSL_IMAGE, + "/work/issue.sh", + ) + print("certificates created") + + +def pem_bundle(cert: Path, key: Path, dest: Path) -> None: + write(dest, cert.read_text(encoding="utf-8").strip() + "\n" + key.read_text(encoding="utf-8").strip() + "\n") + + +def yaml_pem(value: str, indent: int) -> str: + pad = " " * indent + return "\n".join(pad + line for line in value.strip().splitlines()) + + +def grafana_datasources(prometheus_password: str) -> None: + ca = (CERTS / "ca.crt").read_text(encoding="utf-8").strip() + cert = (CERTS / "grafana.crt").read_text(encoding="utf-8").strip() + key = (CERTS / "grafana.key").read_text(encoding="utf-8").strip() + text = """apiVersion: 1 + +datasources: + - name: Prometheus + uid: prometheus + type: prometheus + access: proxy + url: https://prometheus:9090 + isDefault: true + editable: false + basicAuth: true + basicAuthUser: grafana + jsonData: + tlsAuthWithCACert: true + serverName: prometheus + timeInterval: 10s + secureJsonData: + basicAuthPassword: "%s" + tlsCACert: | +%s + - name: Loki + uid: loki + type: loki + access: proxy + url: https://loki.lab.internal:3100 + editable: false + jsonData: + tlsAuth: true + tlsAuthWithCACert: true + serverName: loki.lab.internal + derivedFields: + - name: trace_id + matcherRegex: "\\"trace_id\\":\\"([0-9a-f]+)\\"" + url: "$${__value.raw}" + datasourceUid: tempo + urlDisplayLabel: Открыть трассу + secureJsonData: + tlsCACert: | +%s + tlsClientCert: | +%s + tlsClientKey: | +%s + - name: Tempo + uid: tempo + type: tempo + access: proxy + url: https://tempo.lab.internal:3200 + editable: false + jsonData: + tlsAuth: true + tlsAuthWithCACert: true + serverName: tempo.lab.internal + tracesToLogsV2: + datasourceUid: loki + filterByTraceID: false + customQuery: true + query: '{service_name=~"messenger-.+"} | trace_id="$${__trace.traceId}"' + tracesToMetrics: + datasourceUid: prometheus + serviceMap: + datasourceUid: prometheus + nodeGraph: + enabled: true + lokiSearch: + datasourceUid: loki + secureJsonData: + tlsCACert: | +%s + tlsClientCert: | +%s + tlsClientKey: | +%s +""" % ( + prometheus_password, + yaml_pem(ca, 8), + yaml_pem(ca, 8), + yaml_pem(cert, 8), + yaml_pem(key, 8), + yaml_pem(ca, 8), + yaml_pem(cert, 8), + yaml_pem(key, 8), + ) + write(SECRETS / "grafana" / "datasources.yml", text) + + +def prometheus_web(password: str) -> None: + raw = subprocess.check_output( + ["docker", "run", "--rm", HTTPD_IMAGE, "htpasswd", "-nbB", "grafana", password], + text=True, + ).strip() + hashed = raw.split(":", 1)[1] + write( + SECRETS / "prometheus" / "web.yml", + "tls_server_config:\n" + " cert_file: /certs/prometheus.crt\n" + " key_file: /certs/prometheus.key\n" + "basic_auth_users:\n" + ' grafana: "%s"\n' % hashed, + ) + + +def rabbit_definitions() -> None: + relay = password("rabbit_relay") + worker = password("rabbit_worker") + pattern = "^(attachments|attachment\\\\.jobs.*)$" + text = """{ + "vhosts": [{"name": "/"}], + "users": [ + {"name": "relay", "password": "%s", "tags": ""}, + {"name": "worker", "password": "%s", "tags": ""} + ], + "permissions": [ + {"user": "relay", "vhost": "/", "configure": "%s", "write": "%s", "read": "%s"}, + {"user": "worker", "vhost": "/", "configure": "%s", "write": "%s", "read": "%s"} + ] +} +""" % (relay, worker, pattern, pattern, pattern, pattern, pattern, pattern) + write(SECRETS / "rabbit-definitions.json", text) + + +def runtime_copies() -> None: + roles = { + "api": ["ca.crt", "api.crt", "api.key"], + "worker": ["ca.crt"], + "relay": ["ca.crt"], + "gc": ["ca.crt"], + "migrate": ["ca.crt"], + } + for role, names in roles.items(): + folder = SECRETS / "runtime" / role + place(CERTS / "ca.crt", folder / "ca.crt") + if "api.crt" in names: + place(CERTS / "api.crt", folder / "server.crt") + place(CERTS / "api.key", folder / "server.key") + haproxy = SECRETS / "haproxy" + place(CERTS / "ca.crt", haproxy / "ca.crt") + pem_bundle(CERTS / "lb-server.crt", CERTS / "lb-server.key", haproxy / "lb-server.pem") + pem_bundle(CERTS / "lb-client.crt", CERTS / "lb-client.key", haproxy / "lb-client.pem") + + +def main() -> None: + PASSWORDS.mkdir(parents=True, exist_ok=True) + for name in ( + "db_migrator", + "db_api", + "db_worker", + "db_relay", + "db_gc", + "redis", + "rabbit_operator", + "rabbit_relay", + "rabbit_worker", + "minio_root_password", + "s3_api_key", + "s3_api_secret", + "s3_worker_key", + "s3_worker_secret", + "s3_gc_key", + "s3_gc_secret", + "grafana_admin", + "prometheus_grafana", + "otel_token", + ): + password(name) + write(PASSWORDS / "minio_root_user", "labroot\n") + write(PASSWORDS / "rabbit_operator_name", "operator\n") + write( + SECRETS / "minio.env", + "MINIO_ROOT_USER=%s\nMINIO_ROOT_PASSWORD=%s\n" % (password("minio_root_user"), password("minio_root_password")), + ) + write(SECRETS / "otel.env", "OTEL_INGEST_TOKEN=%s\n" % password("otel_token")) + write(ROOT / ".env", "APP_ENV=lab\n") + issue_certificates() + runtime_copies() + rabbit_definitions() + prometheus_password = password("prometheus_grafana") + prometheus_web(prometheus_password) + grafana_datasources(prometheus_password) + print("bootstrap complete") + print("CA_FILE=%s" % (CERTS / "ca.crt")) + + +if __name__ == "__main__": + try: + main() + except subprocess.CalledProcessError as exc: + print("bootstrap command failed", file=sys.stderr) + sys.exit(exc.returncode) diff --git a/scripts/mtls_probe.py b/scripts/mtls_probe.py new file mode 100644 index 0000000..8fb371b --- /dev/null +++ b/scripts/mtls_probe.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +"""Negative and positive probes for LB-to-API mTLS. Run inside the lab network.""" +import socket +import ssl +import sys +from pathlib import Path + +HOST = "api" +PORT = 8443 +CA = Path("/certs/ca.crt") +LB_CERT = Path("/certs/lb-client.crt") +LB_KEY = Path("/certs/lb-client.key") +INTRUDER_CERT = Path("/certs/intruder.crt") +INTRUDER_KEY = Path("/certs/intruder.key") +FOREIGN_CERT = Path("/certs/foreign-client.crt") +FOREIGN_KEY = Path("/certs/foreign-client.key") +FOREIGN_CA = Path("/certs/foreign-ca.crt") + + +def ips(): + found = sorted({item[4][0] for item in socket.getaddrinfo(HOST, PORT, type=socket.SOCK_STREAM)}) + if len(found) < 2: + raise SystemExit("expected at least two API addresses, got %s" % found) + return found + + +def context(ca, cert=None, key=None): + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ctx.minimum_version = ssl.TLSVersion.TLSv1_2 + ctx.check_hostname = True + ctx.verify_mode = ssl.CERT_REQUIRED + ctx.load_verify_locations(cafile=str(ca)) + if cert and key: + ctx.load_cert_chain(str(cert), str(key)) + return ctx + + +def http_get(ip, ctx): + sock = socket.create_connection((ip, PORT), timeout=5) + try: + tls = ctx.wrap_socket(sock, server_hostname=HOST) + except ssl.SSLError as exc: + return "handshake", type(exc).__name__ + try: + tls.sendall(b"GET /health/live HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n") + data = b"" + while True: + chunk = tls.recv(4096) + if not chunk: + break + data += chunk + if len(data) > 65536: + break + except (ssl.SSLError, OSError, ConnectionError) as exc: + return "closed", type(exc).__name__ + finally: + try: + tls.close() + except OSError: + pass + status = data.split(b" ", 2)[1].decode("ascii", "replace") if data.startswith(b"HTTP/") and b" " in data else "none" + return "http", status + + +def expect(ip, label, ca, cert, key, kind): + outcome, detail = http_get(ip, context(ca, cert, key)) + if kind == "reject-handshake" and outcome == "handshake": + print("PASS %s %s handshake rejected (%s)" % (ip, label, detail)) + return + if kind == "reject-http" and outcome != "http" and detail != "200": + print("PASS %s %s rejected (%s %s)" % (ip, label, outcome, detail)) + return + if kind == "reject-http" and outcome == "http" and detail != "200": + print("PASS %s %s rejected status %s" % (ip, label, detail)) + return + if kind == "allow" and outcome == "http" and detail == "200": + print("PASS %s %s accepted" % (ip, label)) + return + raise SystemExit("FAIL %s %s -> %s %s" % (ip, label, outcome, detail)) + + +def main(): + for ip in ips(): + expect(ip, "no-cert", CA, None, None, "reject-handshake") + expect(ip, "foreign-ca", CA, FOREIGN_CERT, FOREIGN_KEY, "reject-handshake") + expect(ip, "wrong-identity", CA, INTRUDER_CERT, INTRUDER_KEY, "reject-http") + expect(ip, "lb-identity", CA, LB_CERT, LB_KEY, "allow") + print("PASS mTLS identity checks") + + +if __name__ == "__main__": + try: + main() + except Exception as exc: + print("FAIL %s" % type(exc).__name__, file=sys.stderr) + raise diff --git a/scripts/openbao_bootstrap.py b/scripts/openbao_bootstrap.py new file mode 100644 index 0000000..805967e --- /dev/null +++ b/scripts/openbao_bootstrap.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python3 +"""Init, unseal and load scoped AppRole secrets. Does not print tokens or keys.""" +import json +import os +import ssl +import sys +import time +import urllib.error +import urllib.request +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SECRETS = Path(os.environ.get("SECRETS_DIR", str(ROOT / "secrets"))) +POLICIES = Path(os.environ.get("POLICIES_DIR", str(ROOT / "infra" / "openbao" / "policies"))) +ADDR = os.environ.get("BAO_ADDR", "https://127.0.0.1:8200").rstrip("/") +CA = os.environ.get("BAO_CACERT", str(SECRETS / "certs" / "ca.crt")) + +ROLES = ("api", "worker", "relay", "gc", "migrate") + + +def read(name: str) -> str: + return (SECRETS / "passwords" / name).read_text(encoding="utf-8").strip() + + +def call(ctx, method, path, body=None, token=""): + data = None if body is None else json.dumps(body).encode("utf-8") + request = urllib.request.Request(ADDR + path, data=data, method=method) + request.add_header("Content-Type", "application/json") + if token: + request.add_header("X-Vault-Token", token) + try: + with urllib.request.urlopen(request, context=ctx, timeout=5) as response: + raw = response.read() + return response.status, json.loads(raw.decode("utf-8")) if raw else {} + except urllib.error.HTTPError as exc: + raw = exc.read() + try: + payload = json.loads(raw.decode("utf-8")) if raw else {} + except json.JSONDecodeError: + payload = {} + return exc.code, payload + + +def wait_status(ctx): + for _ in range(60): + try: + code, payload = call(ctx, "GET", "/v1/sys/seal-status") + if code == 200 and isinstance(payload, dict) and "initialized" in payload: + return payload + except (urllib.error.URLError, TimeoutError, OSError): + pass + time.sleep(1) + raise SystemExit("openbao did not become reachable") + + +def write_mode(path: Path, text: str, mode: int) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8", newline="\n") + try: + os.chmod(path, mode) + except OSError: + pass + + +def ensure_secret_id(ctx, token, role): + target = SECRETS / "runtime" / role / "secret_id" + if target.is_file() and target.read_text(encoding="utf-8").strip(): + return + code, payload = call(ctx, "POST", "/v1/auth/approle/role/%s/secret-id" % role, {}, token) + if code != 200: + raise SystemExit("secret-id was not issued for %s" % role) + secret_id = payload.get("data", {}).get("secret_id", "") + if not secret_id: + raise SystemExit("secret-id was empty") + write_mode(target, secret_id + "\n", 0o644) + + +def main() -> None: + ctx = ssl.create_default_context(cafile=CA) + ctx.minimum_version = ssl.TLSVersion.TLSv1_2 + status = wait_status(ctx) + init_path = SECRETS / "openbao" / "init.json" + if not status.get("initialized"): + code, payload = call(ctx, "POST", "/v1/sys/init", {"secret_shares": 1, "secret_threshold": 1}) + if code != 200 or not payload.get("root_token") or not payload.get("keys"): + raise SystemExit("openbao init failed") + write_mode(init_path, json.dumps({"keys": payload["keys"], "root_token": payload["root_token"]}) + "\n", 0o600) + print("openbao initialized") + status = wait_status(ctx) + saved = json.loads(init_path.read_text(encoding="utf-8")) + if status.get("sealed"): + code, _payload = call(ctx, "POST", "/v1/sys/unseal", {"key": saved["keys"][0]}) + if code != 200: + raise SystemExit("openbao unseal failed") + print("openbao unsealed") + token = saved["root_token"] + code, _payload = call(ctx, "POST", "/v1/sys/mounts/secret", {"type": "kv", "options": {"version": "2"}}, token) + if code not in {200, 204, 400}: + raise SystemExit("kv mount failed") + code, _payload = call(ctx, "POST", "/v1/sys/auth/approle", {"type": "approle"}, token) + if code not in {200, 204, 400}: + raise SystemExit("approle enable failed") + db = { + "migrate": ("messenger", read("db_migrator")), + "api": ("api_user", read("db_api")), + "worker": ("worker_user", read("db_worker")), + "relay": ("relay_user", read("db_relay")), + "gc": ("gc_user", read("db_gc")), + } + secrets = { + "migrate": {"database_url": "postgresql+asyncpg://%s:%s@postgres:5432/messenger" % db["migrate"]}, + "api": { + "database_url": "postgresql+asyncpg://%s:%s@postgres:5432/messenger" % db["api"], + "redis_url": "rediss://:%s@redis:6379/0" % read("redis"), + "s3_access_key_id": read("s3_api_key"), + "s3_secret_access_key": read("s3_api_secret"), + "otel_token": read("otel_token"), + }, + "worker": { + "database_url": "postgresql+asyncpg://%s:%s@postgres:5432/messenger" % db["worker"], + "s3_access_key_id": read("s3_worker_key"), + "s3_secret_access_key": read("s3_worker_secret"), + "broker_url": "amqps://worker:%s@rabbitmq:5671/%s" % (read("rabbit_worker"), "%2F"), + "otel_token": read("otel_token"), + }, + "relay": { + "database_url": "postgresql+asyncpg://%s:%s@postgres:5432/messenger" % db["relay"], + "broker_url": "amqps://relay:%s@rabbitmq:5671/%s" % (read("rabbit_relay"), "%2F"), + "otel_token": read("otel_token"), + }, + "gc": { + "database_url": "postgresql+asyncpg://%s:%s@postgres:5432/messenger" % db["gc"], + "s3_access_key_id": read("s3_gc_key"), + "s3_secret_access_key": read("s3_gc_secret"), + "otel_token": read("otel_token"), + }, + } + for role in ROLES: + policy = (POLICIES / ("messenger-%s.hcl" % role)).read_text(encoding="utf-8") + code, _payload = call(ctx, "PUT", "/v1/sys/policies/acl/messenger-%s" % role, {"policy": policy}, token) + if code not in {200, 204}: + raise SystemExit("policy write failed for %s" % role) + code, _payload = call( + ctx, + "POST", + "/v1/auth/approle/role/%s" % role, + { + "token_policies": ["messenger-%s" % role], + "token_ttl": "1h", + "token_max_ttl": "4h", + "secret_id_ttl": "0", + "secret_id_num_uses": 0, + }, + token, + ) + if code not in {200, 204}: + raise SystemExit("approle role failed for %s" % role) + code, payload = call(ctx, "GET", "/v1/auth/approle/role/%s/role-id" % role, token=token) + role_id = payload.get("data", {}).get("role_id", "") if code == 200 else "" + if not role_id: + raise SystemExit("role-id missing for %s" % role) + write_mode(SECRETS / "runtime" / role / "role_id", role_id + "\n", 0o644) + ensure_secret_id(ctx, token, role) + code, _payload = call(ctx, "POST", "/v1/secret/data/messenger/%s" % role, {"data": secrets[role]}, token) + if code not in {200, 204}: + raise SystemExit("kv write failed for %s" % role) + print("openbao policies and secrets are in place") + + +if __name__ == "__main__": + main() diff --git a/scripts/prove_level3.py b/scripts/prove_level3.py new file mode 100644 index 0000000..0f5a252 --- /dev/null +++ b/scripts/prove_level3.py @@ -0,0 +1,189 @@ +#!/usr/bin/env python3 +"""Grade-3 negative checks that the public smoke does not cover.""" +import base64 +import json +import os +import ssl +import subprocess +import sys +import urllib.error +import urllib.request +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "scripts")) +CA = ROOT / "secrets" / "certs" / "ca.crt" +BASE = os.environ.get("BASE_URL", "https://localhost:8443").rstrip("/") + + +def compose(*args, timeout=180): + return subprocess.run( + ["docker", "compose", "--env-file", str(ROOT / ".env"), *args], + cwd=ROOT, + text=True, + capture_output=True, + timeout=timeout, + check=False, + ) + + +def trusted(): + ctx = ssl.create_default_context(cafile=str(CA)) + with urllib.request.urlopen(BASE + "/health/ready", context=ctx, timeout=10) as response: + body = response.read() + if response.status != 200: + raise SystemExit("trusted HTTPS did not return 200") + return body + + +def untrusted(): + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ctx.verify_mode = ssl.CERT_REQUIRED + ctx.check_hostname = True + try: + urllib.request.urlopen(BASE + "/health/ready", context=ctx, timeout=5).read() + except urllib.error.URLError as exc: + if not isinstance(exc.reason, ssl.SSLCertVerificationError): + raise SystemExit("untrusted CA failed for a non-certificate reason") + return + raise SystemExit("empty trust store was accepted") + + +def closed_port(): + import socket + + sock = socket.socket() + sock.settimeout(2) + try: + result = sock.connect_ex(("127.0.0.1", 8080)) + finally: + sock.close() + if result == 0: + raise SystemExit("plaintext port 8080 is reachable on the host") + + +def rate_limit(): + ctx = ssl.create_default_context(cafile=str(CA)) + raw = base64.b64encode(b"rate_limit_user:wrong-password-value").decode("ascii") + saw = None + for _ in range(12): + request = urllib.request.Request( + BASE + "/api/v1/auth/sessions", + method="POST", + headers={"Authorization": "Basic " + raw, "Accept": "application/json"}, + ) + try: + urllib.request.urlopen(request, context=ctx, timeout=20).read() + code = 200 + headers = {} + except urllib.error.HTTPError as exc: + code = exc.code + headers = exc.headers + exc.read() + saw = code + if code == 429: + if not headers.get("Retry-After"): + raise SystemExit("429 without Retry-After") + return + raise SystemExit("login was not rate limited, last status %s" % saw) + + +def oversized(): + ctx = ssl.create_default_context(cafile=str(CA)) + payload = b'{"username":"abc","display_name":"x","password":"' + (b"a" * 70000) + b'"}' + request = urllib.request.Request( + BASE + "/api/v1/users", + data=payload, + method="POST", + headers={"Content-Type": "application/json", "Accept": "application/json"}, + ) + try: + urllib.request.urlopen(request, context=ctx, timeout=20).read() + except urllib.error.HTTPError as exc: + if exc.code != 413: + raise SystemExit("oversized body returned %s" % exc.code) from None + return + raise SystemExit("oversized body was accepted") + + +def openbao_deny(): + sys.path.insert(0, str(ROOT)) + os.environ["BAO_ADDR"] = "https://127.0.0.1:8200" + os.environ["BAO_CACERT"] = str(CA) + ctx = ssl.create_default_context(cafile=str(CA)) + role = (ROOT / "secrets" / "runtime" / "worker" / "role_id").read_text(encoding="utf-8").strip() + secret = (ROOT / "secrets" / "runtime" / "worker" / "secret_id").read_text(encoding="utf-8").strip() + body = json.dumps({"role_id": role, "secret_id": secret}).encode("utf-8") + request = urllib.request.Request( + "https://127.0.0.1:8200/v1/auth/approle/login", + data=body, + method="POST", + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, context=ctx, timeout=10) as response: + token = json.loads(response.read().decode("utf-8"))["auth"]["client_token"] + own = urllib.request.Request( + "https://127.0.0.1:8200/v1/secret/data/messenger/worker", + headers={"X-Vault-Token": token}, + ) + with urllib.request.urlopen(own, context=ctx, timeout=10) as response: + if response.status != 200: + raise SystemExit("worker cannot read its own secret") + foreign = urllib.request.Request( + "https://127.0.0.1:8200/v1/secret/data/messenger/api", + headers={"X-Vault-Token": token}, + ) + try: + urllib.request.urlopen(foreign, context=ctx, timeout=10).read() + except urllib.error.HTTPError as exc: + if exc.code != 403: + raise SystemExit("worker read of api secret returned %s" % exc.code) from None + return + raise SystemExit("worker token read the api secret") + + +def mtls(): + proc = compose( + "run", + "--rm", + "--no-deps", + "--entrypoint", + "python", + "-v", + "%s:/probe.py:ro" % (ROOT / "scripts" / "mtls_probe.py"), + "-v", + "%s:/certs:ro" % (ROOT / "secrets" / "certs"), + "api", + "/probe.py", + ) + sys.stdout.write(proc.stdout) + sys.stderr.write(proc.stderr) + if proc.returncode != 0: + raise SystemExit("mTLS probe failed") + + +def main(): + trusted() + print("PASS trusted HTTPS") + untrusted() + print("PASS untrusted CA rejected") + closed_port() + print("PASS host port 8080 is closed") + rate_limit() + print("PASS login rate limit") + oversized() + print("PASS request size limit") + openbao_deny() + print("PASS OpenBao worker policy deny") + mtls() + evidence = ROOT / "evidence" + evidence.mkdir(exist_ok=True) + (evidence / "level7.json").write_text( + json.dumps({"result": "pass", "base_url": BASE}, indent=2) + "\n", + encoding="utf-8", + ) + print("PASS level 3 security checks") + + +if __name__ == "__main__": + main() diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 0000000..ec7fda2 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,15 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +if command -v python3 >/dev/null 2>&1; then + PY=python3 +else + PY=python +fi +docker compose --env-file .env restart postgres redis minio rabbitmq openbao +docker compose --env-file .env restart minio-tls || true +BAO_ADDR=https://127.0.0.1:8200 \ +BAO_CACERT="$PWD/secrets/certs/ca.crt" \ +SECRETS_DIR="$PWD/secrets" \ +"$PY" scripts/openbao_bootstrap.py +docker compose --env-file .env restart api worker relay gc diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100644 index 0000000..462773a --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,14 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +: "${TARGET_INSTANCE_ID:?missing TARGET_INSTANCE_ID}" +ids=$(docker compose --env-file .env ps -q api) +for id in $ids; do + host=$(docker inspect -f '{{.Config.Hostname}}' "$id") + if [ "$host" = "$TARGET_INSTANCE_ID" ]; then + docker stop -t 2 "$id" >/dev/null + exit 0 + fi +done +echo "api instance was not found" >&2 +exit 1 diff --git a/scripts/up.py b/scripts/up.py new file mode 100644 index 0000000..241c806 --- /dev/null +++ b/scripts/up.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 +"""Bootstrap local secrets and start the lab7 stand.""" +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def compose(*args): + subprocess.check_call(["docker", "compose", "--env-file", str(ROOT / ".env"), *args], cwd=ROOT) + + +def main() -> None: + subprocess.check_call([sys.executable, str(ROOT / "scripts" / "bootstrap.py")], cwd=ROOT) + compose("up", "-d", "--build", "--scale", "api=2") + ids = subprocess.check_output( + ["docker", "compose", "--env-file", str(ROOT / ".env"), "ps", "-q", "api"], + cwd=ROOT, + text=True, + ).split() + if len(ids) < 2: + raise SystemExit("expected two API replicas, got %s" % len(ids)) + print("stand is up; wait for https://localhost:8443/health/ready") + print("CA_FILE=%s" % (ROOT / "secrets" / "certs" / "ca.crt")) + + +if __name__ == "__main__": + main() diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/app/__init__.py b/src/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/app/__main__.py b/src/app/__main__.py new file mode 100644 index 0000000..cbd00d9 --- /dev/null +++ b/src/app/__main__.py @@ -0,0 +1,44 @@ +import logging + +import uvicorn + +from app.config import load_settings +from app.mtls import start_mtls_proxy +from app.telemetry import setup_logging, setup_telemetry + + +def main() -> None: + settings = load_settings() + setup_logging(settings.app_role) + setup_telemetry(settings) + if settings.mtls_enabled: + if not settings.tls_cert_file or not settings.tls_key_file or not settings.tls_ca_file: + raise SystemExit("TLS_CERT_FILE, TLS_KEY_FILE and TLS_CA_FILE are required for mTLS") + start_mtls_proxy(settings) + bind_host = "127.0.0.1" + bind_port = settings.internal_port + else: + bind_host = settings.host + bind_port = settings.port + logging.getLogger("app").info( + "starting host=%s port=%s env=%s instance_id=%s mtls=%s", + bind_host, + bind_port, + settings.env, + settings.instance_id, + settings.mtls_enabled, + ) + uvicorn.run( + "app.main:app", + host=bind_host, + port=bind_port, + workers=1, + access_log=False, + timeout_keep_alive=5, + timeout_graceful_shutdown=5, + log_config=None, + ) + + +if __name__ == "__main__": + main() diff --git a/src/app/api/__init__.py b/src/app/api/__init__.py new file mode 100644 index 0000000..a2b2300 --- /dev/null +++ b/src/app/api/__init__.py @@ -0,0 +1,14 @@ +from fastapi import APIRouter + +from app.api.attachments import router as attachments_router +from app.api.auth import router as auth_router +from app.api.chats import router as chats_router +from app.api.messages import router as messages_router +from app.api.users import router as users_router + +api_router = APIRouter(prefix="/api/v1") +api_router.include_router(users_router) +api_router.include_router(auth_router) +api_router.include_router(chats_router) +api_router.include_router(messages_router) +api_router.include_router(attachments_router) diff --git a/src/app/api/attachments.py b/src/app/api/attachments.py new file mode 100644 index 0000000..8a0769e --- /dev/null +++ b/src/app/api/attachments.py @@ -0,0 +1,71 @@ +from uuid import UUID + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import Response + +from app.crud.attachments import create_attachment, metadata_for_member, open_content +from app.deps import get_current_user +from app.errors import AppError +from app.present import PublicUser +from app.runtime import require_settings, require_store +from app.schemas.attachment import AttachmentOut + +router = APIRouter() + + +async def read_limited_body(request: Request) -> bytes: + limit = require_settings().max_upload_bytes + raw_length = request.headers.get("content-length") + if raw_length is not None: + try: + announced = int(raw_length) + except ValueError: + raise AppError(400, "invalid_request", "Некорректный запрос") from None + if announced > limit: + raise AppError(413, "payload_too_large", "Файл слишком большой") + chunks: list[bytes] = [] + total = 0 + async for chunk in request.stream(): + total += len(chunk) + if total > limit: + raise AppError(413, "payload_too_large", "Файл слишком большой") + if chunk: + chunks.append(chunk) + return b"".join(chunks) + + +@router.post("/chats/{chat_id}/attachments", status_code=202, response_model=AttachmentOut) +async def upload_attachment( + chat_id: UUID, + request: Request, + filename: str = Query(min_length=1, max_length=255), + user: PublicUser = Depends(get_current_user), +) -> dict: + payload = await read_limited_body(request) + created = await create_attachment( + chat_id, + user.id, + filename, + request.headers.get("content-type"), + payload, + ) + return created.to_dict() + + +@router.get("/attachments/{attachment_id}", response_model=AttachmentOut) +async def get_attachment( + attachment_id: UUID, + user: PublicUser = Depends(get_current_user), +) -> dict: + return (await metadata_for_member(attachment_id, user.id)).to_dict() + + +@router.get("/attachments/{attachment_id}/content") +async def download_attachment( + attachment_id: UUID, + user: PublicUser = Depends(get_current_user), + variant: str = Query(default="original"), +) -> Response: + key, media_type = await open_content(attachment_id, user.id, variant) + payload = await require_store().get(key) + return Response(content=payload, media_type=media_type) diff --git a/src/app/api/auth.py b/src/app/api/auth.py new file mode 100644 index 0000000..430f67a --- /dev/null +++ b/src/app/api/auth.py @@ -0,0 +1,40 @@ +from fastapi import APIRouter, Depends, Header +from starlette.responses import Response + +from app.crud.users import authenticate +from app.deps import BASIC_CHALLENGE, BEARER_CHALLENGE, require_token, unauthorized +from app.ratelimit import enforce_login_limit +from app.schemas.session import SessionOut +from app.security import parse_basic, verify_password +from app.sessions import create_session, revoke_session +from app.timeutil import format_time + +router = APIRouter() + + +@router.post("/auth/sessions", status_code=201, response_model=SessionOut) +async def create_session_route(authorization: str | None = Header(default=None)) -> dict: + parsed = parse_basic(authorization or "") + username = parsed[0] if parsed is not None else "malformed" + await enforce_login_limit(username) + if parsed is None: + verify_password("invalid-basic-auth", None) + raise unauthorized(BASIC_CHALLENGE) + username, password = parsed + user = await authenticate(username, password) + if user is None: + raise unauthorized(BASIC_CHALLENGE) + token, expires_at = await create_session(user.id) + return { + "token": token, + "token_type": "Bearer", + "expires_at": format_time(expires_at), + "user": user.to_dict(), + } + + +@router.delete("/auth/sessions/current", status_code=204) +async def revoke_current_session(token: str = Depends(require_token)) -> Response: + if not await revoke_session(token): + raise unauthorized(BEARER_CHALLENGE) + return Response(status_code=204) diff --git a/src/app/api/chats.py b/src/app/api/chats.py new file mode 100644 index 0000000..9015540 --- /dev/null +++ b/src/app/api/chats.py @@ -0,0 +1,31 @@ +from uuid import UUID + +from fastapi import APIRouter, Depends, Query + +from app.crud.chats import chat_for_member, chats_for_user, create_chat as save_chat +from app.deps import get_current_user +from app.present import PublicUser +from app.schemas.chat import ChatOut, ChatPage, CreateChat + +router = APIRouter() + + +@router.post("/chats", status_code=201, response_model=ChatOut) +async def create_chat(body: CreateChat, user: PublicUser = Depends(get_current_user)) -> dict: + chat = await save_chat(user.id, body.title, tuple(body.member_ids)) + return chat.to_dict() + + +@router.get("/chats", response_model=ChatPage) +async def list_chats( + user: PublicUser = Depends(get_current_user), + limit: int = Query(default=50, ge=1, le=100), + cursor: str | None = Query(default=None, min_length=1), +) -> dict: + return await chats_for_user(user.id, limit, cursor) + + +@router.get("/chats/{chat_id}", response_model=ChatOut) +async def get_chat(chat_id: UUID, user: PublicUser = Depends(get_current_user)) -> dict: + chat = await chat_for_member(chat_id, user.id) + return chat.to_dict() diff --git a/src/app/api/health.py b/src/app/api/health.py new file mode 100644 index 0000000..2eff6da --- /dev/null +++ b/src/app/api/health.py @@ -0,0 +1,43 @@ +import logging + +from fastapi import APIRouter, Request +from pydantic import BaseModel +from sqlalchemy import text + +from app.db import is_dependency_error +from app.errors import AppError + +router = APIRouter() +logger = logging.getLogger("app.health") + + +class HealthOut(BaseModel): + status: str + + +@router.get("/health/live", response_model=HealthOut) +async def live() -> dict: + return {"status": "ok"} + + +@router.get("/health/ready", response_model=HealthOut) +async def ready(request: Request) -> dict: + if not getattr(request.app.state, "accepting", False): + raise AppError(503, "unavailable", "Сервер не готов") + engine = getattr(request.app.state, "engine", None) + redis = getattr(request.app.state, "redis", None) + store = getattr(request.app.state, "store", None) + if engine is None or redis is None or store is None: + raise AppError(503, "unavailable", "Сервис временно недоступен") + try: + async with engine.connect() as conn: + await conn.execute(text("SELECT 1")) + await redis.ping() + await store.ping() + except AppError: + raise + except Exception as exc: + if not is_dependency_error(exc): + logger.warning("readiness check failed type=%s", type(exc).__name__) + raise AppError(503, "unavailable", "Сервис временно недоступен") from None + return {"status": "ok"} diff --git a/src/app/api/messages.py b/src/app/api/messages.py new file mode 100644 index 0000000..3c2ac43 --- /dev/null +++ b/src/app/api/messages.py @@ -0,0 +1,43 @@ +import re +from uuid import UUID + +from fastapi import APIRouter, Depends, Query, Request + +from app.crud.messages import create_message as save_message +from app.crud.messages import messages_for_member +from app.deps import get_current_user +from app.errors import AppError +from app.present import PublicUser +from app.schemas.message import CreateMessage, MessageOut, MessagePage + +router = APIRouter() +_IDEMPOTENCY_KEY = re.compile(r"^[A-Za-z0-9._:-]{1,128}$") + + +def require_idempotency_key(request: Request) -> str: + value = request.headers.get("idempotency-key") + if value is None or _IDEMPOTENCY_KEY.fullmatch(value) is None: + raise AppError(400, "invalid_request", "Некорректный Idempotency-Key") + return value + + +@router.post("/chats/{chat_id}/messages", status_code=201, response_model=MessageOut) +async def create_message( + chat_id: UUID, + body: CreateMessage, + request: Request, + user: PublicUser = Depends(get_current_user), +) -> dict: + key = require_idempotency_key(request) + message = await save_message(chat_id, user.id, body.text, key, body.attachment_ids) + return message.to_dict() + + +@router.get("/chats/{chat_id}/messages", response_model=MessagePage) +async def list_messages( + chat_id: UUID, + user: PublicUser = Depends(get_current_user), + limit: int = Query(default=50, ge=1, le=100), + cursor: str | None = Query(default=None, min_length=1), +) -> dict: + return await messages_for_member(chat_id, user.id, limit, cursor) diff --git a/src/app/api/users.py b/src/app/api/users.py new file mode 100644 index 0000000..72a90b2 --- /dev/null +++ b/src/app/api/users.py @@ -0,0 +1,19 @@ +from fastapi import APIRouter, Depends + +from app.crud.users import create_user +from app.deps import get_current_user +from app.present import PublicUser +from app.schemas.user import CreateUser, UserOut + +router = APIRouter() + + +@router.post("/users", status_code=201, response_model=UserOut) +async def register(body: CreateUser) -> dict: + user = await create_user(body.username, body.display_name, body.password) + return user.to_dict() + + +@router.get("/users/me", response_model=UserOut) +async def me(user: PublicUser = Depends(get_current_user)) -> dict: + return user.to_dict() diff --git a/src/app/broker.py b/src/app/broker.py new file mode 100644 index 0000000..a165540 --- /dev/null +++ b/src/app/broker.py @@ -0,0 +1,57 @@ +import logging + +import aio_pika + +from app.tlsutil import ca_file_from_env, client_context + +logger = logging.getLogger("app.broker") + +EXCHANGE = "attachments" +WORK_QUEUE = "attachment.jobs" +DLQ = "attachment.jobs.dlq" +WORK_KEY = "attachment.process" +DLQ_KEY = "attachment.failed" + + +async def connect(url: str) -> aio_pika.abc.AbstractRobustConnection: + kwargs = {"timeout": 10} + if url.startswith("amqps://"): + ca_file = ca_file_from_env() + if not ca_file: + raise SystemExit("TLS_CA_FILE is required for amqps") + kwargs["ssl_context"] = client_context(ca_file) + return await aio_pika.connect_robust(url, **kwargs) + + +async def declare(channel: aio_pika.abc.AbstractChannel) -> tuple[aio_pika.abc.AbstractExchange, aio_pika.abc.AbstractQueue]: + exchange = await channel.declare_exchange(EXCHANGE, aio_pika.ExchangeType.TOPIC, durable=True) + work = await channel.declare_queue( + WORK_QUEUE, + durable=True, + arguments={ + "x-dead-letter-exchange": EXCHANGE, + "x-dead-letter-routing-key": DLQ_KEY, + }, + ) + await work.bind(exchange, routing_key=WORK_KEY) + dead = await channel.declare_queue(DLQ, durable=True) + await dead.bind(exchange, routing_key=DLQ_KEY) + return exchange, work + + +def job_message(payload: str, headers: dict | None = None) -> aio_pika.Message: + return aio_pika.Message( + body=payload.encode("utf-8"), + delivery_mode=aio_pika.DeliveryMode.PERSISTENT, + content_type="application/json", + headers=headers or {}, + ) + + +async def publish( + exchange: aio_pika.abc.AbstractExchange, + payload: str, + routing_key: str, + headers: dict | None = None, +) -> None: + await exchange.publish(job_message(payload, headers), routing_key=routing_key, mandatory=True) diff --git a/src/app/config.py b/src/app/config.py new file mode 100644 index 0000000..65d40ca --- /dev/null +++ b/src/app/config.py @@ -0,0 +1,228 @@ +import os +import socket +from dataclasses import dataclass +from pathlib import Path + +from app.vault import hydrate_secrets + + +@dataclass(frozen=True) +class Settings: + host: str + port: int + env: str + app_role: str + instance_id: str + run_migrations: bool + session_ttl_seconds: int + idempotency_ttl_seconds: int + database_url: str + cache_url: str + s3_endpoint: str + s3_region: str + s3_bucket: str + s3_access_key_id: str + s3_secret_access_key: str + max_upload_bytes: int + max_image_pixels: int + attachment_gc_grace_seconds: int + migrations_dir: Path + db_pool_size: int + db_max_overflow: int + db_pool_timeout_seconds: float + db_connect_timeout_seconds: float + db_command_timeout_seconds: float + redis_socket_timeout_seconds: float + redis_max_connections: int + broker_url: str + worker_concurrency: int + job_max_attempts: int + job_timeout_seconds: int + job_lease_seconds: int + job_backoff_base_seconds: float + job_backoff_cap_seconds: float + pipeline_version: int + staging_retention_seconds: int + worker_image_memory_bytes: int + jpeg_quality: int + webp_quality: int + webp_method: int + faults_file: str + tls_ca_file: str + tls_cert_file: str + tls_key_file: str + mtls_enabled: bool + mtls_allowed_dns: str + internal_port: int + argon2_memory_kib: int + argon2_iterations: int + argon2_parallelism: int + login_rate_limit: int + login_rate_window_seconds: int + max_json_bytes: int + + +def _int(name: str, default: int, low: int, high: int) -> int: + raw = os.environ.get(name, str(default)).strip() + try: + value = int(raw) + except ValueError as exc: + raise SystemExit(f"{name} must be an integer") from exc + if not low <= value <= high: + raise SystemExit(f"{name} is out of range") + return value + + +def _float(name: str, default: float, low: float, high: float) -> float: + raw = os.environ.get(name, str(default)).strip() + try: + value = float(raw) + except ValueError as exc: + raise SystemExit(f"{name} must be a number") from exc + if not low <= value <= high: + raise SystemExit(f"{name} is out of range") + return value + + +def _secret(direct_name: str, file_name: str) -> str: + direct = os.environ.get(direct_name, "").strip() + if direct: + return direct + path = os.environ.get(file_name, "").strip() + if not path: + raise SystemExit(f"set {direct_name} or {file_name}") + try: + value = Path(path).read_text(encoding="utf-8").strip() + except OSError as exc: + raise SystemExit(f"cannot read {file_name}") from exc + if not value: + raise SystemExit(f"{file_name} is empty") + return value + + +def _migrations_dir() -> Path: + configured = os.environ.get("MIGRATIONS_DIR", "").strip() + if configured: + return Path(configured) + return Path(__file__).resolve().parents[2] / "migrations" + + +def _flag(name: str, default: bool) -> bool: + raw = os.environ.get(name, "1" if default else "0").strip().lower() + if raw in {"1", "true", "yes", "on"}: + return True + if raw in {"0", "false", "no", "off"}: + return False + raise SystemExit(f"{name} must be a boolean") + + +def _instance_id() -> str: + configured = os.environ.get("INSTANCE_ID", "").strip() + if configured: + return configured + host = os.environ.get("HOSTNAME", "").strip() or socket.gethostname() + if not host: + raise SystemExit("INSTANCE_ID is empty") + return host + + +def load_settings() -> Settings: + hydrate_secrets() + host = os.environ.get("APP_HOST", "0.0.0.0").strip() or "0.0.0.0" + env_name = os.environ.get("APP_ENV", "lab").strip() or "lab" + role = os.environ.get("APP_ROLE", "api").strip() or "api" + if role not in {"api", "migrate", "gc", "worker", "relay", "replay"}: + raise SystemExit("APP_ROLE must be api, migrate, gc, worker, relay or replay") + port = _int("APP_PORT", 8080, 1, 65535) + database_url = _secret("DATABASE_URL", "DATABASE_URL_FILE") + if not database_url.startswith("postgresql+asyncpg://"): + raise SystemExit("DATABASE_URL must start with postgresql+asyncpg://") + cache_url = "" + s3_endpoint = "" + s3_region = os.environ.get("S3_REGION", "us-east-1").strip() or "us-east-1" + s3_bucket = os.environ.get("S3_BUCKET", "messenger-attachments").strip() or "messenger-attachments" + s3_access_key_id = "" + s3_secret_access_key = "" + broker_url = "" + if role == "api": + cache_url = _secret("REDIS_URL", "CACHE_URL_FILE") + if not cache_url.startswith(("redis://", "rediss://")): + raise SystemExit("REDIS_URL must start with redis:// or rediss://") + if role in {"api", "gc", "worker"}: + s3_endpoint = os.environ.get("S3_ENDPOINT", "").strip() + if not s3_endpoint: + raise SystemExit("S3_ENDPOINT is required") + s3_access_key_id = _secret("S3_ACCESS_KEY_ID", "S3_ACCESS_KEY_ID_FILE") + s3_secret_access_key = _secret("S3_SECRET_ACCESS_KEY", "S3_SECRET_ACCESS_KEY_FILE") + if role in {"worker", "relay"}: + broker_url = _secret("BROKER_URL", "BROKER_URL_FILE") + if not broker_url.startswith(("amqp://", "amqps://")): + raise SystemExit("BROKER_URL must start with amqp:// or amqps://") + timeout_seconds = _int("JOB_TIMEOUT_SECONDS", 45, 1, 600) + lease_seconds = _int("JOB_LEASE_SECONDS", 90, 2, 3600) + mtls_enabled = _flag("MTLS_ENABLED", False) + internal_port = _int("INTERNAL_PORT", 8080, 1, 65535) + if mtls_enabled and internal_port == port: + raise SystemExit("INTERNAL_PORT must differ from APP_PORT when mTLS is enabled") + argon2_memory_kib = _int("ARGON2_MEMORY_KIB", 19456, 19456, 1048576) + argon2_iterations = _int("ARGON2_ITERATIONS", 2, 2, 16) + argon2_parallelism = _int("ARGON2_PARALLELISM", 1, 1, 8) + if lease_seconds <= timeout_seconds: + raise SystemExit("JOB_LEASE_SECONDS must be greater than JOB_TIMEOUT_SECONDS") + migrations = _migrations_dir() + if not migrations.is_dir(): + raise SystemExit("migrations directory is missing") + return Settings( + host=host, + port=port, + env=env_name, + app_role=role, + instance_id=_instance_id(), + run_migrations=_flag("RUN_MIGRATIONS", True), + session_ttl_seconds=_int("SESSION_TTL_SECONDS", 3600, 1, 30 * 24 * 3600), + idempotency_ttl_seconds=_int("IDEMPOTENCY_TTL_SECONDS", 86400, 60, 30 * 24 * 3600), + database_url=database_url, + cache_url=cache_url, + s3_endpoint=s3_endpoint, + s3_region=s3_region, + s3_bucket=s3_bucket, + s3_access_key_id=s3_access_key_id, + s3_secret_access_key=s3_secret_access_key, + max_upload_bytes=_int("MAX_UPLOAD_BYTES", 10 * 1024 * 1024, 1024, 10 * 1024 * 1024), + max_image_pixels=_int("MAX_IMAGE_PIXELS", 40_000_000, 1, 40_000_000), + attachment_gc_grace_seconds=_int("ATTACHMENT_GC_GRACE_SECONDS", 900, 1, 24 * 3600), + migrations_dir=migrations, + db_pool_size=_int("DB_POOL_SIZE", 10, 1, 50), + db_max_overflow=_int("DB_MAX_OVERFLOW", 10, 0, 50), + db_pool_timeout_seconds=_float("DB_POOL_TIMEOUT_SECONDS", 5, 0.1, 30), + db_connect_timeout_seconds=_float("DB_CONNECT_TIMEOUT_SECONDS", 2, 0.1, 30), + db_command_timeout_seconds=_float("DB_COMMAND_TIMEOUT_SECONDS", 5, 0.1, 60), + redis_socket_timeout_seconds=_float("REDIS_SOCKET_TIMEOUT_SECONDS", 1, 0.1, 30), + redis_max_connections=_int("REDIS_MAX_CONNECTIONS", 50, 1, 200), + broker_url=broker_url, + worker_concurrency=_int("WORKER_CONCURRENCY", 2, 1, 8), + job_max_attempts=_int("JOB_MAX_ATTEMPTS", 5, 1, 20), + job_timeout_seconds=timeout_seconds, + job_lease_seconds=lease_seconds, + job_backoff_base_seconds=_float("JOB_BACKOFF_BASE_SECONDS", 0.4, 0.05, 60), + job_backoff_cap_seconds=_float("JOB_BACKOFF_CAP_SECONDS", 8, 0.1, 300), + pipeline_version=_int("PIPELINE_VERSION", 1, 1, 1000), + staging_retention_seconds=_int("STAGING_RETENTION_SECONDS", 86400, 30, 30 * 24 * 3600), + worker_image_memory_bytes=_int("WORKER_IMAGE_MEMORY_BYTES", 256 * 1024 * 1024, 8 * 1024 * 1024, 1024 * 1024 * 1024), + jpeg_quality=_int("JPEG_QUALITY", 85, 1, 95), + webp_quality=_int("WEBP_QUALITY", 80, 1, 100), + webp_method=_int("WEBP_METHOD", 6, 0, 6), + faults_file=os.environ.get("FAULTS_FILE", "").strip(), + tls_ca_file=os.environ.get("TLS_CA_FILE", "").strip(), + tls_cert_file=os.environ.get("TLS_CERT_FILE", "").strip(), + tls_key_file=os.environ.get("TLS_KEY_FILE", "").strip(), + mtls_enabled=mtls_enabled, + mtls_allowed_dns=os.environ.get("MTLS_ALLOWED_DNS", "lb.lab.internal").strip() or "lb.lab.internal", + internal_port=internal_port, + argon2_memory_kib=argon2_memory_kib, + argon2_iterations=argon2_iterations, + argon2_parallelism=argon2_parallelism, + login_rate_limit=_int("LOGIN_RATE_LIMIT", 10, 1, 1000), + login_rate_window_seconds=_int("LOGIN_RATE_WINDOW_SECONDS", 60, 1, 3600), + max_json_bytes=_int("MAX_JSON_BYTES", 65536, 1024, 1048576), + ) diff --git a/src/app/crud/__init__.py b/src/app/crud/__init__.py new file mode 100644 index 0000000..cbee6a2 --- /dev/null +++ b/src/app/crud/__init__.py @@ -0,0 +1 @@ +"""Чтение и изменение PostgreSQL. Сессии живут в Redis, не в этих таблицах.""" diff --git a/src/app/crud/attachments.py b/src/app/crud/attachments.py new file mode 100644 index 0000000..7b5f434 --- /dev/null +++ b/src/app/crud/attachments.py @@ -0,0 +1,243 @@ +import asyncio +import hashlib +import logging +from datetime import timedelta +from uuid import UUID, uuid4 + +from sqlalchemy import and_, or_, select +from sqlalchemy.exc import IntegrityError + +from app.db import map_integrity, session_scope +from app.errors import AppError +from app.images import declared_content_type, inspect_image +from app.jobs import job_document +from app.models import Attachment, AttachmentJob, AttachmentVariant, ChatMember, JobOutbox +from app.pipeline import variant_names +from app.present import PublicAttachment +from app.runtime import require_settings, require_store +from app.timeutil import utcnow + +logger = logging.getLogger("app.attachments") + +_VARIANT_ORDER = {name: index for index, name in enumerate(variant_names())} + + +def validate_filename(filename: str | None) -> str: + if filename is None or filename.strip() == "": + raise AppError(400, "invalid_request", "Некорректное имя файла") + if len(filename) > 255: + raise AppError(400, "invalid_request", "Некорректное имя файла") + for char in filename: + code = ord(char) + if char in {"/", "\\", "\x00"} or code < 32 or code == 127: + raise AppError(400, "invalid_request", "Некорректное имя файла") + return filename + + +def _variant_dict(row: AttachmentVariant) -> dict: + return { + "name": row.name, + "content_type": row.content_type, + "size_bytes": row.size_bytes, + "width": row.width, + "height": row.height, + "sha256": row.sha256, + } + + +def _public(row: Attachment, variants: list[dict] | None = None) -> PublicAttachment: + visible = tuple(variants or ()) if row.status == "ready" else () + return PublicAttachment( + id=row.id, + chat_id=row.chat_id, + owner_id=row.owner_id, + filename=row.filename, + content_type=row.content_type, + size_bytes=row.size_bytes, + sha256=row.sha256, + status=row.status, + variants=visible, + error_code=row.error_code, + created_at=row.created_at, + updated_at=row.updated_at, + ) + + +async def _require_member(session, chat_id: UUID, user_id: UUID) -> None: + member = await session.scalar( + select(ChatMember.user_id).where(ChatMember.chat_id == chat_id, ChatMember.user_id == user_id) + ) + if member is None: + raise AppError(404, "not_found", "Объект не найден") + + +async def _variants_for(session, attachment_id: UUID) -> list[dict]: + rows = ( + await session.scalars(select(AttachmentVariant).where(AttachmentVariant.attachment_id == attachment_id)) + ).all() + payload = [_variant_dict(row) for row in rows] + payload.sort(key=lambda item: _VARIANT_ORDER.get(item["name"], 9)) + return payload + + +async def create_attachment( + chat_id: UUID, + owner_id: UUID, + filename: str, + content_type_header: str | None, + payload: bytes, +) -> PublicAttachment: + settings = require_settings() + store = require_store() + filename = validate_filename(filename) + declared = declared_content_type(content_type_header) + if not payload: + raise AppError(415, "unsupported_media_type", "Неподдерживаемый тип изображения") + if len(payload) > settings.max_upload_bytes: + raise AppError(413, "payload_too_large", "Файл слишком большой") + async with session_scope() as session: + async with session.begin(): + await _require_member(session, chat_id, owner_id) + await asyncio.to_thread(inspect_image, payload, declared, settings.max_image_pixels) + digest = hashlib.sha256(payload).hexdigest() + attachment_id = uuid4() + job_id = uuid4() + staging_key = "staging/%s" % attachment_id + object_key = "att/%s/original" % attachment_id + created_at = utcnow() + await store.put(staging_key, payload, declared) + try: + async with session_scope() as session: + try: + async with session.begin(): + await _require_member(session, chat_id, owner_id) + session.add( + Attachment( + id=attachment_id, + chat_id=chat_id, + owner_id=owner_id, + filename=filename, + content_type=declared, + size_bytes=len(payload), + sha256=digest, + object_key=object_key, + staging_key=staging_key, + status="queued", + error_code=None, + created_at=created_at, + updated_at=created_at, + ) + ) + await session.flush() + session.add( + AttachmentJob( + job_id=job_id, + attachment_id=attachment_id, + pipeline_version=settings.pipeline_version, + status="queued", + attempt=0, + max_attempts=settings.job_max_attempts, + staging_key=staging_key, + objects_written_at=None, + created_at=created_at, + updated_at=created_at, + ) + ) + await session.flush() + session.add( + JobOutbox( + id=uuid4(), + job_id=job_id, + payload=job_document(job_id, attachment_id, settings.pipeline_version, 1, created_at), + available_at=created_at, + created_at=created_at, + published_at=None, + publish_attempts=0, + gap_injected=False, + ) + ) + await session.flush() + except IntegrityError as exc: + raise map_integrity(exc, "Конфликт записи") from None + except Exception: + await store.delete(staging_key) + raise + return PublicAttachment( + id=attachment_id, + chat_id=chat_id, + owner_id=owner_id, + filename=filename, + content_type=declared, + size_bytes=len(payload), + sha256=digest, + status="queued", + variants=(), + error_code=None, + created_at=created_at, + updated_at=created_at, + ) + + +async def metadata_for_member(attachment_id: UUID, user_id: UUID) -> PublicAttachment: + async with session_scope() as session: + async with session.begin(): + row = await session.get(Attachment, attachment_id) + if row is None: + raise AppError(404, "not_found", "Объект не найден") + await _require_member(session, row.chat_id, user_id) + variants = await _variants_for(session, row.id) if row.status == "ready" else [] + return _public(row, variants) + + +async def open_content(attachment_id: UUID, user_id: UUID, variant: str) -> tuple[str, str]: + if variant not in {"original", "thumbnail", "crop", "optimized"}: + raise AppError(400, "invalid_request", "Некорректный запрос") + async with session_scope() as session: + async with session.begin(): + row = await session.get(Attachment, attachment_id) + if row is None: + raise AppError(404, "not_found", "Объект не найден") + await _require_member(session, row.chat_id, user_id) + if row.status != "ready": + raise AppError(409, "conflict", "Вложение ещё не готово") + if variant == "original": + return row.object_key, row.content_type + found = await session.scalar( + select(AttachmentVariant).where( + AttachmentVariant.attachment_id == row.id, + AttachmentVariant.name == variant, + ) + ) + if found is None: + raise AppError(404, "not_found", "Объект не найден") + return found.object_key, found.content_type + + +async def known_object_keys() -> set[str]: + settings = require_settings() + retain_after = utcnow() - timedelta(seconds=settings.staging_retention_seconds) + async with session_scope() as session: + async with session.begin(): + keys = set((await session.scalars(select(Attachment.object_key))).all()) + keys.update((await session.scalars(select(AttachmentVariant.object_key))).all()) + staging_jobs = ( + await session.scalars( + select(AttachmentJob.staging_key).where( + or_( + AttachmentJob.status.in_(("queued", "processing")), + and_(AttachmentJob.status == "failed", AttachmentJob.updated_at > retain_after), + ) + ) + ) + ).all() + keys.update(staging_jobs) + staging_rows = ( + await session.scalars( + select(Attachment.staging_key).where( + Attachment.staging_key.is_not(None), + Attachment.status.in_(("queued", "processing")), + ) + ) + ).all() + keys.update(key for key in staging_rows if key) + return keys diff --git a/src/app/crud/chats.py b/src/app/crud/chats.py new file mode 100644 index 0000000..5bd42e9 --- /dev/null +++ b/src/app/crud/chats.py @@ -0,0 +1,101 @@ +from uuid import UUID, uuid4 + +from sqlalchemy import select, tuple_ +from sqlalchemy.exc import IntegrityError + +from app.db import map_integrity, session_scope +from app.errors import AppError +from app.models import Chat, ChatMember, User +from app.pagination import decode_position, slice_page +from app.present import PublicChat +from app.timeutil import utcnow + + +def _invalid_members() -> AppError: + return AppError(400, "invalid_request", "Некорректный список участников") + + +async def create_chat( + owner_id: UUID, + title: str, + member_ids: tuple[UUID, ...], + *, + fail_after_insert: bool = False, +) -> PublicChat: + if ( + not member_ids + or len(member_ids) > 100 + or len(set(member_ids)) != len(member_ids) + or owner_id not in member_ids + ): + raise _invalid_members() + chat_id = uuid4() + created_at = utcnow() + async with session_scope() as session: + try: + async with session.begin(): + found = set((await session.scalars(select(User.id).where(User.id.in_(member_ids)))).all()) + if found != set(member_ids): + raise _invalid_members() + session.add(Chat(id=chat_id, title=title, created_at=created_at)) + await session.flush() + # Точка для проверки отката: строка чата уже вставлена, COMMIT ещё нет. + if fail_after_insert: + raise RuntimeError("rollback-check") + for ordinal, member_id in enumerate(member_ids): + session.add(ChatMember(chat_id=chat_id, user_id=member_id, ordinal=ordinal)) + await session.flush() + except IntegrityError as exc: + raise map_integrity(exc, "Конфликт записи") from None + return PublicChat(id=chat_id, title=title, member_ids=tuple(member_ids), created_at=created_at) + + +async def _member_ids(session, chat_id: UUID) -> tuple[UUID, ...]: + rows = await session.execute( + select(ChatMember.user_id).where(ChatMember.chat_id == chat_id).order_by(ChatMember.ordinal) + ) + return tuple(row[0] for row in rows) + + +async def chat_for_member(chat_id: UUID, user_id: UUID) -> PublicChat: + async with session_scope() as session: + async with session.begin(): + member = await session.scalar( + select(ChatMember.user_id).where(ChatMember.chat_id == chat_id, ChatMember.user_id == user_id) + ) + chat = await session.get(Chat, chat_id) + if member is None or chat is None: + raise AppError(404, "not_found", "Объект не найден") + return PublicChat( + id=chat.id, + title=chat.title, + member_ids=await _member_ids(session, chat.id), + created_at=chat.created_at, + ) + + +async def chats_for_user(user_id: UUID, limit: int, cursor: str | None) -> dict: + position = decode_position(cursor, "c", user_id) if cursor else None + async with session_scope() as session: + async with session.begin(): + stmt = ( + select(Chat) + .join(ChatMember, ChatMember.chat_id == Chat.id) + .where(ChatMember.user_id == user_id) + ) + if position is not None: + created_at, cursor_id = position + stmt = stmt.where(tuple_(Chat.created_at, Chat.id) > tuple_(created_at, cursor_id)) + stmt = stmt.order_by(Chat.created_at.asc(), Chat.id.asc()).limit(limit + 1) + chats = (await session.scalars(stmt)).unique().all() + public = [] + for chat in chats: + public.append( + PublicChat( + id=chat.id, + title=chat.title, + member_ids=await _member_ids(session, chat.id), + created_at=chat.created_at, + ) + ) + return slice_page(public, limit, "c", user_id) diff --git a/src/app/crud/messages.py b/src/app/crud/messages.py new file mode 100644 index 0000000..b93563c --- /dev/null +++ b/src/app/crud/messages.py @@ -0,0 +1,196 @@ +import hashlib +import json +from datetime import timedelta +from uuid import UUID, uuid4 + +from sqlalchemy import delete, select, text, tuple_ +from sqlalchemy.exc import IntegrityError + +from app.db import map_integrity, session_scope +from app.errors import AppError +from app.models import Attachment, ChatMember, IdempotencyRecord, Message, MessageAttachment +from app.pagination import decode_position, slice_page +from app.present import PublicMessage +from app.runtime import require_settings +from app.timeutil import utcnow + + +def message_path(chat_id: UUID) -> str: + return "/api/v1/chats/%s/messages" % chat_id + + +def request_fingerprint(text_value: str, attachment_ids: list[UUID]) -> str: + payload = json.dumps( + { + "attachment_ids": [str(item) for item in attachment_ids], + "text": text_value, + }, + ensure_ascii=False, + separators=(",", ":"), + sort_keys=True, + ) + return hashlib.sha256(payload.encode("utf-8")).hexdigest() + + +def _lock_keys(scope: str) -> tuple[int, int]: + digest = hashlib.sha256(scope.encode("utf-8")).digest() + first = int.from_bytes(digest[:4], "big", signed=True) + second = int.from_bytes(digest[4:8], "big", signed=True) + return first, second + + +def _public(row: Message, attachment_ids: list[UUID]) -> PublicMessage: + return PublicMessage( + id=row.id, + chat_id=row.chat_id, + sender_id=row.sender_id, + text=row.text, + created_at=row.created_at, + attachment_ids=tuple(attachment_ids), + ) + + +async def _require_member(session, chat_id: UUID, user_id: UUID) -> None: + member = await session.scalar( + select(ChatMember.user_id).where(ChatMember.chat_id == chat_id, ChatMember.user_id == user_id) + ) + if member is None: + raise AppError(404, "not_found", "Объект не найден") + + +async def _attachment_map(session, message_ids: list[UUID]) -> dict[UUID, list[UUID]]: + grouped: dict[UUID, list[UUID]] = {message_id: [] for message_id in message_ids} + if not message_ids: + return grouped + rows = ( + await session.execute( + select(MessageAttachment.message_id, MessageAttachment.attachment_id) + .where(MessageAttachment.message_id.in_(message_ids)) + .order_by(MessageAttachment.message_id, MessageAttachment.ordinal) + ) + ).all() + for message_id, attachment_id in rows: + grouped.setdefault(message_id, []).append(attachment_id) + return grouped + + +async def create_message( + chat_id: UUID, + sender_id: UUID, + text_value: str, + idempotency_key: str, + attachment_ids: list[UUID] | None = None, +) -> PublicMessage: + settings = require_settings() + files = list(attachment_ids or []) + path = message_path(chat_id) + request_hash = request_fingerprint(text_value, files) + lock_a, lock_b = _lock_keys("POST:%s:%s:%s" % (sender_id, path, idempotency_key)) + ttl = timedelta(seconds=settings.idempotency_ttl_seconds) + async with session_scope() as session: + try: + async with session.begin(): + await session.execute( + text("SELECT pg_advisory_xact_lock(:a, :b)"), + {"a": lock_a, "b": lock_b}, + ) + await _require_member(session, chat_id, sender_id) + if files: + found = ( + await session.scalars(select(Attachment).where(Attachment.id.in_(files))) + ).all() + by_id = {row.id: row for row in found} + if len(by_id) != len(files): + raise AppError(404, "not_found", "Объект не найден") + for item in files: + row = by_id[item] + if row.chat_id != chat_id: + raise AppError(404, "not_found", "Объект не найден") + if row.status == "failed": + raise AppError(409, "conflict", "Вложение недоступно") + existing = await session.scalar( + select(IdempotencyRecord).where( + IdempotencyRecord.user_id == sender_id, + IdempotencyRecord.method == "POST", + IdempotencyRecord.request_path == path, + IdempotencyRecord.idempotency_key == idempotency_key, + ) + ) + now = utcnow() + if existing is not None and existing.created_at + ttl >= now: + if existing.request_hash != request_hash: + raise AppError(409, "conflict", "Повтор ключа с другим сообщением") + row = await session.get(Message, existing.message_id) + if row is None: + raise AppError(500, "internal_error", "Внутренняя ошибка") + mapping = await _attachment_map(session, [row.id]) + return _public(row, mapping.get(row.id, [])) + if existing is not None: + await session.execute( + delete(IdempotencyRecord).where( + IdempotencyRecord.user_id == existing.user_id, + IdempotencyRecord.method == existing.method, + IdempotencyRecord.request_path == existing.request_path, + IdempotencyRecord.idempotency_key == existing.idempotency_key, + ) + ) + await session.flush() + message_id = uuid4() + created_at = now + session.add( + Message( + id=message_id, + chat_id=chat_id, + sender_id=sender_id, + text=text_value, + created_at=created_at, + ) + ) + await session.flush() + for ordinal, attachment_id in enumerate(files): + session.add( + MessageAttachment( + message_id=message_id, + attachment_id=attachment_id, + ordinal=ordinal, + ) + ) + session.add( + IdempotencyRecord( + user_id=sender_id, + method="POST", + request_path=path, + idempotency_key=idempotency_key, + request_hash=request_hash, + status_code=201, + message_id=message_id, + created_at=created_at, + ) + ) + await session.flush() + except IntegrityError as exc: + raise map_integrity(exc, "Конфликт записи") from None + return PublicMessage( + id=message_id, + chat_id=chat_id, + sender_id=sender_id, + text=text_value, + created_at=created_at, + attachment_ids=tuple(files), + ) + + +async def messages_for_member(chat_id: UUID, user_id: UUID, limit: int, cursor: str | None) -> dict: + async with session_scope() as session: + async with session.begin(): + await _require_member(session, chat_id, user_id) + position = decode_position(cursor, "m", chat_id) if cursor else None + stmt = select(Message).where(Message.chat_id == chat_id) + if position is not None: + created_at, message_id = position + stmt = stmt.where(tuple_(Message.created_at, Message.id) > tuple_(created_at, message_id)) + stmt = stmt.order_by(Message.created_at.asc(), Message.id.asc()).limit(limit + 1) + rows = (await session.scalars(stmt)).all() + mapping = await _attachment_map(session, [row.id for row in rows]) + public = [_public(row, mapping.get(row.id, [])) for row in rows] + return slice_page(public, limit, "m", chat_id) diff --git a/src/app/crud/users.py b/src/app/crud/users.py new file mode 100644 index 0000000..884381f --- /dev/null +++ b/src/app/crud/users.py @@ -0,0 +1,78 @@ +import re +from uuid import UUID, uuid4 + +from sqlalchemy import select +from sqlalchemy.exc import IntegrityError + +from app.db import map_integrity, session_scope +from app.models import User +from app.present import PublicUser +from app.security import hash_password, verify_password +from app.timeutil import utcnow + +_USERNAME = re.compile(r"^[a-z0-9_]{3,32}$") + + +async def get_user(user_id: UUID) -> PublicUser | None: + async with session_scope() as session: + async with session.begin(): + row = ( + await session.execute( + select(User.id, User.username, User.display_name, User.created_at).where(User.id == user_id) + ) + ).one_or_none() + if row is None: + return None + return PublicUser(id=row.id, username=row.username, display_name=row.display_name, created_at=row.created_at) + + +async def create_user(username: str, display_name: str, password: str) -> PublicUser: + # Argon2 считается до открытия транзакции, чтобы не держать соединение пула. + password_hash = hash_password(password) + user_id = uuid4() + created_at = utcnow() + async with session_scope() as session: + try: + async with session.begin(): + session.add( + User( + id=user_id, + username=username, + display_name=display_name, + password_hash=password_hash, + created_at=created_at, + ) + ) + await session.flush() + except IntegrityError as exc: + raise map_integrity(exc, "Имя пользователя занято") from None + return PublicUser(id=user_id, username=username, display_name=display_name, created_at=created_at) + + +async def authenticate(username: str, password: str) -> PublicUser | None: + if _USERNAME.fullmatch(username) is None or not 12 <= len(password) <= 128: + verify_password("rejected-credential", None) + return None + async with session_scope() as session: + async with session.begin(): + row = ( + await session.execute( + select(User.id, User.username, User.display_name, User.created_at, User.password_hash).where( + User.username == username + ) + ) + ).one_or_none() + if row is None: + stored = None + snapshot = None + else: + stored = row.password_hash + snapshot = PublicUser( + id=row.id, + username=row.username, + display_name=row.display_name, + created_at=row.created_at, + ) + if not verify_password(password, stored): + return None + return snapshot diff --git a/src/app/db.py b/src/app/db.py new file mode 100644 index 0000000..d0235ae --- /dev/null +++ b/src/app/db.py @@ -0,0 +1,83 @@ +import logging +from contextlib import asynccontextmanager + +from redis.exceptions import RedisError +from sqlalchemy.exc import DBAPIError, IntegrityError, InterfaceError, OperationalError +from sqlalchemy.exc import TimeoutError as SATimeout +from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker, create_async_engine + +from app.config import Settings +from app.errors import AppError +from app.tlsutil import client_context + +logger = logging.getLogger("app.db") + + +def build_engine(settings: Settings) -> AsyncEngine: + command_ms = str(int(settings.db_command_timeout_seconds * 1000)) + lock_ms = str(int(settings.db_pool_timeout_seconds * 1000)) + connect_args = { + "timeout": settings.db_connect_timeout_seconds, + "command_timeout": settings.db_command_timeout_seconds, + "server_settings": { + "statement_timeout": command_ms, + "lock_timeout": lock_ms, + "idle_in_transaction_session_timeout": "10000", + }, + } + if settings.tls_ca_file: + connect_args["ssl"] = client_context(settings.tls_ca_file) + return create_async_engine( + settings.database_url, + pool_size=settings.db_pool_size, + max_overflow=settings.db_max_overflow, + pool_timeout=settings.db_pool_timeout_seconds, + pool_pre_ping=True, + pool_recycle=1800, + echo=False, + connect_args=connect_args, + ) + + +def build_session_factory(engine: AsyncEngine) -> async_sessionmaker[AsyncSession]: + return async_sessionmaker(engine, expire_on_commit=False, autoflush=False) + + +def is_dependency_error(exc: BaseException) -> bool: + if isinstance(exc, (OperationalError, InterfaceError, SATimeout, RedisError, ConnectionError, TimeoutError)): + return True + return isinstance(exc, DBAPIError) and bool(getattr(exc, "connection_invalidated", False)) + + +def map_integrity(exc: IntegrityError, duplicate_message: str) -> AppError: + orig = getattr(exc, "orig", None) + code = getattr(orig, "sqlstate", None) or getattr(orig, "pgcode", None) + if code == "23505": + return AppError(409, "conflict", duplicate_message) + if code in {"23503", "23514", "23502"}: + return AppError(400, "invalid_request", "Некорректный запрос") + return AppError(500, "internal_error", "Внутренняя ошибка") + + +@asynccontextmanager +async def session_scope(): + from app.runtime import require_factory + + factory = require_factory() + try: + session = factory() + except Exception as exc: + if is_dependency_error(exc): + logger.warning("database unavailable type=%s", type(exc).__name__) + raise AppError(503, "unavailable", "Сервис временно недоступен") from None + raise + try: + async with session: + yield session + except AppError: + raise + except Exception as exc: + if is_dependency_error(exc): + logger.warning("database unavailable type=%s", type(exc).__name__) + raise AppError(503, "unavailable", "Сервис временно недоступен") from None + raise diff --git a/src/app/deps.py b/src/app/deps.py new file mode 100644 index 0000000..7fdf11c --- /dev/null +++ b/src/app/deps.py @@ -0,0 +1,50 @@ +from fastapi import Depends, Header, Request +from app.crud.users import get_user +from app.errors import AppError +from app.present import PublicUser +from app.sessions import resolve_session + +BEARER_CHALLENGE = 'Bearer realm="messenger"' +BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"' + + +def unauthorized(challenge: str) -> AppError: + return AppError( + 401, + "unauthorized", + "Требуется идентификация", + headers={"WWW-Authenticate": challenge}, + ) + + +async def get_current_user( + request: Request, + authorization: str | None = Header(default=None), +) -> PublicUser: + # Нет заголовка — клиент анонимный. Redis для этого не нужен и не делает его доверенным. + if authorization is None: + raise unauthorized(BEARER_CHALLENGE) + scheme, _, token = authorization.partition(" ") + token = token.strip() + if scheme.lower() != "bearer" or not token or len(token) > 512: + raise unauthorized(BEARER_CHALLENGE) + user_id = await resolve_session(token) + if user_id is None: + raise unauthorized(BEARER_CHALLENGE) + user = await get_user(user_id) + if user is None: + raise unauthorized(BEARER_CHALLENGE) + request.state.session_token = token + return user + + +def current_token(request: Request) -> str: + token = getattr(request.state, "session_token", "") + if not token: + raise unauthorized(BEARER_CHALLENGE) + return token + + +def require_token(request: Request, user: PublicUser = Depends(get_current_user)) -> str: + del user + return current_token(request) diff --git a/src/app/errors.py b/src/app/errors.py new file mode 100644 index 0000000..c0785a1 --- /dev/null +++ b/src/app/errors.py @@ -0,0 +1,54 @@ +import logging + +from fastapi import Request +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse +from starlette.exceptions import HTTPException + + +class AppError(Exception): + def __init__(self, status: int, code: str, message: str, headers: dict | None = None) -> None: + super().__init__(message) + self.status = status + self.code = code + self.message = message + self.headers = headers + + +def request_id_of(request: Request) -> str: + return getattr(request.state, "request_id", "") or "missing" + + +def error_response( + status: int, + code: str, + message: str, + request_id: str, + headers: dict | None = None, +) -> JSONResponse: + return JSONResponse( + status_code=status, + content={"error": {"code": code, "message": message, "request_id": request_id}}, + headers=headers, + ) + + +async def handle_app_error(request: Request, exc: AppError) -> JSONResponse: + return error_response(exc.status, exc.code, exc.message, request_id_of(request), exc.headers) + + +async def handle_dependency(request: Request, exc: Exception) -> JSONResponse: + # Текст исключения может содержать SQL или параметры. В ответ и лог его не кладём. + logging.getLogger("app").warning("dependency unavailable type=%s", type(exc).__name__) + return error_response(503, "unavailable", "Сервис временно недоступен", request_id_of(request)) + + +async def handle_validation_error(request: Request, _exc: RequestValidationError) -> JSONResponse: + return error_response(400, "invalid_request", "Некорректный запрос", request_id_of(request)) + + +async def handle_http_error(request: Request, exc: HTTPException) -> JSONResponse: + # Тело не в UTF-8 FastAPI превращает в HTTPException 400 с полем detail. + if exc.status_code == 400: + return error_response(400, "invalid_request", "Некорректный запрос", request_id_of(request)) + return JSONResponse(status_code=exc.status_code, content={"detail": exc.detail}, headers=exc.headers) diff --git a/src/app/faults.py b/src/app/faults.py new file mode 100644 index 0000000..3491117 --- /dev/null +++ b/src/app/faults.py @@ -0,0 +1,45 @@ +import json +from dataclasses import dataclass +from pathlib import Path + + +@dataclass(frozen=True) +class Faults: + inject_transient: bool = False + crash_after_s3: bool = False + relay_exit_before_publish: bool = False + stall_seconds: float = 0 + timeout_seconds: float = 0 + + +def read_faults(path: str) -> Faults: + if not path: + return Faults() + file = Path(path) + if not file.is_file(): + return Faults() + try: + raw = json.loads(file.read_text(encoding="utf-8")) + except (OSError, ValueError, UnicodeError): + return Faults() + if not isinstance(raw, dict): + return Faults() + + def flag(name: str) -> bool: + return bool(raw.get(name)) + + def number(name: str) -> float: + value = raw.get(name, 0) + if isinstance(value, bool) or not isinstance(value, (int, float)): + return 0 + if value < 0: + return 0 + return float(value) + + return Faults( + inject_transient=flag("inject_transient"), + crash_after_s3=flag("crash_after_s3"), + relay_exit_before_publish=flag("relay_exit_before_publish"), + stall_seconds=number("stall_seconds"), + timeout_seconds=number("timeout_seconds"), + ) diff --git a/src/app/gc.py b/src/app/gc.py new file mode 100644 index 0000000..970d162 --- /dev/null +++ b/src/app/gc.py @@ -0,0 +1,66 @@ +import asyncio +import logging +import os +import sys +from datetime import timedelta + +from app.config import load_settings +from app.crud.attachments import known_object_keys +from app.db import build_engine, build_session_factory +from app.migrate import wait_for_database, wait_for_schema +from app.runtime import configure +from app.s3 import build_store +from app.timeutil import utcnow + +logger = logging.getLogger("app.gc") + + +async def sweep_once() -> int: + settings = load_settings() + store = build_store(settings) + engine = build_engine(settings) + try: + await wait_for_database(engine) + await wait_for_schema(engine, settings.migrations_dir) + configure(build_session_factory(engine), None, settings, store) + cutoff = utcnow() - timedelta(seconds=settings.attachment_gc_grace_seconds) + known = await known_object_keys() + deleted = 0 + for key, modified in await store.list_objects(): + if key in known or modified > cutoff: + continue + await store.delete(key) + deleted += 1 + if deleted: + logger.info("orphan objects deleted count=%s", deleted) + return deleted + finally: + await engine.dispose() + + +async def run_loop() -> None: + settings = load_settings() + interval = min(60, max(15, settings.attachment_gc_grace_seconds // 6)) + while True: + try: + await sweep_once() + except Exception as exc: + logger.warning("gc sweep failed type=%s", type(exc).__name__) + await asyncio.sleep(interval) + + +def main() -> None: + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s %(levelname)s %(name)s %(message)s", + stream=sys.stdout, + force=True, + ) + if os.environ.get("GC_ONCE", "").strip() in {"1", "true", "yes"}: + asyncio.run(sweep_once()) + return + asyncio.run(run_loop()) + + +if __name__ == "__main__": + main() diff --git a/src/app/images.py b/src/app/images.py new file mode 100644 index 0000000..0a2f4b6 --- /dev/null +++ b/src/app/images.py @@ -0,0 +1,53 @@ +import io +from dataclasses import dataclass + +from PIL import Image, ImageFile, UnidentifiedImageError + +from app.errors import AppError + +ImageFile.LOAD_TRUNCATED_IMAGES = False + +_PNG = b"\x89PNG\r\n\x1a\n" +_JPEG = b"\xff\xd8\xff" + + +@dataclass(frozen=True) +class ImageMeta: + content_type: str + + +def declared_content_type(header: str | None) -> str: + value = (header or "").split(";", 1)[0].strip().lower() + if value in {"image/png", "image/jpeg"}: + return value + raise AppError(415, "unsupported_media_type", "Неподдерживаемый тип изображения") + + +def sniff_content_type(data: bytes) -> str | None: + if data.startswith(_PNG): + return "image/png" + if data.startswith(_JPEG): + return "image/jpeg" + return None + + +def inspect_image(data: bytes, declared: str, max_pixels: int) -> ImageMeta: + sniffed = sniff_content_type(data) + if sniffed is None or sniffed != declared: + raise AppError(415, "unsupported_media_type", "Неподдерживаемый тип изображения") + Image.MAX_IMAGE_PIXELS = max_pixels + try: + with Image.open(io.BytesIO(data)) as image: + width, height = image.size + if width < 1 or height < 1: + raise AppError(415, "unsupported_media_type", "Неподдерживаемый тип изображения") + if width * height > max_pixels: + raise AppError(413, "payload_too_large", "Слишком большое изображение") + image.verify() + except AppError: + raise + except Image.DecompressionBombError: + raise AppError(413, "payload_too_large", "Слишком большое изображение") from None + except (UnidentifiedImageError, OSError, ValueError, SyntaxError): + raise AppError(415, "unsupported_media_type", "Неподдерживаемый тип изображения") from None + return ImageMeta(content_type=declared) diff --git a/src/app/jobs.py b/src/app/jobs.py new file mode 100644 index 0000000..eb81c0a --- /dev/null +++ b/src/app/jobs.py @@ -0,0 +1,428 @@ +import json +import logging +import random +from dataclasses import dataclass +from datetime import datetime, timedelta +from uuid import UUID, uuid4 + +from sqlalchemy import select + +from app.db import session_scope +from app.models import Attachment, AttachmentJob, AttachmentVariant, JobFailure, JobOutbox, JobReplay +from app.pipeline import variant_names +from app.runtime import require_settings +from app.timeutil import format_time, utcnow + +logger = logging.getLogger("app.jobs") + +REQUIRED_VARIANTS = set(variant_names()) + + +@dataclass(frozen=True) +class AcquireResult: + action: str + job_id: UUID | None = None + attachment_id: UUID | None = None + pipeline_version: int = 1 + attempt: int = 0 + max_attempts: int = 1 + staging_key: str = "" + object_key: str = "" + content_type: str = "" + sha256: str = "" + size_bytes: int = 0 + objects_written_at: datetime | None = None + + +def backoff_seconds(attempt: int, base: float, cap: float) -> float: + delay = base * (2 ** min(max(attempt - 1, 0), 8)) + if delay > cap: + delay = cap + total = delay + random.uniform(0, base) + if total > cap: + return cap + return total + + +def job_document(job_id: UUID, attachment_id: UUID, pipeline_version: int, attempt: int, created_at: datetime) -> str: + body = { + "schema_version": 1, + "job_id": str(job_id), + "type": "attachment.process.v1", + "attachment_id": str(attachment_id), + "pipeline_version": pipeline_version, + "attempt": max(1, attempt), + "created_at": format_time(created_at), + } + from app.telemetry import current_trace_fields + + body.update(current_trace_fields()) + return json.dumps(body, separators=(",", ":"), sort_keys=True) + + +def _outbox(job: AttachmentJob, when: datetime, attempt: int) -> JobOutbox: + return JobOutbox( + id=uuid4(), + job_id=job.job_id, + payload=job_document(job.job_id, job.attachment_id, job.pipeline_version, attempt, job.created_at), + available_at=when, + created_at=when, + published_at=None, + publish_attempts=0, + gap_injected=False, + ) + + +def _failure(job: AttachmentJob, code: str, permanent: bool, when: datetime) -> JobFailure: + return JobFailure( + id=uuid4(), + job_id=job.job_id, + attachment_id=job.attachment_id, + attempt=job.attempt, + error_code=code, + permanent=permanent, + created_at=when, + ) + + +async def _variant_names(session, attachment_id: UUID) -> set[str]: + rows = ( + await session.scalars(select(AttachmentVariant.name).where(AttachmentVariant.attachment_id == attachment_id)) + ).all() + return set(rows) + + +async def acquire_job(job_id: UUID, owner: str, redelivered: bool) -> AcquireResult: + settings = require_settings() + now = utcnow() + until = now + timedelta(seconds=settings.job_lease_seconds) + async with session_scope() as session: + async with session.begin(): + job = await session.get(AttachmentJob, job_id, with_for_update=True) + if job is None: + return AcquireResult(action="missing") + attachment = await session.get(Attachment, job.attachment_id, with_for_update=True) + if attachment is None: + return AcquireResult(action="missing") + if attachment.status == "ready" or job.status == "ready": + job.status = "ready" + job.lease_until = None + job.lease_owner = None + job.error_code = None + job.updated_at = now + if attachment.status != "ready": + attachment.status = "ready" + attachment.error_code = None + attachment.updated_at = now + return AcquireResult(action="ready", job_id=job.job_id, attachment_id=attachment.id) + if job.status == "failed" or attachment.status == "failed": + return AcquireResult(action="failed", job_id=job.job_id, attachment_id=attachment.id) + if job.status == "queued" and job.attempt >= job.max_attempts: + code = "retry_exhausted" + job.status = "failed" + job.error_code = code + job.lease_until = None + job.lease_owner = None + job.updated_at = now + attachment.status = "failed" + attachment.error_code = code + attachment.updated_at = now + session.add(_failure(job, code, True, now)) + return AcquireResult(action="failed", job_id=job.job_id, attachment_id=attachment.id) + held = ( + job.status == "processing" + and job.lease_owner + and job.lease_owner != owner + and job.lease_until is not None + and job.lease_until > now + and not redelivered + ) + if held: + return AcquireResult(action="busy", job_id=job.job_id, attachment_id=attachment.id) + if job.status == "queued": + job.attempt += 1 + job.status = "processing" + job.lease_until = until + job.lease_owner = owner + job.updated_at = now + attachment.status = "processing" + attachment.error_code = None + attachment.updated_at = now + return AcquireResult( + action="acquired", + job_id=job.job_id, + attachment_id=attachment.id, + pipeline_version=job.pipeline_version, + attempt=job.attempt, + max_attempts=job.max_attempts, + staging_key=job.staging_key, + object_key=attachment.object_key, + content_type=attachment.content_type, + sha256=attachment.sha256, + size_bytes=attachment.size_bytes, + objects_written_at=job.objects_written_at, + ) + + +async def mark_objects_written(job_id: UUID) -> None: + now = utcnow() + async with session_scope() as session: + async with session.begin(): + job = await session.get(AttachmentJob, job_id, with_for_update=True) + if job is None or job.objects_written_at is not None: + return + job.objects_written_at = now + job.updated_at = now + + +async def fail_or_retry(job_id: UUID, code: str, permanent: bool) -> str: + settings = require_settings() + now = utcnow() + async with session_scope() as session: + async with session.begin(): + job = await session.get(AttachmentJob, job_id, with_for_update=True) + if job is None or job.status == "ready": + return "ignored" + attachment = await session.get(Attachment, job.attachment_id, with_for_update=True) + if attachment is None or attachment.status == "ready": + return "ignored" + terminal = permanent or job.attempt >= job.max_attempts + final_code = code if permanent else "retry_exhausted" + session.add(_failure(job, final_code if terminal else code, terminal, now)) + job.lease_until = None + job.lease_owner = None + job.updated_at = now + if terminal: + job.status = "failed" + job.error_code = final_code + attachment.status = "failed" + attachment.error_code = final_code + attachment.updated_at = now + payload = job_document(job.job_id, job.attachment_id, job.pipeline_version, max(1, job.attempt), job.created_at) + return "failed:" + payload + delay = backoff_seconds(job.attempt, settings.job_backoff_base_seconds, settings.job_backoff_cap_seconds) + job.status = "queued" + job.error_code = None + job.next_attempt_at = now + timedelta(seconds=delay) + attachment.status = "queued" + attachment.error_code = None + attachment.updated_at = now + session.add(_outbox(job, job.next_attempt_at, job.attempt + 1)) + logger.info( + "job retry scheduled job_id=%s attempt=%s backoff_seconds=%.3f", + job.job_id, + job.attempt, + delay, + ) + return "retry" + + +async def finalize_job(job_id: UUID, variants: list[dict]) -> str: + now = utcnow() + async with session_scope() as session: + async with session.begin(): + job = await session.get(AttachmentJob, job_id, with_for_update=True) + if job is None: + return "missing" + attachment = await session.get(Attachment, job.attachment_id, with_for_update=True) + if attachment is None: + return "missing" + if job.status == "ready" and attachment.status == "ready": + return "already" + for item in variants: + existing = await session.scalar( + select(AttachmentVariant).where( + AttachmentVariant.attachment_id == attachment.id, + AttachmentVariant.name == item["name"], + ) + ) + if existing is not None and existing.pipeline_version > job.pipeline_version: + continue + if existing is None: + session.add( + AttachmentVariant( + attachment_id=attachment.id, + name=item["name"], + content_type=item["content_type"], + size_bytes=item["size_bytes"], + width=item["width"], + height=item["height"], + sha256=item["sha256"], + object_key=item["object_key"], + pipeline_version=job.pipeline_version, + ) + ) + else: + existing.content_type = item["content_type"] + existing.size_bytes = item["size_bytes"] + existing.width = item["width"] + existing.height = item["height"] + existing.sha256 = item["sha256"] + existing.object_key = item["object_key"] + existing.pipeline_version = job.pipeline_version + names = await _variant_names(session, attachment.id) + names.update(item["name"] for item in variants) + if not REQUIRED_VARIANTS <= names: + return "incomplete" + attachment.status = "ready" + attachment.error_code = None + attachment.updated_at = now + job.status = "ready" + job.error_code = None + job.lease_until = None + job.lease_owner = None + job.updated_at = now + created = attachment.created_at + if created.tzinfo is None: + from datetime import timezone + + created = created.replace(tzinfo=timezone.utc) + from app.telemetry import record_time_to_ready + + record_time_to_ready((now - created).total_seconds()) + return "ready" + + +async def sweep_expired_leases() -> int: + settings = require_settings() + now = utcnow() + changed = 0 + async with session_scope() as session: + async with session.begin(): + rows = ( + await session.scalars( + select(AttachmentJob) + .where( + AttachmentJob.status == "processing", + AttachmentJob.lease_until.is_not(None), + AttachmentJob.lease_until < now, + ) + .with_for_update(skip_locked=True) + ) + ).all() + for job in rows: + attachment = await session.get(Attachment, job.attachment_id, with_for_update=True) + if attachment is None or attachment.status == "ready" or job.status == "ready": + job.status = "ready" + job.lease_until = None + job.lease_owner = None + job.updated_at = now + continue + job.lease_until = None + job.lease_owner = None + job.updated_at = now + if job.attempt >= job.max_attempts: + job.status = "failed" + job.error_code = "retry_exhausted" + attachment.status = "failed" + attachment.error_code = "retry_exhausted" + attachment.updated_at = now + session.add(_failure(job, "retry_exhausted", True, now)) + else: + delay = backoff_seconds(job.attempt, settings.job_backoff_base_seconds, settings.job_backoff_cap_seconds) + when = now + timedelta(seconds=delay) + job.status = "queued" + job.error_code = None + job.next_attempt_at = when + attachment.status = "queued" + attachment.error_code = None + attachment.updated_at = now + session.add(_outbox(job, when, job.attempt + 1)) + changed += 1 + if changed: + logger.info("expired leases recovered count=%s", changed) + return changed + + +async def mark_gap_and_list(limit: int, crash_enabled: bool) -> tuple[list[dict], UUID | None]: + now = utcnow() + async with session_scope() as session: + async with session.begin(): + rows = ( + await session.scalars( + select(JobOutbox) + .where(JobOutbox.published_at.is_(None), JobOutbox.available_at <= now) + .order_by(JobOutbox.created_at.asc(), JobOutbox.id.asc()) + .limit(limit) + .with_for_update(skip_locked=True) + ) + ).all() + crash_id = None + # Один аварийный выход на пачку: если разрыв уже отмечен, публикуем, а не падаем снова. + if crash_enabled and rows and not any(row.gap_injected for row in rows): + rows[0].gap_injected = True + crash_id = rows[0].id + batch = [ + { + "id": row.id, + "job_id": row.job_id, + "payload": row.payload, + "gap_injected": row.gap_injected, + } + for row in rows + ] + return batch, crash_id + + +async def mark_published(outbox_id: UUID) -> None: + now = utcnow() + async with session_scope() as session: + async with session.begin(): + row = await session.get(JobOutbox, outbox_id, with_for_update=True) + if row is None or row.published_at is not None: + return + row.published_at = now + row.publish_attempts += 1 + + +async def note_publish_attempt(outbox_id: UUID) -> None: + async with session_scope() as session: + async with session.begin(): + row = await session.get(JobOutbox, outbox_id) + if row is None: + return + row.publish_attempts += 1 + + +async def replay_job(job_id: UUID) -> dict: + now = utcnow() + async with session_scope() as session: + async with session.begin(): + job = await session.get(AttachmentJob, job_id, with_for_update=True) + if job is None: + return {"outcome": "not_found", "job_id": str(job_id)} + attachment = await session.get(Attachment, job.attachment_id, with_for_update=True) + if attachment is None: + return {"outcome": "not_found", "job_id": str(job_id)} + names = await _variant_names(session, attachment.id) + if attachment.status == "ready" and job.status == "ready" and REQUIRED_VARIANTS <= names: + session.add(JobReplay(id=uuid4(), job_id=job.job_id, outcome="already_ready", created_at=now)) + return { + "outcome": "already_ready", + "job_id": str(job.job_id), + "attachment_id": str(attachment.id), + } + if job.status in {"queued", "processing"} and attachment.status != "failed": + session.add(JobReplay(id=uuid4(), job_id=job.job_id, outcome="in_progress", created_at=now)) + return { + "outcome": "in_progress", + "job_id": str(job.job_id), + "attachment_id": str(attachment.id), + } + job.status = "queued" + job.attempt = 0 + job.error_code = None + job.lease_until = None + job.lease_owner = None + job.next_attempt_at = now + job.updated_at = now + attachment.status = "queued" + attachment.error_code = None + attachment.updated_at = now + session.add(_outbox(job, now, 1)) + session.add(JobReplay(id=uuid4(), job_id=job.job_id, outcome="enqueued", created_at=now)) + return { + "outcome": "enqueued", + "job_id": str(job.job_id), + "attachment_id": str(attachment.id), + } diff --git a/src/app/main.py b/src/app/main.py new file mode 100644 index 0000000..ccccf19 --- /dev/null +++ b/src/app/main.py @@ -0,0 +1,123 @@ +import asyncio +import logging +from contextlib import asynccontextmanager + +from fastapi import FastAPI +from fastapi.exceptions import RequestValidationError +from redis.exceptions import RedisError +from sqlalchemy.exc import InterfaceError, OperationalError, ProgrammingError +from sqlalchemy.exc import TimeoutError as SATimeout +from starlette.exceptions import HTTPException + +from app.api import api_router +from app.api.health import router as health_router +from app.config import load_settings +from app.db import build_engine, build_session_factory, is_dependency_error +from app.errors import AppError, handle_app_error, handle_dependency, handle_http_error, handle_validation_error +from app.migrate import apply_migrations, wait_for_database, wait_for_schema +from app.middleware import request_context +from app.runtime import configure +from app.s3 import build_store +from app.security import init_security +from app.sessions import build_redis +from app.telemetry import bind_engine, sample_queue, setup_telemetry + +logger = logging.getLogger("app") + + +async def open_stores(engine, redis, store, settings) -> None: + await wait_for_database(engine) + for attempt in range(40): + try: + await redis.ping() + break + except Exception as exc: + if not is_dependency_error(exc): + logger.error("redis probe failed type=%s", type(exc).__name__) + raise SystemExit("redis probe failed") from None + logger.warning("redis not ready type=%s attempt=%s", type(exc).__name__, attempt + 1) + if attempt == 39: + raise SystemExit("redis is not ready") from None + await asyncio.sleep(0.5) + for attempt in range(40): + try: + await store.ping() + break + except AppError: + logger.warning("s3 not ready attempt=%s", attempt + 1) + if attempt == 39: + raise SystemExit("s3 is not ready") from None + await asyncio.sleep(0.5) + except Exception as exc: + logger.warning("s3 probe failed type=%s attempt=%s", type(exc).__name__, attempt + 1) + if attempt == 39: + raise SystemExit("s3 is not ready") from None + await asyncio.sleep(0.5) + if settings.run_migrations: + try: + applied = await apply_migrations(engine, settings.migrations_dir) + logger.info("migrations newly_applied=%s", applied) + except ProgrammingError as exc: + sqlstate = getattr(getattr(exc, "orig", None), "sqlstate", "") + logger.error("migration rejected type=%s sqlstate=%s", type(exc).__name__, sqlstate) + raise SystemExit("migration failed") from None + else: + await wait_for_schema(engine, settings.migrations_dir) + + +@asynccontextmanager +async def lifespan(app: FastAPI): + settings = load_settings() + setup_telemetry(settings) + engine = build_engine(settings) + bind_engine(engine, settings.db_pool_size + settings.db_max_overflow) + redis = build_redis(settings) + store = build_store(settings) + app.state.engine = engine + app.state.redis = redis + app.state.store = store + app.state.settings = settings + app.state.instance_id = settings.instance_id + app.state.accepting = False + sampler_stop = asyncio.Event() + sampler = None + try: + await open_stores(engine, redis, store, settings) + configure(build_session_factory(engine), redis, settings, store) + init_security(settings.argon2_memory_kib, settings.argon2_iterations, settings.argon2_parallelism) + sampler = asyncio.create_task(sample_queue(engine, sampler_stop)) + app.state.accepting = True + logger.info( + "ready env=%s instance_id=%s session_ttl_seconds=%s db_pool=%s", + settings.env, + settings.instance_id, + settings.session_ttl_seconds, + settings.db_pool_size, + ) + yield + finally: + app.state.accepting = False + sampler_stop.set() + if sampler is not None: + sampler.cancel() + logger.info("shutdown: new requests are no longer accepted") + await redis.aclose() + await engine.dispose() + + +def create_app() -> FastAPI: + app = FastAPI(title="MTUSI Messenger", version="1.6.0", lifespan=lifespan) + app.state.instance_id = "starting" + app.state.accepting = False + app.add_exception_handler(AppError, handle_app_error) + app.add_exception_handler(RequestValidationError, handle_validation_error) + app.add_exception_handler(HTTPException, handle_http_error) + for cls in (OperationalError, InterfaceError, SATimeout, RedisError): + app.add_exception_handler(cls, handle_dependency) + app.middleware("http")(request_context) + app.include_router(health_router) + app.include_router(api_router) + return app + + +app = create_app() diff --git a/src/app/middleware.py b/src/app/middleware.py new file mode 100644 index 0000000..bb22ee0 --- /dev/null +++ b/src/app/middleware.py @@ -0,0 +1,134 @@ +import logging +import time +from uuid import uuid4 + +from fastapi import Request +from opentelemetry.trace import Status, StatusCode + +from app.db import is_dependency_error +from app.errors import error_response +from app.telemetry import record_http, server_span + +logger = logging.getLogger("app.access") + + +def _instance_id(request: Request) -> str: + settings = getattr(request.app.state, "settings", None) + if settings is not None: + return settings.instance_id + return getattr(request.app.state, "instance_id", "starting") + + +def _route_template(request: Request) -> str: + route = request.scope.get("route") + path = getattr(route, "path", None) + if isinstance(path, str) and path.startswith("/"): + return path + return "unmatched" + + +def _trace_carrier(request: Request) -> dict: + carrier = {} + for key in ("traceparent", "tracestate"): + value = request.headers.get(key) + if value: + carrier[key] = value + return carrier + + +async def _dispatch(request: Request, call_next, request_id: str): + accepting = getattr(request.app.state, "accepting", True) + if not accepting and request.url.path != "/health/live": + return error_response(503, "unavailable", "Сервер останавливается", request_id) + try: + return await call_next(request) + except Exception as exc: + if is_dependency_error(exc): + logger.warning("dependency unavailable type=%s", type(exc).__name__) + return error_response(503, "unavailable", "Сервис временно недоступен", request_id) + logger.error("internal error request_id=%s type=%s", request_id, type(exc).__name__) + return error_response(500, "internal_error", "Внутренняя ошибка", request_id) + + +def _finish_span(span, method: str, route: str, status: int) -> None: + if span is None: + return + span.update_name("%s %s" % (method, route)) + span.set_attribute("http.route", route) + span.set_attribute("http.response.status_code", status) + if status >= 500: + span.set_status(Status(StatusCode.ERROR)) + else: + span.set_status(Status(StatusCode.OK)) + + +def _too_large(request: Request, request_id: str): + if request.method not in {"POST", "PUT", "PATCH"}: + return None + settings = getattr(request.app.state, "settings", None) + if settings is None: + return None + upload = request.method == "POST" and request.url.path.endswith("/attachments") + limit = settings.max_upload_bytes if upload else settings.max_json_bytes + raw = request.headers.get("content-length") + if raw is None: + return None + try: + announced = int(raw) + except ValueError: + return error_response(400, "invalid_request", "Некорректный запрос", request_id) + if announced > limit: + return error_response(413, "payload_too_large", "Тело запроса слишком большое", request_id) + return None + + +async def request_context(request: Request, call_next): + request_id = uuid4().hex + request.state.request_id = request_id + limited = _too_large(request, request_id) + if limited is not None: + limited.headers["X-Request-Id"] = request_id + limited.headers["X-Instance-Id"] = _instance_id(request) + return limited + started = time.perf_counter() + status = 500 + route = "unmatched" + traced = not request.url.path.startswith("/health/") + if not traced: + try: + response = await _dispatch(request, call_next, request_id) + response.headers["X-Request-Id"] = request_id + response.headers["X-Instance-Id"] = _instance_id(request) + status = response.status_code + route = _route_template(request) + return response + finally: + record_http(request.method, route, status, time.perf_counter() - started) + logger.info( + "event=http.request method=%s route=%s status=%s request_id=%s duration_ms=%s", + request.method, + route, + status, + request_id, + int((time.perf_counter() - started) * 1000), + ) + with server_span(request.method, _trace_carrier(request)) as span: + try: + response = await _dispatch(request, call_next, request_id) + response.headers["X-Request-Id"] = request_id + response.headers["X-Instance-Id"] = _instance_id(request) + status = response.status_code + route = _route_template(request) + return response + finally: + route = _route_template(request) if route == "unmatched" else route + _finish_span(span, request.method, route, status) + record_http(request.method, route, status, time.perf_counter() - started) + logger.info( + "event=http.request method=%s route=%s status=%s request_id=%s duration_ms=%s", + request.method, + route, + status, + request_id, + int((time.perf_counter() - started) * 1000), + ) diff --git a/src/app/migrate.py b/src/app/migrate.py new file mode 100644 index 0000000..3d6770e --- /dev/null +++ b/src/app/migrate.py @@ -0,0 +1,141 @@ +import asyncio +import logging +import sys +from pathlib import Path + +from sqlalchemy import text +from sqlalchemy.exc import ProgrammingError +from sqlalchemy.ext.asyncio import AsyncEngine + +from app.config import load_settings +from app.db import build_engine, is_dependency_error + +logger = logging.getLogger("app.migrate") + +# Один номер на все процессы, чтобы две миграции не применяли DDL одновременно. +_ADVISORY_LOCK = 842021 + + +def sql_statements(script: str) -> list[str]: + lines = [] + for line in script.splitlines(): + if line.strip().startswith("--"): + continue + lines.append(line) + statements = [] + for part in "\n".join(lines).split(";"): + statement = part.strip() + if statement: + statements.append(statement) + return statements + + +def expected_versions(directory: Path) -> list[str]: + files = sorted(path for path in directory.glob("*.sql") if path.is_file()) + if not files: + raise SystemExit("no SQL migrations found") + return [path.name for path in files] + + +async def apply_migrations(engine: AsyncEngine, directory: Path) -> int: + files = sorted(path for path in directory.glob("*.sql") if path.is_file()) + if not files: + raise SystemExit("no SQL migrations found") + applied = 0 + async with engine.begin() as conn: + await conn.execute(text("SELECT pg_advisory_xact_lock(:lock_id)"), {"lock_id": _ADVISORY_LOCK}) + await conn.execute( + text( + """ + CREATE TABLE IF NOT EXISTS schema_migrations ( + version TEXT PRIMARY KEY, + applied_at TIMESTAMPTZ NOT NULL DEFAULT now() + ) + """ + ) + ) + for path in files: + version = path.name + exists = await conn.scalar( + text("SELECT version FROM schema_migrations WHERE version = :version"), + {"version": version}, + ) + if exists: + continue + for statement in sql_statements(path.read_text(encoding="utf-8")): + await conn.execute(text(statement)) + await conn.execute( + text("INSERT INTO schema_migrations (version) VALUES (:version)"), + {"version": version}, + ) + applied += 1 + logger.info("migration applied version=%s", version) + return applied + + +async def wait_for_database(engine: AsyncEngine) -> None: + for attempt in range(40): + try: + async with engine.connect() as conn: + await conn.execute(text("SELECT 1")) + return + except Exception as exc: + if not is_dependency_error(exc): + logger.error("database probe failed type=%s", type(exc).__name__) + raise SystemExit("database probe failed") from None + logger.warning("database not ready type=%s attempt=%s", type(exc).__name__, attempt + 1) + if attempt == 39: + raise SystemExit("database is not ready") from None + await asyncio.sleep(0.5) + + +async def wait_for_schema(engine: AsyncEngine, directory: Path) -> None: + needed = set(expected_versions(directory)) + for attempt in range(40): + try: + async with engine.connect() as conn: + rows = (await conn.execute(text("SELECT version FROM schema_migrations"))).all() + found = {row[0] for row in rows} + if needed <= found: + logger.info("schema ready versions=%s", ",".join(sorted(found))) + return + logger.warning("schema incomplete attempt=%s", attempt + 1) + except ProgrammingError: + logger.warning("schema_migrations missing attempt=%s", attempt + 1) + except Exception as exc: + if not is_dependency_error(exc): + logger.error("schema probe failed type=%s", type(exc).__name__) + raise SystemExit("schema probe failed") from None + logger.warning("schema probe unavailable type=%s attempt=%s", type(exc).__name__, attempt + 1) + if attempt == 39: + raise SystemExit("schema is not ready") + await asyncio.sleep(0.5) + + +async def run_job() -> None: + settings = load_settings() + engine = build_engine(settings) + try: + await wait_for_database(engine) + applied = await apply_migrations(engine, settings.migrations_dir) + logger.info("migrations newly_applied=%s", applied) + except ProgrammingError as exc: + sqlstate = getattr(getattr(exc, "orig", None), "sqlstate", "") + logger.error("migration rejected type=%s sqlstate=%s", type(exc).__name__, sqlstate) + raise SystemExit("migration failed") from None + finally: + await engine.dispose() + + +def main() -> None: + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s %(levelname)s %(name)s %(message)s", + stream=sys.stdout, + force=True, + ) + asyncio.run(run_job()) + + +if __name__ == "__main__": + main() diff --git a/src/app/models.py b/src/app/models.py new file mode 100644 index 0000000..cf60db2 --- /dev/null +++ b/src/app/models.py @@ -0,0 +1,300 @@ +import uuid +from datetime import datetime + +from sqlalchemy import ( + Boolean, + CheckConstraint, + DateTime, + ForeignKey, + Index, + Integer, + SmallInteger, + Text, + UniqueConstraint, +) +from sqlalchemy.dialects.postgresql import UUID +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column + + +class Base(DeclarativeBase): + pass + + +class User(Base): + __tablename__ = "users" + __table_args__ = ( + UniqueConstraint("username", name="uq_users_username"), + CheckConstraint("username ~ '^[a-z0-9_]{3,32}$'", name="ck_users_username_format"), + CheckConstraint( + "char_length(btrim(display_name)) >= 1 AND char_length(display_name) <= 100", + name="ck_users_display_name_len", + ), + CheckConstraint("char_length(password_hash) >= 20", name="ck_users_password_hash_len"), + ) + + id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True) + username: Mapped[str] = mapped_column(Text, nullable=False) + display_name: Mapped[str] = mapped_column(Text, nullable=False) + password_hash: Mapped[str] = mapped_column(Text, nullable=False) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) + + +class Chat(Base): + __tablename__ = "chats" + __table_args__ = ( + CheckConstraint( + "char_length(btrim(title)) >= 1 AND char_length(title) <= 100", + name="ck_chats_title", + ), + ) + + id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True) + title: Mapped[str] = mapped_column(Text, nullable=False) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) + + +class ChatMember(Base): + __tablename__ = "chat_members" + __table_args__ = ( + CheckConstraint("ordinal >= 0 AND ordinal < 100", name="ck_chat_members_ordinal"), + Index("ix_chat_members_user", "user_id", "chat_id"), + ) + + chat_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), + ForeignKey("chats.id"), + primary_key=True, + ) + user_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), + ForeignKey("users.id"), + primary_key=True, + ) + ordinal: Mapped[int] = mapped_column(SmallInteger, nullable=False) + + +class Message(Base): + __tablename__ = "messages" + __table_args__ = ( + CheckConstraint( + "char_length(body) <= 4000", + name="ck_messages_text", + ), + # Keyset: WHERE chat_id = $1 AND (created_at, id) > ($2, $3) ORDER BY created_at, id LIMIT $4 + Index("ix_messages_history", "chat_id", "created_at", "id"), + ) + + id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True) + chat_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("chats.id"), nullable=False) + sender_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False) + text: Mapped[str] = mapped_column("body", Text, nullable=False) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) + + +class IdempotencyRecord(Base): + __tablename__ = "idempotency_records" + __table_args__ = ( + CheckConstraint("method = 'POST'", name="ck_idem_method"), + CheckConstraint("status_code = 201", name="ck_idem_status"), + CheckConstraint("idempotency_key ~ '^[A-Za-z0-9._:-]{1,128}$'", name="ck_idem_key"), + CheckConstraint("char_length(request_path) BETWEEN 1 AND 300", name="ck_idem_path"), + CheckConstraint("char_length(request_hash) = 64", name="ck_idem_hash"), + Index("ix_idempotency_message", "message_id"), + Index("ix_idempotency_created", "created_at"), + ) + + user_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), + ForeignKey("users.id"), + primary_key=True, + ) + method: Mapped[str] = mapped_column(Text, primary_key=True) + request_path: Mapped[str] = mapped_column(Text, primary_key=True) + idempotency_key: Mapped[str] = mapped_column(Text, primary_key=True) + request_hash: Mapped[str] = mapped_column(Text, nullable=False) + status_code: Mapped[int] = mapped_column(SmallInteger, nullable=False) + message_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), + ForeignKey("messages.id"), + nullable=False, + ) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) + + +class Attachment(Base): + __tablename__ = "attachments" + __table_args__ = ( + UniqueConstraint("object_key", name="uq_attachments_object_key"), + CheckConstraint("char_length(filename) BETWEEN 1 AND 255", name="ck_attachments_filename"), + CheckConstraint("content_type IN ('image/png', 'image/jpeg')", name="ck_attachments_content_type"), + CheckConstraint("size_bytes >= 1 AND size_bytes <= 10485760", name="ck_attachments_size"), + CheckConstraint("sha256 ~ '^[a-f0-9]{64}$'", name="ck_attachments_sha256"), + CheckConstraint( + "status IN ('queued', 'processing', 'ready', 'failed')", + name="ck_attachments_status", + ), + CheckConstraint( + "(status = 'failed' AND error_code IS NOT NULL) OR (status <> 'failed' AND error_code IS NULL)", + name="ck_attachments_error", + ), + CheckConstraint( + "staging_key IS NULL OR char_length(staging_key) BETWEEN 8 AND 300", + name="ck_attachments_staging", + ), + Index("ix_attachments_chat", "chat_id", "created_at", "id"), + ) + + id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True) + chat_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("chats.id"), nullable=False) + owner_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False) + filename: Mapped[str] = mapped_column(Text, nullable=False) + content_type: Mapped[str] = mapped_column(Text, nullable=False) + size_bytes: Mapped[int] = mapped_column(Integer, nullable=False) + sha256: Mapped[str] = mapped_column(Text, nullable=False) + object_key: Mapped[str] = mapped_column(Text, nullable=False) + staging_key: Mapped[str | None] = mapped_column(Text, nullable=True) + status: Mapped[str] = mapped_column(Text, nullable=False) + error_code: Mapped[str | None] = mapped_column(Text, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) + + +class AttachmentVariant(Base): + __tablename__ = "attachment_variants" + __table_args__ = ( + UniqueConstraint("object_key", name="uq_attachment_variants_object_key"), + CheckConstraint("name IN ('thumbnail', 'crop', 'optimized')", name="ck_variants_name"), + CheckConstraint( + "content_type IN ('image/jpeg', 'image/png', 'image/webp')", + name="ck_variants_type", + ), + CheckConstraint("size_bytes >= 1", name="ck_variants_size"), + CheckConstraint("width >= 1 AND height >= 1", name="ck_variants_dim"), + CheckConstraint("sha256 ~ '^[a-f0-9]{64}$'", name="ck_variants_sha"), + CheckConstraint("pipeline_version >= 1", name="ck_variants_pipeline"), + ) + + attachment_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), + ForeignKey("attachments.id"), + primary_key=True, + ) + name: Mapped[str] = mapped_column(Text, primary_key=True) + content_type: Mapped[str] = mapped_column(Text, nullable=False) + size_bytes: Mapped[int] = mapped_column(Integer, nullable=False) + width: Mapped[int] = mapped_column(Integer, nullable=False) + height: Mapped[int] = mapped_column(Integer, nullable=False) + sha256: Mapped[str] = mapped_column(Text, nullable=False) + object_key: Mapped[str] = mapped_column(Text, nullable=False) + pipeline_version: Mapped[int] = mapped_column(Integer, nullable=False) + + +class AttachmentJob(Base): + __tablename__ = "attachment_jobs" + __table_args__ = ( + UniqueConstraint("attachment_id", "pipeline_version", name="uq_attachment_jobs_effect"), + CheckConstraint("status IN ('queued', 'processing', 'ready', 'failed')", name="ck_jobs_status"), + CheckConstraint("attempt >= 0 AND attempt <= max_attempts", name="ck_jobs_attempt"), + CheckConstraint("max_attempts BETWEEN 1 AND 20", name="ck_jobs_max"), + CheckConstraint("pipeline_version >= 1", name="ck_jobs_pipeline"), + Index("ix_jobs_lease", "status", "lease_until"), + ) + + job_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True) + attachment_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), + ForeignKey("attachments.id"), + nullable=False, + ) + pipeline_version: Mapped[int] = mapped_column(Integer, nullable=False) + status: Mapped[str] = mapped_column(Text, nullable=False) + attempt: Mapped[int] = mapped_column(Integer, nullable=False) + max_attempts: Mapped[int] = mapped_column(Integer, nullable=False) + lease_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + lease_owner: Mapped[str | None] = mapped_column(Text, nullable=True) + next_attempt_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + error_code: Mapped[str | None] = mapped_column(Text, nullable=True) + staging_key: Mapped[str] = mapped_column(Text, nullable=False) + objects_written_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) + + +class JobOutbox(Base): + __tablename__ = "job_outbox" + __table_args__ = ( + CheckConstraint("publish_attempts >= 0", name="ck_outbox_attempts"), + Index("ix_outbox_pending", "available_at", "created_at"), + ) + + id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True) + job_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), + ForeignKey("attachment_jobs.job_id"), + nullable=False, + ) + payload: Mapped[str] = mapped_column(Text, nullable=False) + available_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) + published_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + publish_attempts: Mapped[int] = mapped_column(Integer, nullable=False) + gap_injected: Mapped[bool] = mapped_column(Boolean, nullable=False) + + +class JobFailure(Base): + __tablename__ = "job_failures" + __table_args__ = ( + CheckConstraint("char_length(error_code) BETWEEN 1 AND 64", name="ck_job_failures_code"), + Index("ix_job_failures_job", "job_id", "created_at"), + ) + + id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True) + job_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), + ForeignKey("attachment_jobs.job_id"), + nullable=False, + ) + attachment_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False) + attempt: Mapped[int] = mapped_column(Integer, nullable=False) + error_code: Mapped[str] = mapped_column(Text, nullable=False) + permanent: Mapped[bool] = mapped_column(Boolean, nullable=False) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) + + +class JobReplay(Base): + __tablename__ = "job_replays" + __table_args__ = ( + CheckConstraint( + "outcome IN ('enqueued', 'already_ready', 'in_progress')", + name="ck_replays_outcome", + ), + ) + + id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True) + job_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), + ForeignKey("attachment_jobs.job_id"), + nullable=False, + ) + outcome: Mapped[str] = mapped_column(Text, nullable=False) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) + + +class MessageAttachment(Base): + __tablename__ = "message_attachments" + __table_args__ = ( + CheckConstraint("ordinal >= 0 AND ordinal < 10", name="ck_message_attachments_ordinal"), + Index("ix_message_attachments_attachment", "attachment_id"), + ) + + message_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), + ForeignKey("messages.id"), + primary_key=True, + ) + attachment_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), + ForeignKey("attachments.id"), + primary_key=True, + ) + ordinal: Mapped[int] = mapped_column(SmallInteger, nullable=False) diff --git a/src/app/mtls.py b/src/app/mtls.py new file mode 100644 index 0000000..c52022b --- /dev/null +++ b/src/app/mtls.py @@ -0,0 +1,96 @@ +import asyncio +import logging +import ssl +import threading + +from app.config import Settings + +logger = logging.getLogger("app.mtls") + + +def _server_context(settings: Settings) -> ssl.SSLContext: + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + ctx.minimum_version = ssl.TLSVersion.TLSv1_2 + ctx.load_cert_chain(settings.tls_cert_file, settings.tls_key_file) + ctx.load_verify_locations(settings.tls_ca_file) + ctx.verify_mode = ssl.CERT_REQUIRED + return ctx + + +def _allowed(peercert: dict | None, allowed: set[str]) -> bool: + if not peercert: + return False + names = set() + for kind, value in peercert.get("subjectAltName", ()): + if kind == "DNS" and isinstance(value, str): + names.add(value) + return bool(names & allowed) + + +async def _pipe(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + try: + while True: + chunk = await reader.read(65536) + if not chunk: + break + writer.write(chunk) + await writer.drain() + except Exception: + return + finally: + try: + writer.close() + await writer.wait_closed() + except Exception: + return + + +async def _handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter, settings: Settings, allowed: set[str]) -> None: + peer = writer.get_extra_info("ssl_object") + names: list[str] = [] + try: + cert = peer.getpeercert() if peer is not None else None + names = [value for kind, value in (cert or {}).get("subjectAltName", ()) if kind == "DNS"] + if not _allowed(cert, allowed): + logger.warning("mtls identity rejected sans=%s", ",".join(names) or "none") + writer.close() + await writer.wait_closed() + return + upstream_reader, upstream_writer = await asyncio.open_connection("127.0.0.1", settings.internal_port) + except Exception as exc: + logger.warning("mtls upstream failed type=%s", type(exc).__name__) + try: + writer.close() + except Exception: + return + return + await asyncio.gather( + _pipe(reader, upstream_writer), + _pipe(upstream_reader, writer), + ) + + +async def _serve(settings: Settings) -> None: + allowed = {item.strip() for item in settings.mtls_allowed_dns.split(",") if item.strip()} + if not allowed: + raise SystemExit("MTLS_ALLOWED_DNS is empty") + server = await asyncio.start_server( + lambda reader, writer: _handle(reader, writer, settings, allowed), + host=settings.host, + port=settings.port, + ssl=_server_context(settings), + ) + logger.info("mtls listening port=%s allowed=%s", settings.port, ",".join(sorted(allowed))) + async with server: + await server.serve_forever() + + +def start_mtls_proxy(settings: Settings) -> None: + def run() -> None: + try: + asyncio.run(_serve(settings)) + except Exception as exc: + logger.error("mtls proxy stopped type=%s", type(exc).__name__) + + thread = threading.Thread(target=run, name="mtls-proxy", daemon=True) + thread.start() diff --git a/src/app/pagination.py b/src/app/pagination.py new file mode 100644 index 0000000..f536d6c --- /dev/null +++ b/src/app/pagination.py @@ -0,0 +1,50 @@ +import base64 +import json +from datetime import datetime +from uuid import UUID + +from app.errors import AppError +from app.timeutil import format_time, parse_time + + +def encode_cursor(kind: str, resource_id: UUID, created_at: datetime, entity_id: UUID) -> str: + payload = { + "i": str(entity_id), + "k": kind, + "r": str(resource_id), + "t": format_time(created_at), + } + raw = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("ascii") + return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=") + + +def decode_position(token: str, kind: str, resource_id: UUID) -> tuple[datetime, UUID]: + if len(token) > 1024: + raise AppError(400, "invalid_request", "Некорректный cursor") + padding = "=" * (-len(token) % 4) + try: + data = json.loads(base64.urlsafe_b64decode(token + padding)) + if ( + not isinstance(data, dict) + or data.get("k") != kind + or data.get("r") != str(resource_id) + or not isinstance(data.get("t"), str) + or not isinstance(data.get("i"), str) + ): + raise ValueError("cursor") + created_at = parse_time(data["t"]) + entity_id = UUID(data["i"]) + except (KeyError, TypeError, ValueError, AttributeError, json.JSONDecodeError): + raise AppError(400, "invalid_request", "Некорректный cursor") from None + return created_at, entity_id + + +def slice_page(rows: list, limit: int, kind: str, resource_id: UUID) -> dict: + # SQL уже вернул не больше limit + 1 строк, отфильтрованных keyset-условием. + has_more = len(rows) > limit + page = rows[:limit] + next_cursor = None + if has_more and page: + last = page[-1] + next_cursor = encode_cursor(kind, resource_id, last.created_at, last.id) + return {"items": [row.to_dict() for row in page], "next_cursor": next_cursor} diff --git a/src/app/pipeline.py b/src/app/pipeline.py new file mode 100644 index 0000000..aea1e99 --- /dev/null +++ b/src/app/pipeline.py @@ -0,0 +1,165 @@ +import io +import multiprocessing +import time + +from PIL import Image, ImageFile, ImageOps, UnidentifiedImageError + +ImageFile.LOAD_TRUNCATED_IMAGES = False + +THUMBNAIL_BOX = 256 +CROP_SIDE = 128 +OPTIMIZED_BOX = 1280 + +_VARIANT_ORDER = ("thumbnail", "crop", "optimized") + + +def _without_metadata(image: Image.Image) -> Image.Image: + bare = Image.new("RGB", image.size) + bare.paste(image) + return bare + + +def _to_rgb(image: Image.Image) -> Image.Image: + oriented = ImageOps.exif_transpose(image) + if oriented.mode == "RGB": + return _without_metadata(oriented) + if oriented.mode in {"RGBA", "LA"} or (oriented.mode == "P" and "transparency" in oriented.info): + rgba = oriented.convert("RGBA") + base = Image.new("RGB", rgba.size, (255, 255, 255)) + base.paste(rgba, mask=rgba.getchannel("A")) + return base + return _without_metadata(oriented.convert("RGB")) + + +def _fit_within(image: Image.Image, box: int) -> Image.Image: + width, height = image.size + scale = min(box / width, box / height, 1.0) + new_width = max(1, int(width * scale)) + new_height = max(1, int(height * scale)) + if new_width == width and new_height == height: + return image + return image.resize((new_width, new_height), Image.Resampling.LANCZOS) + + +def _center_square(image: Image.Image, side: int) -> Image.Image: + width, height = image.size + source = min(width, height) + left = (width - source) // 2 + top = (height - source) // 2 + cropped = image.crop((left, top, left + source, top + source)) + if cropped.size != (side, side): + cropped = cropped.resize((side, side), Image.Resampling.LANCZOS) + return cropped + + +def _jpeg_bytes(image: Image.Image, quality: int) -> bytes: + buffer = io.BytesIO() + image.save(buffer, format="JPEG", quality=quality, optimize=True) + return buffer.getvalue() + + +def _webp_bytes(image: Image.Image, quality: int, method: int) -> bytes: + buffer = io.BytesIO() + image.save(buffer, format="WEBP", quality=quality, method=method) + return buffer.getvalue() + + +def _fail(code: str, permanent: bool) -> dict: + return {"ok": False, "code": code, "permanent": permanent} + + +def render_variants( + data: bytes, + max_pixels: int, + memory_budget: int, + jpeg_quality: int, + webp_quality: int, + webp_method: int, +) -> dict: + Image.MAX_IMAGE_PIXELS = max_pixels + try: + with Image.open(io.BytesIO(data)) as source: + width, height = source.size + if width < 1 or height < 1: + return _fail("invalid_image", True) + if width * height > max_pixels or width * height * 4 > memory_budget: + return _fail("payload_too_large", True) + source.load() + rgb = _to_rgb(source) + thumbnail = _fit_within(rgb, THUMBNAIL_BOX) + crop = _center_square(rgb, CROP_SIDE) + optimized = _fit_within(rgb, OPTIMIZED_BOX) + variants = { + "thumbnail": { + "content_type": "image/jpeg", + "width": thumbnail.size[0], + "height": thumbnail.size[1], + "data": _jpeg_bytes(thumbnail, jpeg_quality), + }, + "crop": { + "content_type": "image/jpeg", + "width": crop.size[0], + "height": crop.size[1], + "data": _jpeg_bytes(crop, jpeg_quality), + }, + "optimized": { + "content_type": "image/webp", + "width": optimized.size[0], + "height": optimized.size[1], + "data": _webp_bytes(optimized, webp_quality, webp_method), + }, + } + return {"ok": True, "variants": variants} + except Image.DecompressionBombError: + return _fail("payload_too_large", True) + except MemoryError: + return _fail("payload_too_large", True) + except (UnidentifiedImageError, OSError, ValueError, SyntaxError): + return _fail("invalid_image", True) + + +def _spawn_render(queue, data, max_pixels, memory_budget, jpeg_quality, webp_quality, webp_method, stall_seconds) -> None: + if stall_seconds > 0: + time.sleep(stall_seconds) + queue.put(render_variants(data, max_pixels, memory_budget, jpeg_quality, webp_quality, webp_method)) + + +def render_in_process( + data: bytes, + max_pixels: int, + memory_budget: int, + jpeg_quality: int, + webp_quality: int, + webp_method: int, + timeout_seconds: float, + stall_seconds: float = 0, +) -> dict: + context = multiprocessing.get_context("spawn") + queue = context.Queue(maxsize=1) + process = context.Process( + target=_spawn_render, + args=(queue, data, max_pixels, memory_budget, jpeg_quality, webp_quality, webp_method, stall_seconds), + ) + process.start() + process.join(timeout_seconds) + try: + if process.is_alive(): + process.terminate() + process.join(5) + if process.is_alive(): + process.kill() + process.join(2) + return _fail("processing_failed", False) + if process.exitcode != 0: + return _fail("processing_failed", False) + try: + return queue.get_nowait() + except Exception: + return _fail("processing_failed", False) + finally: + queue.close() + queue.cancel_join_thread() + + +def variant_names() -> tuple[str, ...]: + return _VARIANT_ORDER diff --git a/src/app/present.py b/src/app/present.py new file mode 100644 index 0000000..213fb13 --- /dev/null +++ b/src/app/present.py @@ -0,0 +1,89 @@ +from dataclasses import dataclass +from datetime import datetime +from uuid import UUID + +from app.timeutil import format_time + + +@dataclass(frozen=True) +class PublicUser: + id: UUID + username: str + display_name: str + created_at: datetime + + def to_dict(self) -> dict: + return { + "id": self.id, + "username": self.username, + "display_name": self.display_name, + "created_at": format_time(self.created_at), + } + + +@dataclass(frozen=True) +class PublicChat: + id: UUID + title: str + member_ids: tuple[UUID, ...] + created_at: datetime + + def to_dict(self) -> dict: + return { + "id": self.id, + "title": self.title, + "member_ids": list(self.member_ids), + "created_at": format_time(self.created_at), + } + + +@dataclass(frozen=True) +class PublicMessage: + id: UUID + chat_id: UUID + sender_id: UUID + text: str + created_at: datetime + attachment_ids: tuple[UUID, ...] = () + + def to_dict(self) -> dict: + return { + "id": self.id, + "chat_id": self.chat_id, + "sender_id": self.sender_id, + "text": self.text, + "created_at": format_time(self.created_at), + "attachment_ids": list(self.attachment_ids), + } + + +@dataclass(frozen=True) +class PublicAttachment: + id: UUID + chat_id: UUID + owner_id: UUID + filename: str + content_type: str + size_bytes: int + sha256: str + status: str + error_code: str | None + created_at: datetime + updated_at: datetime + variants: tuple = () + + def to_dict(self) -> dict: + return { + "id": self.id, + "chat_id": self.chat_id, + "owner_id": self.owner_id, + "filename": self.filename, + "content_type": self.content_type, + "size_bytes": self.size_bytes, + "sha256": self.sha256, + "status": self.status, + "variants": list(self.variants), + "error_code": self.error_code, + "created_at": format_time(self.created_at), + "updated_at": format_time(self.updated_at), + } diff --git a/src/app/ratelimit.py b/src/app/ratelimit.py new file mode 100644 index 0000000..9ebe39a --- /dev/null +++ b/src/app/ratelimit.py @@ -0,0 +1,32 @@ +import logging + +from app.errors import AppError +from app.runtime import require_redis, require_settings + +logger = logging.getLogger("app.ratelimit") + + +async def enforce_login_limit(username: str) -> None: + settings = require_settings() + limit = settings.login_rate_limit + window = settings.login_rate_window_seconds + if limit <= 0: + return + key = "login:rate:" + username + try: + redis = require_redis() + count = int(await redis.incr(key)) + ttl = int(await redis.ttl(key)) + if count == 1 or ttl < 0: + await redis.expire(key, window) + ttl = window + except Exception as exc: + logger.warning("login rate limit unavailable type=%s", type(exc).__name__) + raise AppError(503, "unavailable", "Сервис временно недоступен") from None + if count > limit: + raise AppError( + 429, + "rate_limited", + "Слишком много попыток входа", + {"Retry-After": str(max(1, ttl))}, + ) diff --git a/src/app/relay.py b/src/app/relay.py new file mode 100644 index 0000000..657a626 --- /dev/null +++ b/src/app/relay.py @@ -0,0 +1,174 @@ +import asyncio +import json +import logging +import os +import signal +import sys +from pathlib import Path + +from opentelemetry.trace import SpanKind + +from app.broker import WORK_KEY, connect, declare, publish +from app.config import load_settings +from app.db import build_engine, build_session_factory +from app.faults import read_faults +from app.jobs import mark_gap_and_list, mark_published, note_publish_attempt +from app.migrate import wait_for_database, wait_for_schema +from app.runtime import configure +from app.telemetry import bind_engine, flush_telemetry, inject_headers, messaging_span, setup_logging, setup_telemetry + +logger = logging.getLogger("app.relay") + + +def flush_logs() -> None: + for handler in logging.getLogger().handlers: + handler.flush() + sys.stdout.flush() + + +async def beat(path: str, stop: asyncio.Event) -> None: + file = Path(path) + while not stop.is_set(): + file.write_text("ok", encoding="utf-8") + try: + await asyncio.wait_for(stop.wait(), timeout=2) + except asyncio.TimeoutError: + continue + + +async def open_broker(url: str): + for attempt in range(40): + try: + return await connect(url) + except Exception as exc: + logger.warning("broker not ready type=%s attempt=%s", type(exc).__name__, attempt + 1) + await asyncio.sleep(0.5) + raise SystemExit("broker is not ready") + + +async def publish_loop(stop: asyncio.Event) -> None: + settings = require_settings_later() + while not stop.is_set(): + connection = None + try: + connection = await open_broker(settings.broker_url) + channel = await connection.channel(publisher_confirms=True) + exchange, _queue = await declare(channel) + logger.info("relay publishing with confirms") + while not stop.is_set(): + faults = read_faults(settings.faults_file) + batch, crash_id = await mark_gap_and_list(10, faults.relay_exit_before_publish) + if crash_id is not None: + logger.error( + "injected exit after outbox commit before broker publish outbox_id=%s", + crash_id, + ) + flush_logs() + flush_telemetry() + os._exit(42) + if not batch: + try: + await asyncio.wait_for(stop.wait(), timeout=0.4) + except asyncio.TimeoutError: + continue + break + for item in batch: + try: + body, headers = traced_payload(item) + with messaging_span("publish attachment.jobs", SpanKind.PRODUCER, headers) as span: + span.set_attribute("messaging.system", "rabbitmq") + span.set_attribute("messaging.destination.name", "attachment.jobs") + span.set_attribute("messaging.operation.name", "publish") + span.set_attribute("messaging.operation.type", "publish") + span.set_attribute("messaging.message.id", str(item["job_id"])) + outgoing = inject_headers() or headers + if outgoing.get("traceparent"): + body, headers = replace_trace(body, outgoing) + await publish(exchange, body, WORK_KEY, headers) + logger.info("outbox published job_id=%s", item["job_id"]) + except Exception as exc: + logger.warning("publish failed type=%s job_id=%s", type(exc).__name__, item["job_id"]) + await note_publish_attempt(item["id"]) + continue + await mark_published(item["id"]) + except Exception as exc: + if stop.is_set(): + break + logger.warning("relay interrupted type=%s", type(exc).__name__) + await asyncio.sleep(1) + finally: + if connection is not None: + try: + await connection.close() + except Exception as exc: + logger.warning("broker close failed type=%s", type(exc).__name__) + + +def traced_payload(item: dict) -> tuple[str, dict]: + raw = item["payload"] + try: + payload = json.loads(raw) + except (UnicodeError, ValueError): + return raw, {} + if not isinstance(payload, dict): + return raw, {} + headers = {} + for key in ("traceparent", "tracestate"): + value = payload.get(key) + if isinstance(value, str) and value: + headers[key] = value + return raw, headers + + +def replace_trace(raw: str, headers: dict) -> tuple[str, dict]: + try: + payload = json.loads(raw) + except (UnicodeError, ValueError): + return raw, headers + if not isinstance(payload, dict): + return raw, headers + for key in ("traceparent", "tracestate"): + if headers.get(key): + payload[key] = headers[key] + return json.dumps(payload, separators=(",", ":"), sort_keys=True), headers + + +def require_settings_later(): + from app.runtime import require_settings + + return require_settings() + + +async def serve() -> None: + settings = load_settings() + setup_logging(settings.app_role) + setup_telemetry(settings) + engine = build_engine(settings) + bind_engine(engine, settings.db_pool_size + settings.db_max_overflow) + stop = asyncio.Event() + try: + await wait_for_database(engine) + await wait_for_schema(engine, settings.migrations_dir) + configure(build_session_factory(engine), None, settings, None) + loop = asyncio.get_running_loop() + for sig in (signal.SIGTERM, signal.SIGINT): + try: + loop.add_signal_handler(sig, stop.set) + except NotImplementedError: + pass + heart = asyncio.create_task(beat("/tmp/relay-heartbeat", stop)) + try: + await publish_loop(stop) + finally: + stop.set() + heart.cancel() + finally: + await engine.dispose() + + +def main() -> None: + asyncio.run(serve()) + + +if __name__ == "__main__": + main() diff --git a/src/app/replay.py b/src/app/replay.py new file mode 100644 index 0000000..a345a1c --- /dev/null +++ b/src/app/replay.py @@ -0,0 +1,43 @@ +import asyncio +import json +import logging +import sys +from uuid import UUID + +from app.config import load_settings +from app.db import build_engine, build_session_factory +from app.jobs import replay_job +from app.migrate import wait_for_database +from app.runtime import configure + + +async def run(job_id: UUID) -> int: + settings = load_settings() + engine = build_engine(settings) + try: + await wait_for_database(engine) + configure(build_session_factory(engine), None, settings, None) + result = await replay_job(job_id) + finally: + await engine.dispose() + print(json.dumps(result, ensure_ascii=False), flush=True) + if result.get("outcome") == "not_found": + return 2 + return 0 + + +def main() -> None: + logging.basicConfig(level=logging.WARNING, stream=sys.stderr, force=True) + if len(sys.argv) != 2: + print("usage: python -m app.replay JOB_ID", file=sys.stderr) + raise SystemExit(2) + try: + job_id = UUID(sys.argv[1]) + except ValueError: + print("job id must be a uuid", file=sys.stderr) + raise SystemExit(2) + raise SystemExit(asyncio.run(run(job_id))) + + +if __name__ == "__main__": + main() diff --git a/src/app/runtime.py b/src/app/runtime.py new file mode 100644 index 0000000..172061c --- /dev/null +++ b/src/app/runtime.py @@ -0,0 +1,46 @@ +from app.config import Settings + +_factory = None +_redis = None +_store = None +_settings: Settings | None = None + + +def configure(factory, redis, settings: Settings, store=None) -> None: + global _factory, _redis, _store, _settings + _factory = factory + _redis = redis + _store = store + _settings = settings + + +def require_factory(): + if _factory is None: + from app.errors import AppError + + raise AppError(503, "unavailable", "Сервис временно недоступен") + return _factory + + +def require_redis(): + if _redis is None: + from app.errors import AppError + + raise AppError(503, "unavailable", "Сервис временно недоступен") + return _redis + + +def require_settings() -> Settings: + if _settings is None: + from app.errors import AppError + + raise AppError(503, "unavailable", "Сервис временно недоступен") + return _settings + + +def require_store(): + if _store is None: + from app.errors import AppError + + raise AppError(503, "unavailable", "Сервис временно недоступен") + return _store diff --git a/src/app/s3.py b/src/app/s3.py new file mode 100644 index 0000000..5d62f3d --- /dev/null +++ b/src/app/s3.py @@ -0,0 +1,106 @@ +import asyncio +import logging +from datetime import datetime, timezone + +import boto3 +from botocore.config import Config +from botocore.exceptions import BotoCoreError, ClientError, EndpointConnectionError + +from app.config import Settings +from app.errors import AppError + +logger = logging.getLogger("app.s3") + + +class ObjectStore: + def __init__(self, settings: Settings) -> None: + self.bucket = settings.s3_bucket + verify: str | bool = settings.tls_ca_file or True + if settings.s3_endpoint.startswith("https://") and not settings.tls_ca_file: + raise SystemExit("TLS_CA_FILE is required for https S3") + self._client = boto3.client( + "s3", + endpoint_url=settings.s3_endpoint, + aws_access_key_id=settings.s3_access_key_id, + aws_secret_access_key=settings.s3_secret_access_key, + region_name=settings.s3_region, + verify=verify, + config=Config( + s3={"addressing_style": "path"}, + connect_timeout=2, + read_timeout=30, + retries={"max_attempts": 2, "mode": "standard"}, + ), + ) + + def _call(self, fn, *args, **kwargs): + try: + return fn(*args, **kwargs) + except EndpointConnectionError: + logger.warning("s3 endpoint unavailable type=%s", "EndpointConnectionError") + raise AppError(503, "unavailable", "Сервис временно недоступен") from None + except ClientError as exc: + code = str(exc.response.get("Error", {}).get("Code", "")) + if code in {"NoSuchKey", "404"}: + raise AppError(404, "not_found", "Объект не найден") from None + logger.warning("s3 client error type=%s code=%s", type(exc).__name__, code or "unknown") + raise AppError(503, "unavailable", "Сервис временно недоступен") from None + except BotoCoreError: + logger.warning("s3 unavailable type=%s", "BotoCoreError") + raise AppError(503, "unavailable", "Сервис временно недоступен") from None + + async def ping(self) -> None: + await asyncio.to_thread(self._call, self._client.head_bucket, Bucket=self.bucket) + + async def put(self, key: str, data: bytes, content_type: str) -> None: + await asyncio.to_thread( + self._call, + self._client.put_object, + Bucket=self.bucket, + Key=key, + Body=data, + ContentType=content_type, + ContentLength=len(data), + ) + + async def get(self, key: str) -> bytes: + def _read() -> bytes: + body = self._call(self._client.get_object, Bucket=self.bucket, Key=key)["Body"] + return body.read() + + return await asyncio.to_thread(_read) + + async def delete(self, key: str) -> None: + try: + await asyncio.to_thread(self._call, self._client.delete_object, Bucket=self.bucket, Key=key) + except AppError: + return + + async def list_objects(self) -> list[tuple[str, datetime]]: + def _list() -> list[tuple[str, datetime]]: + items: list[tuple[str, datetime]] = [] + for prefix in ("att/", "staging/"): + token = None + while True: + kwargs = {"Bucket": self.bucket, "Prefix": prefix} + if token: + kwargs["ContinuationToken"] = token + page = self._call(self._client.list_objects_v2, **kwargs) + for obj in page.get("Contents") or []: + key = str(obj["Key"]) + modified = obj["LastModified"] + if modified.tzinfo is None: + modified = modified.replace(tzinfo=timezone.utc) + items.append((key, modified.astimezone(timezone.utc))) + if not page.get("IsTruncated"): + break + token = page.get("NextContinuationToken") + if not token: + break + return items + + return await asyncio.to_thread(_list) + + +def build_store(settings: Settings) -> ObjectStore: + return ObjectStore(settings) diff --git a/src/app/schemas/__init__.py b/src/app/schemas/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/app/schemas/attachment.py b/src/app/schemas/attachment.py new file mode 100644 index 0000000..5f11b02 --- /dev/null +++ b/src/app/schemas/attachment.py @@ -0,0 +1,27 @@ +from uuid import UUID + +from pydantic import BaseModel + + +class VariantOut(BaseModel): + name: str + content_type: str + size_bytes: int + width: int + height: int + sha256: str + + +class AttachmentOut(BaseModel): + id: UUID + chat_id: UUID + owner_id: UUID + filename: str + content_type: str + size_bytes: int + sha256: str + status: str + variants: list[VariantOut] + error_code: str | None + created_at: str + updated_at: str diff --git a/src/app/schemas/chat.py b/src/app/schemas/chat.py new file mode 100644 index 0000000..ea694c6 --- /dev/null +++ b/src/app/schemas/chat.py @@ -0,0 +1,35 @@ +from uuid import UUID + +from pydantic import BaseModel, ConfigDict, Field, field_validator + + +class CreateChat(BaseModel): + model_config = ConfigDict(extra="forbid") + title: str + member_ids: list[UUID] = Field(min_length=1, max_length=100) + + @field_validator("title") + @classmethod + def check_title(cls, value: str) -> str: + if value.strip() == "" or len(value) > 100: + raise ValueError("title") + return value + + @field_validator("member_ids") + @classmethod + def unique_members(cls, value: list[UUID]) -> list[UUID]: + if len(set(value)) != len(value): + raise ValueError("duplicate members") + return value + + +class ChatOut(BaseModel): + id: UUID + title: str + member_ids: list[UUID] + created_at: str + + +class ChatPage(BaseModel): + items: list[ChatOut] + next_cursor: str | None diff --git a/src/app/schemas/message.py b/src/app/schemas/message.py new file mode 100644 index 0000000..e0c3c61 --- /dev/null +++ b/src/app/schemas/message.py @@ -0,0 +1,43 @@ +from uuid import UUID + +from pydantic import BaseModel, ConfigDict, field_validator, model_validator + + +class CreateMessage(BaseModel): + model_config = ConfigDict(extra="forbid") + text: str + attachment_ids: list[UUID] = [] + + @field_validator("text") + @classmethod + def check_text(cls, value: str) -> str: + if len(value) > 4000: + raise ValueError("text") + return value + + @field_validator("attachment_ids") + @classmethod + def check_attachments(cls, value: list[UUID]) -> list[UUID]: + if len(value) > 10 or len(set(value)) != len(value): + raise ValueError("attachment_ids") + return value + + @model_validator(mode="after") + def require_payload(self): + if self.text.strip() == "" and not self.attachment_ids: + raise ValueError("text") + return self + + +class MessageOut(BaseModel): + id: UUID + chat_id: UUID + sender_id: UUID + text: str + created_at: str + attachment_ids: list[UUID] + + +class MessagePage(BaseModel): + items: list[MessageOut] + next_cursor: str | None diff --git a/src/app/schemas/session.py b/src/app/schemas/session.py new file mode 100644 index 0000000..beb07f1 --- /dev/null +++ b/src/app/schemas/session.py @@ -0,0 +1,10 @@ +from pydantic import BaseModel + +from app.schemas.user import UserOut + + +class SessionOut(BaseModel): + token: str + token_type: str + expires_at: str + user: UserOut diff --git a/src/app/schemas/user.py b/src/app/schemas/user.py new file mode 100644 index 0000000..2e31335 --- /dev/null +++ b/src/app/schemas/user.py @@ -0,0 +1,41 @@ +import re + +from uuid import UUID + +from pydantic import BaseModel, ConfigDict, field_validator + + +class CreateUser(BaseModel): + model_config = ConfigDict(extra="forbid") + username: str + display_name: str + password: str + + @field_validator("username") + @classmethod + def check_username(cls, value: str) -> str: + if re.fullmatch(r"[a-z0-9_]{3,32}", value) is None: + raise ValueError("username") + return value + + @field_validator("display_name") + @classmethod + def check_display_name(cls, value: str) -> str: + if value.strip() == "" or len(value) > 100: + raise ValueError("display_name") + return value + + @field_validator("password") + @classmethod + def check_password(cls, value: str) -> str: + # Длина в code points. Пароль не обрезается и не нормализуется. + if not 12 <= len(value) <= 128: + raise ValueError("password") + return value + + +class UserOut(BaseModel): + id: UUID + username: str + display_name: str + created_at: str diff --git a/src/app/security.py b/src/app/security.py new file mode 100644 index 0000000..ee12183 --- /dev/null +++ b/src/app/security.py @@ -0,0 +1,68 @@ +import base64 +import binascii + +from argon2 import PasswordHasher +from argon2.exceptions import InvalidHashError, VerifyMismatchError +from argon2.low_level import Type + +# Ниже минимума lab7 (19 MiB, t=2, p=1) процесс не стартует. +_MIN_MEMORY_KIB = 19456 +_MIN_TIME_COST = 2 +_MIN_PARALLELISM = 1 + +_hasher: PasswordHasher | None = None +_dummy_hash: str | None = None + + +def init_security(memory_kib: int, iterations: int, parallelism: int) -> None: + global _hasher, _dummy_hash + if memory_kib < _MIN_MEMORY_KIB or iterations < _MIN_TIME_COST or parallelism < _MIN_PARALLELISM: + raise SystemExit("argon2 parameters are below the lab7 minimum") + if _hasher is None: + _hasher = PasswordHasher( + time_cost=iterations, + memory_cost=memory_kib, + parallelism=parallelism, + hash_len=32, + salt_len=16, + type=Type.ID, + ) + if _dummy_hash is None: + _dummy_hash = _hasher.hash("messenger-dummy-password-not-used-for-login") + + +def get_hasher() -> PasswordHasher: + if _hasher is None: + raise SystemExit("password hasher is not initialized") + return _hasher + + +def hash_password(password: str) -> str: + return get_hasher().hash(password) + + +def verify_password(password: str, password_hash: str | None) -> bool: + init_security() + try: + get_hasher().verify(password_hash or _dummy_hash, password) + matched = True + except (VerifyMismatchError, InvalidHashError): + matched = False + return password_hash is not None and matched + + +def parse_basic(header: str) -> tuple[str, str] | None: + if not header: + return None + scheme, _, rest = header.partition(" ") + if scheme.lower() != "basic" or not rest.strip(): + return None + try: + decoded = base64.b64decode(rest.strip(), validate=True) + text = decoded.decode("utf-8") + except (ValueError, UnicodeError, binascii.Error): + return None + username, separator, password = text.partition(":") + if separator != ":" or len(username) > 256 or len(password) > 1024: + return None + return username, password diff --git a/src/app/sessions.py b/src/app/sessions.py new file mode 100644 index 0000000..3caa3b8 --- /dev/null +++ b/src/app/sessions.py @@ -0,0 +1,97 @@ +import hashlib +import json +import logging +import secrets +from datetime import timedelta +from uuid import UUID + +from redis.asyncio import Redis +from redis.exceptions import RedisError + +from app.config import Settings +from app.errors import AppError +from app.runtime import require_redis, require_settings +from app.timeutil import format_time, parse_time, utcnow +from app.tlsutil import client_context + +logger = logging.getLogger("app.sessions") + + +def build_redis(settings: Settings) -> Redis: + kwargs = { + "decode_responses": True, + "socket_timeout": settings.redis_socket_timeout_seconds, + "socket_connect_timeout": settings.redis_socket_timeout_seconds, + "health_check_interval": 30, + "max_connections": settings.redis_max_connections, + } + if settings.cache_url.startswith("rediss://"): + if not settings.tls_ca_file: + raise SystemExit("TLS_CA_FILE is required for rediss") + kwargs["ssl_cert_reqs"] = "required" + kwargs["ssl_ca_certs"] = settings.tls_ca_file + kwargs["ssl_check_hostname"] = True + return Redis.from_url(settings.cache_url, **kwargs) + + +def session_key(token: str) -> str: + digest = hashlib.sha256(token.encode("utf-8")).hexdigest() + return "sess:" + digest + + +async def _call(awaitable): + try: + return await awaitable + except RedisError: + logger.warning("redis unavailable type=%s", "RedisError") + raise AppError(503, "unavailable", "Сервис временно недоступен") from None + + +def _read_payload(raw: str) -> tuple[UUID, object] | None: + try: + data = json.loads(raw) + if not isinstance(data, dict): + raise ValueError("payload") + return UUID(str(data["user_id"])), parse_time(data["expires_at"]) + except (ValueError, KeyError, TypeError): + return None + + +async def create_session(user_id: UUID) -> tuple[str, object]: + settings = require_settings() + token = secrets.token_urlsafe(32) + expires_at = utcnow() + timedelta(seconds=settings.session_ttl_seconds) + payload = json.dumps( + {"user_id": str(user_id), "expires_at": format_time(expires_at)}, + separators=(",", ":"), + ) + # PXAT — абсолютное время. Повтор AOF после рестарта не продлевает TTL. + await _call(require_redis().set(session_key(token), payload, pxat=int(expires_at.timestamp() * 1000))) + return token, expires_at + + +async def resolve_session(token: str) -> UUID | None: + key = session_key(token) + raw = await _call(require_redis().get(key)) + if raw is None: + return None + parsed = _read_payload(raw) + if parsed is None: + await _call(require_redis().delete(key)) + return None + user_id, expires_at = parsed + if expires_at <= utcnow(): + await _call(require_redis().delete(key)) + return None + return user_id + + +async def revoke_session(token: str) -> bool: + raw = await _call(require_redis().getdel(session_key(token))) + if raw is None: + return False + parsed = _read_payload(raw) + if parsed is None: + return False + _, expires_at = parsed + return expires_at > utcnow() diff --git a/src/app/storage/__init__.py b/src/app/storage/__init__.py new file mode 100644 index 0000000..f1a2a51 --- /dev/null +++ b/src/app/storage/__init__.py @@ -0,0 +1 @@ +"""Состояние лабораторной 2 хранится в PostgreSQL и Redis, не в памяти процесса.""" diff --git a/src/app/storage/memory.py b/src/app/storage/memory.py new file mode 100644 index 0000000..e8b0b7f --- /dev/null +++ b/src/app/storage/memory.py @@ -0,0 +1,5 @@ +"""Память процесса больше не хранит пользователей, чаты и сообщения. + +Источник истины для этих данных — PostgreSQL. +Источник истины для сессий — Redis с AOF и абсолютным PXAT. +""" diff --git a/src/app/telemetry.py b/src/app/telemetry.py new file mode 100644 index 0000000..d0840dc --- /dev/null +++ b/src/app/telemetry.py @@ -0,0 +1,504 @@ +import json +import logging +import os +import re +import sys +import threading +import time +from datetime import datetime, timezone + +from opentelemetry import metrics, trace +from opentelemetry.context import Context +from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter +from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter +from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter +from opentelemetry.propagate import extract, inject +from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler +from opentelemetry.sdk._logs.export import BatchLogRecordProcessor +from opentelemetry.sdk.metrics import MeterProvider +from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader +from opentelemetry.sdk.metrics.view import ExplicitBucketHistogramAggregation, View +from opentelemetry.sdk.resources import Resource +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import BatchSpanProcessor +from opentelemetry.trace import SpanKind, Status, StatusCode + +logger = logging.getLogger("app.telemetry") + +SERVICE_VERSION = "1.6.0" +_TRACEPARENT = re.compile(r"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$") +_SECRET = re.compile( + r"(?i)(authorization\s*[:=]\s*\S+|bearer\s+[A-Za-z0-9._~+/=-]+|password\s*[:=]\s*\S+|token\s*[:=]\s*\S+)" +) + +_lock = threading.Lock() +_logging_ready = False +_telemetry_ready = False +_service_name = "messenger" +_http_requests = None +_http_duration = None +_jobs = None +_job_duration = None +_time_to_ready = None +_queue_depth = 0.0 +_queue_age = 0.0 +_engine = None +_pool_capacity = 0 +_pool_waiting = 0 +_worker_busy = 0 +_worker_capacity = 0 +_cpu_last = None +_cpu_at = None + + +def service_name_for(role: str) -> str: + configured = os.environ.get("OTEL_SERVICE_NAME", "").strip() + if configured: + return configured + return { + "api": "messenger-api", + "worker": "messenger-worker", + "relay": "messenger-relay", + "gc": "messenger-gc", + }.get(role, "messenger-" + role) + + +def _redact(text: str) -> str: + cleaned = _SECRET.sub("[redacted]", text) + if len(cleaned) > 2000: + return cleaned[:2000] + return cleaned + + +class EventFilter(logging.Filter): + def filter(self, record: logging.LogRecord) -> bool: + message = record.getMessage() + if message.startswith("event="): + record.event = message.split(" ", 1)[0].split("=", 1)[1] + else: + record.event = record.name + return True + + +class JsonFormatter(logging.Formatter): + def format(self, record: logging.LogRecord) -> str: + span = trace.get_current_span() + context = span.get_span_context() + trace_id = format(context.trace_id, "032x") if context.is_valid else "" + span_id = format(context.span_id, "016x") if context.is_valid else "" + payload = { + "timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ"), + "severity": record.levelname, + "service.name": _service_name, + "event": getattr(record, "event", record.name), + "message": _redact(record.getMessage()), + "trace_id": trace_id, + "span_id": span_id, + } + return json.dumps(payload, ensure_ascii=False) + + +def setup_logging(role: str) -> None: + global _logging_ready, _service_name + _service_name = service_name_for(role) + if _logging_ready: + return + root = logging.getLogger() + root.handlers.clear() + root.setLevel(logging.INFO) + root.addFilter(EventFilter()) + stream = logging.StreamHandler(sys.stdout) + stream.setFormatter(JsonFormatter()) + root.addHandler(stream) + for name in ( + "sqlalchemy.engine", + "sqlalchemy.pool", + "asyncpg", + "aio_pika", + "aiormq", + "botocore", + "boto3", + "urllib3", + "opentelemetry", + "uvicorn.access", + ): + logging.getLogger(name).setLevel(logging.WARNING) + _logging_ready = True + + +def _endpoint(suffix: str) -> str: + base = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "http://otel-collector:4318").strip().rstrip("/") + if base.endswith(suffix): + return base + return base + suffix + + +def _disabled() -> bool: + return os.environ.get("OTEL_SDK_DISABLED", "").strip().lower() in {"1", "true", "yes", "on"} + + +def _otlp_kwargs() -> dict: + kwargs = {} + ca_file = os.environ.get("OTEL_EXPORTER_OTLP_CERTIFICATE", "").strip() or os.environ.get("TLS_CA_FILE", "").strip() + endpoint = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "") + if endpoint.startswith("https://"): + if not ca_file: + raise SystemExit("TLS CA is required for https OTLP") + kwargs["certificate_file"] = ca_file + token = os.environ.get("OTEL_AUTH_TOKEN", "").strip() + if token: + kwargs["headers"] = {"Authorization": "Bearer " + token} + return kwargs + + +def setup_telemetry(settings) -> None: + global _telemetry_ready, _http_requests, _http_duration, _jobs, _job_duration, _time_to_ready + setup_logging(settings.app_role) + if _telemetry_ready or _disabled(): + return + resource = Resource.create( + { + "service.name": service_name_for(settings.app_role), + "service.version": SERVICE_VERSION, + "service.instance.id": settings.instance_id, + "deployment.environment.name": settings.env or "lab", + } + ) + timeout = 5 + otlp_kwargs = _otlp_kwargs() + tracer_provider = TracerProvider(resource=resource) + tracer_provider.add_span_processor( + BatchSpanProcessor( + OTLPSpanExporter(endpoint=_endpoint("/v1/traces"), timeout=timeout, **otlp_kwargs), + max_queue_size=2048, + schedule_delay_millis=5000, + max_export_batch_size=256, + export_timeout_millis=10000, + ) + ) + trace.set_tracer_provider(tracer_provider) + reader = PeriodicExportingMetricReader( + OTLPMetricExporter(endpoint=_endpoint("/v1/metrics"), timeout=timeout, **otlp_kwargs), + export_interval_millis=10000, + export_timeout_millis=5000, + ) + meter_provider = MeterProvider( + resource=resource, + metric_readers=[reader], + views=[ + View( + instrument_name="http.server.duration", + aggregation=ExplicitBucketHistogramAggregation((0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10)), + ), + View( + instrument_name="jobs.duration", + aggregation=ExplicitBucketHistogramAggregation((0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60)), + ), + View( + instrument_name="attachment.time_to_ready", + aggregation=ExplicitBucketHistogramAggregation((0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120)), + ), + ], + ) + metrics.set_meter_provider(meter_provider) + meter = metrics.get_meter("messenger", SERVICE_VERSION) + _http_requests = meter.create_counter("http.server.requests", unit="1", description="Business and health HTTP requests") + _http_duration = meter.create_histogram("http.server.duration", unit="s", description="HTTP server duration") + _jobs = meter.create_counter("jobs.processed", unit="1", description="Attachment jobs by outcome") + _job_duration = meter.create_histogram("jobs.duration", unit="s", description="Job handling duration") + _time_to_ready = meter.create_histogram( + "attachment.time_to_ready", + unit="s", + description="Seconds from durable acceptance to ready", + ) + meter.create_observable_gauge("queue.depth", callbacks=[_observe_depth], unit="1", description="Jobs queued or processing") + meter.create_observable_gauge( + "queue.oldest_age", + callbacks=[_observe_age], + unit="s", + description="Age of the oldest queued or processing job", + ) + meter.create_observable_gauge( + "db.pool.connections", + callbacks=[_observe_pool], + unit="1", + description="Database pool used, waiting and capacity", + ) + meter.create_observable_gauge( + "worker.slots", + callbacks=[_observe_worker], + unit="1", + description="Worker slots busy and capacity", + ) + meter.create_observable_gauge( + "process.cpu.utilization", + callbacks=[_observe_cpu], + unit="1", + description="Process CPU seconds per wall second", + ) + meter.create_observable_gauge( + "process.memory.usage", + callbacks=[_observe_memory], + unit="By", + description="Process resident memory", + ) + log_provider = LoggerProvider(resource=resource) + log_provider.add_log_record_processor( + BatchLogRecordProcessor( + OTLPLogExporter(endpoint=_endpoint("/v1/logs"), timeout=timeout, **otlp_kwargs), + max_queue_size=2048, + schedule_delay_millis=5000, + max_export_batch_size=256, + export_timeout_millis=10000, + ) + ) + class _SkipSdk(logging.Filter): + def filter(self, record: logging.LogRecord) -> bool: + return not record.name.startswith("opentelemetry") + + log_handler = LoggingHandler(level=logging.INFO, logger_provider=log_provider) + log_handler.addFilter(_SkipSdk()) + logging.getLogger().addHandler(log_handler) + _telemetry_ready = True + logger.info("telemetry enabled service=%s", service_name_for(settings.app_role)) + + +def bind_engine(engine, capacity: int) -> None: + global _engine, _pool_capacity + _engine = engine + _pool_capacity = capacity + pool = engine.sync_engine.pool + if getattr(pool, "_messenger_wrapped", False): + return + original = getattr(pool, "_do_get", None) + if original is None: + return + + def wrapped(*args, **kwargs): + global _pool_waiting + with _lock: + _pool_waiting += 1 + try: + return original(*args, **kwargs) + finally: + with _lock: + _pool_waiting = max(0, _pool_waiting - 1) + + pool._do_get = wrapped + pool._messenger_wrapped = True + + +def set_worker_capacity(value: int) -> None: + global _worker_capacity + _worker_capacity = value + + +def worker_enter() -> None: + global _worker_busy + with _lock: + _worker_busy += 1 + + +def worker_leave() -> None: + global _worker_busy + with _lock: + _worker_busy = max(0, _worker_busy - 1) + + +def set_queue_snapshot(depth: int, age_seconds: float) -> None: + global _queue_depth, _queue_age + with _lock: + _queue_depth = float(depth) + _queue_age = float(age_seconds) + + +def _observe_depth(_options): + from opentelemetry.metrics import Observation + + with _lock: + value = _queue_depth + yield Observation(value, {"queue": "attachment.jobs"}) + + +def _observe_age(_options): + from opentelemetry.metrics import Observation + + with _lock: + value = _queue_age + yield Observation(value, {"queue": "attachment.jobs"}) + + +def _observe_pool(_options): + from opentelemetry.metrics import Observation + + used = 0 + engine = _engine + if engine is not None: + try: + used = int(engine.sync_engine.pool.checkedout()) + except Exception: + used = 0 + with _lock: + waiting = _pool_waiting + capacity = _pool_capacity + yield Observation(used, {"state": "used"}) + yield Observation(waiting, {"state": "waiting"}) + yield Observation(capacity, {"state": "capacity"}) + + +def _observe_worker(_options): + from opentelemetry.metrics import Observation + + with _lock: + busy = _worker_busy + capacity = _worker_capacity + yield Observation(busy, {"state": "busy"}) + yield Observation(capacity, {"state": "capacity"}) + + +def _cpu_seconds() -> float | None: + try: + raw = open("/proc/self/stat", encoding="utf-8").read() + fields = raw.rsplit(")", 1)[1].split() + ticks = os.sysconf("SC_CLK_TCK") + return (int(fields[11]) + int(fields[12])) / ticks + except (OSError, IndexError, ValueError): + return None + + +def _observe_cpu(_options): + from opentelemetry.metrics import Observation + + global _cpu_last, _cpu_at + now = time.monotonic() + cpu = _cpu_seconds() + ratio = 0.0 + if cpu is not None and _cpu_last is not None and _cpu_at is not None: + elapsed = now - _cpu_at + if elapsed > 0: + ratio = max(0.0, (cpu - _cpu_last) / elapsed) + if cpu is not None: + _cpu_last = cpu + _cpu_at = now + yield Observation(ratio, {}) + + +def _observe_memory(_options): + from opentelemetry.metrics import Observation + + value = 0 + try: + pages = int(open("/proc/self/statm", encoding="utf-8").read().split()[1]) + value = pages * os.sysconf("SC_PAGE_SIZE") + except (OSError, IndexError, ValueError): + value = 0 + yield Observation(value, {}) + + +def record_http(method: str, route: str, status: int, duration_seconds: float) -> None: + if _http_requests is None or _http_duration is None: + return + status_class = "%sxx" % (int(status) // 100) + sli = "excluded" if route.startswith("/health/") else "business" + attributes = {"method": method, "route": route, "status_class": status_class, "sli": sli} + _http_requests.add(1, attributes) + _http_duration.record(max(0.0, duration_seconds), attributes) + + +def record_job(outcome: str, duration_seconds: float) -> None: + if _jobs is None or _job_duration is None: + return + attributes = {"job_type": "attachment.process.v1", "outcome": outcome} + _jobs.add(1, attributes) + _job_duration.record(max(0.0, duration_seconds), attributes) + + +def record_time_to_ready(seconds: float) -> None: + if _time_to_ready is None: + return + _time_to_ready.record(max(0.0, seconds), {"job_type": "attachment.process.v1"}) + + +def current_trace_fields() -> dict: + carrier: dict[str, str] = {} + inject(carrier) + fields = {} + parent = carrier.get("traceparent") + if isinstance(parent, str) and _TRACEPARENT.match(parent): + fields["traceparent"] = parent + state = carrier.get("tracestate") + if isinstance(state, str) and state: + fields["tracestate"] = state[:512] + return fields + + +def trace_context(carrier: dict) -> Context: + return extract({key: value for key, value in carrier.items() if value}) + + +def inject_headers() -> dict: + return current_trace_fields() + + +def flush_telemetry() -> None: + provider = trace.get_tracer_provider() + force = getattr(provider, "force_flush", None) + if force is not None: + try: + force(timeout_millis=2000) + except Exception: + logger.warning("trace flush failed") + + +def server_span(method: str, carrier: dict): + tracer = trace.get_tracer("messenger.api", SERVICE_VERSION) + return tracer.start_as_current_span( + method, + context=trace_context(carrier), + kind=SpanKind.SERVER, + attributes={"http.request.method": method}, + ) + + +def messaging_span(name: str, kind: SpanKind, carrier: dict | None = None): + tracer = trace.get_tracer("messenger.jobs", SERVICE_VERSION) + kwargs = {"kind": kind} + if carrier: + kwargs["context"] = trace_context(carrier) + return tracer.start_as_current_span(name, **kwargs) + + +def child_span(name: str): + tracer = trace.get_tracer("messenger.jobs", SERVICE_VERSION) + return tracer.start_as_current_span(name, kind=SpanKind.INTERNAL) + + +def mark_error(span) -> None: + if span is not None: + span.set_status(Status(StatusCode.ERROR)) + + +async def sample_queue(engine, stop) -> None: + import asyncio + + from sqlalchemy import text + + while not stop.is_set(): + try: + async with engine.connect() as conn: + depth = await conn.scalar( + text("SELECT count(*) FROM attachment_jobs WHERE status IN ('queued', 'processing')") + ) + age = await conn.scalar( + text( + "SELECT COALESCE(EXTRACT(EPOCH FROM (now() - min(created_at))), 0) " + "FROM attachment_jobs WHERE status IN ('queued', 'processing')" + ) + ) + set_queue_snapshot(int(depth or 0), float(age or 0)) + except Exception as exc: + logger.warning("queue sample failed type=%s", type(exc).__name__) + try: + await asyncio.wait_for(stop.wait(), timeout=5) + except asyncio.TimeoutError: + continue diff --git a/src/app/timeutil.py b/src/app/timeutil.py new file mode 100644 index 0000000..08421fb --- /dev/null +++ b/src/app/timeutil.py @@ -0,0 +1,20 @@ +from datetime import datetime, timezone + + +def utcnow() -> datetime: + return datetime.now(timezone.utc) + + +def format_time(value: datetime) -> str: + if value.tzinfo is None: + value = value.replace(tzinfo=timezone.utc) + return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ") + + +def parse_time(value: str) -> datetime: + if not isinstance(value, str) or not value.endswith("Z"): + raise ValueError("time") + parsed = datetime.fromisoformat(value[:-1] + "+00:00") + if parsed.tzinfo is None: + raise ValueError("time") + return parsed.astimezone(timezone.utc) diff --git a/src/app/tlsutil.py b/src/app/tlsutil.py new file mode 100644 index 0000000..fd3bfa3 --- /dev/null +++ b/src/app/tlsutil.py @@ -0,0 +1,16 @@ +import os +import ssl + + +def client_context(ca_file: str) -> ssl.SSLContext: + if not ca_file: + raise SystemExit("TLS CA file is empty") + ctx = ssl.create_default_context(cafile=ca_file) + ctx.minimum_version = ssl.TLSVersion.TLSv1_2 + ctx.check_hostname = True + ctx.verify_mode = ssl.CERT_REQUIRED + return ctx + + +def ca_file_from_env() -> str: + return os.environ.get("TLS_CA_FILE", "").strip() diff --git a/src/app/vault.py b/src/app/vault.py new file mode 100644 index 0000000..33f3fa7 --- /dev/null +++ b/src/app/vault.py @@ -0,0 +1,109 @@ +import json +import logging +import os +import ssl +import time +import urllib.error +import urllib.request +from pathlib import Path + +logger = logging.getLogger("app.vault") + +_ENV = { + "database_url": "DATABASE_URL", + "redis_url": "REDIS_URL", + "s3_access_key_id": "S3_ACCESS_KEY_ID", + "s3_secret_access_key": "S3_SECRET_ACCESS_KEY", + "broker_url": "BROKER_URL", + "otel_token": "OTEL_AUTH_TOKEN", +} + + +def _read(path: str) -> str: + try: + value = Path(path).read_text(encoding="utf-8").strip() + except OSError as exc: + raise SystemExit("cannot read OpenBao credential file") from exc + if not value: + raise SystemExit("OpenBao credential file is empty") + return value + + +def _request(url: str, ctx: ssl.SSLContext, method: str, body: dict | None, token: str) -> dict: + data = None if body is None else json.dumps(body).encode("utf-8") + request = urllib.request.Request(url, data=data, method=method) + request.add_header("Content-Type", "application/json") + if token: + request.add_header("X-Vault-Token", token) + try: + with urllib.request.urlopen(request, context=ctx, timeout=5) as response: + raw = response.read() + except urllib.error.HTTPError as exc: + # Тело ответа может содержать подробности политики. В лог его не кладём. + raise RuntimeError("openbao http %s" % exc.code) from None + if not raw: + return {} + try: + parsed = json.loads(raw.decode("utf-8")) + except (UnicodeError, json.JSONDecodeError) as exc: + raise RuntimeError("openbao returned invalid json") from exc + if not isinstance(parsed, dict): + raise RuntimeError("openbao returned an unexpected payload") + return parsed + + +def hydrate_secrets() -> None: + addr = os.environ.get("BAO_ADDR", "").strip().rstrip("/") + if not addr: + return + if os.environ.get("DATABASE_URL", "").strip(): + return + ca = os.environ.get("BAO_CACERT", "").strip() or os.environ.get("TLS_CA_FILE", "").strip() + role_file = os.environ.get("BAO_ROLE_ID_FILE", "").strip() + secret_file = os.environ.get("BAO_SECRET_ID_FILE", "").strip() + kv_path = os.environ.get("BAO_KV_PATH", "").strip().lstrip("/") + if not ca or not role_file or not secret_file or not kv_path: + raise SystemExit("BAO_CACERT, BAO_ROLE_ID_FILE, BAO_SECRET_ID_FILE and BAO_KV_PATH are required") + ctx = ssl.create_default_context(cafile=ca) + ctx.minimum_version = ssl.TLSVersion.TLSv1_2 + ctx.check_hostname = True + role_id = _read(role_file) + secret_id = _read(secret_file) + token = "" + for attempt in range(60): + try: + if not token: + login = _request( + addr + "/v1/auth/approle/login", + ctx, + "POST", + {"role_id": role_id, "secret_id": secret_id}, + "", + ) + auth = login.get("auth") + if not isinstance(auth, dict) or not auth.get("client_token"): + raise RuntimeError("openbao login has no token") + token = str(auth["client_token"]) + payload = _request(addr + "/v1/" + kv_path, ctx, "GET", None, token) + data = payload.get("data", {}) + secret = data.get("data") if isinstance(data, dict) else None + if not isinstance(secret, dict): + raise RuntimeError("openbao kv payload is missing") + applied = 0 + for source, target in _ENV.items(): + value = secret.get(source) + if isinstance(value, str) and value.strip(): + os.environ[target] = value.strip() + applied += 1 + if applied == 0: + raise RuntimeError("openbao kv secret is empty") + logger.info("secrets loaded from openbao path=%s fields=%s", kv_path, applied) + return + except RuntimeError as exc: + logger.warning("openbao not ready reason=%s attempt=%s", exc, attempt + 1) + except (urllib.error.URLError, TimeoutError, OSError) as exc: + logger.warning("openbao unreachable type=%s attempt=%s", type(exc).__name__, attempt + 1) + token = "" + if attempt == 59: + raise SystemExit("openbao secrets are not available") from None + time.sleep(1) diff --git a/src/app/worker.py b/src/app/worker.py new file mode 100644 index 0000000..c313c4d --- /dev/null +++ b/src/app/worker.py @@ -0,0 +1,345 @@ +import asyncio +import hashlib +import json +import logging +import os +import signal +import socket +import sys +import time +from pathlib import Path +from uuid import UUID + +from opentelemetry.trace import SpanKind + +from app.broker import DLQ_KEY, connect, declare, publish +from app.config import load_settings +from app.db import build_engine, build_session_factory +from app.errors import AppError +from app.faults import read_faults +from app.jobs import acquire_job, fail_or_retry, finalize_job, mark_objects_written, sweep_expired_leases +from app.migrate import wait_for_database, wait_for_schema +from app.pipeline import render_in_process, variant_names +from app.runtime import configure, require_settings, require_store +from app.s3 import build_store +from app.telemetry import ( + bind_engine, + child_span, + flush_telemetry, + mark_error, + messaging_span, + record_job, + set_worker_capacity, + setup_logging, + setup_telemetry, + worker_enter, + worker_leave, +) + +logger = logging.getLogger("app.worker") + + +class Publisher: + exchange = None + + +def flush_logs() -> None: + for handler in logging.getLogger().handlers: + handler.flush() + sys.stdout.flush() + + +def message_carrier(message) -> dict: + carrier = {} + headers = getattr(message, "headers", None) or {} + for key in ("traceparent", "tracestate"): + value = headers.get(key) + if isinstance(value, bytes): + value = value.decode("utf-8", "replace") + if isinstance(value, str) and value: + carrier[key] = value + if "traceparent" in carrier: + return carrier + try: + payload = json.loads(message.body.decode("utf-8")) + except (UnicodeError, ValueError): + return carrier + if isinstance(payload, dict): + for key in ("traceparent", "tracestate"): + value = payload.get(key) + if isinstance(value, str) and value and key not in carrier: + carrier[key] = value + return carrier + + +def outcome_of(result: str) -> str: + if result == "retry": + return "retry" + if result.startswith("failed:"): + return "failed" + return "ignored" + + +def parse_job_id(body: bytes) -> UUID | None: + try: + payload = json.loads(body.decode("utf-8")) + except (UnicodeError, ValueError): + return None + if not isinstance(payload, dict) or payload.get("type") != "attachment.process.v1": + return None + try: + return UUID(str(payload.get("job_id"))) + except (TypeError, ValueError): + return None + + +async def emit_terminal(result: str) -> None: + if not result.startswith("failed:"): + return + payload = result[len("failed:") :] + exchange = Publisher.exchange + if exchange is None: + logger.warning("dlq skipped because the broker exchange is not ready") + return + try: + await publish(exchange, payload, DLQ_KEY) + logger.info("terminal failure copied to dlq") + except Exception as exc: + logger.warning("dlq publish failed type=%s", type(exc).__name__) + + +async def handle(message, owner: str) -> str: + job_id = parse_job_id(message.body) + if job_id is None: + logger.warning("discarded job message type=invalid") + return "invalid" + from opentelemetry import trace as otel_trace + + otel_trace.get_current_span().set_attribute("messaging.message.id", str(job_id)) + acquired = await acquire_job(job_id, owner, bool(getattr(message, "redelivered", False))) + if acquired.action != "acquired" or acquired.job_id is None or acquired.attachment_id is None: + action = acquired.action or "ignored" + return "duplicate" if action == "ready" else action + settings = require_settings() + faults = read_faults(settings.faults_file) + if faults.inject_transient and acquired.objects_written_at is None: + logger.warning("injected transient failure job_id=%s attempt=%s", acquired.job_id, acquired.attempt) + result = await fail_or_retry(acquired.job_id, "processing_failed", False) + await emit_terminal(result) + return outcome_of(result) + store = require_store() + try: + with child_span("s3.get"): + data = await store.get(acquired.staging_key) + except AppError as exc: + permanent = exc.status == 404 + result = await fail_or_retry(acquired.job_id, "processing_failed", permanent) + await emit_terminal(result) + return outcome_of(result) + digest = hashlib.sha256(data).hexdigest() + if digest != acquired.sha256 or len(data) != acquired.size_bytes: + result = await fail_or_retry(acquired.job_id, "processing_failed", True) + await emit_terminal(result) + return outcome_of(result) + timeout = faults.timeout_seconds or settings.job_timeout_seconds + with child_span("image.render"): + rendered = await asyncio.to_thread( + render_in_process, + data, + settings.max_image_pixels, + settings.worker_image_memory_bytes, + settings.jpeg_quality, + settings.webp_quality, + settings.webp_method, + timeout, + faults.stall_seconds, + ) + if not rendered.get("ok"): + result = await fail_or_retry( + acquired.job_id, + str(rendered.get("code") or "processing_failed"), + bool(rendered.get("permanent")), + ) + await emit_terminal(result) + return outcome_of(result) + with child_span("s3.put"): + await store.put(acquired.object_key, data, acquired.content_type) + stored = [] + for name in variant_names(): + item = rendered["variants"][name] + blob = item["data"] + key = "att/%s/%s" % (acquired.attachment_id, name) + await store.put(key, blob, item["content_type"]) + stored.append( + { + "name": name, + "content_type": item["content_type"], + "size_bytes": len(blob), + "width": item["width"], + "height": item["height"], + "sha256": hashlib.sha256(blob).hexdigest(), + "object_key": key, + } + ) + with child_span("db.mark_objects"): + await mark_objects_written(acquired.job_id) + if faults.crash_after_s3 and acquired.objects_written_at is None: + logger.error("injected crash after object write before ack job_id=%s", acquired.job_id) + current = otel_trace.get_current_span() + mark_error(current) + if hasattr(current, "end"): + current.end() + flush_logs() + flush_telemetry() + os._exit(86) + with child_span("db.finalize"): + outcome = await finalize_job(acquired.job_id, stored) + if outcome == "incomplete": + result = await fail_or_retry(acquired.job_id, "processing_failed", False) + await emit_terminal(result) + return outcome_of(result) + try: + await store.delete(acquired.staging_key) + except AppError: + logger.warning("staging delete failed job_id=%s", acquired.job_id) + logger.info("job ready job_id=%s attachment_id=%s", acquired.job_id, acquired.attachment_id) + return "ready" if outcome == "ready" else "duplicate" + + +async def beat(path: str, stop: asyncio.Event) -> None: + file = Path(path) + while not stop.is_set(): + file.write_text("ok", encoding="utf-8") + try: + await asyncio.wait_for(stop.wait(), timeout=2) + except asyncio.TimeoutError: + continue + + +async def sweep_loop(stop: asyncio.Event) -> None: + while not stop.is_set(): + try: + await sweep_expired_leases() + except Exception as exc: + logger.warning("lease sweep failed type=%s", type(exc).__name__) + try: + await asyncio.wait_for(stop.wait(), timeout=2) + except asyncio.TimeoutError: + continue + + +async def open_broker(url: str): + for attempt in range(40): + try: + return await connect(url) + except Exception as exc: + logger.warning("broker not ready type=%s attempt=%s", type(exc).__name__, attempt + 1) + await asyncio.sleep(0.5) + raise SystemExit("broker is not ready") + + +async def consume(stop: asyncio.Event) -> None: + settings = require_settings() + owner = "%s:%s" % (socket.gethostname(), os.getpid()) + semaphore = asyncio.Semaphore(settings.worker_concurrency) + set_worker_capacity(settings.worker_concurrency) + + async def on_message(message) -> None: + with messaging_span("process attachment.jobs", SpanKind.CONSUMER, message_carrier(message)) as span: + span.set_attribute("messaging.system", "rabbitmq") + span.set_attribute("messaging.destination.name", "attachment.jobs") + span.set_attribute("messaging.operation.name", "process") + span.set_attribute("messaging.operation.type", "process") + async with semaphore: + worker_enter() + started = time.perf_counter() + outcome = "error" + try: + outcome = await handle(message, owner) + span.set_attribute("app.job.outcome", outcome) + if outcome in {"failed", "error"}: + mark_error(span) + await message.ack() + except Exception as exc: + outcome = "error" + mark_error(span) + logger.warning("worker message failed type=%s", type(exc).__name__) + try: + await message.nack(requeue=False) + except Exception as nack_error: + logger.warning("nack failed type=%s", type(nack_error).__name__) + finally: + record_job(outcome, time.perf_counter() - started) + worker_leave() + + while not stop.is_set(): + connection = None + try: + connection = await open_broker(settings.broker_url) + channel = await connection.channel() + await channel.set_qos(prefetch_count=settings.worker_concurrency) + publisher = await connection.channel(publisher_confirms=True) + exchange, _queue = await declare(publisher) + _exchange, queue = await declare(channel) + Publisher.exchange = exchange + await queue.consume(on_message) + logger.info("worker consuming prefetch=%s", settings.worker_concurrency) + await stop.wait() + except Exception as exc: + if stop.is_set(): + break + logger.warning("worker consume interrupted type=%s", type(exc).__name__) + await asyncio.sleep(1) + finally: + if connection is not None: + try: + await connection.close() + except Exception as exc: + logger.warning("broker close failed type=%s", type(exc).__name__) + + +async def serve() -> None: + settings = load_settings() + setup_logging(settings.app_role) + setup_telemetry(settings) + engine = build_engine(settings) + bind_engine(engine, settings.db_pool_size + settings.db_max_overflow) + store = build_store(settings) + stop = asyncio.Event() + try: + await wait_for_database(engine) + await wait_for_schema(engine, settings.migrations_dir) + for _attempt in range(40): + try: + await store.ping() + break + except Exception: + logger.warning("s3 not ready") + await asyncio.sleep(0.5) + else: + raise SystemExit("s3 is not ready") + configure(build_session_factory(engine), None, settings, store) + loop = asyncio.get_running_loop() + for sig in (signal.SIGTERM, signal.SIGINT): + try: + loop.add_signal_handler(sig, stop.set) + except NotImplementedError: + pass + heart = asyncio.create_task(beat("/tmp/worker-heartbeat", stop)) + sweeper = asyncio.create_task(sweep_loop(stop)) + try: + await consume(stop) + finally: + stop.set() + heart.cancel() + sweeper.cancel() + finally: + await engine.dispose() + + +def main() -> None: + asyncio.run(serve()) + + +if __name__ == "__main__": + main() diff --git a/student-tests/attachments.py b/student-tests/attachments.py new file mode 100644 index 0000000..52d195f --- /dev/null +++ b/student-tests/attachments.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python3 +"""Негативные проверки вложений для оценки 4: лимиты, MIME, ACL, чужой чат.""" + +import json +import os +import struct +import sys +import time +import uuid +import zlib +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +from client import Client, Failure, check, run + +EVIDENCE = ROOT / "evidence" +BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/") +SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes() + + +def png(width: int, height: int, extra: bytes = b"") -> bytes: + def chunk(tag: bytes, data: bytes) -> bytes: + crc = zlib.crc32(tag + data) & 0xFFFFFFFF + return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", crc) + + ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0) + return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + extra + chunk(b"IEND", b"") + + +def upload(client, actor, chat, filename, body, content_type, expected): + return client.call( + "POST", + "/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], filename), + expected, + actor=actor, + raw=body, + headers={"Content-Type": content_type}, + schema="Attachment" if expected in (201, 202) else None, + ) + + +def main(): + client = Client(BASE, timeout=30) + alice, bob, eve, chat = client.bootstrap() + other = client.call( + "POST", + "/api/v1/chats", + 201, + actor=eve, + body={"title": "Чужой", "member_ids": [eve["id"]]}, + schema="Chat", + )["json"] + att, content = client.attachment(alice, chat) + att = client.wait_ready(alice, att) + check(content == SAMPLE, "fixture changed") + + too_big = upload(client, alice, chat, "big.png", SAMPLE + b"x" * (10 * 1024 * 1024), "image/png", 413) + check(too_big["json"]["error"]["code"] == "payload_too_large", "oversize code") + + spoof = upload(client, alice, chat, "spoof.png", SAMPLE, "image/jpeg", 415) + check(spoof["json"]["error"]["code"] == "unsupported_media_type", "spoofed MIME code") + + broken = upload(client, alice, chat, "broken.png", b"\x89PNG\r\n\x1a\nnot-an-image", "image/png", 415) + check(broken["json"]["error"]["code"] == "unsupported_media_type", "corrupt image code") + + huge = upload(client, alice, chat, "huge.png", png(10001, 4000), "image/png", 413) + check(huge["json"]["error"]["code"] == "payload_too_large", "pixel limit code") + + slash = upload(client, alice, chat, "a/b.png", SAMPLE, "image/png", 400) + check(slash["json"]["error"]["code"] == "invalid_request", "slash filename code") + + missing = client.call( + "GET", + "/api/v1/attachments/%s" % uuid.uuid4(), + 404, + actor=alice, + ) + check(missing["json"]["error"]["code"] == "not_found", "unknown attachment") + + stolen = client.call("GET", "/api/v1/attachments/%s" % att["id"], 404, actor=eve) + check(stolen["json"]["error"]["code"] == "not_found", "outsider metadata") + stolen_bytes = client.call("GET", "/api/v1/attachments/%s/content" % att["id"], 404, actor=eve) + check(stolen_bytes["json"]["error"]["code"] == "not_found", "outsider bytes") + + foreign_file = upload(client, eve, other, "other.png", SAMPLE, "image/png", 202)["json"] + linked = client.call( + "POST", + "/api/v1/chats/%s/messages" % chat["id"], + 404, + actor=alice, + body={"text": "", "attachment_ids": [foreign_file["id"]]}, + headers={"Idempotency-Key": uuid.uuid4().hex}, + ) + check(linked["json"]["error"]["code"] == "not_found", "cross-chat attachment") + + unknown_link = client.call( + "POST", + "/api/v1/chats/%s/messages" % chat["id"], + 404, + actor=alice, + body={"text": "x", "attachment_ids": [str(uuid.uuid4())]}, + headers={"Idempotency-Key": uuid.uuid4().hex}, + ) + check(unknown_link["json"]["error"]["code"] == "not_found", "unknown attachment_id") + + ok = client.message(alice, chat, "", attachments=[att["id"]])["json"] + check(ok["attachment_ids"] == [att["id"]], "empty text with attachment") + download = client.call("GET", "/api/v1/attachments/%s/content" % att["id"], actor=bob) + check(download["bytes"] == SAMPLE, "member download mismatch") + + EVIDENCE.mkdir(exist_ok=True) + (EVIDENCE / "attachments.json").write_text( + json.dumps( + { + "date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "oversize": too_big["status"], + "spoofed_mime": spoof["status"], + "corrupt": broken["status"], + "pixels": huge["status"], + "foreign_chat": linked["status"], + "outsider": stolen["status"], + }, + indent=2, + ) + + "\n", + encoding="utf-8", + ) + print("PASS: attachment validation and ACL") + + +if __name__ == "__main__": + run(main) diff --git a/student-tests/failover.py b/student-tests/failover.py new file mode 100644 index 0000000..a655e07 --- /dev/null +++ b/student-tests/failover.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 +"""Запуск публичного failover на Windows и POSIX с тем же scripts/stop-one.sh.""" + +import os +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def script(): + if os.name == "nt": + cmd = ROOT / "scripts" / "stop-one.cmd" + if cmd.is_file(): + return str(cmd) + sh = ROOT / "scripts" / "stop-one.sh" + return str(sh) + + +def main(): + env = os.environ.copy() + command = [ + sys.executable, + str(ROOT / "tests" / "resilience.py"), + "--mode", + "failover", + "--action-script", + script(), + "--base-url", + env.get("BASE_URL", "http://127.0.0.1:8080"), + ] + completed = subprocess.run(command, cwd=str(ROOT), env=env) + raise SystemExit(completed.returncode) + + +if __name__ == "__main__": + main() diff --git a/student-tests/gc_orphans.py b/student-tests/gc_orphans.py new file mode 100644 index 0000000..36227e2 --- /dev/null +++ b/student-tests/gc_orphans.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Orphan object after S3 PUT without DB row is removed after the grace period.""" + +import json +import os +import subprocess +import sys +import time +import uuid +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +from client import Client, Failure, check, run + +EVIDENCE = ROOT / "evidence" +BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/") +BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments") + + +def compose(*args, timeout=120): + proc = subprocess.run( + ["docker", "compose", "--env-file", ".env", *args], + cwd=str(ROOT), + capture_output=True, + text=True, + timeout=timeout, + encoding="utf-8", + errors="replace", + ) + if proc.returncode != 0: + raise Failure("docker compose failed: " + (proc.stderr or proc.stdout)[-400:]) + return proc.stdout + + +def main(): + client = Client(BASE, timeout=20) + alice, _bob, _eve, chat = client.bootstrap() + att, _content = client.attachment(alice, chat) + orphan = "att/orphan-%s" % uuid.uuid4().hex + script = """ +set -eu +ROOT_USER=$(cat /run/secrets/minio_root_user) +ROOT_PASS=$(cat /run/secrets/minio_root_password) +mc alias set local http://minio:9000 "$ROOT_USER" "$ROOT_PASS" >/dev/null +printf 'orphan' | mc pipe local/%s/%s +mc ls local/%s/%s >/dev/null +""" % (BUCKET, orphan, BUCKET, orphan) + compose("run", "--rm", "--no-deps", "--entrypoint", "/bin/sh", "minio-init", "-c", script) + time.sleep(2) + compose( + "run", + "--rm", + "--no-deps", + "-e", + "APP_ROLE=gc", + "-e", + "GC_ONCE=1", + "-e", + "ATTACHMENT_GC_GRACE_SECONDS=1", + "gc", + timeout=180, + ) + missing = compose( + "run", + "--rm", + "--no-deps", + "--entrypoint", + "/bin/sh", + "minio-init", + "-c", + """ +set -eu +ROOT_USER=$(cat /run/secrets/minio_root_user) +ROOT_PASS=$(cat /run/secrets/minio_root_password) +mc alias set local http://minio:9000 "$ROOT_USER" "$ROOT_PASS" >/dev/null +if mc ls local/%s/%s >/dev/null 2>&1; then exit 7; fi +""" + % (BUCKET, orphan), + ) + del missing + client.call("GET", "/api/v1/attachments/%s" % att["id"], actor=alice, schema="Attachment") + EVIDENCE.mkdir(exist_ok=True) + (EVIDENCE / "gc_orphans.json").write_text( + json.dumps( + { + "date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "orphan_removed": True, + "live_attachment_kept": att["id"], + "grace_seconds": 1, + }, + indent=2, + ) + + "\n", + encoding="utf-8", + ) + print("PASS: orphan object removed, live attachment kept") + + +if __name__ == "__main__": + run(main) diff --git a/student-tests/grade4.py b/student-tests/grade4.py new file mode 100644 index 0000000..3ff1e97 --- /dev/null +++ b/student-tests/grade4.py @@ -0,0 +1,408 @@ +#!/usr/bin/env python3 +"""Сценарии оценки 4: варианты, остановка worker, outbox, crash до ack, lease, replay. + +Стенд уже поднят. Скрипт останавливает worker, relay, rabbitmq и API и снова их запускает. +Токены и пароли не печатаются. +""" + +import hashlib +import json +import os +import subprocess +import sys +import time +import uuid +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +from client import Client, Failure, check, run +from image_probe import jpeg_size + +EVIDENCE = ROOT / "evidence" +BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/") +FAULTS = ROOT / "infra" / "faults.json" +SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes() +SAFE = { + "inject_transient": False, + "crash_after_s3": False, + "relay_exit_before_publish": False, + "stall_seconds": 0, + "timeout_seconds": 0, +} + + +def compose(*args, timeout=180): + proc = subprocess.run( + ["docker", "compose", "--env-file", ".env", *args], + cwd=str(ROOT), + capture_output=True, + text=True, + timeout=timeout, + encoding="utf-8", + errors="replace", + ) + if proc.returncode != 0: + raise Failure("docker compose %s failed" % args[0]) + return proc.stdout + + +def psql(sql): + proc = subprocess.run( + [ + "docker", + "compose", + "--env-file", + ".env", + "exec", + "-T", + "postgres", + "psql", + "-U", + "messenger", + "-d", + "messenger", + "-v", + "ON_ERROR_STOP=1", + "-At", + "-c", + sql, + ], + cwd=str(ROOT), + capture_output=True, + text=True, + timeout=60, + encoding="utf-8", + errors="replace", + ) + if proc.returncode != 0: + raise Failure("database query failed") + return proc.stdout.strip() + + +def logs(service): + proc = subprocess.run( + ["docker", "compose", "--env-file", ".env", "logs", "--since", "3m", "--no-log-prefix", service], + cwd=str(ROOT), + capture_output=True, + text=True, + timeout=60, + encoding="utf-8", + errors="replace", + ) + return proc.stdout + + +def write_faults(data): + payload = dict(SAFE) + payload.update(data) + temporary = FAULTS.with_suffix(".tmp") + temporary.write_text(json.dumps(payload), encoding="utf-8") + temporary.replace(FAULTS) + + +def job_id_for(attachment_id): + uuid.UUID(attachment_id) + return psql("SELECT job_id FROM attachment_jobs WHERE attachment_id = '%s'" % attachment_id) + + +def variant_counts(attachment_id): + uuid.UUID(attachment_id) + text = psql( + "SELECT name || ':' || count(*) FROM attachment_variants WHERE attachment_id = '%s' GROUP BY name ORDER BY name" + % attachment_id + ) + counts = {} + if text: + for line in text.splitlines(): + name, amount = line.split(":", 1) + counts[name] = int(amount) + return counts + + +def assert_single_variants(attachment_id): + counts = variant_counts(attachment_id) + check(counts == {"crop": 1, "optimized": 1, "thumbnail": 1}, "variant rows are not unique") + return counts + + +def wait_status(client, actor, attachment, status, seconds=90): + deadline = time.monotonic() + seconds + last = attachment + while time.monotonic() < deadline: + last = client.call("GET", "/api/v1/attachments/" + attachment["id"], actor=actor, schema="Attachment")["json"] + if last["status"] == status: + return last + if status != "failed" and last["status"] == "failed": + raise Failure("attachment failed while waiting for " + status) + time.sleep(0.4) + raise Failure("attachment stayed " + str(last.get("status")) + " while waiting for " + status) + + +def replay(job): + uuid.UUID(job) + proc = subprocess.run( + [ + "docker", + "compose", + "--env-file", + ".env", + "run", + "--rm", + "--no-deps", + "--entrypoint", + "python", + "worker", + "-m", + "app.replay", + job, + ], + cwd=str(ROOT), + capture_output=True, + text=True, + timeout=90, + encoding="utf-8", + errors="replace", + ) + if proc.returncode != 0: + raise Failure("replay command failed") + line = [item for item in proc.stdout.splitlines() if item.startswith("{")] + check(line, "replay did not print a result") + return json.loads(line[-1]) + + +def check_ready_image(client, actor, ready, content): + variants = {item["name"]: item for item in ready["variants"]} + check(set(variants) == {"thumbnail", "crop", "optimized"}, "ready variants mismatch") + thumb = variants["thumbnail"] + crop = variants["crop"] + optimized = variants["optimized"] + check((thumb["width"], thumb["height"]) == (256, 160), "thumbnail metadata mismatch") + check(thumb["content_type"] == "image/jpeg", "thumbnail type mismatch") + check((crop["width"], crop["height"]) == (128, 128), "crop metadata mismatch") + check(crop["content_type"] == "image/jpeg", "crop type mismatch") + check((optimized["width"], optimized["height"]) == (320, 200), "optimized metadata mismatch") + check(optimized["content_type"] == "image/webp", "optimized type mismatch") + original = client.call("GET", "/api/v1/attachments/" + ready["id"] + "/content", actor=actor) + check(original["bytes"] == content, "original bytes changed") + for name, meta, magic in ( + ("thumbnail", thumb, b"\xff\xd8"), + ("crop", crop, b"\xff\xd8"), + ("optimized", optimized, b"RIFF"), + ): + body = client.call( + "GET", + "/api/v1/attachments/" + ready["id"] + "/content?variant=" + name, + actor=actor, + ) + check(body["headers"].get_content_type() == meta["content_type"], name + " content type mismatch") + check(len(body["bytes"]) == meta["size_bytes"], name + " size mismatch") + check(hashlib.sha256(body["bytes"]).hexdigest() == meta["sha256"], name + " checksum mismatch") + check(body["bytes"][:4] == magic or body["bytes"][:2] == magic, name + " magic mismatch") + if name != "optimized": + check(jpeg_size(body["bytes"]) == (meta["width"], meta["height"]), name + " jpeg size mismatch") + check(optimized and body["bytes"][8:12] == b"WEBP", "optimized is not webp") + + +def main(): + write_faults({}) + evidence = {"date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} + client = Client(BASE, timeout=30) + alice, bob, _eve, chat = client.bootstrap() + try: + att, content = client.attachment(alice, chat) + check(att["status"] == "queued" and att["variants"] == [], "upload snapshot is not queued") + ready = client.wait_ready(bob, att, wait_seconds=90) + check_ready_image(client, bob, ready, content) + assert_single_variants(att["id"]) + evidence["happy_path"] = {"attachment_id": att["id"], "job_id": job_id_for(att["id"]), "status": "ready"} + print("PASS: thumbnail, crop and optimized") + + compose("stop", "worker") + queued, queued_bytes = client.attachment(alice, chat) + blocked = client.call("GET", "/api/v1/attachments/" + queued["id"] + "/content", 409, actor=bob) + check(blocked["json"]["error"]["code"] == "conflict", "content of a queued file is not 409") + linked = client.message(alice, chat, "", attachments=[queued["id"]])["json"] + check(linked["attachment_ids"] == [queued["id"]], "queued attachment was rejected") + client.message(bob, chat, "сообщение без вложения") + compose("restart", "api") + compose("restart", "rabbitmq") + deadline = time.monotonic() + 60 + while time.monotonic() < deadline: + try: + client.call("GET", "/health/ready", schema="Health") + break + except Failure: + time.sleep(1) + else: + raise Failure("api did not recover after restart") + still = client.call("GET", "/api/v1/attachments/" + queued["id"], actor=alice, schema="Attachment")["json"] + check(still["status"] in {"queued", "processing", "ready"}, "accepted job disappeared") + compose("start", "worker") + recovered = wait_status(client, bob, queued, "ready", 90) + downloaded = client.call("GET", "/api/v1/attachments/" + queued["id"] + "/content", actor=bob) + check(downloaded["bytes"] == queued_bytes, "recovered original changed") + assert_single_variants(queued["id"]) + evidence["worker_stopped"] = { + "attachment_id": queued["id"], + "job_id": job_id_for(queued["id"]), + "content_before_worker": 409, + "status_after_recovery": recovered["status"], + "rabbit_restarted": True, + "api_restarted": True, + } + print("PASS: stopped worker, broker restart, same job reached ready") + + compose("stop", "relay") + held, _held_bytes = client.attachment(alice, chat) + held_job = job_id_for(held["id"]) + unpublished = psql( + "SELECT count(*) FROM job_outbox WHERE job_id = '%s' AND published_at IS NULL" % held_job + ) + check(unpublished == "1", "outbox row was published while relay was stopped") + compose("start", "relay") + held_ready = wait_status(client, alice, held, "ready", 90) + evidence["outbox_gap"] = { + "attachment_id": held["id"], + "job_id": held_job, + "unpublished_before_restart": int(unpublished), + "status": held_ready["status"], + } + print("PASS: commit without publish recovered from the outbox") + + write_faults({"relay_exit_before_publish": True}) + time.sleep(0.8) + crashed, _bytes = client.attachment(alice, chat) + crash_job = job_id_for(crashed["id"]) + seen = False + deadline = time.monotonic() + 40 + while time.monotonic() < deadline: + if "injected exit after outbox commit before broker publish" in logs("relay"): + seen = True + break + time.sleep(0.5) + check(seen, "relay did not exit between commit and publish") + crash_ready = wait_status(client, alice, crashed, "ready", 90) + gap = psql("SELECT gap_injected FROM job_outbox WHERE job_id = '%s' ORDER BY created_at LIMIT 1" % crash_job) + check(gap == "t", "gap latch was not stored") + jobs = psql("SELECT count(*) FROM attachment_jobs WHERE attachment_id = '%s'" % crashed["id"]) + check(jobs == "1", "crash recovery created another job") + evidence["relay_crash"] = { + "attachment_id": crashed["id"], + "job_id": crash_job, + "gap_injected": True, + "log_seen": True, + "status": crash_ready["status"], + } + write_faults({}) + print("PASS: relay crash before publish recovered the same job") + + write_faults({"crash_after_s3": True}) + time.sleep(0.8) + side, side_bytes = client.attachment(alice, chat) + side_job = job_id_for(side["id"]) + seen = False + deadline = time.monotonic() + 40 + while time.monotonic() < deadline: + if "injected crash after object write before ack job_id=%s" % side_job in logs("worker"): + seen = True + break + time.sleep(0.5) + check(seen, "worker did not exit after the object write") + side_ready = wait_status(client, bob, side, "ready", 90) + side_download = client.call("GET", "/api/v1/attachments/" + side["id"] + "/content", actor=bob) + check(side_download["bytes"] == side_bytes, "redelivery changed the original") + assert_single_variants(side["id"]) + evidence["crash_before_ack"] = { + "attachment_id": side["id"], + "job_id": side_job, + "log_seen": True, + "status": side_ready["status"], + "variant_rows": assert_single_variants(side["id"]), + } + write_faults({}) + print("PASS: crash after object write redelivered the same result") + + compose("stop", "worker", "relay") + leased, _leased_bytes = client.attachment(alice, chat) + leased_job = job_id_for(leased["id"]) + psql( + "UPDATE attachment_jobs SET status = 'processing', attempt = 1, lease_owner = 'dead', " + "lease_until = now() - interval '2 minutes' WHERE job_id = '%s'" % leased_job + ) + psql("UPDATE job_outbox SET published_at = now() WHERE job_id = '%s' AND published_at IS NULL" % leased_job) + psql("UPDATE attachments SET status = 'processing', error_code = NULL WHERE id = '%s'" % leased["id"]) + compose("start", "relay", "worker") + lease_ready = wait_status(client, alice, leased, "ready", 90) + evidence["expired_lease"] = { + "attachment_id": leased["id"], + "job_id": leased_job, + "status": lease_ready["status"], + } + print("PASS: expired processing lease was recovered") + + write_faults({"inject_transient": True}) + time.sleep(0.8) + failed, _failed_bytes = client.attachment(alice, chat) + failed_job = job_id_for(failed["id"]) + failed_meta = wait_status(client, alice, failed, "failed", 90) + check(failed_meta["error_code"] == "retry_exhausted", "exhausted job has no safe error code") + denied = client.call("GET", "/api/v1/attachments/" + failed["id"] + "/content", 409, actor=alice) + check(denied["json"]["error"]["code"] == "conflict", "failed content is not 409") + registry = psql("SELECT count(*) FROM job_failures WHERE job_id = '%s'" % failed_job) + check(int(registry) >= 1, "failure registry is empty") + dlq = compose("exec", "-T", "rabbitmq", "rabbitmqctl", "list_queues", "name", "messages") + check("attachment.jobs.dlq" in dlq, "dlq is missing") + write_faults({}) + time.sleep(0.5) + first = replay(failed_job) + check(first["outcome"] == "enqueued", "failed job was not replayed") + replayed = wait_status(client, alice, failed, "ready", 90) + second = replay(failed_job) + check(second["outcome"] == "already_ready", "replay of a ready job was not a no-op") + assert_single_variants(failed["id"]) + evidence["retry_and_replay"] = { + "attachment_id": failed["id"], + "job_id": failed_job, + "error_code": failed_meta["error_code"], + "failure_rows": int(registry), + "first_replay": first["outcome"], + "second_replay": second["outcome"], + "status": replayed["status"], + } + print("PASS: backoff exhausted to failed, replay is safe") + + write_faults({"stall_seconds": 5, "timeout_seconds": 1}) + time.sleep(0.8) + stalled, _stalled_bytes = client.attachment(alice, chat) + client.message(alice, chat, "API отвечает, пока worker ограничен по времени") + client.call("GET", "/health/ready", schema="Health") + stalled_meta = wait_status(client, alice, stalled, "failed", 90) + check(stalled_meta["error_code"] == "retry_exhausted", "timed out job was not exhausted") + write_faults({}) + time.sleep(0.5) + stalled_job = job_id_for(stalled["id"]) + outcome = replay(stalled_job) + check(outcome["outcome"] == "enqueued", "timed out job was not replayed") + stalled_ready = wait_status(client, alice, stalled, "ready", 90) + evidence["timeout"] = { + "attachment_id": stalled["id"], + "job_id": stalled_job, + "error_code": stalled_meta["error_code"], + "status": stalled_ready["status"], + "api_ready_during_stall": True, + } + print("PASS: worker time limit does not block the API") + finally: + write_faults({}) + try: + compose("start", "worker", "relay", "api", "rabbitmq") + except Failure: + pass + EVIDENCE.mkdir(exist_ok=True) + (EVIDENCE / "grade4.json").write_text(json.dumps(evidence, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print("PASS: grade 4 failure scenarios") + + +if __name__ == "__main__": + run(main) diff --git a/student-tests/level3.py b/student-tests/level3.py new file mode 100644 index 0000000..057caab --- /dev/null +++ b/student-tests/level3.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +"""Проверки lab3: разные реплики, идемпотентность через LB, гонка одного ключа.""" + +import json +import os +import sys +import threading +import time +import uuid +from collections import Counter +from pathlib import Path +from urllib.parse import quote + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +from client import Client, Failure, check, run + +EVIDENCE = ROOT / "evidence" +BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/") + + +def history(client, actor, chat): + path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100" + result = [] + seen = set() + for _ in range(1000): + page = client.call("GET", path, actor=actor, schema="MessagePage")["json"] + result.extend(page["items"]) + cursor = page["next_cursor"] + if cursor is None: + return result + check(cursor not in seen, "cursor cycle") + seen.add(cursor) + path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100&cursor=" + quote(cursor, safe="") + raise Failure("history pagination exceeded safety bound") + + +def test_instances(client, actor): + seen = [] + for _ in range(40): + seen.append(client.call("GET", "/api/v1/users/me", actor=actor, schema="User")["headers"]["X-Instance-Id"]) + unique = sorted(set(seen)) + check(len(unique) >= 2, "less than two API instances observed: %s" % unique) + return {"unique_instance_ids": unique, "samples": len(seen), "counts": dict(Counter(seen))} + + +def test_idempotency(client, alice, bob, chat): + key = uuid.uuid4().hex + first = client.message(alice, chat, "Один ключ", key=key) + replay = client.message(alice, chat, "Один ключ", key=key) + check(first["json"] == replay["json"], "idempotent replay differs") + check(first["json"]["id"] == replay["json"]["id"], "idempotent replay allocated a new id") + conflict = client.call( + "POST", + "/api/v1/chats/" + chat["id"] + "/messages", + 409, + actor=alice, + body={"text": "другой body"}, + headers={"Idempotency-Key": key}, + ) + check(conflict["json"]["error"]["code"] == "conflict", "wrong body code") + missing = client.call( + "POST", + "/api/v1/chats/" + chat["id"] + "/messages", + 400, + actor=alice, + body={"text": "без ключа"}, + ) + check(missing["json"]["error"]["code"] == "invalid_request", "missing key code") + other_user = client.message(bob, chat, "Один ключ", key=key) + check(other_user["json"]["id"] != first["json"]["id"], "key leaked across users") + return first["json"]["id"] + + +def test_concurrent_key(client, alice, chat): + key = uuid.uuid4().hex + text = "Гонка ключа " + key + barrier = threading.Barrier(12) + results = [] + errors = [] + lock = threading.Lock() + + def worker(): + local = Client(BASE, timeout=20) + try: + barrier.wait(20) + response = local.message(alice, chat, text, key=key) + with lock: + results.append((response["status"], response["json"]["id"], response["headers"]["X-Instance-Id"])) + except Exception as exc: + with lock: + errors.append("%s: %s" % (type(exc).__name__, exc)) + + threads = [threading.Thread(target=worker) for _ in range(12)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + check(not errors, "concurrent idempotent POST failed: " + "; ".join(errors[:5])) + check(len(results) == 12, "expected 12 successes, got %s" % len(results)) + ids = {item[1] for item in results} + instances = sorted({item[2] for item in results}) + check(len(ids) == 1, "concurrent key created %s messages" % len(ids)) + listed = history(client, alice, chat) + matches = [item for item in listed if item["text"] == text] + check(len(matches) == 1, "history contains %s copies of the concurrent key" % len(matches)) + return {"message_id": next(iter(ids)), "instances": instances, "successes": len(results)} + + +def main(): + client = Client(BASE, timeout=10) + alice, bob, _eve, chat = client.bootstrap() + instances = test_instances(client, alice) + message_id = test_idempotency(client, alice, bob, chat) + race = test_concurrent_key(client, alice, chat) + EVIDENCE.mkdir(exist_ok=True) + report = { + "date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "base_url": BASE, + "instances": instances, + "idempotent_message_id_present": bool(message_id), + "concurrent_key": race, + } + (EVIDENCE / "level3.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print("PASS: level 3 replica routing and shared idempotency") + + +if __name__ == "__main__": + run(main) diff --git a/student-tests/level4.py b/student-tests/level4.py new file mode 100644 index 0000000..5633d01 --- /dev/null +++ b/student-tests/level4.py @@ -0,0 +1,642 @@ +#!/usr/bin/env python3 +"""Проверки уровня 4: гонка, откат, EXPLAIN, TTL, logout и отказ Redis/PostgreSQL. + +Стенд уже должен быть поднят: scripts/bootstrap и docker compose up. +Скрипт останавливает redis и postgres и снова их запускает. +Токены и пароли не печатаются и не пишутся в evidence. +""" + +import asyncio +import base64 +import json +import os +import socket +import subprocess +import sys +import threading +import time +import urllib.error +import urllib.request +import uuid +from datetime import datetime, timezone +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +EVIDENCE = ROOT / "evidence" +sys.path.insert(0, str(ROOT / "src")) + +BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/") + + +class Failure(AssertionError): + pass + + +def check(condition, message): + if not condition: + raise Failure(message) + + +def host_secret(name): + path = ROOT / "secrets" / name + if not path.is_file(): + raise Failure("missing secrets/%s; run scripts/bootstrap first" % name) + value = path.read_text(encoding="utf-8").strip() + if not value: + raise Failure("empty secrets/%s" % name) + return value + + +def call(method, path, expected, body=None, token=None, authorization=None, user_id=None, timeout=15, headers=None): + extra = headers or {} + headers = {"Accept": "application/json"} + headers.update(extra) + data = None + if body is not None: + data = json.dumps(body, ensure_ascii=False).encode("utf-8") + headers["Content-Type"] = "application/json" + if authorization: + headers["Authorization"] = authorization + elif token: + headers["Authorization"] = "Bearer " + token + if user_id: + headers["X-User-Id"] = user_id + request = urllib.request.Request(BASE + path, data=data, headers=headers, method=method) + try: + response = urllib.request.urlopen(request, timeout=timeout) + except urllib.error.HTTPError as error: + response = error + except (urllib.error.URLError, TimeoutError, OSError) as exc: + raise Failure(method + " " + path.split("?")[0] + " failed: " + type(exc).__name__) from None + with response: + status = response.status + payload = response.read() + header_id = response.headers.get("X-Request-Id") + challenge = response.headers.get("WWW-Authenticate", "") + allowed = [expected] if isinstance(expected, int) else list(expected) + check(status in allowed, "%s %s: expected %s, got %s" % (method, path.split("?")[0], allowed, status)) + check(header_id and header_id.strip(), "missing X-Request-Id") + parsed = None + if payload: + try: + parsed = json.loads(payload) + except json.JSONDecodeError as exc: + raise Failure("response is not JSON") from exc + if status >= 400: + check(isinstance(parsed, dict) and set(parsed) == {"error"}, "error envelope") + error = parsed["error"] + check(set(error) == {"code", "message", "request_id"}, "error fields") + check(error["request_id"] == header_id, "request_id differs from header") + lowered = error["message"].lower() + for leaked in ("traceback", "select ", "password", "syntax", "asyncpg", "sqlalchemy"): + check(leaked not in lowered, "error message leaked internals") + if status == 204: + check(not payload, "204 must not contain a body") + return {"status": status, "json": parsed, "www": challenge} + + +def basic(username, password): + raw = base64.b64encode(("%s:%s" % (username, password)).encode("utf-8")).decode("ascii") + return "Basic " + raw + + +def register(label, password=None): + username = ("u_%s_%s" % (label, uuid.uuid4().hex[:10])).lower() + password = password or ("T3st-" + uuid.uuid4().hex) + created = call( + "POST", + "/api/v1/users", + 201, + body={"username": username, "display_name": "Студент " + label, "password": password}, + )["json"] + check("password" not in created, "password leaked") + session = call("POST", "/api/v1/auth/sessions", 201, authorization=basic(username, password))["json"] + check(session["token_type"] == "Bearer" and session["user"]["id"] == created["id"], "session shape") + check(len(session["token"]) >= 32, "token is too short") + return {"id": created["id"], "username": username, "password": password, "token": session["token"]} + + +def compose(*args, timeout=120): + proc = subprocess.run( + ["docker", "compose", *args], + cwd=str(ROOT), + capture_output=True, + text=True, + timeout=timeout, + encoding="utf-8", + errors="replace", + ) + if proc.returncode != 0: + raise Failure("docker compose %s failed with code %s" % (args[0], proc.returncode)) + return proc.stdout + + +def psql(sql, timeout=60): + proc = subprocess.run( + [ + "docker", + "compose", + "exec", + "-T", + "postgres", + "psql", + "-U", + "messenger", + "-d", + "messenger", + "-v", + "ON_ERROR_STOP=1", + "-At", + "-c", + sql, + ], + cwd=str(ROOT), + capture_output=True, + text=True, + timeout=timeout, + encoding="utf-8", + errors="replace", + ) + if proc.returncode != 0: + raise Failure("psql failed") + return proc.stdout.strip() + + +def redis_cli(*args): + proc = subprocess.run( + ["docker", "compose", "exec", "-T", "redis", "redis-cli", *args], + cwd=str(ROOT), + capture_output=True, + text=True, + timeout=20, + encoding="utf-8", + errors="replace", + ) + if proc.returncode != 0: + raise Failure("redis-cli failed") + return proc.stdout.strip() + + +def sql_quote(value): + text = str(value) + if "'" in text or ";" in text or "\n" in text: + raise Failure("refusing unsafe SQL literal") + return "'" + text + "'" + + +def free_port(): + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return sock.getsockname()[1] + + +def wait_ready(timeout=90): + deadline = time.monotonic() + timeout + last = "" + while time.monotonic() < deadline: + try: + call("GET", "/health/ready", 200, timeout=5) + return + except Failure as exc: + last = str(exc) + time.sleep(0.5) + raise Failure("API did not become ready: " + last) + + +def test_credentials(): + user = register("cred") + wrong = call( + "POST", + "/api/v1/auth/sessions", + 401, + authorization=basic(user["username"], "wrong-password-value"), + ) + missing = call( + "POST", + "/api/v1/auth/sessions", + 401, + authorization=basic("no_such_user_zz", "wrong-password-value"), + ) + check(wrong["json"]["error"]["code"] == "unauthorized", "wrong password code") + check(wrong["json"]["error"]["message"] == missing["json"]["error"]["message"], "credential errors differ") + check(wrong["www"].lower().startswith("basic "), "basic challenge") + bare = call("GET", "/api/v1/users/me", 401) + check(bare["www"].lower().startswith("bearer "), "bearer challenge") + only_header = call("GET", "/api/v1/users/me", 401, user_id=user["id"]) + check(only_header["json"]["error"]["code"] == "unauthorized", "X-User-Id alone was accepted") + other = register("other") + me = call("GET", "/api/v1/users/me", 200, token=user["token"], user_id=other["id"])["json"] + check(me["id"] == user["id"], "X-User-Id overrode bearer") + basic_on_api = call("GET", "/api/v1/users/me", 401, authorization=basic(user["username"], user["password"])) + check(basic_on_api["www"].lower().startswith("bearer "), "basic accepted on business API") + print("PASS: credentials, same 401, X-User-Id ignored") + + +def test_unicode_password(): + password = "Пароль:пример-12" + check(12 <= len(password) <= 128 and ":" in password, "fixture password") + user = register("uni", password=password) + again = call("POST", "/api/v1/auth/sessions", 201, authorization=basic(user["username"], password))["json"] + check(again["user"]["id"] == user["id"], "unicode password login failed") + print("PASS: unicode password with colon") + + +def test_logout(): + user = register("bye") + call("DELETE", "/api/v1/auth/sessions/current", 204, token=user["token"]) + rejected = call("GET", "/api/v1/users/me", 401, token=user["token"]) + check(rejected["www"].lower().startswith("bearer "), "revoked token challenge") + again = call("DELETE", "/api/v1/auth/sessions/current", 401, token=user["token"]) + check(again["json"]["error"]["code"] == "unauthorized", "second logout") + print("PASS: logout revokes the session") + + +def test_injection_and_rollback(): + user = register("sql") + chat = call( + "POST", + "/api/v1/chats", + 201, + token=user["token"], + body={"title": "SQL", "member_ids": [user["id"]]}, + )["json"] + payload = "'; DROP TABLE messages; --" + sent = call( + "POST", + "/api/v1/chats/%s/messages" % chat["id"], + 201, + token=user["token"], + body={"text": payload}, + headers={"Idempotency-Key": uuid.uuid4().hex}, + )["json"] + check(sent["text"] == payload, "text was rewritten") + check(psql("SELECT to_regclass('public.messages')") == "messages", "messages table disappeared") + listed = call("GET", "/api/v1/chats/%s/messages?limit=10" % chat["id"], 200, token=user["token"])["json"] + check(listed["items"][0]["text"] == payload, "stored text differs") + + before = int(psql("SELECT count(*) FROM chats")) + title = "partial-" + uuid.uuid4().hex + rejected = call( + "POST", + "/api/v1/chats", + 400, + token=user["token"], + body={"title": title, "member_ids": [user["id"], str(uuid.uuid4())]}, + ) + check(rejected["json"]["error"]["code"] == "invalid_request", "unknown member code") + after = int(psql("SELECT count(*) FROM chats")) + check(before == after, "unknown member committed a chat") + check(psql("SELECT count(*) FROM chats WHERE title = %s" % sql_quote(title)) == "0", "partial chat row exists") + print("PASS: parameterized text and unknown-member chat is not stored") + return user, chat + + +async def failpoint(owner_id, other_id, title): + os.environ["DATABASE_URL"] = host_secret("host_database_url") + os.environ["REDIS_URL"] = host_secret("host_cache_url") + from app.config import load_settings + from app.crud.chats import create_chat + from app.db import build_engine, build_session_factory + from app.runtime import configure + from app.sessions import build_redis + + settings = load_settings() + engine = build_engine(settings) + redis = build_redis(settings) + configure(build_session_factory(engine), redis, settings) + try: + try: + await create_chat( + uuid.UUID(owner_id), + title, + (uuid.UUID(owner_id), uuid.UUID(other_id)), + fail_after_insert=True, + ) + except RuntimeError as exc: + check(str(exc) == "rollback-check", "failpoint raised a different error") + else: + raise Failure("failpoint committed a chat") + finally: + await redis.aclose() + await engine.dispose() + + +def test_failpoint(owner_id, other_id): + title = "rollback-" + uuid.uuid4().hex + before = int(psql("SELECT count(*) FROM chats")) + try: + asyncio.run(failpoint(owner_id, other_id, title)) + except Failure: + raise + except Exception as exc: + raise Failure("rollback check failed: " + type(exc).__name__) from None + after = int(psql("SELECT count(*) FROM chats")) + left = psql("SELECT count(*) FROM chats WHERE title = %s" % sql_quote(title)) + check(before == after and left == "0", "chat insert survived the rollback") + print("PASS: composite chat insert rolls back before commit") + return {"chats_before": before, "chats_after": after, "title_rows": int(left)} + + +def test_race(): + username = "race_" + uuid.uuid4().hex[:8] + password = "Race-password-" + uuid.uuid4().hex[:8] + body = {"username": username, "display_name": "Гонка", "password": password} + barrier = threading.Barrier(16) + statuses = [] + lock = threading.Lock() + + def worker(): + try: + barrier.wait(20) + result = call("POST", "/api/v1/users", [201, 409], body=body, timeout=30) + with lock: + statuses.append(result["status"]) + except Exception as exc: + with lock: + statuses.append(str(exc)[:120]) + + threads = [threading.Thread(target=worker) for _ in range(16)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + created = statuses.count(201) + conflict = statuses.count(409) + check(created == 1 and conflict == 15 and len(statuses) == 16, "race statuses %s" % statuses) + print("PASS: 16 parallel registrations, one 201 and fifteen 409") + return {"created": created, "conflict": conflict} + + +def assert_plan(name, plan): + check("ix_messages_history" in plan, name + " plan ignores ix_messages_history") + check("Seq Scan" not in plan, name + " plan seq-scans messages") + check("Index Scan" in plan or "Index Only Scan" in plan, name + " plan is not an index scan") + check("Buffers:" in plan, name + " plan has no buffer stats") + + +def test_explain(user): + chat = call( + "POST", + "/api/v1/chats", + 201, + token=user["token"], + body={"title": "План", "member_ids": [user["id"]]}, + )["json"] + chat_sql = sql_quote(chat["id"]) + user_sql = sql_quote(user["id"]) + psql( + "INSERT INTO messages (id, chat_id, sender_id, body, created_at) " + "SELECT gen_random_uuid(), %s, %s, 'row-' || g, " + "TIMESTAMPTZ '2026-01-01 00:00:00+00' + (g || ' microseconds')::interval " + "FROM generate_series(1, 10000) AS g" % (chat_sql, user_sql), + timeout=60, + ) + count = int(psql("SELECT count(*) FROM messages WHERE chat_id = %s" % chat_sql)) + check(count >= 10000, "expected at least 10000 messages, got %s" % count) + psql("ANALYZE messages") + midpoint = psql( + "SELECT to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS.US'), id::text " + "FROM messages WHERE chat_id = %s ORDER BY created_at, id OFFSET 5000 LIMIT 1" % chat_sql + ) + created_at, message_id = midpoint.split("|") + late = psql( + "EXPLAIN (ANALYZE, BUFFERS) SELECT id, body FROM messages " + "WHERE chat_id = %s AND (created_at, id) > (%s::timestamptz, %s::uuid) " + "ORDER BY created_at, id LIMIT 50" + % (chat_sql, sql_quote(created_at + "+00"), sql_quote(message_id)), + timeout=60, + ) + first = psql( + "EXPLAIN (ANALYZE, BUFFERS) SELECT id, body FROM messages " + "WHERE chat_id = %s ORDER BY created_at, id LIMIT 50" % chat_sql, + timeout=60, + ) + EVIDENCE.mkdir(exist_ok=True) + (EVIDENCE / "explain_messages.txt").write_text( + "messages=%s\n\n-- first page\n%s\n\n-- page after row 5000\n%s\n" % (count, first, late), + encoding="utf-8", + ) + assert_plan("first", first) + assert_plan("late", late) + print("PASS: EXPLAIN uses ix_messages_history on %s messages" % count) + return {"messages": count, "chat_id": chat["id"]} + + +def test_expiry_and_migrations(): + from app.timeutil import parse_time + + users_before = int(psql("SELECT count(*) FROM users")) + port = free_port() + env = os.environ.copy() + env["PYTHONPATH"] = str(ROOT / "src") + env["PYTHONUNBUFFERED"] = "1" + env["APP_HOST"] = "127.0.0.1" + env["APP_PORT"] = str(port) + env["APP_ENV"] = "lab" + env["DATABASE_URL"] = host_secret("host_database_url") + env["REDIS_URL"] = host_secret("host_cache_url") + env["S3_ENDPOINT"] = host_secret("host_s3_endpoint") + env["S3_ACCESS_KEY_ID"] = host_secret("s3_access_key_id") + env["S3_SECRET_ACCESS_KEY"] = host_secret("s3_secret_access_key") + env["S3_BUCKET"] = "messenger-attachments" + env["SESSION_TTL_SECONDS"] = "2" + env.pop("DATABASE_URL_FILE", None) + env.pop("CACHE_URL_FILE", None) + proc = subprocess.Popen( + [sys.executable, "-m", "app"], + cwd=str(ROOT), + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + encoding="utf-8", + errors="replace", + ) + logs = [] + + def read_logs(): + if proc.stdout is None: + return + for line in proc.stdout: + if "://" not in line and "password" not in line.lower(): + logs.append(line) + + reader = threading.Thread(target=read_logs, daemon=True) + reader.start() + base = "http://127.0.0.1:%s" % port + try: + deadline = time.monotonic() + 40 + ready = False + while time.monotonic() < deadline: + if proc.poll() is not None: + raise Failure("short-ttl server exited: " + "".join(logs[-8:])) + try: + urllib.request.urlopen(base + "/health/ready", timeout=2).read() + ready = True + break + except (urllib.error.URLError, TimeoutError, OSError): + time.sleep(0.2) + check(ready, "short-ttl server did not become ready: " + "".join(logs[-8:])) + username = "ttl_" + uuid.uuid4().hex[:8] + password = "Ttl-password-" + uuid.uuid4().hex[:8] + body = json.dumps( + {"username": username, "display_name": "TTL", "password": password}, + ensure_ascii=False, + ).encode("utf-8") + request = urllib.request.Request( + base + "/api/v1/users", + data=body, + headers={"Content-Type": "application/json", "Accept": "application/json"}, + method="POST", + ) + with urllib.request.urlopen(request, timeout=20) as response: + created = json.loads(response.read()) + login = urllib.request.Request( + base + "/api/v1/auth/sessions", + data=b"", + headers={"Authorization": basic(username, password), "Accept": "application/json"}, + method="POST", + ) + with urllib.request.urlopen(login, timeout=20) as response: + session = json.loads(response.read()) + expires = parse_time(session["expires_at"]) + delta = (expires - datetime.now(timezone.utc)).total_seconds() + check(0 < delta <= 3, "SESSION_TTL_SECONDS=2 was not applied") + time.sleep(delta + 1.0) + probe = urllib.request.Request( + base + "/api/v1/users/me", + headers={"Authorization": "Bearer " + session["token"], "Accept": "application/json"}, + ) + try: + with urllib.request.urlopen(probe, timeout=10) as response: + status = response.status + except urllib.error.HTTPError as error: + status = error.status + check(status == 401, "expired session status %s" % status) + finally: + if proc.poll() is None: + proc.terminate() + try: + proc.wait(timeout=8) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait(timeout=5) + reader.join(timeout=2) + users_after = int(psql("SELECT count(*) FROM users")) + versions = psql("SELECT count(*) FROM schema_migrations") + version_name = psql("SELECT version FROM schema_migrations ORDER BY version") + check(users_after == users_before + 1, "migrations duplicated or dropped users") + names = psql("SELECT version FROM schema_migrations ORDER BY version") + check(versions == "3", "expected three applied migrations, got %s" % versions) + check( + "001_initial.sql" in names and "002_idempotency.sql" in names and "003_attachments.sql" in names, + "migration set changed: %s" % names, + ) + print("PASS: short TTL expires and migrations stay idempotent") + return {"users_before": users_before, "users_after": users_after, "migration": version_name} + + +def test_redis_persistence(user): + from app.sessions import session_key + + before = int(redis_cli("PTTL", session_key(user["token"]))) + check(before > 300000, "session ttl is unexpectedly short") + compose("restart", "redis") + wait_ready() + after = int(redis_cli("PTTL", session_key(user["token"]))) + check(after > 0, "session disappeared after redis restart") + check(after <= before + 1000, "redis restart extended the session ttl") + me = call("GET", "/api/v1/users/me", 200, token=user["token"])["json"] + check(me["id"] == user["id"], "token did not survive redis restart") + print("PASS: Redis AOF kept the session and did not refresh TTL") + return {"pttl_before_ms": before, "pttl_after_ms": after} + + +def test_dependency_loss(user, chat_id): + observed = {} + compose("stop", "redis") + try: + live = call("GET", "/health/live", 200) + ready = call("GET", "/health/ready", 503) + anonymous = call("GET", "/api/v1/users/me", 401) + trusted = call("GET", "/api/v1/users/me", 503, token=user["token"]) + check(live["json"]["status"] == "ok", "live failed while redis is down") + check(ready["json"]["error"]["code"] == "unavailable", "ready code") + check(anonymous["json"]["error"]["code"] == "unauthorized", "anonymous became trusted") + check(trusted["json"]["error"]["code"] == "unavailable", "unverified token was accepted") + observed["redis_down"] = { + "live": live["status"], + "ready": ready["status"], + "anonymous": anonymous["status"], + "bearer": trusted["status"], + } + finally: + compose("start", "redis") + wait_ready() + me = call("GET", "/api/v1/users/me", 200, token=user["token"])["json"] + check(me["id"] == user["id"], "token lost after redis came back") + + compose("stop", "postgres") + try: + live = call("GET", "/health/live", 200) + ready = call("GET", "/health/ready", 503, timeout=20) + anonymous = call("GET", "/api/v1/users/me", 401, timeout=20) + denied = call("GET", "/api/v1/chats/" + chat_id, 503, token=user["token"], timeout=20) + check(live["json"]["status"] == "ok", "live depends on postgres") + check(ready["json"]["error"]["code"] == "unavailable", "ready while postgres is down") + check(anonymous["json"]["error"]["code"] == "unauthorized", "anonymous trusted without postgres") + check(denied["json"]["error"]["code"] == "unavailable", "request served without postgres") + observed["postgres_down"] = { + "live": live["status"], + "ready": ready["status"], + "anonymous": anonymous["status"], + "bearer": denied["status"], + } + finally: + compose("start", "postgres") + wait_ready(timeout=90) + history = call("GET", "/api/v1/chats/%s/messages?limit=5" % chat_id, 200, token=user["token"])["json"] + check(history["items"], "messages lost after postgres restart") + print("PASS: redis and postgres outages return 503 and do not trust anonymous clients") + return observed + + +def main(): + os.environ["DATABASE_URL"] = host_secret("host_database_url") + os.environ["REDIS_URL"] = host_secret("host_cache_url") + wait_ready(timeout=60) + test_credentials() + test_unicode_password() + test_logout() + user, chat = test_injection_and_rollback() + other = register("pair") + rollback = test_failpoint(user["id"], other["id"]) + race = test_race() + explain = test_explain(user) + expiry = test_expiry_and_migrations() + pttl = test_redis_persistence(user) + faults = test_dependency_loss(user, chat["id"]) + remaining = int(psql("SELECT count(*) FROM messages WHERE chat_id = %s" % sql_quote(explain["chat_id"]))) + check(remaining == explain["messages"], "bulk history lost after postgres restart") + EVIDENCE.mkdir(exist_ok=True) + report = { + "date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "base_url": BASE, + "race": race, + "rollback": rollback, + "explain": {"messages": explain["messages"]}, + "expiry_and_migrations": expiry, + "redis_restart": pttl, + "dependency_loss": faults, + "messages_after_postgres_restart": remaining, + } + (EVIDENCE / "level4.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print("PASS: level 4 checks") + + +if __name__ == "__main__": + try: + main() + except Failure as exc: + print("FAIL:", exc) + sys.exit(1) diff --git a/student-tests/persistence.py b/student-tests/persistence.py new file mode 100644 index 0000000..d2edcf6 --- /dev/null +++ b/student-tests/persistence.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""Тот же сценарий, что tests/resilience.py, но hook запускается так, как умеет ОС. + +Linux выполняет scripts/restart.sh напрямую. +Windows не умеет CreateProcess для shell-скрипта, поэтому здесь используется Git Bash. +Скрипт тот же: перезапуск api, postgres и redis без удаления томов. +""" + +import os +import subprocess +import sys +import time +from pathlib import Path +from urllib.parse import quote + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) + +from client import Client, Failure, check, run + + +def hook_command(): + script = ROOT / "scripts" / "restart.sh" + if os.name != "nt": + return [str(script)] + bash = Path(os.environ.get("BASH", r"C:\Program Files\Git\bin\bash.exe")) + check(bash.is_file(), "Git Bash is required to launch scripts/restart.sh on Windows") + return [str(bash), "-c", "sh scripts/restart.sh"] + + +def history(client, actor, chat): + path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100" + result = [] + seen = set() + for _ in range(1000): + page = client.call("GET", path, actor=actor, schema="MessagePage")["json"] + result.extend(page["items"]) + cursor = page["next_cursor"] + if cursor is None: + return result + check(cursor not in seen, "cursor cycle") + seen.add(cursor) + path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100&cursor=" + quote(cursor, safe="") + raise Failure("history pagination exceeded safety bound") + + +def main(): + client = Client("http://127.0.0.1:8080", timeout=5) + alice, bob, _eve, chat = client.bootstrap() + original = client.message(alice, chat, "Сохранить при отказе")["json"] + print("Executing scripts/restart.sh") + completed = subprocess.run(hook_command(), cwd=str(ROOT)) + check(completed.returncode == 0, "restart hook failed") + deadline = time.monotonic() + 90 + while True: + try: + client.call("GET", "/health/ready", schema="Health") + client.call("GET", "/api/v1/users/me", actor=alice, schema="User") + break + except Failure: + check(time.monotonic() < deadline, "stack/session did not recover within 90 seconds") + time.sleep(0.5) + messages = history(client, bob, chat) + check(any(item == original for item in messages), "confirmed message lost or altered") + print("PASS: persistence preserved confirmed data and existing session") + + +if __name__ == "__main__": + run(main) diff --git a/student-tests/persistence_hook.py b/student-tests/persistence_hook.py new file mode 100644 index 0000000..db14fd8 --- /dev/null +++ b/student-tests/persistence_hook.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 +"""Публичный persistence-сценарий с restart.cmd на Windows и restart.sh на POSIX.""" + +import os +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def script(): + if os.name == "nt": + cmd = ROOT / "scripts" / "restart.cmd" + if cmd.is_file(): + return str(cmd) + return str(ROOT / "scripts" / "restart.sh") + + +def main(): + env = os.environ.copy() + command = [ + sys.executable, + str(ROOT / "tests" / "resilience.py"), + "--mode", + "persistence", + "--action-script", + script(), + "--base-url", + env.get("BASE_URL", "http://127.0.0.1:8080"), + ] + completed = subprocess.run(command, cwd=str(ROOT), env=env) + raise SystemExit(completed.returncode) + + +if __name__ == "__main__": + main() diff --git a/student-tests/rolling.py b/student-tests/rolling.py new file mode 100644 index 0000000..e697ee2 --- /dev/null +++ b/student-tests/rolling.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python3 +"""Поочерёдная замена API-реплик под нагрузкой POST сообщений.""" + +import json +import os +import subprocess +import sys +import threading +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +from client import Client, Failure, check, run + +EVIDENCE = ROOT / "evidence" +BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/") + + +def compose(*args, timeout=180): + proc = subprocess.run( + ["docker", "compose", "--env-file", ".env", *args], + cwd=str(ROOT), + capture_output=True, + text=True, + timeout=timeout, + encoding="utf-8", + errors="replace", + ) + if proc.returncode != 0: + raise Failure("docker compose %s failed" % args[0]) + return proc.stdout + + +def api_ids(): + return [line.strip() for line in compose("ps", "-q", "api").splitlines() if line.strip()] + + +def inspect_health(container_id): + proc = subprocess.run( + ["docker", "inspect", "-f", "{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}", container_id], + capture_output=True, + text=True, + timeout=20, + encoding="utf-8", + errors="replace", + ) + return proc.stdout.strip() + + +def wait_healthy(container_id, timeout=90): + deadline = time.monotonic() + timeout + last = "" + while time.monotonic() < deadline: + last = inspect_health(container_id) + if last == "healthy": + return + time.sleep(0.5) + raise Failure("replica %s did not become healthy: %s" % (container_id[:12], last)) + + +def wait_ready(timeout=90): + client = Client(BASE, timeout=3) + deadline = time.monotonic() + timeout + last = "" + while time.monotonic() < deadline: + try: + client.call("GET", "/health/ready", schema="Health") + return + except Failure as exc: + last = str(exc) + time.sleep(0.4) + raise Failure("LB ready wait failed: " + last) + + +def main(): + client = Client(BASE, timeout=8) + alice, _bob, _eve, chat = client.bootstrap() + halt = threading.Event() + latencies = [] + errors = [] + lock = threading.Lock() + + def worker(index): + local = Client(BASE, timeout=5) + n = 0 + while not halt.is_set(): + started = time.monotonic() + try: + local.message(alice, chat, "rolling-%s-%s" % (index, n)) + with lock: + latencies.append(time.monotonic() - started) + except Failure: + with lock: + errors.append(time.monotonic()) + n += 1 + + threads = [threading.Thread(target=worker, args=(i,), daemon=True) for i in range(4)] + for thread in threads: + thread.start() + time.sleep(5) + before = api_ids() + check(len(before) >= 2, "rolling update needs >=2 replicas") + compose("build", "api") + replaced = [] + for old in list(before): + current = api_ids() + compose("up", "-d", "--no-deps", "--scale", "api=%d" % (len(current) + 1), "--no-recreate", "api") + deadline = time.monotonic() + 60 + new_ids = api_ids() + while len(new_ids) <= len(current) and time.monotonic() < deadline: + time.sleep(0.5) + new_ids = api_ids() + added = [item for item in new_ids if item not in current] + check(added, "new replica was not created") + wait_healthy(added[-1]) + wait_ready() + subprocess.run(["docker", "stop", "-t", "5", old], capture_output=True) + subprocess.run(["docker", "rm", "-f", old], capture_output=True) + remaining = api_ids() + check(old not in remaining, "old replica %s still in service" % old[:12]) + compose("up", "-d", "--no-deps", "--scale", "api=%d" % len(before), "api") + wait_ready() + replaced.append(old[:12]) + time.sleep(5) + halt.set() + for thread in threads: + thread.join(timeout=10) + after = api_ids() + check(len(after) >= 2, "lost replicas after rolling update") + check(len(latencies) > 0, "no successful writes during rolling update") + report = { + "date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "replaced": replaced, + "replicas_before": [item[:12] for item in before], + "replicas_after": [item[:12] for item in after], + "successful_writes": len(latencies), + "failed_writes": len(errors), + "error_ratio": round(len(errors) / max(1, len(latencies) + len(errors)), 6), + } + EVIDENCE.mkdir(exist_ok=True) + (EVIDENCE / "rolling.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print("PASS: rolling update under load") + print(json.dumps(report, ensure_ascii=False)) + + +if __name__ == "__main__": + run(main) diff --git a/student-tests/run.py b/student-tests/run.py new file mode 100644 index 0000000..dd78f31 --- /dev/null +++ b/student-tests/run.py @@ -0,0 +1,509 @@ +#!/usr/bin/env python3 + +import base64 +import json +import os +import socket +import subprocess +import sys +import threading +import time +import urllib.error +import urllib.request +import uuid +from pathlib import Path +from urllib.parse import quote + +ROOT = Path(__file__).resolve().parents[1] +EVIDENCE = ROOT / "evidence" +SECRET = "SECRET_MESSAGE_DO_NOT_LOG_7f3a" +CLIENTS = 10 +PER_CLIENT = 10 + + +class Failure(AssertionError): + pass + + +def check(condition, message): + if not condition: + raise Failure(message) + + +def free_port(): + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return sock.getsockname()[1] + + +class Server: + def __init__(self, port): + self.base = "http://127.0.0.1:%d" % port + env = os.environ.copy() + env["PYTHONPATH"] = str(ROOT / "src") + env["PYTHONUNBUFFERED"] = "1" + env["APP_HOST"] = "127.0.0.1" + env["APP_PORT"] = str(port) + env["APP_ENV"] = "lab" + env["DATABASE_URL"] = host_secret("host_database_url") + env["REDIS_URL"] = host_secret("host_cache_url") + env["S3_ENDPOINT"] = host_secret("host_s3_endpoint") + env["S3_ACCESS_KEY_ID"] = host_secret("s3_access_key_id") + env["S3_SECRET_ACCESS_KEY"] = host_secret("s3_secret_access_key") + env["S3_BUCKET"] = "messenger-attachments" + env["SESSION_TTL_SECONDS"] = "3600" + env.pop("DATABASE_URL_FILE", None) + env.pop("CACHE_URL_FILE", None) + self.logs = [] + self.proc = subprocess.Popen( + [sys.executable, "-m", "app"], + cwd=str(ROOT), + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + encoding="utf-8", + errors="replace", + ) + self._reader = threading.Thread(target=self._read, daemon=True) + self._reader.start() + + def _read(self): + assert self.proc.stdout is not None + for line in self.proc.stdout: + self.logs.append(line) + + def wait_ready(self): + deadline = time.monotonic() + 40 + last = "" + while time.monotonic() < deadline: + if self.proc.poll() is not None: + raise Failure("server exited early:\n" + "".join(self.logs[-40:])) + try: + call(self.base, "GET", "/health/ready", 200) + return + except Failure as exc: + last = str(exc) + except (urllib.error.URLError, TimeoutError, OSError) as exc: + last = type(exc).__name__ + time.sleep(0.1) + raise Failure("server did not become ready: " + last + "\n" + "".join(self.logs[-40:])) + + def stop(self): + if self.proc.poll() is None: + self.proc.terminate() + try: + self.proc.wait(timeout=8) + except subprocess.TimeoutExpired: + self.proc.kill() + self.proc.wait(timeout=5) + self._reader.join(timeout=2) + + def output(self): + return "".join(self.logs) + + +def host_secret(name): + path = ROOT / "secrets" / name + if not path.is_file(): + raise Failure("missing secrets/%s; run scripts/bootstrap.ps1 or scripts/bootstrap.sh" % name) + value = path.read_text(encoding="utf-8").strip() + if not value: + raise Failure("empty secrets/%s" % name) + return value + + +def call( + base, + method, + path, + expected, + body=None, + token=None, + user_id=None, + authorization=None, + raw=None, + content_type="application/json", + timeout=20, + headers=None, +): + extra_headers = headers or {} + headers = {"Accept": "application/json"} + headers.update(extra_headers) + data = None + if raw is not None: + data = raw + headers["Content-Type"] = content_type + elif body is not None: + data = json.dumps(body, ensure_ascii=False).encode("utf-8") + headers["Content-Type"] = content_type + if authorization: + headers["Authorization"] = authorization + elif token: + headers["Authorization"] = "Bearer " + token + if user_id: + headers["X-User-Id"] = user_id + request = urllib.request.Request(base + path, data=data, headers=headers, method=method) + try: + response = urllib.request.urlopen(request, timeout=timeout) + except urllib.error.HTTPError as error: + response = error + except (urllib.error.URLError, TimeoutError, OSError) as exc: + raise Failure(method + " " + path.split("?")[0] + " failed: " + type(exc).__name__) from None + with response: + status = response.status + payload = response.read() + header_id = response.headers.get("X-Request-Id") + instance_id = response.headers.get("X-Instance-Id") + content_type_value = response.headers.get_content_type() + allowed = [expected] if isinstance(expected, int) else list(expected) + check(status in allowed, "%s %s: expected %s, got %s" % (method, path.split("?")[0], allowed, status)) + check(header_id and header_id.strip() and "," not in header_id, "missing or duplicated X-Request-Id") + check(instance_id and instance_id.strip() and "," not in instance_id, "missing or duplicated X-Instance-Id") + parsed = None + if payload: + check(content_type_value == "application/json", "expected application/json") + try: + parsed = json.loads(payload) + except json.JSONDecodeError as exc: + raise Failure("response is not JSON") from exc + if status >= 400: + check(isinstance(parsed, dict) and set(parsed) == {"error"}, "error envelope") + error = parsed["error"] + check(set(error) == {"code", "message", "request_id"}, "error fields") + check(error["request_id"] == header_id, "request_id differs from header") + check(error["message"] and "Traceback" not in error["message"], "error message leaked internals") + return {"status": status, "json": parsed, "request_id": header_id, "instance_id": instance_id} + + +def send_message(base, chat_id, token, text, expected=201, key=None): + headers = {"Idempotency-Key": key or uuid.uuid4().hex} + return call( + base, + "POST", + "/api/v1/chats/%s/messages" % chat_id, + expected, + token=token, + body={"text": text}, + headers=headers, + ) + + +def create_user(base, label): + username = ("u_%s_%s" % (label, uuid.uuid4().hex[:10])).lower() + password = "T3st-" + uuid.uuid4().hex + body = {"username": username, "display_name": "Студент " + label, "password": password} + created = call(base, "POST", "/api/v1/users", 201, body=body)["json"] + check(created["username"] == username, "username changed") + check("password" not in created, "password leaked in user response") + raw = base64.b64encode(("%s:%s" % (username, password)).encode("utf-8")).decode("ascii") + session = call(base, "POST", "/api/v1/auth/sessions", 201, authorization="Basic " + raw)["json"] + check(session["token_type"] == "Bearer", "token type") + check(session["user"]["id"] == created["id"], "session user") + check("password" not in session["user"], "password leaked in session") + created["token"] = session["token"] + created["instance_id"] = session.get("instance_id") + return created + + +def replace_cursor(token, fields): + padding = "=" * (-len(token) % 4) + data = json.loads(base64.urlsafe_b64decode(token + padding)) + data.update(fields) + raw = json.dumps(data, separators=(",", ":"), sort_keys=True).encode("ascii") + return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=") + + +def test_invalid_json(base): + broken = call(base, "POST", "/api/v1/users", 400, raw=b"{") + check(broken["json"]["error"]["code"] == "invalid_request", "malformed JSON code") + extra = call( + base, + "POST", + "/api/v1/users", + 400, + body={"username": "abc_user", "display_name": "Имя", "extra": True}, + ) + check(extra["json"]["error"]["code"] == "invalid_request", "extra field code") + bad_utf = call(base, "POST", "/api/v1/users", 400, raw=b"\xff") + check(bad_utf["json"]["error"]["code"] == "invalid_request", "invalid utf-8 code") + alice = create_user(base, "utf") + chat = call( + base, + "POST", + "/api/v1/chats", + 201, + token=alice["token"], + body={"title": "UTF", "member_ids": [alice["id"]]}, + )["json"] + bad_message = call( + base, + "POST", + "/api/v1/chats/%s/messages" % chat["id"], + 400, + token=alice["token"], + raw=b"\xff", + headers={"Idempotency-Key": uuid.uuid4().hex}, + ) + check(bad_message["json"]["error"]["code"] == "invalid_request", "invalid utf-8 message code") + print("PASS: invalid JSON") + + +def test_duplicate_username(base): + first = create_user(base, "dup") + again = call( + base, + "POST", + "/api/v1/users", + 409, + body={ + "username": first["username"], + "display_name": "Другой", + "password": "T3st-" + uuid.uuid4().hex, + }, + ) + check(again["json"]["error"]["code"] == "conflict", "duplicate username code") + me = call(base, "GET", "/api/v1/users/me", 200, token=first["token"])["json"] + check(me["id"] == first["id"], "first user disappeared after duplicate") + print("PASS: duplicate username") + + +def test_empty_and_foreign(base): + alice = create_user(base, "alice") + bob = create_user(base, "bob") + chat = call( + base, + "POST", + "/api/v1/chats", + 201, + token=alice["token"], + body={"title": "Только Алиса", "member_ids": [alice["id"]]}, + )["json"] + path = "/api/v1/chats/" + chat["id"] + for text in ("", " ", "\n\t"): + denied = call( + base, + "POST", + path + "/messages", + 400, + token=alice["token"], + body={"text": text}, + headers={"Idempotency-Key": uuid.uuid4().hex}, + ) + check(denied["json"]["error"]["code"] == "invalid_request", "empty message code") + for method, target, payload in ( + ("GET", path, None), + ("GET", path + "/messages", None), + ("POST", path + "/messages", {"text": "чужое"}), + ): + extra = {"Idempotency-Key": uuid.uuid4().hex} if method == "POST" else None + hidden = call(base, method, target, 404, token=bob["token"], body=payload, headers=extra) + check(hidden["json"]["error"]["code"] == "not_found", "foreign chat code") + check(chat["title"] not in hidden["json"]["error"]["message"], "foreign chat leaked title") + listed = call(base, "GET", "/api/v1/chats?limit=100", 200, token=bob["token"])["json"] + check(all(item["id"] != chat["id"] for item in listed["items"]), "foreign chat listed") + missing = call(base, "GET", "/api/v1/chats/" + str(uuid.uuid4()), 404, token=bob["token"]) + check(missing["json"]["error"]["code"] == "not_found", "missing chat code") + bad_limit = call(base, "GET", path + "/messages?limit=0", 400, token=alice["token"]) + check(bad_limit["json"]["error"]["code"] == "invalid_request", "limit=0 code") + print("PASS: empty message and foreign chat") + + +def test_pagination(base): + alice = create_user(base, "page") + other = create_user(base, "other") + chat = call( + base, + "POST", + "/api/v1/chats", + 201, + token=alice["token"], + body={"title": "Страницы", "member_ids": [alice["id"]]}, + )["json"] + other_chat = call( + base, + "POST", + "/api/v1/chats", + 201, + token=other["token"], + body={"title": "Другой", "member_ids": [other["id"]]}, + )["json"] + texts = ["p0", "Привет, мир 👋", "p2", "p3", "p4"] + created = [] + for text in texts: + created.append(send_message(base, chat["id"], alice["token"], text)["json"]) + send_message(base, other_chat["id"], other["token"], "x") + send_message(base, other_chat["id"], other["token"], "y") + collected = [] + cursor = None + pages = 0 + while True: + target = "/api/v1/chats/%s/messages?limit=2" % chat["id"] + if cursor: + target += "&cursor=" + quote(cursor, safe="") + page = call(base, "GET", target, 200, token=alice["token"])["json"] + pages += 1 + collected.extend(page["items"]) + cursor = page["next_cursor"] + if cursor is None: + break + check(pages < 10, "pagination did not finish") + check(pages == 3, "expected 3 pages, got %d" % pages) + check(collected == created, "pagination lost, duplicated or reordered messages") + stolen = call( + base, + "GET", + "/api/v1/chats/%s/messages?limit=1" % other_chat["id"], + 200, + token=other["token"], + )["json"] + check(stolen["next_cursor"], "foreign page should expose a cursor") + rejected = call( + base, + "GET", + "/api/v1/chats/%s/messages?limit=2&cursor=%s" % (chat["id"], quote(stolen["next_cursor"], safe="")), + 400, + token=alice["token"], + ) + check(rejected["json"]["error"]["code"] == "invalid_request", "foreign cursor code") + first_page = call( + base, + "GET", + "/api/v1/chats/%s/messages?limit=1" % chat["id"], + 200, + token=alice["token"], + )["json"] + for fields in ({"t": None}, {"t": 123}, {"i": 123}): + broken = call( + base, + "GET", + "/api/v1/chats/%s/messages?limit=1&cursor=%s" + % (chat["id"], quote(replace_cursor(first_page["next_cursor"], fields), safe="")), + 400, + token=alice["token"], + ) + check(broken["json"]["error"]["code"] == "invalid_request", "tampered cursor code") + print("PASS: pagination") + + +def test_concurrency(base): + users = [create_user(base, "c%d" % index) for index in range(CLIENTS)] + chat = call( + base, + "POST", + "/api/v1/chats", + 201, + token=users[0]["token"], + body={"title": "Гонка", "member_ids": [user["id"] for user in users]}, + )["json"] + barrier = threading.Barrier(CLIENTS) + found = [] + errors = [] + lock = threading.Lock() + + def worker(user): + try: + barrier.wait(10) + local = [] + for index in range(PER_CLIENT): + message = send_message( + base, + chat["id"], + user["token"], + "m-%s-%d" % (user["id"][:8], index), + )["json"] + local.append(message["id"]) + with lock: + found.extend(local) + except Exception as exc: + with lock: + errors.append("%s: %s" % (type(exc).__name__, exc)) + + threads = [threading.Thread(target=worker, args=(user,)) for user in users] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + check(not errors, "concurrent sends failed: " + "; ".join(errors[:5])) + check(len(found) == CLIENTS * PER_CLIENT, "submitted count") + check(len(set(found)) == CLIENTS * PER_CLIENT, "duplicate message ids") + + listed = [] + cursor = None + while True: + target = "/api/v1/chats/%s/messages?limit=40" % chat["id"] + if cursor: + target += "&cursor=" + quote(cursor, safe="") + page = call(base, "GET", target, 200, token=users[0]["token"])["json"] + listed.extend(item["id"] for item in page["items"]) + cursor = page["next_cursor"] + if cursor is None: + break + check(len(listed) == 100 and len(set(listed)) == 100, "history does not contain 100 unique messages") + check(set(listed) == set(found), "history ids differ from accepted sends") + EVIDENCE.mkdir(exist_ok=True) + report = { + "date": "2026-10-25", + "command": "python student-tests/run.py", + "clients": CLIENTS, + "messages_per_client": PER_CLIENT, + "submitted": len(found), + "unique_ids": len(set(found)), + "listed": len(listed), + "failed_requests": len(errors), + "pass": True, + } + (EVIDENCE / "concurrency.json").write_text( + json.dumps(report, ensure_ascii=False, indent=2) + "\n", + encoding="utf-8", + ) + print("PASS: concurrency 100 unique messages from 10 clients") + + +def test_logs(server): + alice = create_user(server.base, "logs") + chat = call( + server.base, + "POST", + "/api/v1/chats", + 201, + token=alice["token"], + body={"title": "Логи", "member_ids": [alice["id"]]}, + )["json"] + send_message(server.base, chat["id"], alice["token"], SECRET) + time.sleep(0.2) + output = server.output() + check("duration_ms=" in output and "method=POST" in output, "request log line missing") + check(SECRET not in output, "message text leaked into logs") + check(alice["token"] not in output, "session token leaked into logs") + check("lab-only-password" not in output and "postgresql+asyncpg://" not in output, "database url leaked into logs") + print("PASS: logs omit message text") + + +def main(): + port = free_port() + server = Server(port) + try: + server.wait_ready() + call(server.base, "GET", "/health/live", 200) + call(server.base, "GET", "/api/v1/users/me", 401) + header_only = create_user(server.base, "header") + rejected = call(server.base, "GET", "/api/v1/users/me", 401, user_id=header_only["id"]) + check(rejected["json"]["error"]["code"] == "unauthorized", "X-User-Id was accepted") + test_invalid_json(server.base) + test_duplicate_username(server.base) + test_empty_and_foreign(server.base) + test_pagination(server.base) + test_concurrency(server.base) + test_logs(server) + finally: + server.stop() + print("PASS: student tests") + + +if __name__ == "__main__": + try: + main() + except Failure as exc: + print("FAIL:", exc) + sys.exit(1) diff --git a/student-tests/s3_private.py b/student-tests/s3_private.py new file mode 100644 index 0000000..042e7a7 --- /dev/null +++ b/student-tests/s3_private.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +"""Прямой анонимный доступ к bucket должен быть закрыт.""" + +import json +import os +import sys +import time +import urllib.error +import urllib.request +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +from client import Client, Failure, check, run + +EVIDENCE = ROOT / "evidence" +BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/") +S3 = os.environ.get("S3_PUBLIC_URL", "http://127.0.0.1:9000").rstrip("/") +BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments") + + +def anonymous(path: str) -> int: + request = urllib.request.Request(S3 + path, method="GET") + try: + with urllib.request.urlopen(request, timeout=10) as response: + return response.status + except urllib.error.HTTPError as exc: + return exc.status + except (urllib.error.URLError, TimeoutError, OSError) as exc: + raise Failure("direct s3 probe failed: " + type(exc).__name__) from None + + +def main(): + client = Client(BASE, timeout=20) + alice, _bob, _eve, chat = client.bootstrap() + att, content = client.attachment(alice, chat) + att = client.wait_ready(alice, att) + listed = anonymous("/" + BUCKET) + obj = anonymous("/" + BUCKET + "/att/" + att["id"]) + check(listed in {403, 404}, "anonymous list status %s" % listed) + check(obj in {403, 404}, "anonymous object status %s" % obj) + download = client.call("GET", "/api/v1/attachments/%s/content" % att["id"], actor=alice) + check(download["bytes"] == content, "authorized download after anonymous probe") + EVIDENCE.mkdir(exist_ok=True) + (EVIDENCE / "s3_private.json").write_text( + json.dumps( + { + "date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "anonymous_list": listed, + "anonymous_object": obj, + }, + indent=2, + ) + + "\n", + encoding="utf-8", + ) + print("PASS: private bucket rejects anonymous GET") + + +if __name__ == "__main__": + run(main) diff --git a/student-tests/track1.py b/student-tests/track1.py new file mode 100644 index 0000000..6cb94f5 --- /dev/null +++ b/student-tests/track1.py @@ -0,0 +1,199 @@ +#!/usr/bin/env python3 +"""Трек 5.1: цена масштабирования API при фиксированном и растущем бюджете CPU/RAM.""" + +import json +import math +import os +import subprocess +import sys +import threading +import time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +from client import Client, Failure, check, run + +EVIDENCE = ROOT / "evidence" +BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/") +DURATION = float(os.environ.get("TRACK1_DURATION", "30")) +CONCURRENCY = int(os.environ.get("TRACK1_CONCURRENCY", "8")) +WARMUP = float(os.environ.get("TRACK1_WARMUP", "8")) + + +def compose(*args, timeout=180): + proc = subprocess.run( + ["docker", "compose", "--env-file", ".env", *args], + cwd=str(ROOT), + capture_output=True, + text=True, + timeout=timeout, + encoding="utf-8", + errors="replace", + ) + if proc.returncode != 0: + raise Failure("docker compose %s failed: %s" % (args[0], proc.stderr[-400:])) + return proc.stdout + + +def api_ids(): + return [line.strip() for line in compose("ps", "-q", "api").splitlines() if line.strip()] + + +def wait_ready(timeout=90): + client = Client(BASE, timeout=3) + deadline = time.monotonic() + timeout + last = "" + while time.monotonic() < deadline: + try: + client.call("GET", "/health/ready", schema="Health") + return + except Failure as exc: + last = str(exc) + time.sleep(0.4) + raise Failure("ready wait failed: " + last) + + +def scale_api(n): + compose("up", "-d", "--no-deps", "--scale", "api=%d" % n, "api") + deadline = time.monotonic() + 90 + while time.monotonic() < deadline: + if len(api_ids()) >= n: + wait_ready() + return + time.sleep(0.5) + raise Failure("failed to scale api to %s" % n) + + +def apply_limits(cpus_each, memory_mb_each): + for container_id in api_ids(): + args = ["docker", "update", "--cpus", "%.3f" % cpus_each, "--memory", "%dm" % memory_mb_each, container_id] + proc = subprocess.run(args, capture_output=True, text=True, timeout=30) + if proc.returncode != 0: + raise Failure("docker update failed") + + +def docker_stats(): + proc = subprocess.run( + ["docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}"], + capture_output=True, + text=True, + timeout=30, + encoding="utf-8", + errors="replace", + ) + rows = [] + for line in proc.stdout.splitlines(): + parts = line.split("\t") + if len(parts) == 3: + rows.append({"name": parts[0], "cpu": parts[1], "mem": parts[2]}) + return rows + + +def run_load(duration, concurrency, warmup): + client = Client(BASE, timeout=8) + alice, _bob, _eve, chat = client.bootstrap() + if warmup > 0: + deadline = time.monotonic() + warmup + index = 0 + while time.monotonic() < deadline: + client.message(alice, chat, "warmup-%s" % index) + index += 1 + barrier = threading.Barrier(concurrency) + + def worker(worker_id): + local = Client(BASE, timeout=5) + barrier.wait() + end = time.monotonic() + duration + latencies, errors = [], 0 + index = 0 + while time.monotonic() < end: + started = time.monotonic() + try: + local.message(alice, chat, "track1-%s-%s" % (worker_id, index)) + latencies.append(time.monotonic() - started) + except Failure: + errors += 1 + index += 1 + return latencies, errors + + started = time.monotonic() + with ThreadPoolExecutor(max_workers=concurrency) as pool: + results = list(pool.map(worker, range(concurrency))) + elapsed = time.monotonic() - started + latencies = sorted(item for values, _ in results for item in values) + errors = sum(n for _, n in results) + total = len(latencies) + errors + + def percentile(p): + if not latencies: + return None + return round(1000 * latencies[max(0, math.ceil(p * len(latencies)) - 1)], 3) + + return { + "elapsed_seconds": round(elapsed, 3), + "concurrency": concurrency, + "successful_requests": len(latencies), + "failed_requests": errors, + "error_ratio": round(errors / total, 6) if total else None, + "successful_rps": round(len(latencies) / elapsed, 3) if elapsed else None, + "successful_latency_ms": {"p50": percentile(0.50), "p95": percentile(0.95), "p99": percentile(0.99)}, + "docker_stats": docker_stats(), + } + + +def measure(label, replicas, cpus_each, memory_mb_each): + scale_api(replicas) + apply_limits(cpus_each, memory_mb_each) + wait_ready() + time.sleep(2) + result = run_load(DURATION, CONCURRENCY, WARMUP) + result.update( + { + "label": label, + "replicas": replicas, + "cpus_each": cpus_each, + "memory_mb_each": memory_mb_each, + "total_cpu": round(replicas * cpus_each, 3), + "total_memory_mb": replicas * memory_mb_each, + } + ) + print(json.dumps({k: result[k] for k in ("label", "replicas", "total_cpu", "successful_rps", "error_ratio")}, ensure_ascii=False)) + return result + + +def main(): + wait_ready() + fixed_budget = [ + measure("fixed-1", 1, 1.00, 512), + measure("fixed-2", 2, 0.50, 256), + measure("fixed-4", 4, 0.25, 128), + ] + growing = [ + measure("grow-2x0.25", 2, 0.25, 128), + measure("grow-2x0.50", 2, 0.50, 256), + measure("grow-2x1.00", 2, 1.00, 512), + ] + scale_api(2) + apply_limits(0.50, 256) + report = { + "date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "hypothesis": "При фиксированном суммарном CPU/RAM добавление реплик перестаёт помогать, когда узким местом становится PostgreSQL/HAProxy, а не CPU процесса API.", + "profile": { + "duration_seconds": DURATION, + "concurrency": CONCURRENCY, + "warmup_seconds": WARMUP, + "workload": "closed-loop POST /messages through HAProxy", + }, + "fixed_total_budget": fixed_budget, + "growing_resources": growing, + } + EVIDENCE.mkdir(exist_ok=True) + (EVIDENCE / "track1.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + check(all(item["successful_requests"] > 0 for item in fixed_budget + growing), "a track1 series had no successes") + print("PASS: track1 series written to evidence/track1.json") + + +if __name__ == "__main__": + run(main) diff --git a/student-tests/upload_mem.py b/student-tests/upload_mem.py new file mode 100644 index 0000000..fe546aa --- /dev/null +++ b/student-tests/upload_mem.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""10 параллельных загрузок и пик RSS API-реплик по docker stats.""" + +import json +import os +import subprocess +import sys +import threading +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +from client import Client, Failure, check, run + +EVIDENCE = ROOT / "evidence" +BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/") +WORKERS = 10 +SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes() + + +def api_mem_mib() -> float: + proc = subprocess.run( + ["docker", "compose", "--env-file", ".env", "ps", "-q", "api"], + cwd=str(ROOT), + capture_output=True, + text=True, + timeout=20, + ) + ids = [line.strip() for line in proc.stdout.splitlines() if line.strip()] + if not ids: + raise Failure("no api containers") + stats = subprocess.run( + ["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}", *ids], + capture_output=True, + text=True, + timeout=20, + ) + if stats.returncode != 0: + raise Failure("docker stats failed") + peak = 0.0 + for line in stats.stdout.splitlines(): + used = line.split("/", 1)[0].strip() + if used.endswith("GiB"): + peak = max(peak, float(used[:-3].strip()) * 1024) + elif used.endswith("MiB"): + peak = max(peak, float(used[:-3].strip())) + elif used.endswith("KiB"): + peak = max(peak, float(used[:-3].strip()) / 1024) + return peak + + +def main(): + client = Client(BASE, timeout=30) + alice, _bob, _eve, chat = client.bootstrap() + before = api_mem_mib() + barrier = threading.Barrier(WORKERS) + errors = [] + lock = threading.Lock() + + def worker(index: int) -> None: + local = Client(BASE, timeout=30) + try: + barrier.wait(20) + local.call( + "POST", + "/api/v1/chats/%s/attachments?filename=p%d.png" % (chat["id"], index), + 202, + actor=alice, + raw=SAMPLE, + headers={"Content-Type": "image/png"}, + schema="Attachment", + ) + except Exception as exc: + with lock: + errors.append("%s: %s" % (type(exc).__name__, exc)) + + threads = [threading.Thread(target=worker, args=(i,)) for i in range(WORKERS)] + for thread in threads: + thread.start() + peak = before + deadline = time.monotonic() + 30 + while any(thread.is_alive() for thread in threads) and time.monotonic() < deadline: + peak = max(peak, api_mem_mib()) + time.sleep(0.4) + for thread in threads: + thread.join() + peak = max(peak, api_mem_mib()) + check(not errors, "concurrent uploads failed: " + "; ".join(errors[:3])) + EVIDENCE.mkdir(exist_ok=True) + (EVIDENCE / "upload_mem.json").write_text( + json.dumps( + { + "date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "workers": WORKERS, + "rss_before_mib": round(before, 2), + "rss_peak_mib": round(peak, 2), + }, + indent=2, + ) + + "\n", + encoding="utf-8", + ) + print("PASS: %s concurrent uploads, peak RSS %.1f MiB" % (WORKERS, peak)) + + +if __name__ == "__main__": + run(main)