Шиян Лаб6 - оценка 4 #53
@@ -18,3 +18,13 @@ __pycache__
|
||||
node_modules
|
||||
evidence
|
||||
.DS_Store
|
||||
*.pyc
|
||||
.idea
|
||||
.vscode
|
||||
student-tests/
|
||||
tests/
|
||||
contracts/
|
||||
examples/
|
||||
scripts/
|
||||
*.md
|
||||
Dockerfile.example
|
||||
@@ -23,8 +23,3 @@ WORKER_CONCURRENCY=2
|
||||
JOB_MAX_ATTEMPTS=5
|
||||
JOB_TIMEOUT_SECONDS=60
|
||||
STAGING_RETENTION_SECONDS=86400
|
||||
OTEL_SERVICE_NAME=messenger-api
|
||||
# Worker must set a distinct service.name.
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
|
||||
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
FROM golang:1.26-alpine3.22 AS build
|
||||
# cgo нужен только для WebP-энкодера (chai2010/webp -> libwebp).
|
||||
RUN apk add --no-cache build-base libwebp-dev
|
||||
WORKDIR /src
|
||||
COPY src/go.mod src/go.sum ./
|
||||
RUN go mod download
|
||||
COPY src/ ./
|
||||
ENV CGO_ENABLED=1
|
||||
RUN go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server
|
||||
|
||||
FROM alpine:3.22 AS runtime
|
||||
# runtime-библиотека libwebp для динамически слинкованного бинарника.
|
||||
RUN apk add --no-cache libwebp
|
||||
RUN addgroup -S app && adduser -S -G app app
|
||||
WORKDIR /app
|
||||
COPY --from=build /out/server /app/server
|
||||
USER app
|
||||
EXPOSE 8080
|
||||
ENV APP_HOST=0.0.0.0 APP_PORT=8080
|
||||
HEALTHCHECK --interval=5s --timeout=3s --start-period=5s --retries=3 \
|
||||
CMD wget -q -O /dev/null http://127.0.0.1:8080/health/live || exit 1
|
||||
ENTRYPOINT ["/app/server"]
|
||||
@@ -1,37 +1,47 @@
|
||||
# Отчёт — лабораторная 6
|
||||
# Лабораторная работа 6: Observability (уровень 4)
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
## Краткое описание
|
||||
|
||||
## Запуск из чистого clone
|
||||
Реализована полная observability-инфраструктура для messenger уровня 4: traces, metrics, logs через OpenTelemetry SDK + Collector + Prometheus/Loki/Tempo + Grafana. Все три сигнала (traces, metrics, logs) собираются через единый SDK, экспортируются через OTLP в Collector, хранятся в специализированных бэкендах и визуализируются в Grafana с dashboard и alert rules.
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
## Архитектура наблюдаемости
|
||||
|
||||
## Архитектура и решения
|
||||
### Компоненты
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab5, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
- **SDK**: OpenTelemetry Go SDK (traces, metrics, logs)
|
||||
- **Instrumentation**:
|
||||
- `otelhttp` для HTTP server spans с low-cardinality route
|
||||
- `exaring/otelpgx` для PostgreSQL client spans
|
||||
- Собственный Redis hook для Redis client spans
|
||||
- `otelslog` bridge для structured logging с auto-injection trace_id/span_id
|
||||
- **Propagation**: W3C Trace Context (traceparent/tracestate) через API → broker (Redis Streams) → worker
|
||||
- **Backend**: OTel Collector → Prometheus (metrics, pull) + Loki (logs, OTLP) + Tempo (traces, OTLP)
|
||||
- **Visualization**: Grafana с provisioning из Git (dashboard + alert rules + datasources)
|
||||
|
||||
## Доказательства критериев
|
||||
### Схема потока данных
|
||||
API/Worker
|
||||
↓ OTLP/HTTP
|
||||
OTel Collector (memory_limiter + batch)
|
||||
↓
|
||||
├─→ Prometheus exporter (pull) → Prometheus → Grafana
|
||||
├─→ OTLP/HTTP → Loki → Grafana
|
||||
└─→ OTLP/gRPC → Tempo → Grafana
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
### Сквозная трасса
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
1. HTTP запрос → `otelhttp` создаёт server span
|
||||
2. Upload attachment → producer span в `queue.publish` с `traceparent` в outbox
|
||||
3. Outbox relay → читает outbox, публикует в Redis Streams с `traceparent`
|
||||
4. Worker → consumer span извлекает `traceparent`, становится дочерним к producer
|
||||
5. DB/S3 операции → db client spans (pgx, Redis) как дочерние к consumer
|
||||
6. Логи через `otelslog` bridge имеют `trace_id`/`span_id` автоматически
|
||||
|
||||
## Эксперименты и отказы
|
||||
## Как запустить/проверить
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
### Запуск
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
```bash
|
||||
docker compose --compatibility up -d
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
python -X utf8 tests\smoke.py --base-url http://localhost:8080
|
||||
# PASS: lab6 public API scenario
|
||||
+333
@@ -0,0 +1,333 @@
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
environment:
|
||||
POSTGRES_DB: messenger
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_PASSWORD: messenger_password
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U messenger"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '1.00'
|
||||
memory: 512M
|
||||
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
# LAB 5: брокер durable — AOF с fsync раз в секунду.
|
||||
command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec"]
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '0.50'
|
||||
memory: 128M
|
||||
|
||||
rustfs:
|
||||
image: rustfs/rustfs@sha256:ed9210d6411d77ffceb70d94b964a3cb7d225983368bc25bebe01e995293dcc2
|
||||
environment:
|
||||
RUSTFS_ACCESS_KEY: ${S3_ACCESS_KEY:-minioadmin}
|
||||
RUSTFS_SECRET_KEY: ${S3_SECRET_KEY:-minioadmin}
|
||||
RUSTFS_ADDRESS: 0.0.0.0:9000
|
||||
RUSTFS_CONSOLE_ADDRESS: 127.0.0.1:9001
|
||||
RUSTFS_DATA_DIR: /data
|
||||
MINIO_ROOT_USER: ${S3_ACCESS_KEY:-minioadmin}
|
||||
MINIO_ROOT_PASSWORD: ${S3_SECRET_KEY:-minioadmin}
|
||||
volumes:
|
||||
- rustfs_data:/data
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '0.50'
|
||||
memory: 256M
|
||||
|
||||
# Однократный сервис миграций: применяется ОДИН РАЗ перед стартом реплик.
|
||||
migrate:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
entrypoint: ["/app/server", "-migrate-only"]
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
DATABASE_URL: postgres://messenger:messenger_password@postgres:5432/messenger?sslmode=disable
|
||||
healthcheck:
|
||||
disable: true
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '0.50'
|
||||
memory: 128M
|
||||
|
||||
api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
deploy:
|
||||
replicas: 2
|
||||
resources:
|
||||
limits:
|
||||
cpus: '0.50'
|
||||
memory: 256M
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
rustfs:
|
||||
condition: service_started
|
||||
# LAB 6: Collector поднимается раньше, чтобы первые спаны не терялись.
|
||||
# Условие service_started (не healthy): образ Collector без shell,
|
||||
# healthcheck внутри контейнера невозможен — готовность проверяем
|
||||
# с хоста на http://localhost:13133/.
|
||||
otel:
|
||||
condition: service_started
|
||||
environment:
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: 8080
|
||||
DATABASE_URL: postgres://messenger:messenger_password@postgres:5432/messenger?sslmode=disable
|
||||
REDIS_URL: redis://redis:6379/0
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
CACHE_MODE: ${CACHE_MODE:-versioned}
|
||||
SESSION_STORE: ${SESSION_STORE:-redis}
|
||||
S3_ENDPOINT: rustfs:9000
|
||||
S3_ACCESS_KEY: ${S3_ACCESS_KEY:-minioadmin}
|
||||
S3_SECRET_KEY: ${S3_SECRET_KEY:-minioadmin}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger}
|
||||
S3_USE_SSL: "false"
|
||||
# LAB 6: телеметрия
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: http://otel:4318
|
||||
OTEL_SERVICE_VERSION: lab6
|
||||
OTEL_ENV: lab
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:8080/health/ready"]
|
||||
interval: 2s
|
||||
timeout: 2s
|
||||
retries: 3
|
||||
start_period: 5s
|
||||
|
||||
# LAB 5: отдельный процесс обработки. Не принимает HTTP.
|
||||
worker:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
entrypoint: ["/app/server", "-worker"]
|
||||
deploy:
|
||||
replicas: 1
|
||||
resources:
|
||||
limits:
|
||||
cpus: '0.50'
|
||||
memory: 512M
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
rustfs:
|
||||
condition: service_started
|
||||
otel:
|
||||
condition: service_started
|
||||
environment:
|
||||
DATABASE_URL: postgres://messenger:messenger_password@postgres:5432/messenger?sslmode=disable
|
||||
REDIS_URL: redis://redis:6379/0
|
||||
S3_ENDPOINT: rustfs:9000
|
||||
S3_ACCESS_KEY: ${S3_ACCESS_KEY:-minioadmin}
|
||||
S3_SECRET_KEY: ${S3_SECRET_KEY:-minioadmin}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger}
|
||||
S3_USE_SSL: "false"
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: http://otel:4318
|
||||
OTEL_SERVICE_VERSION: lab6
|
||||
OTEL_ENV: lab
|
||||
healthcheck:
|
||||
disable: true
|
||||
|
||||
# LAB 5 (уровень 4): ручная сверка S3 <-> PostgreSQL.
|
||||
reconcile:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
entrypoint: ["/app/server", "-reconcile"]
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
rustfs:
|
||||
condition: service_started
|
||||
environment:
|
||||
DATABASE_URL: postgres://messenger:messenger_password@postgres:5432/messenger?sslmode=disable
|
||||
S3_ENDPOINT: rustfs:9000
|
||||
S3_ACCESS_KEY: ${S3_ACCESS_KEY:-minioadmin}
|
||||
S3_SECRET_KEY: ${S3_SECRET_KEY:-minioadmin}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger}
|
||||
S3_USE_SSL: "false"
|
||||
RECONCILE_GRACE_PERIOD_SECONDS: ${RECONCILE_GRACE_PERIOD_SECONDS:-3600}
|
||||
profiles:
|
||||
- tools
|
||||
healthcheck:
|
||||
disable: true
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '0.50'
|
||||
memory: 128M
|
||||
|
||||
nginx:
|
||||
image: nginx:1.25-alpine
|
||||
ports:
|
||||
- "8080:8080"
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
volumes:
|
||||
- ./nginx.conf:/etc/nginx/nginx.conf:ro
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '0.25'
|
||||
memory: 64M
|
||||
|
||||
# ─────────────────── LAB 6: наблюдаемость ───────────────────
|
||||
|
||||
# Приёмник/обработчик/экспортёр. Не долговременное хранилище.
|
||||
# memory_limiter 128 MiB при лимите контейнера 256M — запас на пики.
|
||||
otel:
|
||||
image: otel/opentelemetry-collector-contrib:0.115.1
|
||||
command: ["--config=/etc/otel/config.yaml"]
|
||||
volumes:
|
||||
- ./otel-collector.yaml:/etc/otel/config.yaml:ro
|
||||
ports:
|
||||
- "4318:4318" # OTLP/HTTP (API и worker шлют сюда)
|
||||
- "8889:8889" # метрики приложения (Prometheus exporter)
|
||||
- "8888:8888" # собственные метрики Collector
|
||||
- "13133:13133" # health_check extension
|
||||
depends_on:
|
||||
prometheus:
|
||||
condition: service_started
|
||||
loki:
|
||||
condition: service_started
|
||||
tempo:
|
||||
condition: service_started
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '0.50'
|
||||
memory: 256M
|
||||
|
||||
prometheus:
|
||||
image: prom/prometheus:v2.55.1
|
||||
command:
|
||||
- "--config.file=/etc/prometheus/prometheus.yaml"
|
||||
- "--storage.tsdb.path=/prometheus"
|
||||
- "--storage.tsdb.retention.time=6h"
|
||||
- "--storage.tsdb.retention.size=512MB"
|
||||
- "--web.enable-lifecycle"
|
||||
volumes:
|
||||
- ./prometheus.yaml:/etc/prometheus/prometheus.yaml:ro
|
||||
- prometheus_data:/prometheus
|
||||
ports:
|
||||
- "9090:9090"
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:9090/-/healthy"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
start_period: 10s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '0.50'
|
||||
memory: 384M
|
||||
|
||||
loki:
|
||||
image: grafana/loki:3.3.2
|
||||
command: ["-config.file=/etc/loki/config.yaml"]
|
||||
volumes:
|
||||
- ./loki.yaml:/etc/loki/config.yaml:ro
|
||||
- loki_data:/loki
|
||||
ports:
|
||||
- "3100:3100"
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:3100/ready"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
start_period: 20s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '0.50'
|
||||
memory: 384M
|
||||
|
||||
tempo:
|
||||
image: grafana/tempo:2.6.1
|
||||
command: ["-config.file=/etc/tempo/config.yaml"]
|
||||
volumes:
|
||||
- ./tempo.yaml:/etc/tempo/config.yaml:ro
|
||||
- tempo_data:/var/tempo
|
||||
ports:
|
||||
- "3200:3200"
|
||||
# Образ Tempo без гарантированного shell/wget — healthcheck не задаём,
|
||||
# готовность проверяем с хоста: curl http://localhost:3200/ready
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '0.50'
|
||||
memory: 384M
|
||||
|
||||
grafana:
|
||||
image: grafana/grafana:11.4.0
|
||||
environment:
|
||||
GF_SECURITY_ADMIN_USER: ${GRAFANA_ADMIN_USER:-admin}
|
||||
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:-admin}
|
||||
GF_USERS_ALLOW_SIGN_UP: "false"
|
||||
GF_ANALYTICS_REPORTING_ENABLED: "false"
|
||||
GF_ANALYTICS_CHECK_FOR_UPDATES: "false"
|
||||
GF_FEATURE_TOGGLES_ENABLE: "traceqlEditor"
|
||||
volumes:
|
||||
- ./grafana/provisioning:/etc/grafana/provisioning:ro
|
||||
- grafana_data:/var/lib/grafana
|
||||
ports:
|
||||
- "3000:3000"
|
||||
depends_on:
|
||||
prometheus:
|
||||
condition: service_healthy
|
||||
loki:
|
||||
condition: service_healthy
|
||||
tempo:
|
||||
condition: service_started
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:3000/api/health"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
start_period: 20s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '0.50'
|
||||
memory: 256M
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
redis_data:
|
||||
rustfs_data:
|
||||
prometheus_data:
|
||||
loki_data:
|
||||
tempo_data:
|
||||
grafana_data:
|
||||
@@ -0,0 +1,86 @@
|
||||
# LAB 6 (уровень 4): alert rules с окном, порогом, for, описанием и runbook.
|
||||
# Delivery наружу не требуется — достаточно локального состояния firing/resolved.
|
||||
apiVersion: 1
|
||||
groups:
|
||||
- orgId: 1
|
||||
name: messenger
|
||||
folder: Messenger
|
||||
interval: 30s
|
||||
rules:
|
||||
- uid: messenger-high-error-rate
|
||||
title: "Messenger: API 5xx error rate > 1%"
|
||||
condition: C
|
||||
for: 2m
|
||||
labels:
|
||||
severity: warning
|
||||
component: api
|
||||
annotations:
|
||||
summary: "Доля 5xx ответов API превысила 1% в окне 2 минуты."
|
||||
description: |
|
||||
SLI: 5xx / все HTTP-запросы. Окно 2m. Порог 0.01.
|
||||
runbook: |
|
||||
1. Откройте dashboard 'messenger-overview', панель 'HTTP 5xx error ratio'.
|
||||
2. Посмотрите 'HTTP latency p50/p95/p99': резкий рост p99 указывает
|
||||
на зависимый сервис (БД/S3).
|
||||
3. Найдите трассу с 5xx через Tempo: service.name=messenger-api,
|
||||
status.code=ERROR. В дочерних spans ищите db.client или
|
||||
s3.operation с ошибками.
|
||||
4. Проверьте логи Loki: {service_name="messenger-api"} |= "error".
|
||||
5. Отличите медленный DB handler от недоступной БД:
|
||||
- недоступная БД: много 'database unavailable', /health/ready = 503;
|
||||
- медленный handler: /health/ready = 200, но p99 > 5s и
|
||||
db.client.operation.duration растёт.
|
||||
data:
|
||||
- refId: A
|
||||
relativeTimeRange: { from: 120, to: 0 }
|
||||
datasourceUid: prometheus
|
||||
model:
|
||||
expr: "sum(rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_response_status_code=~\"5..\"}[2m])) / sum(rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\"}[2m]))"
|
||||
instant: true
|
||||
- refId: B
|
||||
datasourceUid: __expr__
|
||||
model: { type: "reduce", expression: "A", reducer: "last" }
|
||||
- refId: C
|
||||
datasourceUid: __expr__
|
||||
model: { type: "threshold", expression: "B", conditions: [{ evaluator: { type: "gt", params: [0.01] } }] }
|
||||
|
||||
- uid: messenger-queue-lag
|
||||
title: "Messenger: queue oldest job age > 30s"
|
||||
condition: C
|
||||
for: 2m
|
||||
labels:
|
||||
severity: warning
|
||||
component: worker
|
||||
annotations:
|
||||
summary: "Возраст старейшего задания в очереди превысил 30 секунд в окне 2 минуты."
|
||||
description: |
|
||||
SLI: messenger_queue_oldest_age_seconds. Рост указывает, что worker
|
||||
не справляется или недоступен. Проверьте также messenger_jobs_oldest_queued_age_seconds.
|
||||
runbook: |
|
||||
1. Dashboard 'messenger-overview', панели 'Queue oldest age' и
|
||||
'Worker saturation'.
|
||||
2. Проверьте worker через `docker compose ps worker`:
|
||||
- Up — worker жив, но не справляется (смотрим Job duration p99);
|
||||
- Exited — worker упал, перезапустите и проверьте логи:
|
||||
`docker compose logs worker --tail 100`.
|
||||
3. Если worker жив, а depth растёт — посмотрите 'Jobs processed rate
|
||||
by outcome': высокий retry_scheduled/retry_exhausted указывает
|
||||
на внешнюю проблему (S3, БД).
|
||||
4. Трассы worker'а в Tempo: service.name=messenger-worker,
|
||||
name=attachment.process. Дочерние spans redis/pgsql/s3 покажут,
|
||||
где задержка.
|
||||
5. После устранения причины — очередь должна уменьшиться,
|
||||
alert перейдёт в resolved автоматически.
|
||||
data:
|
||||
- refId: A
|
||||
relativeTimeRange: { from: 120, to: 0 }
|
||||
datasourceUid: prometheus
|
||||
model:
|
||||
expr: "max(messenger_queue_oldest_age_seconds{service_name=\"messenger-api\"})"
|
||||
instant: true
|
||||
- refId: B
|
||||
datasourceUid: __expr__
|
||||
model: { type: "reduce", expression: "A", reducer: "last" }
|
||||
- refId: C
|
||||
datasourceUid: __expr__
|
||||
model: { type: "threshold", expression: "B", conditions: [{ evaluator: { type: "gt", params: [30] } }] }
|
||||
@@ -0,0 +1,16 @@
|
||||
# LAB 6: dashboard импортируется из Git, а не набирается руками.
|
||||
# JSON-файлы кладём в подпапку json/ (добавим на части 2).
|
||||
|
||||
apiVersion: 1
|
||||
|
||||
providers:
|
||||
- name: messenger
|
||||
orgId: 1
|
||||
folder: Messenger
|
||||
type: file
|
||||
disableDeletion: false
|
||||
updateIntervalSeconds: 30
|
||||
allowUiUpdates: true
|
||||
options:
|
||||
path: /etc/grafana/provisioning/dashboards/json
|
||||
foldersFromFilesStructure: false
|
||||
@@ -0,0 +1,189 @@
|
||||
{
|
||||
"uid": "messenger-overview",
|
||||
"title": "Messenger — observability level 4",
|
||||
"description": "API, worker, queue, saturation. PromQL ссылается на реальные имена метрик, экспортированные SDK.",
|
||||
"tags": ["messenger", "lab6"],
|
||||
"timezone": "utc",
|
||||
"editable": true,
|
||||
"time": { "from": "now-30m", "to": "now" },
|
||||
"refresh": "10s",
|
||||
"panels": [
|
||||
{
|
||||
"type": "row",
|
||||
"title": "HTTP API",
|
||||
"gridPos": { "h": 1, "w": 24, "x": 0, "y": 0 },
|
||||
"collapsed": false
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "HTTP RPS (by method, all replicas)",
|
||||
"description": "Сумма rate по всем репликам. Метрика: http_server_request_duration_seconds_count.",
|
||||
"datasource": { "uid": "prometheus", "type": "prometheus" },
|
||||
"gridPos": { "h": 8, "w": 8, "x": 0, "y": 1 },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum by (http_request_method) (rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\"}[$__rate_interval]))",
|
||||
"legendFormat": "{{http_request_method}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": { "unit": "reqps", "custom": { "lineWidth": 2, "fillOpacity": 15 } }
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "HTTP 5xx error ratio",
|
||||
"description": "SLI: 5xx / все запросы. Health GET не даёт 5xx при живой БД и не искажает знаменатель.",
|
||||
"datasource": { "uid": "prometheus", "type": "prometheus" },
|
||||
"gridPos": { "h": 8, "w": 8, "x": 8, "y": 1 },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum(rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_response_status_code=~\"5..\"}[$__rate_interval])) / sum(rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\"}[$__rate_interval]))",
|
||||
"legendFormat": "5xx ratio"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": { "unit": "percentunit", "max": 1, "custom": { "lineWidth": 2 } },
|
||||
"overrides": [
|
||||
{ "matcher": { "id": "byName", "options": "5xx ratio" },
|
||||
"properties": [{ "id": "color", "value": { "mode": "fixed", "fixedColor": "red" } }] }
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "HTTP latency p50 / p95 / p99",
|
||||
"description": "Глобальные percentiles из суммы histogram buckets всех реплик. Среднее p99 реплик НЕ вычисляется.",
|
||||
"datasource": { "uid": "prometheus", "type": "prometheus" },
|
||||
"gridPos": { "h": 8, "w": 8, "x": 16, "y": 1 },
|
||||
"targets": [
|
||||
{ "expr": "histogram_quantile(0.50, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\"}[$__rate_interval])))", "legendFormat": "p50" },
|
||||
{ "expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\"}[$__rate_interval])))", "legendFormat": "p95" },
|
||||
{ "expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\"}[$__rate_interval])))", "legendFormat": "p99" }
|
||||
],
|
||||
"fieldConfig": { "defaults": { "unit": "s" } }
|
||||
},
|
||||
{
|
||||
"type": "row",
|
||||
"title": "Worker & Jobs",
|
||||
"gridPos": { "h": 1, "w": 24, "x": 0, "y": 9 },
|
||||
"collapsed": false
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Jobs processed rate (by outcome)",
|
||||
"description": "Успехи, retries, терминальные отказы. Метрика: messenger_jobs_processed_total.",
|
||||
"datasource": { "uid": "prometheus", "type": "prometheus" },
|
||||
"gridPos": { "h": 8, "w": 8, "x": 0, "y": 10 },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum by (outcome) (rate(messenger_jobs_processed_total{service_name=\"messenger-worker\"}[$__rate_interval]))",
|
||||
"legendFormat": "{{outcome}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": { "defaults": { "unit": "ops" } }
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Job processing duration p50 / p95 / p99",
|
||||
"description": "Время в worker.process (staging -> variants -> original -> COMMIT). Метрика: messenger_job_duration_seconds.",
|
||||
"datasource": { "uid": "prometheus", "type": "prometheus" },
|
||||
"gridPos": { "h": 8, "w": 8, "x": 8, "y": 10 },
|
||||
"targets": [
|
||||
{ "expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_job_duration_seconds_bucket{service_name=\"messenger-worker\"}[$__rate_interval])))", "legendFormat": "p50" },
|
||||
{ "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket{service_name=\"messenger-worker\"}[$__rate_interval])))", "legendFormat": "p95" },
|
||||
{ "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_duration_seconds_bucket{service_name=\"messenger-worker\"}[$__rate_interval])))", "legendFormat": "p99" }
|
||||
],
|
||||
"fieldConfig": { "defaults": { "unit": "s" } }
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "End-to-end time to ready p50 / p95 / p99",
|
||||
"description": "От durable acceptance (202) до ready. SLI. Метрика: messenger_time_to_ready_seconds.",
|
||||
"datasource": { "uid": "prometheus", "type": "prometheus" },
|
||||
"gridPos": { "h": 8, "w": 8, "x": 16, "y": 10 },
|
||||
"targets": [
|
||||
{ "expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_time_to_ready_seconds_bucket[$__rate_interval])))", "legendFormat": "p50" },
|
||||
{ "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_time_to_ready_seconds_bucket[$__rate_interval])))", "legendFormat": "p95" },
|
||||
{ "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_time_to_ready_seconds_bucket[$__rate_interval])))", "legendFormat": "p99" }
|
||||
],
|
||||
"fieldConfig": { "defaults": { "unit": "s" } }
|
||||
},
|
||||
{
|
||||
"type": "row",
|
||||
"title": "Queue & Backlog",
|
||||
"gridPos": { "h": 1, "w": 24, "x": 0, "y": 18 },
|
||||
"collapsed": false
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Queue depth (broker stream + DB jobs queued)",
|
||||
"description": "Broker = Redis Streams PEL (pending не-acked). DB = jobs.status='queued'. Источники: messenger_queue_depth, messenger_jobs_queued.",
|
||||
"datasource": { "uid": "prometheus", "type": "prometheus" },
|
||||
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 19 },
|
||||
"targets": [
|
||||
{ "expr": "sum(messenger_queue_depth{service_name=\"messenger-api\"})", "legendFormat": "broker pending" },
|
||||
{ "expr": "sum(messenger_jobs_queued{service_name=\"messenger-api\"})", "legendFormat": "DB queued jobs" }
|
||||
],
|
||||
"fieldConfig": { "defaults": { "unit": "short" } }
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Queue oldest age (broker + DB)",
|
||||
"description": "Сколько секунд старейшее сообщение/задание ещё не обработано. Рост = worker не справляется или недоступен.",
|
||||
"datasource": { "uid": "prometheus", "type": "prometheus" },
|
||||
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 19 },
|
||||
"targets": [
|
||||
{ "expr": "max(messenger_queue_oldest_age_seconds{service_name=\"messenger-api\"})", "legendFormat": "broker oldest (s)" },
|
||||
{ "expr": "max(messenger_jobs_oldest_queued_age_seconds{service_name=\"messenger-api\"})", "legendFormat": "DB oldest (s)" }
|
||||
],
|
||||
"fieldConfig": { "defaults": { "unit": "s" } }
|
||||
},
|
||||
{
|
||||
"type": "row",
|
||||
"title": "Saturation",
|
||||
"gridPos": { "h": 1, "w": 24, "x": 0, "y": 27 },
|
||||
"collapsed": false
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "DB pool used / capacity",
|
||||
"description": "Acquired connections из pgx pool. Метрики: messenger_db_pool_used, messenger_db_pool_capacity.",
|
||||
"datasource": { "uid": "prometheus", "type": "prometheus" },
|
||||
"gridPos": { "h": 8, "w": 8, "x": 0, "y": 28 },
|
||||
"targets": [
|
||||
{ "expr": "sum(messenger_db_pool_used{service_name=\"messenger-api\"})", "legendFormat": "used (api)" },
|
||||
{ "expr": "sum(messenger_db_pool_capacity{service_name=\"messenger-api\"})", "legendFormat": "capacity (api)" },
|
||||
{ "expr": "sum(messenger_db_pool_used{service_name=\"messenger-worker\"})", "legendFormat": "used (worker)" },
|
||||
{ "expr": "sum(messenger_db_pool_capacity{service_name=\"messenger-worker\"})", "legendFormat": "capacity (worker)" }
|
||||
],
|
||||
"fieldConfig": { "defaults": { "unit": "short" } }
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Worker saturation (busy / capacity)",
|
||||
"description": "1 = worker занят, 0 = простаивает. Для одного worker это occupancy rate.",
|
||||
"datasource": { "uid": "prometheus", "type": "prometheus" },
|
||||
"gridPos": { "h": 8, "w": 8, "x": 8, "y": 28 },
|
||||
"targets": [
|
||||
{ "expr": "sum(messenger_worker_busy{service_name=\"messenger-worker\"})", "legendFormat": "busy" },
|
||||
{ "expr": "sum(messenger_worker_capacity{service_name=\"messenger-worker\"})", "legendFormat": "capacity" }
|
||||
],
|
||||
"fieldConfig": { "defaults": { "unit": "short" } }
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "DB pool empty-acquire events",
|
||||
"description": "Счётчик случаев, когда acquire ждал свободного соединения. Рост = пул undersized. Метрика: messenger_db_pool_empty_acquires_total.",
|
||||
"datasource": { "uid": "prometheus", "type": "prometheus" },
|
||||
"gridPos": { "h": 8, "w": 8, "x": 16, "y": 28 },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum by (service_name) (rate(messenger_db_pool_empty_acquires_total[$__rate_interval]))",
|
||||
"legendFormat": "{{service_name}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": { "defaults": { "unit": "ops" } }
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
# LAB 6: три источника данных. Grafana — интерфейс, она НЕ хранит сигналы.
|
||||
# uid фиксированы: на них ссылаются dashboard JSON и alert rules из Git.
|
||||
|
||||
apiVersion: 1
|
||||
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
uid: prometheus
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: http://prometheus:9090
|
||||
isDefault: true
|
||||
editable: false
|
||||
jsonData:
|
||||
timeInterval: 5s
|
||||
httpMethod: POST
|
||||
|
||||
- name: Loki
|
||||
uid: loki
|
||||
type: loki
|
||||
access: proxy
|
||||
url: http://loki:3100
|
||||
editable: false
|
||||
jsonData:
|
||||
maxLines: 1000
|
||||
# Переход лог -> трасса: trace_id из structured metadata OTLP-записи.
|
||||
derivedFields:
|
||||
- name: TraceID
|
||||
matcherRegex: '"?trace_id"?[=:]"?([a-f0-9]{32})'
|
||||
url: '$${__value.raw}'
|
||||
datasourceUid: tempo
|
||||
urlDisplayLabel: Open trace in Tempo
|
||||
|
||||
- name: Tempo
|
||||
uid: tempo
|
||||
type: tempo
|
||||
access: proxy
|
||||
url: http://tempo:3200
|
||||
editable: false
|
||||
jsonData:
|
||||
# Обратный переход трасса -> логи того же trace_id.
|
||||
tracesToLogsV2:
|
||||
datasourceUid: loki
|
||||
filterByTraceID: true
|
||||
filterBySpanID: false
|
||||
customQuery: false
|
||||
serviceMap:
|
||||
datasourceUid: prometheus
|
||||
nodeGraph:
|
||||
enabled: true
|
||||
search:
|
||||
hide: false
|
||||
@@ -0,0 +1,50 @@
|
||||
# LAB 6: Loki — хранилище логов. Single-binary, filesystem, TSDB v13.
|
||||
# Принимает OTLP напрямую: POST /otlp/v1/logs (Loki 3.x).
|
||||
# trace_id/span_id приходят как поля OTLP LogRecord и сохраняются
|
||||
# в structured metadata — по ним лог связывается с трассой в Tempo.
|
||||
|
||||
auth_enabled: false
|
||||
|
||||
server:
|
||||
http_listen_port: 3100
|
||||
grpc_listen_port: 9096
|
||||
log_level: warn
|
||||
|
||||
common:
|
||||
instance_addr: 127.0.0.1
|
||||
path_prefix: /loki
|
||||
storage:
|
||||
filesystem:
|
||||
chunks_directory: /loki/chunks
|
||||
rules_directory: /loki/rules
|
||||
replication_factor: 1
|
||||
ring:
|
||||
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: 24h
|
||||
reject_old_samples: false
|
||||
|
||||
ruler:
|
||||
storage:
|
||||
type: local
|
||||
local:
|
||||
directory: /loki/rules
|
||||
|
||||
compactor:
|
||||
working_directory: /loki/compactor
|
||||
retention_enabled: true
|
||||
delete_request_store: filesystem
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
worker_processes auto;
|
||||
|
||||
events {
|
||||
worker_connections 1024;
|
||||
}
|
||||
|
||||
http {
|
||||
# Встроенный DNS Docker. КЛЮЧЕВОЕ для замечания ревью лабы 3:
|
||||
# перерезолвинг каждые 10 секунд, поэтому после замены/масштабирования
|
||||
# контейнеров nginx сам подхватывает новые адреса реплик.
|
||||
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||
resolver_timeout 3s;
|
||||
|
||||
access_log /dev/stdout;
|
||||
error_log /dev/stderr warn;
|
||||
|
||||
server {
|
||||
listen 8080;
|
||||
server_name _;
|
||||
|
||||
# LAB 4: лимит размера тела. Контракт разрешает ≤10 MiB (10 485 760 байт).
|
||||
# Задаём с запасом 15M, чтобы заголовки и мелкие накладные расходы не резали
|
||||
# легитимный запрос на границе. Реальный лимит 10 MiB применяется в
|
||||
# uploadAttachment через http.MaxBytesReader — до полного чтения.
|
||||
client_max_body_size 15M;
|
||||
|
||||
location / {
|
||||
# Переменная ОБЯЗАТЕЛЬНА: именно она включает динамический резолвинг.
|
||||
# Со статичным proxy_pass адрес резолвится один раз при старте —
|
||||
# это и была причина замечания ревью лабы 3.
|
||||
set $backend "http://api:8080";
|
||||
proxy_pass $backend;
|
||||
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Connection "";
|
||||
|
||||
# LAB 4: стриминг тела вложения на upstream без буферизации.
|
||||
# Без этого nginx читает всё тело в RAM перед отправкой в api —
|
||||
# нарушает требование "потоковая обработка не позволяет одной
|
||||
# загрузке занять неограниченную RAM" (уровень 4).
|
||||
proxy_request_buffering off;
|
||||
|
||||
# Увеличенные таймауты для загрузки/скачивания вложений.
|
||||
proxy_connect_timeout 2s;
|
||||
proxy_send_timeout 60s;
|
||||
proxy_read_timeout 60s;
|
||||
|
||||
# Failover: при ошибке на одной реплике пробуем следующую
|
||||
proxy_next_upstream error timeout http_502 http_503 http_504;
|
||||
proxy_next_upstream_tries 2;
|
||||
proxy_next_upstream_timeout 5s;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
# LAB 6: OTel Collector — приёмник/обработчик/экспортёр, НЕ долговременная БД.
|
||||
#
|
||||
# Схема: API/worker --OTLP/HTTP--> receivers.otlp
|
||||
# -> memory_limiter (жёсткий потолок RAM)
|
||||
# -> resource (нормализация/очистка атрибутов)
|
||||
# -> batch (ограниченная буферизация)
|
||||
# -> exporters: Prometheus (метрики, pull), Loki (логи, OTLP), Tempo (трассы, OTLP)
|
||||
#
|
||||
# Уровень 4: при недоступном backend очередь ОГРАНИЧЕНА (queue_size),
|
||||
# retry имеет max_elapsed_time, излишек дропается. Потери видны в
|
||||
# собственных метриках Collector (otelcol_*), которые тоже скрейпит Prometheus.
|
||||
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
|
||||
processors:
|
||||
# memory_limiter ОБЯЗАТЕЛЬНО первый: отказывает в приёме до аллокации,
|
||||
# защищая контейнер от OOM при всплеске или залипшем exporter.
|
||||
memory_limiter:
|
||||
check_interval: 1s
|
||||
limit_mib: 128
|
||||
spike_limit_mib: 32
|
||||
|
||||
resource:
|
||||
attributes:
|
||||
- key: deployment.environment.name
|
||||
value: lab
|
||||
action: upsert
|
||||
# SDK-атрибуты константны и не нужны в labels метрик — убираем,
|
||||
# чтобы не раздувать кардинальность Prometheus.
|
||||
- key: telemetry.sdk.language
|
||||
action: delete
|
||||
- key: telemetry.sdk.name
|
||||
action: delete
|
||||
- key: telemetry.sdk.version
|
||||
action: delete
|
||||
|
||||
batch:
|
||||
timeout: 5s
|
||||
send_batch_size: 512
|
||||
send_batch_max_size: 1024
|
||||
|
||||
exporters:
|
||||
# Метрики: pull-модель. Collector отдаёт /metrics, Prometheus скрейпит.
|
||||
# resource_to_telemetry_conversion превращает service.name и
|
||||
# service.instance.id в labels — это нужно для группировки по репликам.
|
||||
# Кардинальность ограничена: 2 API + 1 worker, конечный набор метрик.
|
||||
prometheus:
|
||||
endpoint: 0.0.0.0:8889
|
||||
resource_to_telemetry_conversion:
|
||||
enabled: true
|
||||
add_metric_suffixes: true
|
||||
metric_expiration: 5m
|
||||
|
||||
# Логи: Loki 3.x принимает OTLP нативно (/otlp/v1/logs).
|
||||
# Устаревший exporter "loki" удалён из Collector — не используем.
|
||||
otlphttp/loki:
|
||||
endpoint: http://loki:3100/otlp
|
||||
tls:
|
||||
insecure: true
|
||||
timeout: 10s
|
||||
sending_queue:
|
||||
enabled: true
|
||||
num_consumers: 2
|
||||
queue_size: 100 # жёсткий потолок буфера: при переполнении дроп
|
||||
retry_on_failure:
|
||||
enabled: true
|
||||
initial_interval: 1s
|
||||
max_interval: 10s
|
||||
max_elapsed_time: 60s # не ретраим бесконечно
|
||||
|
||||
# Трассы: Tempo, OTLP/gRPC.
|
||||
otlp/tempo:
|
||||
endpoint: tempo:4317
|
||||
tls:
|
||||
insecure: true
|
||||
timeout: 10s
|
||||
sending_queue:
|
||||
enabled: true
|
||||
num_consumers: 2
|
||||
queue_size: 100
|
||||
retry_on_failure:
|
||||
enabled: true
|
||||
initial_interval: 1s
|
||||
max_interval: 10s
|
||||
max_elapsed_time: 60s
|
||||
|
||||
extensions:
|
||||
health_check:
|
||||
endpoint: 0.0.0.0:13133
|
||||
|
||||
service:
|
||||
extensions: [health_check]
|
||||
pipelines:
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, resource, batch]
|
||||
exporters: [otlp/tempo]
|
||||
metrics:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, resource, batch]
|
||||
exporters: [prometheus]
|
||||
logs:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, resource, batch]
|
||||
exporters: [otlphttp/loki]
|
||||
telemetry:
|
||||
logs:
|
||||
level: info
|
||||
# Собственные метрики Collector: otelcol_exporter_send_failed_*,
|
||||
# otelcol_processor_dropped_*, otelcol_exporter_queue_size —
|
||||
# по ним считаем потери телеметрии в инциденте №3.
|
||||
metrics:
|
||||
readers:
|
||||
- pull:
|
||||
exporter:
|
||||
prometheus:
|
||||
host: 0.0.0.0
|
||||
port: 8888
|
||||
@@ -0,0 +1,22 @@
|
||||
# LAB 6: Prometheus — хранилище метрик (pull).
|
||||
# Два job'а: метрики приложения (через Collector exporter) и
|
||||
# собственные метрики Collector (потери/очереди/память).
|
||||
|
||||
global:
|
||||
scrape_interval: 5s
|
||||
evaluation_interval: 5s
|
||||
external_labels:
|
||||
lab: messenger
|
||||
|
||||
scrape_configs:
|
||||
- job_name: otel-app
|
||||
static_configs:
|
||||
- targets: ['otel:8889']
|
||||
labels:
|
||||
source: application
|
||||
|
||||
- job_name: otel-collector
|
||||
static_configs:
|
||||
- targets: ['otel:8888']
|
||||
labels:
|
||||
source: collector
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
# DEMO.md — демонстрация ЛР6 «Observability» (уровень 4)
|
||||
|
||||
Команды для **PowerShell (Windows)**. Стенд: `mtusi2026lab6`.
|
||||
Порядок шагов = порядок показа на защите. У каждого шага: команды → что ожидать → что говорить.
|
||||
|
||||
Эндпоинты стенда:
|
||||
|
||||
| Сервис | URL |
|
||||
|---|---|
|
||||
| API (через nginx) | http://localhost:8080 |
|
||||
| Grafana (admin/admin) | http://localhost:3000 |
|
||||
| Prometheus | http://localhost:9090 |
|
||||
| Tempo | http://localhost:3200 |
|
||||
| Loki | http://localhost:3100 |
|
||||
| Collector: метрики приложения / свои / health | :8889 / :8888 / :13133 |
|
||||
|
||||
---
|
||||
|
||||
## Шаг 0. Поднять стенд с нуля
|
||||
|
||||
```powershell
|
||||
cd C:\Users\maksimator\GolandProjects\mtusi2026lab6
|
||||
docker compose --compatibility down -v --remove-orphans # только если нужен старт «с нуля»
|
||||
docker compose --compatibility up -d --build
|
||||
Start-Sleep -Seconds 45
|
||||
docker compose ps
|
||||
curl.exe -s http://localhost:3000/api/health
|
||||
```
|
||||
|
||||
**Ожидать:** 12–13 контейнеров Up (migrate — Exited(0)); grafana `"database":"ok"`.
|
||||
**Говорить:** «Один `compose up` поднимает приложение и весь observability-стек; миграции — отдельный one-shot сервис».
|
||||
|
||||
---
|
||||
|
||||
## Шаг 1. Provisioning из Git, без ручного набора dashboard
|
||||
|
||||
```powershell
|
||||
docker compose exec -T grafana sh -c "ls -R /etc/grafana/provisioning"
|
||||
curl.exe -s -u admin:admin http://localhost:3000/api/v1/provisioning/alert-rules | Select-String '"provenance":"file"'
|
||||
curl.exe -s -u admin:admin http://localhost:3000/api/dashboards/uid/messenger-overview | Select-String '"title"'
|
||||
```
|
||||
|
||||
**Ожидать:** в контейнере видны `datasources/datasources.yaml`, `dashboards/dashboards.yaml`, `dashboards/json/messenger.json`, `alerting/alerts.yaml`; у правил `"provenance":"file"`; title дашборда = `Messenger — observability level 4`.
|
||||
**Говорить:** «Дашборд и alert rules версионируются в репозитории и применяются provisioning'ом; в UI ничего не набиралось руками».
|
||||
**UI:** открыть http://localhost:3000/d/messenger-overview — панели с данными.
|
||||
|
||||
---
|
||||
|
||||
## Шаг 2. Smoke + нагрузка
|
||||
|
||||
```powershell
|
||||
$env:PYTHONUTF8 = "1"
|
||||
python -X utf8 tests\smoke.py --base-url http://localhost:8080 # PASS
|
||||
1..60 | ForEach-Object { curl.exe -s -o NUL http://localhost:8080/health/ready; curl.exe -s -o NUL http://localhost:8080/health/live }
|
||||
python -X utf8 tests\smoke.py --base-url http://localhost:8080 # второй прогон: ещё jobs и вложения
|
||||
Start-Sleep -Seconds 15
|
||||
```
|
||||
|
||||
**Ожидать:** оба smoke `PASS`; на дашборде в панели «HTTP RPS» виден всплеск запросов.
|
||||
**Говорить:** «Нагрузка синтетическая, но идёт через реальный контракт API; вложения порождают jobs в broker».
|
||||
|
||||
---
|
||||
|
||||
## Шаг 3. Свежие метрики СВОЕГО приложения
|
||||
|
||||
```powershell
|
||||
curl.exe -s -G http://localhost:9090/api/v1/query --data-urlencode 'query=sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api"}[2m]))'
|
||||
curl.exe -s -G http://localhost:9090/api/v1/query --data-urlencode 'query=histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name="messenger-api"}[2m])))'
|
||||
curl.exe -s -G http://localhost:9090/api/v1/query --data-urlencode 'query=sum by (outcome) (messenger_jobs_processed_total{service_name="messenger-worker"})'
|
||||
curl.exe -s -G http://localhost:9090/api/v1/query --data-urlencode 'query=sum(messenger_queue_depth)'
|
||||
```
|
||||
|
||||
**Ожидать:** RPS > 0; p95 в секундах; `outcome="success"` ≥ 2; depth = 0.
|
||||
**Говорить:** «Это метрики моего приложения: префикс `messenger_*`, resource-атрибуты `service_name=messenger-api|worker`, `service_version=lab6`, `deployment.environment.name=lab`; `instance` совпадает с `X-Instance-Id` реплик — значит данные мои, а не чужие».
|
||||
|
||||
---
|
||||
|
||||
## Шаг 4. Маркер: запрос → свой лог → своя трасса
|
||||
|
||||
```powershell
|
||||
$marker = "demo-" + (Get-Date -Format "HHmmss")
|
||||
curl.exe -s -H "X-Request-Id: $marker" http://localhost:8080/health/ready
|
||||
Start-Sleep -Seconds 6
|
||||
docker compose logs --since 2m api | Select-String $marker
|
||||
```
|
||||
|
||||
Скопировать `trace_id` из найденной строки, затем:
|
||||
|
||||
```powershell
|
||||
curl.exe -s http://localhost:3200/api/traces/<TRACE_ID> | Select-String '"name"'
|
||||
curl.exe -s -G http://localhost:3100/loki/api/v1/query_range --data-urlencode 'query={service_name="messenger-api"}' --data-urlencode 'limit=5'
|
||||
```
|
||||
|
||||
**Ожидать:** в stdout-логе API строка с нашим `X-Request-Id` и `trace_id`; трасса с этим id существует в Tempo; в Loki те же записи со structured metadata `trace_id`.
|
||||
**Говорить:** «Я вложил маркер в запрос, нашёл его в своём структурном логе, по `trace_id` открыл трассу своего сервиса и те же логи в Loki — цепочка запрос→лог→трасса замкнута».
|
||||
|
||||
---
|
||||
|
||||
## Шаг 5. Сквозная трасса upload → publish → consume
|
||||
|
||||
```powershell
|
||||
curl.exe -s "http://localhost:3200/api/search?tags=service.name%3Dmessenger-worker&limit=3"
|
||||
# взять traceID свежей трассы
|
||||
curl.exe -s http://localhost:3200/api/traces/<TRACE_ID> > trace.json
|
||||
docker compose logs --since 15m api | Select-String <TRACE_ID>
|
||||
docker compose logs --since 15m worker | Select-String <TRACE_ID>
|
||||
```
|
||||
|
||||
**Ожидать:** один `trace_id` в логах API и worker; в трассе spans: `POST /api/v1/chats/{chat_id}/attachments` (api) → `queue.publish` (api, producer) → `attachment.process` (worker, consumer) → дочерние `redis …`, `SELECT/INSERT …`, s3-операции.
|
||||
**Говорить:** «W3C `traceparent` переносится через поля сообщения broker'а, поэтому consumer span в worker — потомок producer span из API: одна трасса покрывает upload, очередь и обработку».
|
||||
|
||||
---
|
||||
|
||||
## Шаг 6. Инцидент уровня 4: worker down → firing → resolved
|
||||
|
||||
```powershell
|
||||
docker compose stop worker
|
||||
python -X utf8 tests\smoke.py --base-url http://localhost:8080 # ожидаем FAIL (ready не наступит)
|
||||
curl.exe -s -G http://localhost:9090/api/v1/query --data-urlencode 'query=max(messenger_queue_oldest_age_seconds)' # растёт
|
||||
Start-Sleep -Seconds 120 # окно alert: for=2m
|
||||
curl.exe -s -u admin:admin http://localhost:3000/api/alertmanager/grafana/api/v2/alerts | Select-String 'messenger-queue-lag' # FIRING
|
||||
docker compose start worker
|
||||
Start-Sleep -Seconds 40
|
||||
curl.exe -s -G http://localhost:9090/api/v1/query --data-urlencode 'query=sum(messenger_queue_depth)' # 0
|
||||
curl.exe -s -u admin:admin http://localhost:3000/api/alertmanager/grafana/api/v2/alerts # правила нет в active
|
||||
python -X utf8 tests\smoke.py --base-url http://localhost:8080 # PASS
|
||||
```
|
||||
|
||||
**Ожидать:** во время простоя `queue_oldest_age_seconds` > 30 и растёт; alert `messenger-queue-lag` в `active`; после старта worker depth=0, alert исчезает из active, smoke PASS.
|
||||
**UI во время ожидания:** панель «Queue oldest age» растёт вживую; Alerting → Alert rules → состояние правила.
|
||||
**Говорить:** «SLI — возраст старейшего задания, окно 2m, порог 30s, `for=2m`, в runbook описаны шаги диагностики; alert сработал на деградации и сам зарезолвился после восстановления».
|
||||
|
||||
---
|
||||
|
||||
## Шаг 7. Резерв: БД недоступна (отличить от медленного handler)
|
||||
|
||||
```powershell
|
||||
docker pause mtusi2026lab6_postgres_1
|
||||
curl.exe -s -i http://localhost:8080/health/ready # 503 database unavailable
|
||||
python -X utf8 tests\smoke.py --base-url http://localhost:8080 # FAIL
|
||||
docker unpause mtusi2026lab6_postgres_1
|
||||
Start-Sleep -Seconds 15
|
||||
python -X utf8 tests\smoke.py --base-url http://localhost:8080 # PASS
|
||||
```
|
||||
|
||||
**Говорить:** «Недоступная БД = `/health/ready` 503 и db-spans со статусом ERROR; медленный handler был бы 200 с высоким p99 без ошибок — причина различима по трассам и метрикам».
|
||||
|
||||
## Шаг 8. Резерв: Collector остановлен (бизнес жив)
|
||||
|
||||
```powershell
|
||||
docker compose stop otel
|
||||
python -X utf8 tests\smoke.py --base-url http://localhost:8080 # PASS: бизнес не зависит от телеметрии
|
||||
curl.exe -s -G http://localhost:9090/api/v1/query --data-urlencode 'query=up{job="otel-app"}' # пусто
|
||||
docker compose start otel
|
||||
Start-Sleep -Seconds 30
|
||||
curl.exe -s -G http://localhost:9090/api/v1/query --data-urlencode 'query=up{job="otel-app"}' # 1
|
||||
```
|
||||
|
||||
**Говорить:** «SDK с bounded queue дропает сигналы при недоступном backend: RAM не растёт, API работает; потеря видна как пропуск в `up{job="otel-app"}`».
|
||||
|
||||
---
|
||||
|
||||
## Тезисы для защиты (шпаргалка)
|
||||
|
||||
1. Три сигнала через один SDK: traces/metrics/logs → OTLP → Collector → Tempo/Prometheus/Loki → Grafana.
|
||||
2. Сквозная трасса через broker: `traceparent` в `jobs.schema.json`, producer/consumer spans.
|
||||
3. Логи структурные, с `trace_id`/`span_id` при активном span (slog-bridge).
|
||||
4. Cardinality под контролем: route template в span/метriках, фоновый polling подавлен (`ParentBased` + `SuppressTracing` + guard в redis hook).
|
||||
5. Queue depth честная: lag + pending (иначе при мёртвом worker метрика врёт).
|
||||
6. Alert rules из Git: условие, окно, порог, `for`, описание, runbook.
|
||||
7. Три инцидента доказаны: worker down (firing→resolved), БД недоступна (503 vs медленный handler), Collector down (бизнес жив).
|
||||
|
||||
## Быстрый справочник метрик
|
||||
|
||||
| Метрика | Смысл |
|
||||
|---|---|
|
||||
| `http_server_request_duration_seconds_bucket` | latency HTTP (p50/p95/p99 через histogram_quantile) |
|
||||
| `messenger_jobs_processed_total{outcome=…}` | jobs по исходам |
|
||||
| `messenger_job_duration_seconds` | время обработки job |
|
||||
| `messenger_time_to_ready_seconds` | end-to-end: 202 → ready |
|
||||
| `messenger_queue_depth` / `messenger_queue_oldest_age_seconds` | backlog и его возраст |
|
||||
| `messenger_db_pool_used` / `_capacity` / `_empty_acquires_total` | saturation пула БД |
|
||||
| `messenger_worker_busy` / `_capacity` | saturation worker |
|
||||
| `otelcol_exporter_send_failed_*`, `otelcol_receiver_accepted_*` | здоровье pipeline телеметрии |
|
||||
@@ -0,0 +1,445 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/exaring/otelpgx"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"mtusi-messenger/internal/api"
|
||||
"mtusi-messenger/internal/model"
|
||||
"mtusi-messenger/internal/otel"
|
||||
"mtusi-messenger/internal/store"
|
||||
"mtusi-messenger/internal/worker"
|
||||
)
|
||||
|
||||
func getenv(key, def string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func getenvDurationSeconds(key string, def time.Duration) time.Duration {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil && n >= 0 {
|
||||
return time.Duration(n) * time.Second
|
||||
}
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func ensureBucketWithRetry(ctx context.Context, c *store.S3Client, log *slog.Logger) error {
|
||||
const attempts = 30
|
||||
const delay = 2 * time.Second
|
||||
|
||||
var lastErr error
|
||||
for i := 1; i <= attempts; i++ {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
lastErr = c.EnsureBucket(ctx)
|
||||
if lastErr == nil {
|
||||
return nil
|
||||
}
|
||||
log.Warn("s3 bootstrap retry", "attempt", i, "max_attempts", attempts, "error", lastErr.Error())
|
||||
timer := time.NewTimer(delay)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
return lastErr
|
||||
}
|
||||
|
||||
// runOutboxRelay — публикация намерений из outbox в брокер (лаба 5).
|
||||
// Закрывает разрыв COMMIT -> publish: всё, что закоммичено, но не опубликовано
|
||||
// (в т.ч. после краха процесса), будет опубликовано здесь. Повторная публикация
|
||||
// безопасна: воркер идемпотентен через claim-гард.
|
||||
func runOutboxRelay(ctx context.Context, st *store.Store, q *store.Queue, log *slog.Logger) {
|
||||
t := time.NewTicker(500 * time.Millisecond)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
}
|
||||
for {
|
||||
msgs, err := st.FetchUnpublishedOutbox(ctx, 50)
|
||||
if err != nil {
|
||||
log.Warn("outbox fetch", "error", err.Error())
|
||||
break
|
||||
}
|
||||
if len(msgs) == 0 {
|
||||
break
|
||||
}
|
||||
published := 0
|
||||
for _, m := range msgs {
|
||||
var jm model.JobMessage
|
||||
if err := json.Unmarshal(m.Payload, &jm); err != nil {
|
||||
log.Error("outbox payload malformed", "error", err.Error())
|
||||
_ = st.MarkOutboxPublished(ctx, m.ID)
|
||||
continue
|
||||
}
|
||||
if _, err := q.Publish(ctx, jm); err != nil {
|
||||
log.Warn("outbox publish", "error", err.Error())
|
||||
break
|
||||
}
|
||||
_ = st.MarkOutboxPublished(ctx, m.ID)
|
||||
published++
|
||||
}
|
||||
if published > 0 {
|
||||
log.Info("outbox relay published", "count", published)
|
||||
}
|
||||
if published < len(msgs) {
|
||||
break // брокер недоступен: повторим на следующем тике
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// runStatsCollector — периодический сбор gauge-метрик уровня 4 (лаба 6).
|
||||
// Обновляет атомарные значения, которые читают observable gauge callback'ы SDK.
|
||||
// I/O собирается здесь, а не в callback, чтобы сбор метрик не блокировал экспорт.
|
||||
//
|
||||
// ВАЖНО: опросы подаются с подавленной трассировкой (otel.SuppressTracing),
|
||||
// иначе каждые 5 секунд в Tempo создавались бы корневые трассы на пустой
|
||||
// XREADGROUP/XPENDING/SQL — фоновый шум, а не бизнес-операции.
|
||||
func runStatsCollector(ctx context.Context, st *store.Store, q *store.Queue, pool *pgxpool.Pool, log *slog.Logger) {
|
||||
t := time.NewTicker(5 * time.Second)
|
||||
defer t.Stop()
|
||||
|
||||
// pgx v5: Stat.EmptyAcquireCount() возвращает int64.
|
||||
var lastEmptyAcquire int64
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
}
|
||||
|
||||
// Подавляем трассы для служебного опроса.
|
||||
sctx := otel.SuppressTracing(ctx)
|
||||
|
||||
if ps, err := q.PendingStats(sctx); err == nil {
|
||||
otel.SetQueueDepth(ps.Count)
|
||||
otel.SetQueueOldestAge(ps.OldestAgeSeconds)
|
||||
} else {
|
||||
log.Warn("queue pending stats", "error", err.Error())
|
||||
}
|
||||
|
||||
if queued, age, err := st.JobQueueStats(sctx); err == nil {
|
||||
otel.SetJobsQueued(queued)
|
||||
otel.SetJobsOldestQueuedAge(age)
|
||||
} else {
|
||||
log.Warn("job queue stats", "error", err.Error())
|
||||
}
|
||||
|
||||
stat := pool.Stat()
|
||||
otel.SetPoolUsed(int64(stat.AcquiredConns()))
|
||||
otel.SetPoolCapacity(int64(stat.MaxConns()))
|
||||
if empty := stat.EmptyAcquireCount(); empty > lastEmptyAcquire {
|
||||
otel.RecordPoolEmptyAcquire(sctx, empty-lastEmptyAcquire)
|
||||
}
|
||||
lastEmptyAcquire = stat.EmptyAcquireCount()
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
migrateOnly := flag.Bool("migrate-only", false, "Run migrations and exit")
|
||||
reconcileMode := flag.Bool("reconcile", false, "Reconcile orphaned S3 objects and exit")
|
||||
workerMode := flag.Bool("worker", false, "Run attachment processing worker")
|
||||
flag.Parse()
|
||||
|
||||
// LAB 6: slog-bridge пишет и в stdout JSON, и в OTLP с авто-injection trace_id/span_id.
|
||||
// Если OTel ещё не инициализирован, ветка ОТел — no-op, остаётся только stdout.
|
||||
log := slog.New(otel.NewSlogOTelHandler(slog.LevelInfo))
|
||||
|
||||
host := getenv("APP_HOST", "0.0.0.0")
|
||||
port := getenv("APP_PORT", "8080")
|
||||
addr := host + ":" + port
|
||||
|
||||
databaseURL := getenv("DATABASE_URL", "postgres://messenger:messenger_password@localhost:5432/messenger?sslmode=disable")
|
||||
redisURL := getenv("REDIS_URL", "redis://localhost:6379/0")
|
||||
sessionStore := getenv("SESSION_STORE", "postgres")
|
||||
sessionTTL := getenv("SESSION_TTL_SECONDS", "3600")
|
||||
cacheMode := getenv("CACHE_MODE", "versioned")
|
||||
|
||||
s3Endpoint := getenv("S3_ENDPOINT", "localhost:9000")
|
||||
s3AccessKey := getenv("S3_ACCESS_KEY", "")
|
||||
s3SecretKey := getenv("S3_SECRET_KEY", "")
|
||||
s3Bucket := getenv("S3_BUCKET", "messenger")
|
||||
s3UseSSL := getenv("S3_USE_SSL", "false") == "true"
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
// ─────────── PostgreSQL ───────────
|
||||
poolConfig, err := pgxpool.ParseConfig(databaseURL)
|
||||
if err != nil {
|
||||
log.Error("parse database URL", "error", err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// LAB 6: DB client spans для каждого SQL-запроса через exaring/otelpgx.
|
||||
poolConfig.ConnConfig.Tracer = otelpgx.NewTracer()
|
||||
|
||||
poolConfig.MaxConns = 10
|
||||
poolConfig.MinConns = 2
|
||||
poolConfig.ConnConfig.ConnectTimeout = 5 * time.Second
|
||||
poolConfig.MaxConnLifetime = 30 * time.Minute
|
||||
poolConfig.MaxConnIdleTime = 5 * time.Minute
|
||||
poolConfig.HealthCheckPeriod = 10 * time.Second
|
||||
poolConfig.ConnConfig.RuntimeParams["statement_timeout"] = "15000"
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
|
||||
if err != nil {
|
||||
log.Error("connect to postgres", "error", err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
log.Error("ping postgres", "error", err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
log.Info("postgres connected")
|
||||
|
||||
if *migrateOnly {
|
||||
log.Info("migrate-only mode: applying migrations")
|
||||
if err := store.RunMigrations(ctx, pool, log); err != nil {
|
||||
log.Error("migrations failed", "error", err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
log.Info("migrations applied successfully, exiting")
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
// ─────────── Redis ───────────
|
||||
rdb := redis.NewClient(mustParseRedisURL(redisURL, log))
|
||||
// LAB 6: Redis db client spans (XADD/XREADGROUP/GET/SET/etc.).
|
||||
// Хук ставится ОДИН раз на клиент здесь. В store.NewQueue хука быть не
|
||||
// должно, иначе спаны будут дублироваться.
|
||||
rdb.AddHook(otel.RedisTracerHook())
|
||||
|
||||
if err := rdb.Ping(ctx).Err(); err != nil {
|
||||
log.Warn("redis ping failed at startup", "error", err.Error())
|
||||
} else {
|
||||
log.Info("redis connected")
|
||||
}
|
||||
defer rdb.Close()
|
||||
|
||||
var cacheRdb *redis.Client
|
||||
if sessionStore == "redis" {
|
||||
cacheRdb = rdb
|
||||
}
|
||||
|
||||
// ─────────── S3 ───────────
|
||||
var s3client *store.S3Client
|
||||
if s3Endpoint != "" && s3AccessKey != "" && s3SecretKey != "" {
|
||||
s3client, err = store.NewS3Client(s3Endpoint, s3AccessKey, s3SecretKey, s3Bucket, s3UseSSL, log)
|
||||
if err != nil {
|
||||
log.Error("init s3 client", "error", err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
} else {
|
||||
log.Warn("S3 credentials not set; attachments unavailable")
|
||||
}
|
||||
|
||||
// ─────────── Reconcile: однократный режим ───────────
|
||||
if *reconcileMode {
|
||||
if s3client == nil {
|
||||
log.Error("reconcile requires S3 credentials")
|
||||
os.Exit(1)
|
||||
}
|
||||
grace := getenvDurationSeconds("RECONCILE_GRACE_PERIOD_SECONDS", 3600*time.Second)
|
||||
log.Info("reconcile mode: sweeping orphaned objects", "grace_seconds", int(grace.Seconds()))
|
||||
recCtx, recCancel := context.WithTimeout(ctx, 120*time.Second)
|
||||
defer recCancel()
|
||||
if err := store.RunReconcile(recCtx, pool, s3client, grace, log); err != nil {
|
||||
log.Error("reconcile failed", "error", err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
log.Info("reconcile completed successfully, exiting")
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
// ─── LAB 6: OpenTelemetry SDK (только api и worker) ─────────────────
|
||||
// Инициализируем ПОСЛЕ веток migrate/reconcile, чтобы однократные режимы
|
||||
// не тратили время на телеметрию. instanceID считаем один раз и
|
||||
// переиспользуем в API-режиме (заголовок X-Instance-Id).
|
||||
var instanceID string
|
||||
if v := getenv("INSTANCE_ID", ""); v != "" {
|
||||
instanceID = v
|
||||
} else {
|
||||
hostname, _ := os.Hostname()
|
||||
prefix := hostname
|
||||
if len(prefix) > 12 {
|
||||
prefix = prefix[:12]
|
||||
}
|
||||
if prefix == "" {
|
||||
prefix = "local"
|
||||
}
|
||||
instanceID = prefix + "-" + uuid.NewString()[:8]
|
||||
}
|
||||
|
||||
serviceName := "messenger-api"
|
||||
if *workerMode {
|
||||
serviceName = "messenger-worker"
|
||||
}
|
||||
|
||||
if ep := getenv("OTEL_EXPORTER_OTLP_ENDPOINT", ""); ep != "" {
|
||||
otelShutdown, otelErr := otel.Init(ctx, otel.Config{
|
||||
Endpoint: ep,
|
||||
ServiceName: serviceName,
|
||||
ServiceVersion: getenv("OTEL_SERVICE_VERSION", "lab6"),
|
||||
InstanceID: instanceID,
|
||||
Environment: getenv("OTEL_ENV", "lab"),
|
||||
})
|
||||
if otelErr != nil {
|
||||
log.Warn("otel init failed; continuing without telemetry", "error", otelErr.Error())
|
||||
} else {
|
||||
defer func() {
|
||||
shCtx, shCancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer shCancel()
|
||||
if err := otelShutdown(shCtx); err != nil {
|
||||
log.Warn("otel shutdown error", "error", err.Error())
|
||||
}
|
||||
}()
|
||||
log.Info("otel initialized",
|
||||
"endpoint", ep,
|
||||
"service", serviceName,
|
||||
"instance", instanceID)
|
||||
}
|
||||
} else {
|
||||
log.Info("telemetry disabled: OTEL_EXPORTER_OTLP_ENDPOINT not set")
|
||||
}
|
||||
// ─── /LAB 6 ─────────────────────────────────────────────────────────
|
||||
|
||||
st := store.New(pool, cacheRdb, s3client, sessionTTL, cacheMode, log)
|
||||
queue := store.NewQueue(rdb, log)
|
||||
|
||||
// LAB 6: сбор gauge-метрик (queue/pool/jobs) в API и worker режимах.
|
||||
// Стартует до ветвления, чтобы метрики собирались в обоих процессах.
|
||||
go runStatsCollector(ctx, st, queue, pool, log)
|
||||
|
||||
// ─────────── WORKER MODE ───────────
|
||||
if *workerMode {
|
||||
if s3client == nil {
|
||||
log.Error("worker requires S3 credentials")
|
||||
os.Exit(1)
|
||||
}
|
||||
// LAB 5: воркер не должен умирать из-за временной недоступности S3 на старте.
|
||||
// Одна быстрая попытка; при неудаче продолжаем — каждое задание само
|
||||
// получит transient-ошибку и уйдёт в retry с backoff.
|
||||
pingCtx, pingCancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
err := s3client.EnsureBucket(pingCtx)
|
||||
pingCancel()
|
||||
if err != nil {
|
||||
log.Warn("s3 not ready at worker start; continuing, jobs will retry", "error", err.Error())
|
||||
} else {
|
||||
log.Info("s3 ready", "endpoint", s3Endpoint, "bucket", s3Bucket)
|
||||
}
|
||||
|
||||
w := worker.New(st, queue, log)
|
||||
stop := make(chan os.Signal, 1)
|
||||
signal.Notify(stop, syscall.SIGTERM, syscall.SIGINT)
|
||||
errCh := make(chan error, 1)
|
||||
go func() { errCh <- w.Run(ctx) }()
|
||||
select {
|
||||
case err := <-errCh:
|
||||
if err != nil {
|
||||
log.Error("worker failed", "error", err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
case sig := <-stop:
|
||||
log.Info("worker shutdown signal", "signal", sig.String())
|
||||
cancel()
|
||||
<-errCh
|
||||
}
|
||||
log.Info("worker stopped cleanly")
|
||||
return
|
||||
}
|
||||
|
||||
// ─────────── API MODE ───────────
|
||||
log.Info("migrations already applied by migrate service, starting server")
|
||||
if s3client != nil {
|
||||
bootCtx, bootCancel := context.WithTimeout(ctx, 90*time.Second)
|
||||
err = ensureBucketWithRetry(bootCtx, s3client, log)
|
||||
bootCancel()
|
||||
if err != nil {
|
||||
log.Error("ensure s3 bucket", "error", err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
log.Info("s3 ready", "endpoint", s3Endpoint, "bucket", s3Bucket)
|
||||
}
|
||||
|
||||
// Outbox relay: публикация намерений в брокер.
|
||||
go runOutboxRelay(ctx, st, queue, log)
|
||||
|
||||
ready := &atomic.Bool{}
|
||||
ready.Store(true)
|
||||
|
||||
log.Info("instance identity", "instance_id", instanceID)
|
||||
srv := api.NewServer(st, log, ready, instanceID)
|
||||
|
||||
httpSrv := &http.Server{
|
||||
Addr: addr,
|
||||
Handler: srv.Handler(),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 30 * time.Second,
|
||||
WriteTimeout: 60 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() { errCh <- httpSrv.ListenAndServe() }()
|
||||
log.Info("server started", "addr", addr, "pid", os.Getpid())
|
||||
|
||||
stop := make(chan os.Signal, 1)
|
||||
signal.Notify(stop, syscall.SIGTERM, syscall.SIGINT)
|
||||
|
||||
select {
|
||||
case err := <-errCh:
|
||||
if err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
log.Error("server failed", "error", err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
case sig := <-stop:
|
||||
log.Info("shutdown signal received", "signal", sig.String())
|
||||
ready.Store(false)
|
||||
sctx, scancel := context.WithTimeout(context.Background(), 8*time.Second)
|
||||
defer scancel()
|
||||
if err := httpSrv.Shutdown(sctx); err != nil {
|
||||
log.Warn("graceful shutdown exceeded budget, closing", "error", err.Error())
|
||||
_ = httpSrv.Close()
|
||||
}
|
||||
cancel()
|
||||
log.Info("server stopped cleanly")
|
||||
}
|
||||
}
|
||||
|
||||
func mustParseRedisURL(redisURL string, log *slog.Logger) *redis.Options {
|
||||
opts, err := redis.ParseURL(redisURL)
|
||||
if err != nil {
|
||||
log.Error("parse redis URL", "error", err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
return opts
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
module mtusi-messenger
|
||||
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/chai2010/webp v1.4.0
|
||||
github.com/disintegration/imaging v1.6.2
|
||||
github.com/exaring/otelpgx v0.13.0
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgx/v5 v5.9.2
|
||||
github.com/minio/minio-go/v7 v7.0.76
|
||||
github.com/redis/go-redis/v9 v9.5.1
|
||||
go.opentelemetry.io/contrib/bridges/otelslog v0.21.0
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0
|
||||
go.opentelemetry.io/otel v1.47.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.23.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.47.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0
|
||||
go.opentelemetry.io/otel/log v1.47.0
|
||||
go.opentelemetry.io/otel/metric v1.47.0
|
||||
go.opentelemetry.io/otel/sdk v1.47.0
|
||||
go.opentelemetry.io/otel/sdk/log v1.47.0
|
||||
go.opentelemetry.io/otel/sdk/metric v1.47.0
|
||||
go.opentelemetry.io/otel/trace v1.47.0
|
||||
golang.org/x/crypto v0.57.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/felixge/httpsnoop v1.1.0 // indirect
|
||||
github.com/go-ini/ini v1.67.0 // indirect
|
||||
github.com/go-logr/logr v1.4.4 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/goccy/go-json v0.10.3 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/klauspost/compress v1.17.9 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.8 // indirect
|
||||
github.com/minio/md5-simd v1.1.2 // indirect
|
||||
github.com/rs/xid v1.6.0 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.11.0 // indirect
|
||||
golang.org/x/image v0.0.0-20211028202545-6944b10bf410 // indirect
|
||||
golang.org/x/net v0.59.0 // indirect
|
||||
golang.org/x/sync v0.23.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc // indirect
|
||||
google.golang.org/grpc v1.83.2 // indirect
|
||||
google.golang.org/protobuf v1.36.12 // indirect
|
||||
)
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/chai2010/webp v1.4.0 h1:6DA2pkkRUPnbOHvvsmGI3He1hBKf/bkRlniAiSGuEko=
|
||||
github.com/chai2010/webp v1.4.0/go.mod h1:0XVwvZWdjjdxpUEIf7b9g9VkHFnInUSYujwqTLEuldU=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c=
|
||||
github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/exaring/otelpgx v0.13.0 h1:Vi0I2GWRS3nnVzgr73L/XbSLqthR0h6A1rm4Wt3W4aA=
|
||||
github.com/exaring/otelpgx v0.13.0/go.mod h1:3OojrUKhhy3lTbYIMBijP3YjMey/jo14eHAW5cXcUdk=
|
||||
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
|
||||
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
|
||||
github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=
|
||||
github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
|
||||
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA=
|
||||
github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 h1:/Tnpcb2E0Pz/tN9s3bfEY2Q8ePCEX9iuS+cneUwncnw=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0/go.mod h1:zOBXOsUaBSjKgmH4OGzV1esUpR3oUSCPYVd2cUBjKYY=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw=
|
||||
github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA=
|
||||
github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
|
||||
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.8 h1:+StwCXwm9PdpiEkPyzBXIy+M9KUb4ODm0Zarf1kS5BM=
|
||||
github.com/klauspost/cpuid/v2 v2.2.8/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
||||
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
|
||||
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
|
||||
github.com/minio/minio-go/v7 v7.0.76 h1:9nxHH2XDai61cT/EFhyIw/wW4vJfpPNvl7lSFpRt+Ng=
|
||||
github.com/minio/minio-go/v7 v7.0.76/go.mod h1:AVM3IUN6WwKzmwBxVdjzhH8xq+f57JSbbvzqvUzR6eg=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/redis/go-redis/v9 v9.5.1 h1:H1X4D3yHPaYrkL5X06Wh6xNVM/pX0Ft4RV0vMGvLBh8=
|
||||
github.com/redis/go-redis/v9 v9.5.1/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M=
|
||||
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
|
||||
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/bridges/otelslog v0.21.0 h1:/CdgE52i1OEPHhsGUqrggYNRaZy4v4YgVenGd52dRBI=
|
||||
go.opentelemetry.io/contrib/bridges/otelslog v0.21.0/go.mod h1:9pBdbVbuehIDzxN4accnzzxEUPT8Nq7grbZMo+J1VN4=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0/go.mod h1:tOsftB4SslBwwErVEPaenU2RpThXWPIU8DoJHEC4dyw=
|
||||
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
|
||||
go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.23.0 h1:5WVp40k2fJHuc5BtNTgKk+EugKFT8Eg3lywFfCPI/nE=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.23.0/go.mod h1:59nH0RYCGHRlwt15WyioeSYINBbuObeBpTowPhEKWHY=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.47.0 h1:7kszRN4Ze5GeAkUnBjBSUIunVBMA+mZIG04auueqguM=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.47.0/go.mod h1:CLzakYy8jOdkBfcveCWYkeKJxujcF4xPhh2Z7IfE98U=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 h1:aXZXsZ012wOgVkqaiQv+Z/d8V0xKjmg70F6m4CE94lc=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0/go.mod h1:ziu1gUIJhAaxM3EV1e3Ralk5AAyL1UOYz3lJJ4VSI38=
|
||||
go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI=
|
||||
go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw=
|
||||
go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY=
|
||||
go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU=
|
||||
go.opentelemetry.io/otel/metric/x v0.69.0 h1:DjRLr15H83v+hCW7JA9NoJvOkYTtmq5YoDRbe9deYpM=
|
||||
go.opentelemetry.io/otel/metric/x v0.69.0/go.mod h1:uVvsMPMFFyj/HUQfrUnH3JjnOQ1dwFDorgFLRBasM0k=
|
||||
go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I=
|
||||
go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0=
|
||||
go.opentelemetry.io/otel/sdk/log v1.47.0 h1:W4N/ZfgpkRRnmARnqYoQ6BrWA0mrj8IzVDNLlpmUJZY=
|
||||
go.opentelemetry.io/otel/sdk/log v1.47.0/go.mod h1:Wu74Z2EmOKXi2FleSNAb0Hyau2G+r5kubSEMJw5aAMs=
|
||||
go.opentelemetry.io/otel/sdk/log/logtest v0.23.0 h1:j3pm42QCrKYYLLkI6OrV1QHFkUfDA6/4EP+Y1PzggLg=
|
||||
go.opentelemetry.io/otel/sdk/log/logtest v0.23.0/go.mod h1:zt0gEnuTZgDvqvczHwYswz93eqMaIr6upTTsdV/HUlU=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw=
|
||||
go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM=
|
||||
go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0=
|
||||
go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk=
|
||||
go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
||||
golang.org/x/image v0.0.0-20211028202545-6944b10bf410 h1:hTftEOvwiOq2+O8k2D5/Q7COC7k5Qcrgc2TFURJYnvQ=
|
||||
golang.org/x/image v0.0.0-20211028202545-6944b10bf410/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
|
||||
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
|
||||
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc h1:rZHRz0ogq4Pid1IKtA/ivHi8XONVF5tqUQXA2TtgpkE=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc/go.mod h1:K/n0XLazCJHjD73YuMyNJsN38BPPy1kfFnKxUXaThFU=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc h1:4bNTbnb44EqGVy9HaQxSY2jnafSUdgV3qHtedvNpDKg=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
|
||||
google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
|
||||
google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=
|
||||
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
|
||||
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,561 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/apperr"
|
||||
"mtusi-messenger/internal/model"
|
||||
"mtusi-messenger/internal/store"
|
||||
)
|
||||
|
||||
// ───────────────────────────── health ─────────────────────────────
|
||||
|
||||
func (s *Server) healthLive(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, r, http.StatusOK, model.Health{Status: "ok"})
|
||||
}
|
||||
|
||||
func (s *Server) healthReady(w http.ResponseWriter, r *http.Request) {
|
||||
id := requestID(r)
|
||||
if !s.ready.Load() {
|
||||
apperr.Write(w, id, apperr.Unavailable("service is shutting down"))
|
||||
return
|
||||
}
|
||||
if err := s.store.Ping(r.Context()); err != nil {
|
||||
apperr.Write(w, id, apperr.Unavailable("database unavailable"))
|
||||
return
|
||||
}
|
||||
writeJSON(w, r, http.StatusOK, model.Health{Status: "ok"})
|
||||
}
|
||||
|
||||
// ───────────────────────────── users ─────────────────────────────
|
||||
|
||||
func (s *Server) usersRoute(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
methodNotAllowed(w, r)
|
||||
return
|
||||
}
|
||||
id := requestID(r)
|
||||
var req model.CreateUserReq
|
||||
if aerr := decodeJSON(w, r, &req); aerr != nil {
|
||||
apperr.Write(w, id, aerr)
|
||||
return
|
||||
}
|
||||
if !usernameRe.MatchString(req.Username) {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("username must match ^[a-z0-9_]{3,32}$"))
|
||||
return
|
||||
}
|
||||
if !validText(req.DisplayName, 100) {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("display_name must be 1..100 non-space code points"))
|
||||
return
|
||||
}
|
||||
if !validPassword(req.Password) {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("password must be 12..128 non-space code points"))
|
||||
return
|
||||
}
|
||||
u, err := s.store.CreateUser(r.Context(), req.Username, req.DisplayName, req.Password)
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, r, http.StatusCreated, u)
|
||||
}
|
||||
|
||||
func (s *Server) me(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
methodNotAllowed(w, r)
|
||||
return
|
||||
}
|
||||
writeJSON(w, r, http.StatusOK, currentUser(r))
|
||||
}
|
||||
|
||||
// ───────────────────────────── sessions ─────────────────────────────
|
||||
|
||||
func (s *Server) createSession(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
methodNotAllowed(w, r)
|
||||
return
|
||||
}
|
||||
id := requestID(r)
|
||||
creds := currentCreds(r)
|
||||
user, err := s.store.UserByCredentials(r.Context(), creds.Username, creds.Password)
|
||||
if err != nil {
|
||||
w.Header().Set("WWW-Authenticate", wwwBasic)
|
||||
apperr.Write(w, id, apperr.Unauthorized("invalid credentials"))
|
||||
return
|
||||
}
|
||||
token, expiresAt, err := s.store.CreateSession(r.Context(), user.ID)
|
||||
if err != nil {
|
||||
apperr.Write(w, id, apperr.Internal("internal error"))
|
||||
return
|
||||
}
|
||||
writeJSON(w, r, http.StatusCreated, model.SessionResponse{
|
||||
Token: token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: model.Timestamp{Time: expiresAt},
|
||||
User: *user,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) revokeSession(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodDelete {
|
||||
methodNotAllowed(w, r)
|
||||
return
|
||||
}
|
||||
if err := s.store.RevokeSession(r.Context(), currentToken(r)); err != nil {
|
||||
apperr.Write(w, requestID(r), apperr.Unavailable("logout not confirmed, please retry"))
|
||||
return
|
||||
}
|
||||
writeNoContent(w, r)
|
||||
}
|
||||
|
||||
// ───────────────────────────── chats ─────────────────────────────
|
||||
|
||||
func (s *Server) chatsRoute(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
s.createChat(w, r)
|
||||
case http.MethodGet:
|
||||
s.listChats(w, r)
|
||||
default:
|
||||
methodNotAllowed(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) createChat(w http.ResponseWriter, r *http.Request) {
|
||||
id := requestID(r)
|
||||
var req model.CreateChatReq
|
||||
if aerr := decodeJSON(w, r, &req); aerr != nil {
|
||||
apperr.Write(w, id, aerr)
|
||||
return
|
||||
}
|
||||
if !validText(req.Title, 100) {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("title must be 1..100 non-space code points"))
|
||||
return
|
||||
}
|
||||
if len(req.MemberIDs) < 1 || len(req.MemberIDs) > 100 {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("member_ids must contain 1..100 items"))
|
||||
return
|
||||
}
|
||||
seen := make(map[string]bool, len(req.MemberIDs))
|
||||
for _, raw := range req.MemberIDs {
|
||||
uid, err := parseUUID(raw)
|
||||
if err != nil {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("member_ids must be UUID strings"))
|
||||
return
|
||||
}
|
||||
if seen[uid] {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("duplicate member_id"))
|
||||
return
|
||||
}
|
||||
seen[uid] = true
|
||||
}
|
||||
caller := currentUser(r)
|
||||
if !seen[caller.ID] {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("creator must be included in member_ids"))
|
||||
return
|
||||
}
|
||||
chat, err := s.store.CreateChat(r.Context(), req.Title, req.MemberIDs, caller.ID)
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, r, http.StatusCreated, chat)
|
||||
}
|
||||
|
||||
func (s *Server) listChats(w http.ResponseWriter, r *http.Request) {
|
||||
id := requestID(r)
|
||||
caller := currentUser(r)
|
||||
limit, cur, aerr := pagingParams(r, caller.ID)
|
||||
if aerr != nil {
|
||||
apperr.Write(w, id, aerr)
|
||||
return
|
||||
}
|
||||
items, more, err := s.store.ListChats(r.Context(), caller.ID, limit, cur)
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err)
|
||||
return
|
||||
}
|
||||
page := model.Page[*model.Chat]{Items: items}
|
||||
if more && len(items) > 0 {
|
||||
last := items[len(items)-1]
|
||||
encoded := store.EncodeCursor(store.Cursor{Scope: caller.ID, TS: last.CreatedAt.Time, ID: last.ID})
|
||||
page.NextCursor = &encoded
|
||||
}
|
||||
writeJSON(w, r, http.StatusOK, page)
|
||||
}
|
||||
|
||||
func (s *Server) chatRoute(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
methodNotAllowed(w, r)
|
||||
return
|
||||
}
|
||||
id := requestID(r)
|
||||
chatID, err := parseUUID(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("chat_id must be a UUID"))
|
||||
return
|
||||
}
|
||||
chat, err := s.store.ChatForUser(r.Context(), chatID, currentUser(r).ID)
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, r, http.StatusOK, chat)
|
||||
}
|
||||
|
||||
// ───────────────────────────── messages ─────────────────────────────
|
||||
|
||||
func (s *Server) messagesRoute(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
s.createMessage(w, r)
|
||||
case http.MethodGet:
|
||||
s.listMessages(w, r)
|
||||
default:
|
||||
methodNotAllowed(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) createMessage(w http.ResponseWriter, r *http.Request) {
|
||||
id := requestID(r)
|
||||
chatID, err := parseUUID(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("chat_id must be a UUID"))
|
||||
return
|
||||
}
|
||||
chat, err := s.store.ChatForUser(r.Context(), chatID, currentUser(r).ID)
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
idempotencyKey := r.Header.Get("Idempotency-Key")
|
||||
if idempotencyKey == "" {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("Idempotency-Key header is required"))
|
||||
return
|
||||
}
|
||||
|
||||
var req model.CreateMessageReq
|
||||
if aerr := decodeJSON(w, r, &req); aerr != nil {
|
||||
apperr.Write(w, id, aerr)
|
||||
return
|
||||
}
|
||||
if req.AttachmentIDs == nil {
|
||||
req.AttachmentIDs = []string{}
|
||||
}
|
||||
|
||||
if len(req.AttachmentIDs) == 0 {
|
||||
if !validText(req.Text, 4000) {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("text must be 1..4000 non-space code points or provide attachment_ids"))
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if len(req.AttachmentIDs) > 10 {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("attachment_ids must contain at most 10 items"))
|
||||
return
|
||||
}
|
||||
seen := make(map[string]bool, len(req.AttachmentIDs))
|
||||
for _, raw := range req.AttachmentIDs {
|
||||
aid, err := parseUUID(raw)
|
||||
if err != nil {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("attachment_ids must be UUID strings"))
|
||||
return
|
||||
}
|
||||
if seen[aid] {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("duplicate attachment_id"))
|
||||
return
|
||||
}
|
||||
seen[aid] = true
|
||||
}
|
||||
if req.Text != "" && !validText(req.Text, 4000) {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("text must be 1..4000 non-space code points"))
|
||||
return
|
||||
}
|
||||
if err := s.store.ValidateAttachmentsForChat(r.Context(), chat.ID, req.AttachmentIDs); err != nil {
|
||||
s.writeStoreErr(w, r, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
msg, err := s.store.CreateMessage(r.Context(), chat.ID, currentUser(r).ID, req.Text, req.AttachmentIDs, idempotencyKey)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrIdempotencyConflict) {
|
||||
apperr.Write(w, id, apperr.Conflict("idempotency key mismatch"))
|
||||
return
|
||||
}
|
||||
s.writeStoreErr(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, r, http.StatusCreated, msg)
|
||||
}
|
||||
|
||||
func (s *Server) listMessages(w http.ResponseWriter, r *http.Request) {
|
||||
id := requestID(r)
|
||||
chatID, err := parseUUID(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("chat_id must be a UUID"))
|
||||
return
|
||||
}
|
||||
chat, err := s.store.ChatForUser(r.Context(), chatID, currentUser(r).ID)
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err)
|
||||
return
|
||||
}
|
||||
limit, cur, aerr := pagingParams(r, chat.ID)
|
||||
if aerr != nil {
|
||||
apperr.Write(w, id, aerr)
|
||||
return
|
||||
}
|
||||
items, more, err := s.store.ListMessages(r.Context(), chat.ID, limit, cur)
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err)
|
||||
return
|
||||
}
|
||||
page := model.Page[*model.Message]{Items: items}
|
||||
if more && len(items) > 0 {
|
||||
last := items[len(items)-1]
|
||||
encoded := store.EncodeCursor(store.Cursor{Scope: chat.ID, TS: last.CreatedAt.Time, ID: last.ID})
|
||||
page.NextCursor = &encoded
|
||||
}
|
||||
writeJSON(w, r, http.StatusOK, page)
|
||||
}
|
||||
|
||||
// ───────────────────────────── attachments (lab5) ─────────────────────────────
|
||||
|
||||
func (s *Server) attachmentsRoute(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodPost {
|
||||
s.uploadAttachment(w, r)
|
||||
return
|
||||
}
|
||||
methodNotAllowed(w, r)
|
||||
}
|
||||
|
||||
func (s *Server) attachmentRoute(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet {
|
||||
s.getAttachment(w, r)
|
||||
return
|
||||
}
|
||||
methodNotAllowed(w, r)
|
||||
}
|
||||
|
||||
func (s *Server) attachmentContentRoute(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet {
|
||||
s.downloadAttachment(w, r)
|
||||
return
|
||||
}
|
||||
methodNotAllowed(w, r)
|
||||
}
|
||||
|
||||
// uploadAttachment — POST /chats/{chat_id}/attachments?filename=...
|
||||
// LAB 5: сырые байты принимаются в staging, намерение обработать фиксируется
|
||||
// транзакцией (attachment queued + job + outbox), ответ — 202 queued.
|
||||
func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
id := requestID(r)
|
||||
|
||||
chatID, err := parseUUID(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("chat_id must be a UUID"))
|
||||
return
|
||||
}
|
||||
filename := r.URL.Query().Get("filename")
|
||||
if !validFilename(filename) {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("filename must be 1..255 code points without '/', '\\', NUL or control chars"))
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := s.store.ChatForUser(r.Context(), chatID, currentUser(r).ID)
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
media, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if media != "image/png" && media != "image/jpeg" {
|
||||
apperr.Write(w, id, apperr.UnsupportedMedia("Content-Type must be image/png or image/jpeg"))
|
||||
return
|
||||
}
|
||||
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxUploadBytes)
|
||||
|
||||
buf := &bytes.Buffer{}
|
||||
hasher := sha256.New()
|
||||
n, err := io.Copy(io.MultiWriter(buf, hasher), r.Body)
|
||||
if err != nil {
|
||||
var maxErr *http.MaxBytesError
|
||||
if errors.As(err, &maxErr) {
|
||||
apperr.Write(w, id, apperr.PayloadTooLarge("file exceeds 10 MiB limit"))
|
||||
return
|
||||
}
|
||||
apperr.Write(w, id, apperr.InvalidRequest("unable to read request body"))
|
||||
return
|
||||
}
|
||||
if n == 0 {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("empty file"))
|
||||
return
|
||||
}
|
||||
data := buf.Bytes()
|
||||
|
||||
contentType, width, height, serr := sniffImage(data)
|
||||
if serr != nil {
|
||||
apperr.Write(w, id, apperr.UnsupportedMedia("file is not a valid PNG or JPEG image"))
|
||||
return
|
||||
}
|
||||
if contentType != media {
|
||||
apperr.Write(w, id, apperr.UnsupportedMedia("declared Content-Type does not match file content"))
|
||||
return
|
||||
}
|
||||
if int64(width)*int64(height) > maxDecodedPixels {
|
||||
apperr.Write(w, id, apperr.PayloadTooLarge("image exceeds 40 megapixels"))
|
||||
return
|
||||
}
|
||||
// LAB 5 (ревью): целостность файла проверяется ДО приёма задания.
|
||||
// DecodeConfig читает только заголовок, поэтому усечённый PNG иначе
|
||||
// ушёл бы в очередь и упал уже в worker. Ресурсные лимиты сохранены.
|
||||
if ierr := validateImageIntegrity(data, contentType, width, height); ierr != nil {
|
||||
apperr.Write(w, id, apperr.UnsupportedMedia("file is corrupted or truncated"))
|
||||
return
|
||||
}
|
||||
|
||||
attID := uuid.NewString()
|
||||
stagingKey := store.StagingKey(chat.ID, attID)
|
||||
finalKey := store.VariantKey(chat.ID, attID, "original")
|
||||
|
||||
if err := s.store.PutObject(r.Context(), stagingKey, data, contentType); err != nil {
|
||||
apperr.Write(w, id, apperr.Unavailable("object storage unavailable"))
|
||||
return
|
||||
}
|
||||
|
||||
now := model.NowTS()
|
||||
att := &model.Attachment{
|
||||
ID: attID,
|
||||
ChatID: chat.ID,
|
||||
OwnerID: currentUser(r).ID,
|
||||
Filename: filename,
|
||||
ContentType: contentType,
|
||||
SizeBytes: n,
|
||||
SHA256: hex.EncodeToString(hasher.Sum(nil)),
|
||||
Status: model.StatusQueued,
|
||||
Variants: []model.Variant{},
|
||||
ErrorCode: nil,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
S3Key: finalKey,
|
||||
}
|
||||
created, err := s.store.CreateQueuedAttachment(r.Context(), att)
|
||||
if err != nil {
|
||||
_ = s.store.DeleteObject(r.Context(), stagingKey)
|
||||
s.writeStoreErr(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, r, http.StatusAccepted, created)
|
||||
}
|
||||
|
||||
// getAttachment — GET /attachments/{id}: метаданные со статусом и вариантами.
|
||||
func (s *Server) getAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
id := requestID(r)
|
||||
attID, err := parseUUID(r.PathValue("attachment_id"))
|
||||
if err != nil {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("attachment_id must be a UUID"))
|
||||
return
|
||||
}
|
||||
att, err := s.store.GetAttachmentForUser(r.Context(), attID, currentUser(r).ID)
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, r, http.StatusOK, att)
|
||||
}
|
||||
|
||||
// downloadAttachment — GET /attachments/{id}/content[?variant=...].
|
||||
// LAB 5: байты отдаются только в status=ready; до готовности — 409.
|
||||
func (s *Server) downloadAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
id := requestID(r)
|
||||
|
||||
variant := r.URL.Query().Get("variant")
|
||||
if variant == "" {
|
||||
variant = "original"
|
||||
}
|
||||
switch variant {
|
||||
case "original", "thumbnail", "crop", "optimized":
|
||||
default:
|
||||
apperr.Write(w, id, apperr.NotFound("variant not found"))
|
||||
return
|
||||
}
|
||||
|
||||
attID, err := parseUUID(r.PathValue("attachment_id"))
|
||||
if err != nil {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("attachment_id must be a UUID"))
|
||||
return
|
||||
}
|
||||
att, err := s.store.GetAttachmentForUser(r.Context(), attID, currentUser(r).ID)
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
if att.Status != model.StatusReady {
|
||||
apperr.Write(w, id, apperr.Conflict("attachment is not ready yet"))
|
||||
return
|
||||
}
|
||||
|
||||
key := att.S3Key
|
||||
contentType := att.ContentType
|
||||
if variant != "original" {
|
||||
var found *model.Variant
|
||||
for i := range att.Variants {
|
||||
if att.Variants[i].Name == variant {
|
||||
found = &att.Variants[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if found == nil {
|
||||
apperr.Write(w, id, apperr.NotFound("variant not found"))
|
||||
return
|
||||
}
|
||||
key = store.VariantKey(att.ChatID, att.ID, variant)
|
||||
contentType = found.ContentType
|
||||
}
|
||||
|
||||
data, err := s.store.GetObject(r.Context(), key)
|
||||
if err != nil {
|
||||
apperr.Write(w, id, apperr.Unavailable("object storage unavailable"))
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(int64(len(data)), 10))
|
||||
w.Header().Set("X-Request-Id", id)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(data)
|
||||
}
|
||||
|
||||
// ───────────────────────────── общее ─────────────────────────────
|
||||
|
||||
func (s *Server) notFound(w http.ResponseWriter, r *http.Request) {
|
||||
apperr.Write(w, requestID(r), apperr.NotFound("route not found"))
|
||||
}
|
||||
|
||||
// writeStoreErr — маппинг sentinel-ошибок store в HTTP-статусы контракта.
|
||||
func (s *Server) writeStoreErr(w http.ResponseWriter, r *http.Request, err error) {
|
||||
id := requestID(r)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
apperr.Write(w, id, apperr.NotFound("object not found or not accessible"))
|
||||
case errors.Is(err, store.ErrBadMembers):
|
||||
apperr.Write(w, id, apperr.InvalidRequest("unknown member_id"))
|
||||
case errors.Is(err, store.ErrUsernameTaken):
|
||||
apperr.Write(w, id, apperr.Conflict("username is already taken"))
|
||||
case store.IsUnavailable(err):
|
||||
apperr.Write(w, id, apperr.Unavailable("database unavailable"))
|
||||
default:
|
||||
apperr.Write(w, id, apperr.Internal("internal error"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
// package api, helpers.go — пограничный контроль входа (перенос из lab1 + разбор Authorization + валидация вложений lab4).
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"image"
|
||||
_ "image/jpeg" // регистрация декодеров для image.DecodeConfig
|
||||
_ "image/png"
|
||||
"mime"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/apperr"
|
||||
"mtusi-messenger/internal/store"
|
||||
)
|
||||
|
||||
const maxBodyBytes = 1 << 20
|
||||
|
||||
// ─────────────── Лимиты вложений (lab4) ───────────────
|
||||
const (
|
||||
// Ровно 10 MiB, как в контракте: 10 * 1024 * 1024 = 10 485 760 байт.
|
||||
// Это ЖЁСТКИЙ потолок: одна загрузка не может занять больше, даже если
|
||||
// клиент шлёт бесконечный поток (см. http.MaxBytesReader в uploadAttachment).
|
||||
maxUploadBytes = 10 << 20
|
||||
// Не более 40 миллионов декодированных пикселей (ширина * высота).
|
||||
maxDecodedPixels = 40_000_000
|
||||
)
|
||||
|
||||
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
// parseUUID — канонический UUID или ошибка (из lab1).
|
||||
func parseUUID(s string) (string, error) {
|
||||
u, err := uuid.Parse(s)
|
||||
if err != nil || u.String() != s {
|
||||
return "", errors.New("invalid uuid")
|
||||
}
|
||||
return u.String(), nil
|
||||
}
|
||||
|
||||
func runeLen(s string) int { return utf8.RuneCountInString(s) }
|
||||
|
||||
// validText — обязательная строка 1..max code points, не только пробелы (из lab1).
|
||||
func validText(s string, max int) bool {
|
||||
n := runeLen(s)
|
||||
return n >= 1 && n <= max && strings.TrimSpace(s) != ""
|
||||
}
|
||||
|
||||
// validPassword — контракт lab2: 12–128 code points, UTF-8, двоеточие допустимо.
|
||||
func validPassword(s string) bool {
|
||||
n := runeLen(s)
|
||||
return n >= 12 && n <= 128 && strings.TrimSpace(s) != ""
|
||||
}
|
||||
|
||||
// validFilename — отображаемое имя файла (1..255 code points), lab4.
|
||||
// Отклоняем '/', '\', NUL и управляющие символы. Имя используется ТОЛЬКО для
|
||||
// отображения и никогда как путь или ключ S3 — ключ генерирует сервер.
|
||||
func validFilename(s string) bool {
|
||||
n := runeLen(s)
|
||||
if n < 1 || n > 255 {
|
||||
return false
|
||||
}
|
||||
if strings.ContainsAny(s, "/\\\x00") {
|
||||
return false
|
||||
}
|
||||
for _, r := range s {
|
||||
if r < 0x20 || r == 0x7f { // управляющие символы
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// sniffImage — определяет фактический тип изображения по СОДЕРЖИМОМУ и его
|
||||
// геометрические размеры БЕЗ полного декодирования пикселей.
|
||||
// Возвращает (contentType, width, height, error).
|
||||
// Контракт: MIME проверяется по содержимому; лимит пикселей применяется до
|
||||
// полной распаковки. Декодеры берут только заголовок, поэтому память ограничена.
|
||||
func sniffImage(data []byte) (string, int, int, error) {
|
||||
ct := http.DetectContentType(data)
|
||||
if ct != "image/png" && ct != "image/jpeg" {
|
||||
return "", 0, 0, errors.New("unsupported image type")
|
||||
}
|
||||
cfg, format, err := image.DecodeConfig(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return "", 0, 0, err // повреждённое/неполное изображение
|
||||
}
|
||||
// Проверяем, что формат соответствует MIME (подмена типа).
|
||||
expectedFormat := ""
|
||||
if ct == "image/png" {
|
||||
expectedFormat = "png"
|
||||
} else if ct == "image/jpeg" {
|
||||
expectedFormat = "jpeg"
|
||||
}
|
||||
if format != expectedFormat {
|
||||
return "", 0, 0, errors.New("declared Content-Type does not match file content")
|
||||
}
|
||||
return ct, cfg.Width, cfg.Height, nil
|
||||
}
|
||||
|
||||
// ─────────────── Разбор Authorization (из lab2, без изменений) ───────────────
|
||||
type loginCreds struct {
|
||||
Username string
|
||||
Password string
|
||||
}
|
||||
|
||||
func parseBasicHeader(r *http.Request) (loginCreds, bool) {
|
||||
h := r.Header.Get("Authorization")
|
||||
const prefix = "Basic "
|
||||
if !strings.HasPrefix(h, prefix) {
|
||||
return loginCreds{}, false
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(h, prefix))
|
||||
if err != nil {
|
||||
return loginCreds{}, false
|
||||
}
|
||||
u, p, found := strings.Cut(string(raw), ":")
|
||||
if !found {
|
||||
return loginCreds{}, false
|
||||
}
|
||||
return loginCreds{Username: u, Password: p}, true
|
||||
}
|
||||
|
||||
func parseBearerHeader(r *http.Request) (string, bool) {
|
||||
h := r.Header.Get("Authorization")
|
||||
const prefix = "Bearer "
|
||||
if !strings.HasPrefix(h, prefix) {
|
||||
return "", false
|
||||
}
|
||||
t := strings.TrimPrefix(h, prefix)
|
||||
if t == "" {
|
||||
return "", false
|
||||
}
|
||||
return t, true
|
||||
}
|
||||
|
||||
// decodeJSON — конвейер 415 -> 413 -> 400 (из lab1, без изменений).
|
||||
// ВНИМАНИЕ: используется только для JSON-эндпоинтов. Загрузка вложений идёт
|
||||
// сырыми байтами мимо этой функции (см. uploadAttachment).
|
||||
func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) *apperr.AppError {
|
||||
media, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if media != "application/json" {
|
||||
return apperr.UnsupportedMedia("Content-Type must be application/json")
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxBodyBytes)
|
||||
dec := json.NewDecoder(r.Body)
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
var maxErr *http.MaxBytesError
|
||||
if errors.As(err, &maxErr) {
|
||||
return apperr.PayloadTooLarge("request body too large")
|
||||
}
|
||||
return apperr.InvalidRequest("malformed JSON body")
|
||||
}
|
||||
if dec.More() {
|
||||
return apperr.InvalidRequest("multiple JSON documents in body")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// pagingParams — limit 1..100 (default 50) + курсор с проверкой scope (из lab1).
|
||||
func pagingParams(r *http.Request, scope string) (int, *store.Cursor, *apperr.AppError) {
|
||||
limit := 50
|
||||
if v := r.URL.Query().Get("limit"); v != "" {
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil || n < 1 || n > 100 {
|
||||
return 0, nil, apperr.InvalidRequest("limit must be an integer in 1..100")
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
var cur *store.Cursor
|
||||
if v := r.URL.Query().Get("cursor"); v != "" {
|
||||
c, err := store.DecodeCursor(v)
|
||||
if err != nil {
|
||||
return 0, nil, apperr.InvalidRequest("invalid cursor")
|
||||
}
|
||||
if c.Scope != scope {
|
||||
return 0, nil, apperr.InvalidRequest("cursor does not belong to this resource")
|
||||
}
|
||||
cur = &c
|
||||
}
|
||||
return limit, cur, nil
|
||||
}
|
||||
|
||||
// writeJSON — единая точка успешного ответа (из lab1).
|
||||
func writeJSON(w http.ResponseWriter, r *http.Request, status int, payload any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("X-Request-Id", requestID(r))
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(payload)
|
||||
}
|
||||
|
||||
// writeNoContent — 204 без тела (logout). Тела нет, но заголовки контракта остаются.
|
||||
func writeNoContent(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Request-Id", requestID(r))
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func methodNotAllowed(w http.ResponseWriter, r *http.Request) {
|
||||
apperr.Write(w, requestID(r), apperr.New(http.StatusMethodNotAllowed, apperr.CodeInvalidRequest, "method not allowed"))
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
// Package api, image_integrity.go — проверка ЦЕЛОСТНОСТИ изображения до приёма
|
||||
// задания (лаба 5, замечание ревью).
|
||||
//
|
||||
// Почему отдельный шаг: image.DecodeConfig читает только заголовок, поэтому
|
||||
// усечённый PNG с валидным IHDR проходил приём и падал уже в worker. Контракт
|
||||
// требует 415 на приёме для заведомо повреждённых файлов.
|
||||
//
|
||||
// Ресурсные ограничения сохранены:
|
||||
// - размер тела ограничен http.MaxBytesReader (10 MiB) ДО чтения;
|
||||
// - габариты и потолок 40 Мп проверены ДО вызова этой функции;
|
||||
// - PNG проверяется структурно (CRC32 чанков + полный inflate IDAT в discard),
|
||||
// без выделения пиксельного буфера;
|
||||
// - JPEG декодируется полностью, но не более одной проверки одновременно
|
||||
// на реплику (семафор), т.к. пиксельный буфер JPEG заметно меньше RGBA.
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash/crc32"
|
||||
"image/jpeg"
|
||||
"io"
|
||||
)
|
||||
|
||||
var pngSignature = []byte{0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a}
|
||||
|
||||
// jpegDecodeGate — не более одной полной JPEG-проверки на реплику.
|
||||
var jpegDecodeGate = make(chan struct{}, 1)
|
||||
|
||||
// validateImageIntegrity возвращает ошибку, если файл повреждён/усечён.
|
||||
// Вызывается после sniffImage, сверки MIME и проверки потолка пикселей.
|
||||
func validateImageIntegrity(data []byte, contentType string, width, height int) error {
|
||||
switch contentType {
|
||||
case "image/png":
|
||||
return validatePNGIntegrity(data, width, height)
|
||||
case "image/jpeg":
|
||||
return validateJPEGIntegrity(data)
|
||||
default:
|
||||
return errors.New("unsupported image type")
|
||||
}
|
||||
}
|
||||
|
||||
// validatePNGIntegrity — обход чанков с проверкой CRC, обязательный IEND и
|
||||
// полная распаковка IDAT. Пиксели не материализуются.
|
||||
func validatePNGIntegrity(data []byte, width, height int) error {
|
||||
// 8 байт сигнатуры + 25 байт минимального IHDR-чанка.
|
||||
if len(data) < len(pngSignature)+25 || !bytes.HasPrefix(data, pngSignature) {
|
||||
return errors.New("png: missing signature or IHDR")
|
||||
}
|
||||
|
||||
pos := len(pngSignature)
|
||||
var idat bytes.Buffer
|
||||
var sawIEND bool
|
||||
var bitDepth, colorType, interlace byte
|
||||
|
||||
for pos+12 <= len(data) {
|
||||
length := int(binary.BigEndian.Uint32(data[pos : pos+4]))
|
||||
if length < 0 || pos+12+length > len(data) {
|
||||
return errors.New("png: truncated chunk")
|
||||
}
|
||||
typ := data[pos+4 : pos+8]
|
||||
payload := data[pos+8 : pos+8+length]
|
||||
wantCRC := binary.BigEndian.Uint32(data[pos+8+length : pos+12+length])
|
||||
|
||||
h := crc32.NewIEEE()
|
||||
_, _ = h.Write(typ)
|
||||
_, _ = h.Write(payload)
|
||||
if h.Sum32() != wantCRC {
|
||||
return fmt.Errorf("png: bad CRC in %s chunk", typ)
|
||||
}
|
||||
|
||||
switch string(typ) {
|
||||
case "IHDR":
|
||||
if length != 13 {
|
||||
return errors.New("png: bad IHDR length")
|
||||
}
|
||||
bitDepth = payload[8]
|
||||
colorType = payload[9]
|
||||
interlace = payload[12]
|
||||
case "IDAT":
|
||||
idat.Write(payload)
|
||||
case "IEND":
|
||||
sawIEND = true
|
||||
}
|
||||
|
||||
pos += 12 + length
|
||||
if sawIEND {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !sawIEND {
|
||||
return errors.New("png: missing IEND (truncated file)")
|
||||
}
|
||||
if idat.Len() == 0 {
|
||||
return errors.New("png: no IDAT data")
|
||||
}
|
||||
|
||||
zr, err := zlib.NewReader(bytes.NewReader(idat.Bytes()))
|
||||
if err != nil {
|
||||
return fmt.Errorf("png: zlib header: %w", err)
|
||||
}
|
||||
defer zr.Close()
|
||||
|
||||
expected, err := expectedRawPNGSize(width, height, int(bitDepth), int(colorType), int(interlace))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// limit+1 позволяет отличить «ровно ожидаемый объём» от «раздулось больше».
|
||||
// Если поток ровно expected, zlib дочитывается до EOF и проверяет adler32.
|
||||
n, err := io.Copy(io.Discard, io.LimitReader(zr, expected+1))
|
||||
if err != nil {
|
||||
return fmt.Errorf("png: inflate IDAT: %w", err)
|
||||
}
|
||||
if n != expected {
|
||||
return fmt.Errorf("png: inflated %d bytes, expected %d (truncated or malformed)", n, expected)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// expectedRawPNGSize — точный объём распакованных scanline-данных PNG,
|
||||
// включая фильтр-байт каждой строки и все проходы Adam7 при interlace=1.
|
||||
func expectedRawPNGSize(width, height, bitDepth, colorType, interlace int) (int64, error) {
|
||||
var channels int
|
||||
switch colorType {
|
||||
case 0: // grayscale
|
||||
channels = 1
|
||||
case 2: // truecolor
|
||||
channels = 3
|
||||
case 3: // palette
|
||||
channels = 1
|
||||
case 4: // grayscale + alpha
|
||||
channels = 2
|
||||
case 6: // truecolor + alpha
|
||||
channels = 4
|
||||
default:
|
||||
return 0, fmt.Errorf("png: unknown color type %d", colorType)
|
||||
}
|
||||
if width <= 0 || height <= 0 {
|
||||
return 0, errors.New("png: non-positive dimensions")
|
||||
}
|
||||
|
||||
rowBytes := func(w int) int64 {
|
||||
bits := int64(w) * int64(channels) * int64(bitDepth)
|
||||
return 1 + (bits+7)/8 // 1 фильтр-байт + округление вверх до байта
|
||||
}
|
||||
|
||||
if interlace == 0 {
|
||||
return int64(height) * rowBytes(width), nil
|
||||
}
|
||||
|
||||
// Adam7: семь проходов (xStart, yStart, xStep, yStep).
|
||||
passes := [7][4]int{
|
||||
{0, 0, 8, 8}, {4, 0, 8, 8}, {0, 4, 4, 8}, {2, 0, 4, 4},
|
||||
{0, 2, 2, 4}, {1, 0, 2, 2}, {0, 1, 1, 2},
|
||||
}
|
||||
var total int64
|
||||
for _, p := range passes {
|
||||
pw, ph := 0, 0
|
||||
if width > p[0] {
|
||||
pw = (width - p[0] + p[2] - 1) / p[2]
|
||||
}
|
||||
if height > p[1] {
|
||||
ph = (height - p[1] + p[3] - 1) / p[3]
|
||||
}
|
||||
if pw > 0 && ph > 0 {
|
||||
total += int64(ph) * rowBytes(pw)
|
||||
}
|
||||
}
|
||||
if total == 0 {
|
||||
return 0, errors.New("png: empty interlaced image")
|
||||
}
|
||||
return total, nil
|
||||
}
|
||||
|
||||
// validateJPEGIntegrity — маркеры SOI/EOI плюс полное декодирование под гейтом.
|
||||
func validateJPEGIntegrity(data []byte) error {
|
||||
if len(data) < 4 || data[0] != 0xFF || data[1] != 0xD8 {
|
||||
return errors.New("jpeg: missing SOI marker")
|
||||
}
|
||||
if !bytes.HasSuffix(data, []byte{0xFF, 0xD9}) {
|
||||
return errors.New("jpeg: missing EOI marker (truncated file)")
|
||||
}
|
||||
|
||||
jpegDecodeGate <- struct{}{}
|
||||
defer func() { <-jpegDecodeGate }()
|
||||
|
||||
if _, err := jpeg.Decode(bytes.NewReader(data)); err != nil {
|
||||
return fmt.Errorf("jpeg: decode: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"mtusi-messenger/internal/apperr"
|
||||
"mtusi-messenger/internal/model"
|
||||
"mtusi-messenger/internal/store"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type ctxKey int
|
||||
|
||||
const (
|
||||
ctxRequestID ctxKey = iota
|
||||
ctxUser
|
||||
ctxToken
|
||||
ctxCreds
|
||||
)
|
||||
|
||||
const (
|
||||
wwwBearer = `Bearer realm="messenger"`
|
||||
wwwBasic = `Basic realm="messenger", charset="UTF-8"`
|
||||
)
|
||||
|
||||
// ─────────── Охранник 1: номерок (из lab1) ───────────
|
||||
func requestIDMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.Header.Get("X-Request-Id")
|
||||
if id == "" {
|
||||
id = uuid.NewString()
|
||||
}
|
||||
w.Header().Set("X-Request-Id", id)
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxRequestID, id)))
|
||||
})
|
||||
}
|
||||
|
||||
func requestID(r *http.Request) string {
|
||||
if id, ok := r.Context().Value(ctxRequestID).(string); ok && id != "" {
|
||||
return id
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
// ─────────── Охранник 2: журнал без тел (из lab1) ───────────
|
||||
type statusWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (s *statusWriter) WriteHeader(code int) {
|
||||
s.status = code
|
||||
s.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
// loggingMiddleware — структурный лог HTTP-запроса.
|
||||
// LAB 6: InfoContext передаёт ctx с активным HTTP span, поэтому slog-bridge
|
||||
// добавляет trace_id/span_id в запись. r.Pattern (route template из ServeMux
|
||||
// Go 1.22+) используется как low-cardinality route в логах и устанавливается
|
||||
// как атрибут http.route на текущий otelhttp span.
|
||||
func loggingMiddleware(log *slog.Logger, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
||||
next.ServeHTTP(sw, r)
|
||||
|
||||
route := r.Pattern
|
||||
if route == "" {
|
||||
route = r.URL.Path
|
||||
}
|
||||
|
||||
// LAB 6: low-cardinality route на активном HTTP span.
|
||||
// Защищает метрики и трассы от cardinality explosion на UUID.
|
||||
if sc := trace.SpanFromContext(r.Context()); sc.SpanContext().IsValid() {
|
||||
sc.SetAttributes(attribute.String("http.route", route))
|
||||
sc.SetName(r.Method + " " + route)
|
||||
}
|
||||
|
||||
log.InfoContext(r.Context(), "http",
|
||||
"method", r.Method,
|
||||
"route", route,
|
||||
"path", r.URL.Path,
|
||||
"status", sw.status,
|
||||
"dur_ms", time.Since(start).Milliseconds(),
|
||||
"request_id", requestID(r),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
// ─────────── Охранник 3: выключатель паник (из lab1) ───────────
|
||||
func recoverMiddleware(log *slog.Logger, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if rec := recover(); rec != nil {
|
||||
log.ErrorContext(r.Context(), "panic recovered", "path", r.URL.Path, "request_id", requestID(r))
|
||||
apperr.Write(w, requestID(r), apperr.Internal("internal error"))
|
||||
}
|
||||
}()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// ─────────── Охранник 4: Идентификатор реплики (Lab 3) ───────────
|
||||
func instanceIDMiddleware(instanceID string, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Instance-Id", instanceID)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// ─────────── Пропускной пункт lab2: Bearer ───────────
|
||||
func (s *Server) auth(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
id := requestID(r)
|
||||
h := r.Header.Get("Authorization")
|
||||
if strings.HasPrefix(h, "Basic ") {
|
||||
w.Header().Set("WWW-Authenticate", wwwBearer)
|
||||
apperr.Write(w, id, apperr.Unauthorized("Bearer token required"))
|
||||
return
|
||||
}
|
||||
token, ok := parseBearerHeader(r)
|
||||
if !ok {
|
||||
w.Header().Set("WWW-Authenticate", wwwBearer)
|
||||
apperr.Write(w, id, apperr.Unauthorized("Bearer token required"))
|
||||
return
|
||||
}
|
||||
user, err := s.store.SessionUser(r.Context(), token)
|
||||
if err != nil {
|
||||
if store.IsUnavailable(err) {
|
||||
apperr.Write(w, id, apperr.Unavailable("database unavailable"))
|
||||
return
|
||||
}
|
||||
w.Header().Set("WWW-Authenticate", wwwBearer)
|
||||
apperr.Write(w, id, apperr.Unauthorized("valid Bearer token required"))
|
||||
return
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), ctxUser, user)
|
||||
ctx = context.WithValue(ctx, ctxToken, token)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────── Входная дверь: только Basic ───────────
|
||||
func (s *Server) basicOnly(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
id := requestID(r)
|
||||
creds, ok := parseBasicHeader(r)
|
||||
if !ok {
|
||||
w.Header().Set("WWW-Authenticate", wwwBasic)
|
||||
apperr.Write(w, id, apperr.Unauthorized("Basic credentials required"))
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxCreds, creds)))
|
||||
}
|
||||
}
|
||||
|
||||
func currentUser(r *http.Request) *model.User { return r.Context().Value(ctxUser).(*model.User) }
|
||||
func currentToken(r *http.Request) string { return r.Context().Value(ctxToken).(string) }
|
||||
func currentCreds(r *http.Request) loginCreds { return r.Context().Value(ctxCreds).(loginCreds) }
|
||||
@@ -0,0 +1,72 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
|
||||
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
|
||||
|
||||
"mtusi-messenger/internal/store"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
store *store.Store
|
||||
log *slog.Logger
|
||||
ready *atomic.Bool
|
||||
instanceID string // LAB 3: ID реплики
|
||||
}
|
||||
|
||||
func NewServer(st *store.Store, log *slog.Logger, ready *atomic.Bool, instanceID string) *Server {
|
||||
return &Server{store: st, log: log, ready: ready, instanceID: instanceID}
|
||||
}
|
||||
|
||||
func (s *Server) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
|
||||
// Публичные (security: [] в OpenAPI):
|
||||
mux.HandleFunc("/health/live", s.healthLive)
|
||||
mux.HandleFunc("/health/ready", s.healthReady)
|
||||
mux.HandleFunc("/api/v1/users", s.usersRoute)
|
||||
|
||||
// Вход — ТОЛЬКО Basic:
|
||||
mux.HandleFunc("/api/v1/auth/sessions", s.basicOnly(s.createSession))
|
||||
|
||||
// Всё остальное — только Bearer:
|
||||
mux.HandleFunc("/api/v1/auth/sessions/current", s.auth(s.revokeSession))
|
||||
mux.HandleFunc("/api/v1/users/me", s.auth(s.me))
|
||||
mux.HandleFunc("/api/v1/chats", s.auth(s.chatsRoute))
|
||||
mux.HandleFunc("/api/v1/chats/{chat_id}", s.auth(s.chatRoute))
|
||||
mux.HandleFunc("/api/v1/chats/{chat_id}/messages", s.auth(s.messagesRoute))
|
||||
|
||||
// LAB 4/5: вложения
|
||||
mux.HandleFunc("/api/v1/chats/{chat_id}/attachments", s.auth(s.attachmentsRoute))
|
||||
mux.HandleFunc("/api/v1/attachments/{attachment_id}", s.auth(s.attachmentRoute))
|
||||
mux.HandleFunc("/api/v1/attachments/{attachment_id}/content", s.auth(s.attachmentContentRoute))
|
||||
|
||||
mux.HandleFunc("/", s.notFound)
|
||||
|
||||
// LAB 6: порядок middleware снаружи → внутрь:
|
||||
// otelhttp → requestID → recover → logging → instanceID → mux.
|
||||
// otelhttp самый наружный, чтобы HTTP span охватывал ВЕСЬ запрос,
|
||||
// включая middleware и panic recovery. requestID выше logging, чтобы
|
||||
// requestID(r) в логе не был "unknown".
|
||||
var h http.Handler = mux
|
||||
h = instanceIDMiddleware(s.instanceID, h)
|
||||
h = loggingMiddleware(s.log, h)
|
||||
h = recoverMiddleware(s.log, h)
|
||||
h = requestIDMiddleware(h)
|
||||
|
||||
h = otelhttp.NewHandler(h, "http.server",
|
||||
otelhttp.WithSpanNameFormatter(func(operation string, r *http.Request) string {
|
||||
// r.Pattern — route template из ServeMux (Go 1.22+), не реальный UUID.
|
||||
// Это low-cardinality защита метрик и трасс.
|
||||
if pattern := r.Pattern; pattern != "" {
|
||||
return r.Method + " " + pattern
|
||||
}
|
||||
return r.Method + " " + r.URL.Path
|
||||
}),
|
||||
)
|
||||
|
||||
return h
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package apperr
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Code string
|
||||
|
||||
const (
|
||||
CodeInvalidRequest Code = "invalid_request"
|
||||
CodeUnauthorized Code = "unauthorized"
|
||||
CodeNotFound Code = "not_found"
|
||||
CodeConflict Code = "conflict"
|
||||
CodePayloadTooLarge Code = "payload_too_large"
|
||||
CodeUnsupportedMedia Code = "unsupported_media_type"
|
||||
CodeRateLimited Code = "rate_limited"
|
||||
CodeUnavailable Code = "unavailable"
|
||||
CodeInternal Code = "internal_error"
|
||||
)
|
||||
|
||||
type Body struct {
|
||||
Code Code `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
type Envelope struct {
|
||||
Error Body `json:"error"`
|
||||
}
|
||||
|
||||
type AppError struct {
|
||||
Status int
|
||||
Code Code
|
||||
Msg string
|
||||
}
|
||||
|
||||
func (e *AppError) Error() string { return e.Msg }
|
||||
|
||||
func New(status int, code Code, msg string) *AppError {
|
||||
return &AppError{Status: status, Code: code, Msg: msg}
|
||||
}
|
||||
|
||||
func InvalidRequest(msg string) *AppError { return New(http.StatusBadRequest, CodeInvalidRequest, msg) }
|
||||
func Unauthorized(msg string) *AppError { return New(http.StatusUnauthorized, CodeUnauthorized, msg) }
|
||||
func NotFound(msg string) *AppError { return New(http.StatusNotFound, CodeNotFound, msg) }
|
||||
func Conflict(msg string) *AppError { return New(http.StatusConflict, CodeConflict, msg) }
|
||||
func PayloadTooLarge(msg string) *AppError {
|
||||
return New(http.StatusRequestEntityTooLarge, CodePayloadTooLarge, msg)
|
||||
}
|
||||
func UnsupportedMedia(msg string) *AppError {
|
||||
return New(http.StatusUnsupportedMediaType, CodeUnsupportedMedia, msg)
|
||||
}
|
||||
func Unavailable(msg string) *AppError {
|
||||
return New(http.StatusServiceUnavailable, CodeUnavailable, msg)
|
||||
}
|
||||
func Internal(msg string) *AppError { return New(http.StatusInternalServerError, CodeInternal, msg) }
|
||||
|
||||
// Write отдаёт ошибку в формате контракта: {"error":{"code","message","request_id"}}.
|
||||
func Write(w http.ResponseWriter, requestID string, err *AppError) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
w.WriteHeader(err.Status)
|
||||
_ = json.NewEncoder(w).Encode(Envelope{Error: Body{Code: err.Code, Message: err.Msg, RequestID: requestID}})
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Timestamp — детерминированная сериализация времени (ровно 3 знака миллисекунд).
|
||||
type Timestamp struct{ time.Time }
|
||||
|
||||
func (t Timestamp) MarshalJSON() ([]byte, error) {
|
||||
s := t.UTC().Format("2006-01-02T15:04:05.000Z")
|
||||
return strconv.AppendQuote(nil, s), nil
|
||||
}
|
||||
|
||||
func NowTS() Timestamp { return Timestamp{Time: time.Now().UTC().Truncate(time.Millisecond)} }
|
||||
|
||||
// Состояния вложения/задания (лаба 5).
|
||||
const (
|
||||
StatusQueued = "queued"
|
||||
StatusProcessing = "processing"
|
||||
StatusReady = "ready"
|
||||
StatusFailed = "failed"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
}
|
||||
|
||||
type CreateUserReq struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type LoginRequest struct {
|
||||
Username string
|
||||
Password string
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
TokenHash []byte
|
||||
UserID string
|
||||
ExpiresAt time.Time
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type SessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt Timestamp `json:"expires_at"`
|
||||
User User `json:"user"`
|
||||
}
|
||||
|
||||
type Chat struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
}
|
||||
|
||||
type CreateChatReq struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
type CreateMessageReq struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
type Page[T any] struct {
|
||||
Items []T `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type Health struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// ─────────────────────── Вложения (lab4 → lab5) ───────────────────────
|
||||
|
||||
// Attachment — метаданные вложения. В лабе 5 status проходит путь
|
||||
// queued → processing → ready|failed; variants заполняются только в ready.
|
||||
type Attachment struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"` // "image/png" | "image/jpeg"
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Status string `json:"status"` // queued | processing | ready | failed
|
||||
Variants []Variant `json:"variants"` // [] до ready
|
||||
ErrorCode *string `json:"error_code"` // null до failed
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
UpdatedAt Timestamp `json:"updated_at"`
|
||||
|
||||
// Внутренние поля, не отдаются клиенту.
|
||||
PipelineVersion int `json:"-"`
|
||||
ProcessingStartedAt *time.Time `json:"-"`
|
||||
S3Key string `json:"-"` // ключ финального оригинала
|
||||
}
|
||||
|
||||
// Variant — производная версия: thumbnail | crop | optimized.
|
||||
type Variant struct {
|
||||
Name string `json:"name"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
|
||||
// ─────────────────────── Очередь (lab5) ───────────────────────
|
||||
|
||||
// Job — оркестрационная запись обработки (не отдаётся клиенту).
|
||||
type Job struct {
|
||||
ID string `json:"id"`
|
||||
AttachmentID string `json:"attachment_id"`
|
||||
Status string `json:"status"`
|
||||
Attempt int `json:"attempt"`
|
||||
MaxAttempts int `json:"max_attempts"`
|
||||
NextAttemptAt *time.Time `json:"next_attempt_at,omitempty"`
|
||||
LeaseID *string `json:"lease_id,omitempty"`
|
||||
LeaseExpiresAt *time.Time `json:"lease_expires_at,omitempty"`
|
||||
ErrorCode *string `json:"error_code,omitempty"`
|
||||
ErrorMessage *string `json:"error_message,omitempty"`
|
||||
PipelineVersion int `json:"pipeline_version"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
UpdatedAt Timestamp `json:"updated_at"`
|
||||
}
|
||||
|
||||
// JobMessage — сообщение брокера по contracts/jobs.schema.json.
|
||||
// В очередь идут только ID и служебные поля, НЕ байты и НЕ credentials.
|
||||
type JobMessage struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
JobID string `json:"job_id"`
|
||||
Type string `json:"type"`
|
||||
AttachmentID string `json:"attachment_id"`
|
||||
PipelineVersion int `json:"pipeline_version"`
|
||||
Attempt int `json:"attempt"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
// LAB 6: W3C trace context для связи producer/consumer spans.
|
||||
// Поля соответствуют contracts/jobs.schema.json (traceparent, tracestate).
|
||||
// omitempty — чтобы существующие записи outbox (до лабы 6) сериализовались
|
||||
// совместимо и не ломали replay.
|
||||
Traceparent string `json:"traceparent,omitempty"`
|
||||
Tracestate string `json:"tracestate,omitempty"`
|
||||
}
|
||||
|
||||
// OutboxMessage — строка transactional outbox.
|
||||
type OutboxMessage struct {
|
||||
ID string `json:"id"`
|
||||
AggregateType string `json:"aggregate_type"`
|
||||
AggregateID string `json:"aggregate_id"`
|
||||
EventType string `json:"event_type"`
|
||||
Payload []byte `json:"payload"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
PublishedAt *time.Time `json:"published_at,omitempty"`
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
// Package otel, metrics.go — приложения-метрики наблюдаемости (лаба 6, уровень 4).
|
||||
//
|
||||
// Закрывает сигналы контракта observability.md, которые не даёт HTTP-инструментация:
|
||||
// queue depth / возраст старейшей задачи, DB pool, saturation worker,
|
||||
// processed/failed jobs, duration обработки и end-to-end time to ready.
|
||||
//
|
||||
// Кардинальность: labels только из конечных наборов (job.type, outcome, error_code).
|
||||
// attachment_id/chat_id/request_id/UUID в labels НЕ попадают — instance.id
|
||||
// носит resource-атрибут, а не label.
|
||||
package otel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
"sync/atomic"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
)
|
||||
|
||||
// atomicFloat64 — атомарный float64 через битовое представление.
|
||||
// В стандартном sync/atomic нет Float64 (только Int64/Uint64/Bool/Pointer/Value),
|
||||
// поэтому храним биты в Uint64: lock-free, без гонок и без мьютекса в callback.
|
||||
type atomicFloat64 struct{ bits atomic.Uint64 }
|
||||
|
||||
func (f *atomicFloat64) Store(v float64) { f.bits.Store(math.Float64bits(v)) }
|
||||
func (f *atomicFloat64) Load() float64 { return math.Float64frombits(f.bits.Load()) }
|
||||
|
||||
// workerCapacity — учебный стенд: один последовательный worker.
|
||||
const workerCapacity int64 = 1
|
||||
|
||||
// Атомарные значения для observable gauge: их обновляет collector в main,
|
||||
// а callback SDK читает без сетевого I/O в момент сбора метрик.
|
||||
var (
|
||||
queueDepth atomic.Int64
|
||||
queueOldestAge atomicFloat64
|
||||
jobsQueued atomic.Int64
|
||||
jobsOldestQueuedAge atomicFloat64
|
||||
poolUsed atomic.Int64
|
||||
poolCapacity atomic.Int64
|
||||
workerBusy atomic.Int64
|
||||
)
|
||||
|
||||
// Инструменты, создаваемые один раз в initAppMetrics.
|
||||
var (
|
||||
jobsProcessed metric.Int64Counter
|
||||
jobDuration metric.Float64Histogram
|
||||
timeToReady metric.Float64Histogram
|
||||
poolEmptyAcquires metric.Int64Counter
|
||||
)
|
||||
|
||||
// initAppMetrics регистрирует инструменты.
|
||||
// ВАЖНО: вызывается из otel.Init ПОСЛЕ otel.SetMeterProvider(mp), иначе
|
||||
// инструменты создадутся от no-op провайдера и метрики не будут экспортироваться.
|
||||
func initAppMetrics() {
|
||||
meter := otel.Meter("messenger")
|
||||
|
||||
jobsProcessed, _ = meter.Int64Counter("messenger.jobs.processed",
|
||||
metric.WithDescription("Jobs finished processing by outcome"),
|
||||
metric.WithUnit("{job}"),
|
||||
)
|
||||
jobDuration, _ = meter.Float64Histogram("messenger.job.duration",
|
||||
metric.WithDescription("Time spent inside worker processing of one job"),
|
||||
metric.WithUnit("s"),
|
||||
metric.WithExplicitBucketBoundaries(0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60),
|
||||
)
|
||||
timeToReady, _ = meter.Float64Histogram("messenger.time.to_ready",
|
||||
metric.WithDescription("End-to-end: durable acceptance -> ready publication"),
|
||||
metric.WithUnit("s"),
|
||||
metric.WithExplicitBucketBoundaries(0.1, 0.25, 0.5, 1, 2, 5, 10, 30, 60, 120),
|
||||
)
|
||||
poolEmptyAcquires, _ = meter.Int64Counter("messenger.db.pool.empty_acquires",
|
||||
metric.WithDescription("Times a connection acquire had to wait for a free connection"),
|
||||
metric.WithUnit("{acquire}"),
|
||||
)
|
||||
|
||||
// Observable gauges: callback читает атомарные значения, обновляемые collector'ом.
|
||||
_, _ = meter.Int64ObservableGauge("messenger.queue.depth",
|
||||
metric.WithDescription("Unacknowledged messages pending in the broker stream"),
|
||||
metric.WithUnit("{message}"),
|
||||
metric.WithInt64Callback(func(_ context.Context, o metric.Int64Observer) error {
|
||||
o.Observe(queueDepth.Load())
|
||||
return nil
|
||||
}),
|
||||
)
|
||||
_, _ = meter.Float64ObservableGauge("messenger.queue.oldest_age",
|
||||
metric.WithDescription("Age of the oldest pending message in the broker stream"),
|
||||
metric.WithUnit("s"),
|
||||
metric.WithFloat64Callback(func(_ context.Context, o metric.Float64Observer) error {
|
||||
o.Observe(queueOldestAge.Load())
|
||||
return nil
|
||||
}),
|
||||
)
|
||||
_, _ = meter.Int64ObservableGauge("messenger.jobs.queued",
|
||||
metric.WithDescription("Jobs in status queued in PostgreSQL"),
|
||||
metric.WithUnit("{job}"),
|
||||
metric.WithInt64Callback(func(_ context.Context, o metric.Int64Observer) error {
|
||||
o.Observe(jobsQueued.Load())
|
||||
return nil
|
||||
}),
|
||||
)
|
||||
_, _ = meter.Float64ObservableGauge("messenger.jobs.oldest_queued_age",
|
||||
metric.WithDescription("Age of the oldest queued job since acceptance"),
|
||||
metric.WithUnit("s"),
|
||||
metric.WithFloat64Callback(func(_ context.Context, o metric.Float64Observer) error {
|
||||
o.Observe(jobsOldestQueuedAge.Load())
|
||||
return nil
|
||||
}),
|
||||
)
|
||||
_, _ = meter.Int64ObservableGauge("messenger.db.pool.used",
|
||||
metric.WithDescription("Connections currently acquired from the pgx pool"),
|
||||
metric.WithUnit("{connection}"),
|
||||
metric.WithInt64Callback(func(_ context.Context, o metric.Int64Observer) error {
|
||||
o.Observe(poolUsed.Load())
|
||||
return nil
|
||||
}),
|
||||
)
|
||||
_, _ = meter.Int64ObservableGauge("messenger.db.pool.capacity",
|
||||
metric.WithDescription("Maximum connections configured for the pgx pool"),
|
||||
metric.WithUnit("{connection}"),
|
||||
metric.WithInt64Callback(func(_ context.Context, o metric.Int64Observer) error {
|
||||
o.Observe(poolCapacity.Load())
|
||||
return nil
|
||||
}),
|
||||
)
|
||||
_, _ = meter.Int64ObservableGauge("messenger.worker.busy",
|
||||
metric.WithDescription("1 while the worker is processing a job, otherwise 0"),
|
||||
metric.WithUnit("{worker}"),
|
||||
metric.WithInt64Callback(func(_ context.Context, o metric.Int64Observer) error {
|
||||
o.Observe(workerBusy.Load())
|
||||
return nil
|
||||
}),
|
||||
)
|
||||
_, _ = meter.Int64ObservableGauge("messenger.worker.capacity",
|
||||
metric.WithDescription("Concurrent job slots the worker can occupy"),
|
||||
metric.WithUnit("{worker}"),
|
||||
metric.WithInt64Callback(func(_ context.Context, o metric.Int64Observer) error {
|
||||
o.Observe(workerCapacity)
|
||||
return nil
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
// ─────────────── setters для collector'а (main) ───────────────
|
||||
|
||||
func SetQueueDepth(v int64) { queueDepth.Store(v) }
|
||||
func SetQueueOldestAge(v float64) { queueOldestAge.Store(v) }
|
||||
func SetJobsQueued(v int64) { jobsQueued.Store(v) }
|
||||
func SetJobsOldestQueuedAge(v float64) { jobsOldestQueuedAge.Store(v) }
|
||||
func SetPoolUsed(v int64) { poolUsed.Store(v) }
|
||||
func SetPoolCapacity(v int64) { poolCapacity.Store(v) }
|
||||
func SetWorkerBusy(v int64) { workerBusy.Store(v) }
|
||||
|
||||
// ─────────────── record-функции для worker'а ───────────────
|
||||
|
||||
// RecordJobProcessed фиксирует исход и длительность одной попытки обработки.
|
||||
// outcome: success | permanent_failure | retry_scheduled | retry_exhausted.
|
||||
func RecordJobProcessed(ctx context.Context, jobType, outcome, errorCode string, durationSeconds float64) {
|
||||
attrs := []attribute.KeyValue{
|
||||
attribute.String("job.type", jobType),
|
||||
attribute.String("outcome", outcome),
|
||||
}
|
||||
if errorCode != "" {
|
||||
attrs = append(attrs, attribute.String("error_code", errorCode))
|
||||
}
|
||||
if jobsProcessed != nil {
|
||||
jobsProcessed.Add(ctx, 1, metric.WithAttributes(attrs...))
|
||||
}
|
||||
if jobDuration != nil {
|
||||
jobDuration.Record(ctx, durationSeconds, metric.WithAttributes(
|
||||
attribute.String("job.type", jobType),
|
||||
attribute.String("outcome", outcome),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
// RecordTimeToReady фиксирует end-to-end задержку от durable acceptance до ready.
|
||||
func RecordTimeToReady(ctx context.Context, seconds float64) {
|
||||
if timeToReady != nil {
|
||||
timeToReady.Record(ctx, seconds)
|
||||
}
|
||||
}
|
||||
|
||||
// RecordPoolEmptyAcquire добавляет дельту ожиданий свободного соединения пула.
|
||||
func RecordPoolEmptyAcquire(ctx context.Context, delta int64) {
|
||||
if delta > 0 && poolEmptyAcquires != nil {
|
||||
poolEmptyAcquires.Add(ctx, delta)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
// Package otel — инициализация OpenTelemetry SDK (лаба 6).
|
||||
//
|
||||
// Создаёт три провайдера (tracer, meter, logger) и экспортирует их через
|
||||
// OTLP/HTTP в Collector. Resource attributes (service.name, service.version,
|
||||
// service.instance.id, deployment.environment.name) ставятся один раз при Init
|
||||
// и попадают во все сигналы автоматически — требование observability.md.
|
||||
//
|
||||
// При недоступном Collector SDK не блокирует бизнес-логику: batch-процессоры
|
||||
// буферизуют ограниченное число элементов и дропают излишек, поэтому RAM не
|
||||
// растёт бесконечно (требование уровня 4 про остановку telemetry-хранилища).
|
||||
//
|
||||
// ВАЖНО (найденный дефект): WithEndpointURL перезаписывает путь сигнала путём
|
||||
// из переданного URL. Если передать базовый адрес без пути ("http://otel:4318"),
|
||||
// экспортёр отправит запрос в "/" и Collector ответит 404. Поэтому путь
|
||||
// задаётся явно для каждого сигнала: /v1/traces, /v1/metrics, /v1/logs.
|
||||
package otel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
|
||||
"go.opentelemetry.io/otel/log/global"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
sdklog "go.opentelemetry.io/otel/sdk/log"
|
||||
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
|
||||
"go.opentelemetry.io/otel/sdk/resource"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
|
||||
)
|
||||
|
||||
// Config — параметры инициализации.
|
||||
type Config struct {
|
||||
// Endpoint — базовый URL Collector с схемой, например "http://otel:4318".
|
||||
Endpoint string
|
||||
// ServiceName — "messenger-api" или "messenger-worker".
|
||||
ServiceName string
|
||||
// ServiceVersion — из OTEL_SERVICE_VERSION.
|
||||
ServiceVersion string
|
||||
// InstanceID — уникальный ID реплики (из INSTANCE_ID или hostname+suffix).
|
||||
InstanceID string
|
||||
// Environment — deployment.environment.name, по умолчанию "lab".
|
||||
Environment string
|
||||
}
|
||||
|
||||
// signalURL собирает полный OTLP-URL для конкретного сигнала.
|
||||
// TrimRight защищает от двойного слэша, если в Endpoint пришёл адрес с "/".
|
||||
func signalURL(base, path string) string {
|
||||
return strings.TrimRight(base, "/") + path
|
||||
}
|
||||
|
||||
// Init настраивает global tracer/meter/logger providers.
|
||||
// Возвращает shutdown-функцию, которую нужно defer'ить в main.
|
||||
func Init(ctx context.Context, cfg Config) (shutdown func(context.Context) error, err error) {
|
||||
if cfg.Endpoint == "" {
|
||||
return nil, errors.New("otel: endpoint is empty")
|
||||
}
|
||||
if cfg.Environment == "" {
|
||||
cfg.Environment = "lab"
|
||||
}
|
||||
|
||||
res, err := resource.New(ctx,
|
||||
resource.WithAttributes(
|
||||
semconv.ServiceName(cfg.ServiceName),
|
||||
semconv.ServiceVersion(cfg.ServiceVersion),
|
||||
semconv.ServiceInstanceID(cfg.InstanceID),
|
||||
// deployment.environment.name задаём строкой: конструктор зависит
|
||||
// от версии semconv, а ключ семантической конвенции стабилен.
|
||||
attribute.String("deployment.environment.name", cfg.Environment),
|
||||
),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("otel resource: %w", err)
|
||||
}
|
||||
|
||||
// W3C Trace Context + Baggage — стандартная propagation для переноса
|
||||
// trace context через API → broker → worker.
|
||||
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
|
||||
propagation.TraceContext{},
|
||||
propagation.Baggage{},
|
||||
))
|
||||
|
||||
// --- Traces ---
|
||||
traceExp, err := otlptracehttp.New(ctx,
|
||||
otlptracehttp.WithEndpointURL(signalURL(cfg.Endpoint, "/v1/traces")),
|
||||
otlptracehttp.WithTimeout(5*time.Second),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("otel trace exporter: %w", err)
|
||||
}
|
||||
tp := sdktrace.NewTracerProvider(
|
||||
sdktrace.WithBatcher(traceExp),
|
||||
sdktrace.WithResource(res),
|
||||
// Учебный стенд: сэмплируем всё. На проде — ParentBased(TraceIDRatio).
|
||||
sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample())),
|
||||
)
|
||||
otel.SetTracerProvider(tp)
|
||||
|
||||
// --- Metrics ---
|
||||
metricExp, err := otlpmetrichttp.New(ctx,
|
||||
otlpmetrichttp.WithEndpointURL(signalURL(cfg.Endpoint, "/v1/metrics")),
|
||||
otlpmetrichttp.WithTimeout(5*time.Second),
|
||||
)
|
||||
if err != nil {
|
||||
_ = tp.Shutdown(ctx)
|
||||
return nil, fmt.Errorf("otel metric exporter: %w", err)
|
||||
}
|
||||
mp := sdkmetric.NewMeterProvider(
|
||||
sdkmetric.WithReader(sdkmetric.NewPeriodicReader(metricExp,
|
||||
sdkmetric.WithInterval(5*time.Second),
|
||||
)),
|
||||
sdkmetric.WithResource(res),
|
||||
)
|
||||
otel.SetMeterProvider(mp)
|
||||
|
||||
// Приложения-метрики регистрируются ПОСЛЕ установки MeterProvider,
|
||||
// иначе инструменты создадутся от no-op провайдера и не будут экспортироваться.
|
||||
initAppMetrics()
|
||||
|
||||
// --- Logs ---
|
||||
logExp, err := otlploghttp.New(ctx,
|
||||
otlploghttp.WithEndpointURL(signalURL(cfg.Endpoint, "/v1/logs")),
|
||||
otlploghttp.WithTimeout(5*time.Second),
|
||||
)
|
||||
if err != nil {
|
||||
_ = mp.Shutdown(ctx)
|
||||
_ = tp.Shutdown(ctx)
|
||||
return nil, fmt.Errorf("otel log exporter: %w", err)
|
||||
}
|
||||
lp := sdklog.NewLoggerProvider(
|
||||
sdklog.WithProcessor(sdklog.NewBatchProcessor(logExp)),
|
||||
sdklog.WithResource(res),
|
||||
)
|
||||
global.SetLoggerProvider(lp)
|
||||
|
||||
shutdown = func(ctx context.Context) error {
|
||||
var firstErr error
|
||||
if err := lp.Shutdown(ctx); err != nil && firstErr == nil {
|
||||
firstErr = fmt.Errorf("log provider: %w", err)
|
||||
}
|
||||
if err := mp.Shutdown(ctx); err != nil && firstErr == nil {
|
||||
firstErr = fmt.Errorf("meter provider: %w", err)
|
||||
}
|
||||
if err := tp.Shutdown(ctx); err != nil && firstErr == nil {
|
||||
firstErr = fmt.Errorf("tracer provider: %w", err)
|
||||
}
|
||||
return firstErr
|
||||
}
|
||||
return shutdown, nil
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
// Package otel, redis_hook.go — Redis-инструментация через go-redis Hook (лаба 6).
|
||||
//
|
||||
// Создаёт db client spans для каждой Redis-команды (XADD, XREADGROUP, XACK,
|
||||
// XAUTOCLAIM, GET, SET и т.д.) с атрибутами db.system, db.operation,
|
||||
// db.statement. Работает как в API (producer), так и в worker (consumer).
|
||||
//
|
||||
// Почему собственная реализация, а не contrib/otelredis: в последних релизах
|
||||
// contrib-пакет был удалён для go-redis v9; ручная реализация стабильна.
|
||||
package otel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// RedisTracerHook возвращает go-redis Hook для OTel-инструментации.
|
||||
// Используется в API и worker для создания db client spans.
|
||||
func RedisTracerHook() redis.Hook { return redisTracerHook{} }
|
||||
|
||||
type redisTracerHook struct{}
|
||||
|
||||
// DialHook — go-redis v9: next возвращает net.Conn, а не redis.Conn.
|
||||
// Dial не оборачиваем в span (он происходит один раз на соединение),
|
||||
// просто пробрасываем вызов.
|
||||
func (redisTracerHook) DialHook(next redis.DialHook) redis.DialHook {
|
||||
return func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
return next(ctx, network, addr)
|
||||
}
|
||||
}
|
||||
|
||||
// ProcessHook — создаём span для каждой Redis-команды.
|
||||
func (redisTracerHook) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
|
||||
return func(ctx context.Context, cmd redis.Cmder) error {
|
||||
// LAB 6: инструментируем только команды внутри активной сэмплированной
|
||||
// трассы (XADD в publish, XACK в обработке job). Фоновый polling
|
||||
// (XREADGROUP/XPENDING/XAUTOCLAIM из циклов с корневым контекстом)
|
||||
// не должен порождать корневые трассы — иначе Tempo тонет в шуме.
|
||||
if sc := trace.SpanContextFromContext(ctx); !sc.IsValid() || !sc.IsSampled() {
|
||||
return next(ctx, cmd)
|
||||
}
|
||||
|
||||
cmdName := strings.ToUpper(cmd.Name())
|
||||
ctx, span := otel.Tracer("messenger-redis").Start(ctx, "redis "+cmdName,
|
||||
trace.WithSpanKind(trace.SpanKindClient),
|
||||
trace.WithAttributes(
|
||||
attribute.String("db.system", "redis"),
|
||||
attribute.String("db.operation", cmdName),
|
||||
attribute.String("db.statement", truncateStmt(cmd.String(), 512)),
|
||||
),
|
||||
)
|
||||
err := next(ctx, cmd)
|
||||
if err != nil && err != redis.Nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
}
|
||||
span.End()
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// ProcessPipelineHook — пайплайны проходят как есть.
|
||||
func (redisTracerHook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook {
|
||||
return func(ctx context.Context, cmds []redis.Cmder) error {
|
||||
return next(ctx, cmds)
|
||||
}
|
||||
}
|
||||
|
||||
// truncateStmt обрезает длинные statements для атрибутов span, чтобы не
|
||||
// раздувать хранилище трасс большими XADD-payload.
|
||||
func truncateStmt(s string, maxLen int) string {
|
||||
if len(s) <= maxLen {
|
||||
return s
|
||||
}
|
||||
return s[:maxLen] + "..."
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
// Package otel, slog_bridge.go — «тройник» логов: stdout (JSON) + OTel Logs.
|
||||
//
|
||||
// Почему официальный мост otelslog, а не ручная сборка записей:
|
||||
// конструкторы значений OTel log API (KeyValue/StringValue/...) менялись между
|
||||
// версиями модуля, и ручной код ломается при любом сдвиге версий. Официальный
|
||||
// мост скомпилирован против того же SDK, сам строит записи и сам проставляет
|
||||
// trace_id/span_id из активного span в контексте (требование observability.md).
|
||||
//
|
||||
// В stdout мы дополнительно дублируем trace_id/span_id обычными slog-атрибутами,
|
||||
// чтобы структурный лог в контейнере тоже содержал связку с трассой.
|
||||
package otel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
|
||||
"go.opentelemetry.io/contrib/bridges/otelslog"
|
||||
"go.opentelemetry.io/otel/log/global"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// teeHandler — slog.Handler, пишущий в два приёмника.
|
||||
type teeHandler struct {
|
||||
stdout slog.Handler
|
||||
otel slog.Handler
|
||||
}
|
||||
|
||||
// NewSlogOTelHandler создаёт хендлер: stdout JSON + OTLP через официальный мост.
|
||||
// LoggerProvider берётся из global (установлен в Init); если OTel не
|
||||
// инициализирован, global возвращает no-op провайдер и ветка OTel ничего не шлёт.
|
||||
func NewSlogOTelHandler(level slog.Level) slog.Handler {
|
||||
return &teeHandler{
|
||||
stdout: slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: level}),
|
||||
otel: otelslog.NewHandler("messenger",
|
||||
otelslog.WithLoggerProvider(global.GetLoggerProvider())),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *teeHandler) Enabled(ctx context.Context, level slog.Level) bool {
|
||||
return h.stdout.Enabled(ctx, level) || h.otel.Enabled(ctx, level)
|
||||
}
|
||||
|
||||
func (h *teeHandler) Handle(ctx context.Context, r slog.Record) error {
|
||||
// stdout: добавляем trace_id/span_id явными атрибутами (связка лог↔трасса
|
||||
// видна и в docker logs, и в Loki после filelog/OTLP-приёма).
|
||||
if sc := trace.SpanContextFromContext(ctx); sc.IsValid() {
|
||||
nr := slog.NewRecord(r.Time, r.Level, r.Message, r.PC)
|
||||
r.Attrs(func(a slog.Attr) bool {
|
||||
nr.AddAttrs(a)
|
||||
return true
|
||||
})
|
||||
nr.AddAttrs(
|
||||
slog.String("trace_id", sc.TraceID().String()),
|
||||
slog.String("span_id", sc.SpanID().String()),
|
||||
)
|
||||
if err := h.stdout.Handle(ctx, nr); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if err := h.stdout.Handle(ctx, r); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// OTel: мост сам возьмёт trace context из ctx и положит trace_id/span_id
|
||||
// в поля OTLP-записи.
|
||||
return h.otel.Handle(ctx, r)
|
||||
}
|
||||
|
||||
func (h *teeHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||
return &teeHandler{
|
||||
stdout: h.stdout.WithAttrs(attrs),
|
||||
otel: h.otel.WithAttrs(attrs),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *teeHandler) WithGroup(name string) slog.Handler {
|
||||
return &teeHandler{
|
||||
stdout: h.stdout.WithGroup(name),
|
||||
otel: h.otel.WithGroup(name),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// Package otel, suppress.go — подавление трассировки фоновых циклов (лаба 6).
|
||||
//
|
||||
// Зачем: периодические опросы (XREADGROUP BLOCK, XPENDING, SQL-статистика пула)
|
||||
// не являются бизнес-операциями. Если инструментация создаёт для них корневые
|
||||
// spans, Tempo заполняется шумом, ingest растёт, а полезные трассы upload→job
|
||||
// теряются среди пустых опросов.
|
||||
//
|
||||
// Как: кладём в контекст ВАЛИДНЫЙ, но NOT-sampled SpanContext. С сэмплером
|
||||
// ParentBased все дочерние spans становятся non-recording и не экспортируются.
|
||||
// Бизнес-контексты (HTTP-запрос, обработка job) не затрагиваются.
|
||||
package otel
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// unsampledParent — валидный TraceID/SpanID с TraceFlags=0 (not sampled).
|
||||
// Именно валидность важна: невалидный контекст ParentBased трактует как
|
||||
// "корень" и сэмплирует заново.
|
||||
var unsampledParent = trace.NewSpanContext(trace.SpanContextConfig{
|
||||
TraceID: trace.TraceID{1},
|
||||
SpanID: trace.SpanID{1},
|
||||
TraceFlags: 0,
|
||||
})
|
||||
|
||||
// SuppressTracing возвращает контекст, в котором дочерние spans не записываются.
|
||||
// Применять только к фоновым/служебным циклам, никогда — к обработке запроса.
|
||||
func SuppressTracing(ctx context.Context) context.Context {
|
||||
return trace.ContextWithSpanContext(ctx, unsampledParent)
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// Package store, attach.go — внутренний доступ к вложению (без проверки членства)
|
||||
// и соглашение об object key лабы 5.
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"mtusi-messenger/internal/model"
|
||||
)
|
||||
|
||||
// StagingKey — ключ принятого оригинала до обработки.
|
||||
func StagingKey(chatID, attachmentID string) string {
|
||||
return "staging/" + chatID + "/" + attachmentID
|
||||
}
|
||||
|
||||
// VariantKey — ключ финального объекта: оригинала или варианта.
|
||||
// variant == "original" даёт ключ финального оригинала (совпадает с s3_key).
|
||||
func VariantKey(chatID, attachmentID, variant string) string {
|
||||
return chatID + "/" + attachmentID + "/" + variant
|
||||
}
|
||||
|
||||
const attachCols = ` id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
s3_key, status, error_code, variants, pipeline_version, processing_started_at,
|
||||
created_at, updated_at`
|
||||
|
||||
// GetAttachmentInternal — полное вложение для worker/reconcile (без ACL).
|
||||
// ACL применяется только в публичных хендлерах.
|
||||
func (s *Store) GetAttachmentInternal(ctx context.Context, id string) (*model.Attachment, error) {
|
||||
return scanAttachment(s.pool.QueryRow(ctx, `SELECT`+attachCols+` FROM attachments WHERE id = $1`, id))
|
||||
}
|
||||
|
||||
func scanAttachment(row pgx.Row) (*model.Attachment, error) {
|
||||
var a model.Attachment
|
||||
var createdAt, updatedAt time.Time
|
||||
var variantsRaw []byte
|
||||
var errCode *string
|
||||
var startedAt *time.Time
|
||||
err := row.Scan(
|
||||
&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType,
|
||||
&a.SizeBytes, &a.SHA256, &a.S3Key, &a.Status, &errCode,
|
||||
&variantsRaw, &a.PipelineVersion, &startedAt, &createdAt, &updatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.ErrorCode = errCode
|
||||
a.ProcessingStartedAt = startedAt
|
||||
a.CreatedAt = model.Timestamp{Time: createdAt.UTC()}
|
||||
a.UpdatedAt = model.Timestamp{Time: updatedAt.UTC()}
|
||||
a.Variants = []model.Variant{}
|
||||
if len(variantsRaw) > 0 {
|
||||
if err := json.Unmarshal(variantsRaw, &a.Variants); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return &a, nil
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"mtusi-messenger/internal/model"
|
||||
)
|
||||
|
||||
// redisTimeout — максимальное время на одну Redis-операцию.
|
||||
// При недоступном Redis клиент быстро возвращает ошибку, и мы деградируем
|
||||
// в SQL, а не блокируем запрос (требование уровня 4 про потерю сервиса).
|
||||
const redisTimeout = 300 * time.Millisecond
|
||||
|
||||
// ─────────────── Кэш сессий (уровень 4) ───────────────
|
||||
|
||||
func sessKey(hash [sha256.Size]byte) string { return "sess:" + hex.EncodeToString(hash[:]) }
|
||||
|
||||
// cacheSessionPut: TTL кэша = остаток срока сессии (политика expiry согласована
|
||||
// с источником истины); при ошибке Redis — только warn, запрос живёт через SQL.
|
||||
func (s *Store) cacheSessionPut(ctx context.Context, hash [sha256.Size]byte, userID string, expiresAt time.Time) {
|
||||
if s.rdb == nil {
|
||||
return
|
||||
}
|
||||
ttl := time.Until(expiresAt)
|
||||
if ttl <= 0 {
|
||||
return
|
||||
}
|
||||
val := userID + "|" + expiresAt.Format(time.RFC3339Nano)
|
||||
rctx, cancel := context.WithTimeout(ctx, redisTimeout)
|
||||
defer cancel()
|
||||
if err := s.rdb.Set(rctx, sessKey(hash), val, ttl).Err(); err != nil {
|
||||
s.log.Warn("redis set failed, degrading to postgres", "error", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// cacheSessionGet: miss (redis.Nil) — норма; ошибка/таймаут Redis — деградация;
|
||||
// истёкшее значение в кэше не доверяем (двойная страховка помимо TTL).
|
||||
func (s *Store) cacheSessionGet(ctx context.Context, hash [sha256.Size]byte) (string, bool) {
|
||||
if s.rdb == nil {
|
||||
return "", false
|
||||
}
|
||||
rctx, cancel := context.WithTimeout(ctx, redisTimeout)
|
||||
defer cancel()
|
||||
val, err := s.rdb.Get(rctx, sessKey(hash)).Result()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return "", false
|
||||
}
|
||||
if err != nil {
|
||||
s.log.Warn("redis get failed, degrading to postgres", "error", err.Error())
|
||||
return "", false
|
||||
}
|
||||
parts := strings.SplitN(val, "|", 2)
|
||||
if len(parts) != 2 {
|
||||
return "", false
|
||||
}
|
||||
exp, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil || time.Now().UTC().After(exp) {
|
||||
return "", false
|
||||
}
|
||||
return parts[0], true
|
||||
}
|
||||
|
||||
func (s *Store) cacheSessionDel(ctx context.Context, hash [sha256.Size]byte) error {
|
||||
if s.rdb == nil {
|
||||
return nil
|
||||
}
|
||||
rctx, cancel := context.WithTimeout(ctx, redisTimeout)
|
||||
defer cancel()
|
||||
return s.rdb.Del(rctx, sessKey(hash)).Err()
|
||||
}
|
||||
|
||||
// ─────────────── Версия чата (инвалидация кэша истории, трек 5) ───────────────
|
||||
|
||||
func chatVerKey(chatID string) string { return "chatver:" + chatID }
|
||||
|
||||
func (s *Store) bumpChatVersion(ctx context.Context, chatID string) {
|
||||
if s.rdb == nil {
|
||||
return
|
||||
}
|
||||
var err error
|
||||
for attempt := 1; attempt <= 3; attempt++ {
|
||||
rctx, cancel := context.WithTimeout(ctx, redisTimeout)
|
||||
err = s.rdb.Incr(rctx, chatVerKey(chatID)).Err()
|
||||
cancel()
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
s.log.Warn("redis incr failed, retrying", "attempt", attempt, "error", err.Error())
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
s.log.Warn("redis incr failed after retries; history cache bounded stale until TTL", "error", err.Error())
|
||||
}
|
||||
|
||||
// ChatVersion: 0 при отсутствии Redis/ключа — кэш истории тогда не используется,
|
||||
// корректность не страдает.
|
||||
func (s *Store) ChatVersion(ctx context.Context, chatID string) int64 {
|
||||
if s.rdb == nil {
|
||||
return 0
|
||||
}
|
||||
rctx, cancel := context.WithTimeout(ctx, redisTimeout)
|
||||
defer cancel()
|
||||
v, err := s.rdb.Get(rctx, chatVerKey(chatID)).Int64()
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// ─────────────── Кэш истории (трек 5) ───────────────
|
||||
|
||||
// HistoryCacheKey — ключ страницы истории: версия чата + параметры запроса.
|
||||
// Версия в ключе — это и есть защита от stale read.
|
||||
func HistoryCacheKey(chatID string, version int64, cursorJSON string, limit int) string {
|
||||
return fmt.Sprintf("hist:v%d:%s:%s:%d", version, chatID, cursorJSON, limit)
|
||||
}
|
||||
|
||||
// CacheHistoryPut — положить страницу в кэш. TTL 60 c: кэш для горячего чтения,
|
||||
// не долгосрочное хранилище; источник истины остаётся Postgres.
|
||||
func (s *Store) CacheHistoryPut(ctx context.Context, key string, messages []*model.Message, hasMore bool) {
|
||||
if s.rdb == nil {
|
||||
return
|
||||
}
|
||||
data := map[string]any{
|
||||
"items": messages,
|
||||
"has_more": hasMore,
|
||||
"cached_at": time.Now().UTC().Format(time.RFC3339Nano),
|
||||
}
|
||||
b, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
rctx, cancel := context.WithTimeout(ctx, redisTimeout)
|
||||
defer cancel()
|
||||
if err := s.rdb.Set(rctx, key, b, 60*time.Second).Err(); err != nil {
|
||||
s.log.Warn("redis history set failed", "error", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// CacheHistoryGet — достать страницу из кэша: (items, hasMore, ok).
|
||||
// ok=false означает miss или ошибку Redis — тогда идём в SQL.
|
||||
func (s *Store) CacheHistoryGet(ctx context.Context, key string) ([]*model.Message, bool, bool) {
|
||||
if s.rdb == nil {
|
||||
return nil, false, false
|
||||
}
|
||||
rctx, cancel := context.WithTimeout(ctx, redisTimeout)
|
||||
defer cancel()
|
||||
val, err := s.rdb.Get(rctx, key).Result()
|
||||
if err != nil {
|
||||
return nil, false, false
|
||||
}
|
||||
var data struct {
|
||||
Items []*model.Message `json:"items"`
|
||||
HasMore bool `json:"has_more"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(val), &data); err != nil {
|
||||
return nil, false, false
|
||||
}
|
||||
return data.Items, data.HasMore, true
|
||||
}
|
||||
|
||||
// ─────────────── Single-flight (защита от cache stampede) ───────────────
|
||||
// При конкурирующих холодных чтениях одного ключа только один поток выполняет
|
||||
// fn; остальные ждут его результат. Без этого N конкурентных miss дали бы N
|
||||
// SQL-запросов («лавиной») — это и есть cache stampede.
|
||||
|
||||
type SingleFlight struct {
|
||||
mu sync.Mutex
|
||||
m map[string]*call
|
||||
}
|
||||
|
||||
type call struct {
|
||||
wg sync.WaitGroup
|
||||
val any
|
||||
err error
|
||||
}
|
||||
|
||||
func NewSingleFlight() *SingleFlight {
|
||||
return &SingleFlight{m: make(map[string]*call)}
|
||||
}
|
||||
|
||||
// Do выполняет fn только если нет активного вызова с тем же key; иначе ждёт
|
||||
// готовый результат того вызова.
|
||||
func (sf *SingleFlight) Do(key string, fn func() (any, error)) (any, error) {
|
||||
sf.mu.Lock()
|
||||
if c, ok := sf.m[key]; ok {
|
||||
sf.mu.Unlock()
|
||||
c.wg.Wait()
|
||||
return c.val, c.err
|
||||
}
|
||||
c := new(call)
|
||||
c.wg.Add(1)
|
||||
sf.m[key] = c
|
||||
sf.mu.Unlock()
|
||||
|
||||
c.val, c.err = fn()
|
||||
c.wg.Done()
|
||||
|
||||
sf.mu.Lock()
|
||||
delete(sf.m, key)
|
||||
sf.mu.Unlock()
|
||||
|
||||
return c.val, c.err
|
||||
}
|
||||
|
||||
// EncodeCursorJSON — компактное представление курсора для ключа кэша.
|
||||
func EncodeCursorJSON(c *Cursor) string {
|
||||
if c == nil {
|
||||
return "null"
|
||||
}
|
||||
b, _ := json.Marshal(c)
|
||||
return base64.RawURLEncoding.EncodeToString(b)
|
||||
}
|
||||
@@ -0,0 +1,516 @@
|
||||
// Package store, jobs.go — жизненный цикл заданий обработки и transactional
|
||||
// outbox (лаба 5).
|
||||
//
|
||||
// Инварианты:
|
||||
// - намерение обработать (attachment + job + outbox) фиксируется ОДНОЙ
|
||||
// транзакцией до ответа 202;
|
||||
// - публикация в брокер — отдельный relay, читающий outbox; разрыв
|
||||
// COMMIT -> publish восстанавливается автоматически;
|
||||
// - claim атомарен: одну job не берут два worker'а (lease + статус-гард);
|
||||
// - результат (ready/failed/retry) пишется транзакцией вместе с attachment;
|
||||
// - ack только после COMMIT результата.
|
||||
//
|
||||
// LAB 6: W3C trace context инжектируется в каждое outbox-сообщение через
|
||||
// InjectTraceContext(ctx, &msg) — чтобы трасса инициатора дожила до publish.
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"mtusi-messenger/internal/model"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultMaxAttempts — ограниченный retry (требование уровня 3).
|
||||
DefaultMaxAttempts = 5
|
||||
// LeaseTTL — аренда обработки; после истечения job считается зависшей.
|
||||
LeaseTTL = 60 * time.Second
|
||||
)
|
||||
|
||||
// ClaimedJob — успешно захваченная работа.
|
||||
type ClaimedJob struct {
|
||||
JobID string
|
||||
AttachmentID string
|
||||
Attempt int
|
||||
PipelineVersion int
|
||||
}
|
||||
|
||||
// CreateQueuedAttachment — атомарная фиксация принятого оригинала:
|
||||
// attachment(status=queued) + job + outbox-сообщение в ОДНОЙ транзакции.
|
||||
// Вызывается до ответа 202: после commit работа не теряется даже при падении API.
|
||||
func (s *Store) CreateQueuedAttachment(ctx context.Context, att *model.Attachment) (*model.Attachment, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
now := model.NowTS()
|
||||
att.Status = model.StatusQueued
|
||||
att.Variants = []model.Variant{}
|
||||
att.ErrorCode = nil
|
||||
att.PipelineVersion = 1
|
||||
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO attachments
|
||||
(id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
s3_key, status, error_code, pipeline_version, created_at, updated_at)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)`,
|
||||
att.ID, att.ChatID, att.OwnerID, att.Filename, att.ContentType,
|
||||
att.SizeBytes, att.SHA256, att.S3Key, att.Status, att.ErrorCode,
|
||||
att.PipelineVersion, now.Time, now.Time)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
jobID := uuid.NewString()
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO jobs
|
||||
(id, attachment_id, status, attempt, max_attempts, pipeline_version, created_at, updated_at)
|
||||
VALUES ($1,$2,$3,0,$4,$5,$6,$7)`,
|
||||
jobID, att.ID, model.StatusQueued, DefaultMaxAttempts,
|
||||
att.PipelineVersion, now.Time, now.Time)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msg := model.JobMessage{
|
||||
SchemaVersion: 1,
|
||||
JobID: jobID,
|
||||
Type: "attachment.process.v1",
|
||||
AttachmentID: att.ID,
|
||||
PipelineVersion: att.PipelineVersion,
|
||||
Attempt: 1,
|
||||
CreatedAt: now.Time.UTC().Format("2006-01-02T15:04:05.000Z"),
|
||||
}
|
||||
// LAB 6: трасса инициатора (HTTP upload) сохраняется в outbox-сообщении.
|
||||
InjectTraceContext(ctx, &msg)
|
||||
|
||||
payload, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO outbox (id, aggregate_type, aggregate_id, event_type, payload, created_at)
|
||||
VALUES ($1,$2,$3,$4,$5,$6)`,
|
||||
uuid.NewString(), "attachment", att.ID, msg.Type, payload, now.Time)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
att.CreatedAt = now
|
||||
att.UpdatedAt = now
|
||||
return att, nil
|
||||
}
|
||||
|
||||
// ─────────────── Outbox relay ───────────────
|
||||
|
||||
// FetchUnpublishedOutbox — порция неопубликованных намерений (старые сначала).
|
||||
func (s *Store) FetchUnpublishedOutbox(ctx context.Context, limit int) ([]model.OutboxMessage, error) {
|
||||
rows, err := s.pool.Query(ctx, `SELECT id, aggregate_type, aggregate_id, event_type, payload, created_at FROM outbox WHERE published_at IS NULL ORDER BY created_at LIMIT $1`, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []model.OutboxMessage
|
||||
for rows.Next() {
|
||||
var m model.OutboxMessage
|
||||
var createdAt time.Time
|
||||
if err := rows.Scan(&m.ID, &m.AggregateType, &m.AggregateID, &m.EventType, &m.Payload, &createdAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m.CreatedAt = model.Timestamp{Time: createdAt.UTC()}
|
||||
out = append(out, m)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// MarkOutboxPublished — отметить опубликованным ПОСЛЕ успеха XADD.
|
||||
func (s *Store) MarkOutboxPublished(ctx context.Context, id string) error {
|
||||
_, err := s.pool.Exec(ctx, `UPDATE outbox SET published_at = now() WHERE id = $1`, id)
|
||||
return err
|
||||
}
|
||||
|
||||
// ─────────────── Worker: claim / complete / fail / retry ───────────────
|
||||
|
||||
// ClaimJob — атомарный захват работы с lease.
|
||||
func (s *Store) ClaimJob(ctx context.Context, jobID string, attempt int, leaseID string, expiresAt time.Time) (*ClaimedJob, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
var c ClaimedJob
|
||||
err = tx.QueryRow(ctx, `
|
||||
UPDATE jobs
|
||||
SET status = 'processing',
|
||||
attempt = GREATEST(jobs.attempt, $2),
|
||||
lease_id = $3,
|
||||
lease_expires_at = $4,
|
||||
updated_at = now()
|
||||
WHERE id = $1
|
||||
AND (
|
||||
(status = 'queued' AND (next_attempt_at IS NULL OR next_attempt_at <= now()))
|
||||
OR (status = 'processing' AND lease_expires_at < now() AND attempt < max_attempts)
|
||||
)
|
||||
RETURNING id, attachment_id, attempt, pipeline_version`,
|
||||
jobID, attempt, leaseID, expiresAt.UTC()).
|
||||
Scan(&c.JobID, &c.AttachmentID, &c.Attempt, &c.PipelineVersion)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, `
|
||||
UPDATE attachments
|
||||
SET status = 'processing', processing_started_at = now(), updated_at = now()
|
||||
WHERE id = $1 AND status IN ('queued','processing')`, c.AttachmentID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
// CompleteJob — атомарная фиксация результата.
|
||||
func (s *Store) CompleteJob(ctx context.Context, attachmentID string, variants []model.Variant) error {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
b, err := json.Marshal(variants)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `
|
||||
UPDATE attachments
|
||||
SET status = 'ready', variants = $2, error_code = NULL, updated_at = now()
|
||||
WHERE id = $1 AND status IN ('processing','queued')`, attachmentID, b)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `
|
||||
UPDATE jobs
|
||||
SET status = 'ready', lease_id = NULL, lease_expires_at = NULL,
|
||||
error_code = NULL, error_message = NULL, updated_at = now()
|
||||
WHERE attachment_id = $1 AND status IN ('processing','queued')`, attachmentID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// FailJob — терминальный отказ с машинным error_code и записью в реестр failed.
|
||||
func (s *Store) FailJob(ctx context.Context, attachmentID, code, message string) error {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
var jobID string
|
||||
var attempt int
|
||||
err = tx.QueryRow(ctx, `
|
||||
SELECT id, attempt FROM jobs WHERE attachment_id = $1`, attachmentID).Scan(&jobID, &attempt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `
|
||||
UPDATE attachments
|
||||
SET status = 'failed', error_code = $2, variants = '[]', updated_at = now()
|
||||
WHERE id = $1`, attachmentID, code)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `
|
||||
UPDATE jobs
|
||||
SET status = 'failed', lease_id = NULL, lease_expires_at = NULL,
|
||||
error_code = $2, error_message = $3, updated_at = now()
|
||||
WHERE id = $1`, jobID, code, message)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO job_failures (id, job_id, attachment_id, error_code, error_message, attempt, failed_at)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,now())`,
|
||||
uuid.NewString(), jobID, attachmentID, code, message, attempt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// ScheduleRetry — временная ошибка: job возвращается в queued с отложенной
|
||||
// попыткой, намерение опубликовать сообщение пишется в outbox той же транзакцией.
|
||||
func (s *Store) ScheduleRetry(ctx context.Context, attachmentID string, nextAt time.Time, tempCode string) (bool, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
var jobID string
|
||||
var attempt, pipelineVersion int
|
||||
err = tx.QueryRow(ctx, `
|
||||
UPDATE jobs
|
||||
SET status = 'queued', lease_id = NULL, lease_expires_at = NULL,
|
||||
next_attempt_at = $2, error_code = $3, updated_at = now()
|
||||
WHERE attachment_id = $1 AND status = 'processing'
|
||||
RETURNING id, attempt, pipeline_version`, attachmentID, nextAt.UTC(), tempCode).
|
||||
Scan(&jobID, &attempt, &pipelineVersion)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, `
|
||||
UPDATE attachments SET status = 'queued', updated_at = now()
|
||||
WHERE id = $1`, attachmentID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
msg := model.JobMessage{
|
||||
SchemaVersion: 1,
|
||||
JobID: jobID,
|
||||
Type: "attachment.process.v1",
|
||||
AttachmentID: attachmentID,
|
||||
PipelineVersion: pipelineVersion,
|
||||
Attempt: attempt + 1,
|
||||
CreatedAt: time.Now().UTC().Format("2006-01-02T15:04:05.000Z"),
|
||||
}
|
||||
// LAB 6: контекст worker'а (consumer span) сохраняется в outbox.
|
||||
InjectTraceContext(ctx, &msg)
|
||||
|
||||
payload, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO outbox (id, aggregate_type, aggregate_id, event_type, payload, created_at)
|
||||
VALUES ($1,$2,$3,$4,$5,now())`,
|
||||
uuid.NewString(), "attachment", attachmentID, msg.Type, payload)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// ReapExpiredLeases — защита от зависшего processing.
|
||||
// ВАЖНО: результат каждого RETURNING-запроса сначала полностью вычитывается
|
||||
// и закрывается, потом выполняются tx.Exec (транзакция pgx держит одно соединение).
|
||||
func (s *Store) ReapExpiredLeases(ctx context.Context) (int, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
type reapedJob struct {
|
||||
jobID string
|
||||
attachmentID string
|
||||
attempt int
|
||||
pipeline int
|
||||
}
|
||||
|
||||
// ── 1. Истёкшая аренда, попытки остались → обратно в queued ──
|
||||
rows, err := tx.Query(ctx, `
|
||||
UPDATE jobs
|
||||
SET status = 'queued', lease_id = NULL, lease_expires_at = NULL,
|
||||
next_attempt_at = now(), updated_at = now()
|
||||
WHERE status = 'processing' AND lease_expires_at < now() AND attempt < max_attempts
|
||||
RETURNING id, attachment_id, attempt, pipeline_version`)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var requeued []reapedJob
|
||||
for rows.Next() {
|
||||
var r reapedJob
|
||||
if err := rows.Scan(&r.jobID, &r.attachmentID, &r.attempt, &r.pipeline); err != nil {
|
||||
rows.Close()
|
||||
return 0, err
|
||||
}
|
||||
requeued = append(requeued, r)
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
for _, r := range requeued {
|
||||
if _, err := tx.Exec(ctx, `
|
||||
UPDATE attachments SET status = 'queued', updated_at = now()
|
||||
WHERE id = $1`, r.attachmentID); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
msg := model.JobMessage{
|
||||
SchemaVersion: 1,
|
||||
JobID: r.jobID,
|
||||
Type: "attachment.process.v1",
|
||||
AttachmentID: r.attachmentID,
|
||||
PipelineVersion: r.pipeline,
|
||||
Attempt: r.attempt + 1,
|
||||
CreatedAt: time.Now().UTC().Format("2006-01-02T15:04:05.000Z"),
|
||||
}
|
||||
// LAB 6: контекст reaper'а сохраняется в outbox.
|
||||
InjectTraceContext(ctx, &msg)
|
||||
payload, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO outbox (id, aggregate_type, aggregate_id, event_type, payload, created_at)
|
||||
VALUES ($1,$2,$3,$4,$5,now())`,
|
||||
uuid.NewString(), "attachment", r.attachmentID, msg.Type, payload); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
// ── 2. Истёкшая аренда, попытки исчерпаны → failed ──
|
||||
exhaustedRows, err := tx.Query(ctx, `
|
||||
UPDATE jobs
|
||||
SET status = 'failed', lease_id = NULL, lease_expires_at = NULL,
|
||||
error_code = 'retry_exhausted', error_message = 'lease expired with no attempts left',
|
||||
updated_at = now()
|
||||
WHERE status = 'processing' AND lease_expires_at < now() AND attempt >= max_attempts
|
||||
RETURNING id, attachment_id, attempt`)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var exhausted []reapedJob
|
||||
for exhaustedRows.Next() {
|
||||
var r reapedJob
|
||||
if err := exhaustedRows.Scan(&r.jobID, &r.attachmentID, &r.attempt); err != nil {
|
||||
exhaustedRows.Close()
|
||||
return 0, err
|
||||
}
|
||||
exhausted = append(exhausted, r)
|
||||
}
|
||||
exhaustedRows.Close()
|
||||
if err := exhaustedRows.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
for _, r := range exhausted {
|
||||
if _, err := tx.Exec(ctx, `
|
||||
UPDATE attachments
|
||||
SET status = 'failed', error_code = 'retry_exhausted', variants = '[]', updated_at = now()
|
||||
WHERE id = $1`, r.attachmentID); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO job_failures (id, job_id, attachment_id, error_code, error_message, attempt, failed_at)
|
||||
VALUES ($1,$2,$3,'retry_exhausted','lease expired with no attempts left',$4,now())`,
|
||||
uuid.NewString(), r.jobID, r.attachmentID, r.attempt); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(requeued), nil
|
||||
}
|
||||
|
||||
// EnqueueDueRetries — планировщик отложенных повторов.
|
||||
func (s *Store) EnqueueDueRetries(ctx context.Context) (int, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
rows, err := tx.Query(ctx, `
|
||||
UPDATE jobs
|
||||
SET next_attempt_at = NULL, updated_at = now()
|
||||
WHERE status = 'queued' AND next_attempt_at IS NOT NULL AND next_attempt_at <= now()
|
||||
RETURNING id, attachment_id, attempt, pipeline_version`)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
type dueJob struct {
|
||||
jobID string
|
||||
attachmentID string
|
||||
attempt int
|
||||
pipeline int
|
||||
}
|
||||
var due []dueJob
|
||||
for rows.Next() {
|
||||
var d dueJob
|
||||
if err := rows.Scan(&d.jobID, &d.attachmentID, &d.attempt, &d.pipeline); err != nil {
|
||||
rows.Close()
|
||||
return 0, err
|
||||
}
|
||||
due = append(due, d)
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
for _, d := range due {
|
||||
msg := model.JobMessage{
|
||||
SchemaVersion: 1,
|
||||
JobID: d.jobID,
|
||||
Type: "attachment.process.v1",
|
||||
AttachmentID: d.attachmentID,
|
||||
PipelineVersion: d.pipeline,
|
||||
Attempt: d.attempt + 1,
|
||||
CreatedAt: time.Now().UTC().Format("2006-01-02T15:04:05.000Z"),
|
||||
}
|
||||
// LAB 6: контекст планировщика сохраняется в outbox.
|
||||
InjectTraceContext(ctx, &msg)
|
||||
payload, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO outbox (id, aggregate_type, aggregate_id, event_type, payload, created_at)
|
||||
VALUES ($1,$2,$3,$4,$5,now())`,
|
||||
uuid.NewString(), "attachment", d.attachmentID, msg.Type, payload); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(due), nil
|
||||
}
|
||||
|
||||
// JobQueueStats — глубина и возраст очереди заданий в PostgreSQL.
|
||||
// LAB 6: источник данных для метрик messenger.jobs.queued и
|
||||
// messenger.jobs.oldest_queued_age (observable gauge).
|
||||
func (s *Store) JobQueueStats(ctx context.Context) (queued int64, oldestAgeSeconds float64, err error) {
|
||||
err = s.pool.QueryRow(ctx, `
|
||||
SELECT
|
||||
count(*) FILTER (WHERE status = 'queued'),
|
||||
COALESCE(
|
||||
EXTRACT(EPOCH FROM (now() - MIN(created_at))) FILTER (WHERE status = 'queued'),
|
||||
0
|
||||
)
|
||||
FROM jobs`).Scan(&queued, &oldestAgeSeconds)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
return queued, oldestAgeSeconds, nil
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrationsFS embed.FS
|
||||
|
||||
// RunMigrations запускает все миграции из папки migrations/ по алфавиту.
|
||||
// Идемпотентно: IF NOT EXISTS в SQL защищает от дублей.
|
||||
func RunMigrations(ctx context.Context, pool *pgxpool.Pool, log *slog.Logger) error {
|
||||
entries, err := fs.ReadDir(migrationsFS, "migrations")
|
||||
if err != nil {
|
||||
return fmt.Errorf("read migrations dir: %w", err)
|
||||
}
|
||||
|
||||
// Сортируем по имени файла (0001_init.sql, 0002_..., ...)
|
||||
var files []string
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() && strings.HasSuffix(e.Name(), ".sql") {
|
||||
files = append(files, e.Name())
|
||||
}
|
||||
}
|
||||
sort.Strings(files)
|
||||
|
||||
for _, name := range files {
|
||||
sql, err := fs.ReadFile(migrationsFS, filepath.Join("migrations", name))
|
||||
if err != nil {
|
||||
return fmt.Errorf("read migration %s: %w", name, err)
|
||||
}
|
||||
log.Info("running migration", "file", name)
|
||||
if _, err := pool.Exec(ctx, string(sql)); err != nil {
|
||||
return fmt.Errorf("exec migration %s: %w", name, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
-- Все операции идемпотентны (IF NOT EXISTS)
|
||||
|
||||
-- Пользователи
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL,
|
||||
display_name text NOT NULL,
|
||||
password_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT users_username_re CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
CONSTRAINT users_name_len CHECK (char_length(display_name) BETWEEN 1 AND 100)
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS users_username_key ON users (username);
|
||||
|
||||
-- Чаты
|
||||
CREATE TABLE IF NOT EXISTS chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- Участники чатов
|
||||
CREATE TABLE IF NOT EXISTS chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS chat_members_user_idx ON chat_members (user_id, chat_id);
|
||||
|
||||
-- Сообщения
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id uuid NOT NULL,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
sender_id uuid NOT NULL REFERENCES users(id),
|
||||
text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (chat_id, id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS messages_history_idx ON messages (chat_id, created_at, id);
|
||||
|
||||
-- Сессии (источник истины)
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token_hash bytea PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
expires_at timestamptz NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS sessions_expires_idx ON sessions (expires_at);
|
||||
@@ -0,0 +1,14 @@
|
||||
-- Lab 3: идемпотентность отправки сообщений.
|
||||
-- Все операции идемпотентны (IF NOT EXISTS).
|
||||
|
||||
-- Область ключа: (chat_id, sender_id, idempotency_key).
|
||||
-- Это пользователь + путь + ключ для фиксированного метода POST.
|
||||
|
||||
ALTER TABLE messages
|
||||
ADD COLUMN IF NOT EXISTS idempotency_key text;
|
||||
|
||||
-- У старых сообщений ключа нет (NULL).
|
||||
-- В Postgres NULL'ы в уникальном индексе считаются различающимися,
|
||||
-- поэтому старый контент не нарушит уникальность.
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS messages_idempotency_uq
|
||||
ON messages (chat_id, sender_id, idempotency_key);
|
||||
@@ -0,0 +1,27 @@
|
||||
CREATE TABLE IF NOT EXISTS 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, -- 'image/png' | 'image/jpeg' (MIME по содержимому)
|
||||
size_bytes bigint NOT NULL CHECK (size_bytes >= 1 AND size_bytes <= 10485760),
|
||||
sha256 text NOT NULL, -- lowercase hex, 64 символа
|
||||
s3_key text NOT NULL UNIQUE, -- внутренний ключ бакета; НЕ отдаётся клиенту
|
||||
status text NOT NULL DEFAULT 'ready', -- в лабе 4 всегда 'ready'
|
||||
error_code text, -- в лабе 4 всегда NULL
|
||||
created_at timestamptz NOT NULL,
|
||||
updated_at timestamptz NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_attachments_chat ON attachments(chat_id);
|
||||
|
||||
-- ============================================================
|
||||
-- LAB 4: сообщения ссылаются на вложения этого чата.
|
||||
-- ============================================================
|
||||
-- Массив хранит 0..10 уникальных UUID. Ограничения по количеству и
|
||||
-- уникальности, а также принадлежность вложений ИМЕННО этому чату
|
||||
-- проверяются в приложении при создании сообщения (см. handlers.go).
|
||||
--
|
||||
-- Старые текстовые сообщения получают пустой массив '{}' — это сохраняет
|
||||
-- обратную совместимость и обязательное поле контракта "attachment_ids".
|
||||
ALTER TABLE messages ADD COLUMN IF NOT EXISTS attachment_ids uuid[] NOT NULL DEFAULT '{}';
|
||||
@@ -0,0 +1,18 @@
|
||||
-- LAB 4: разрешаем пустой текст, если сообщение содержит хотя бы одно вложение.
|
||||
--
|
||||
-- Контракт lab4:
|
||||
-- либо text непустой (1..4000),
|
||||
-- либо attachment_ids содержит хотя бы один элемент.
|
||||
--
|
||||
-- Старое ограничение lab3 требовало char_length(text) >= 1 всегда,
|
||||
-- поэтому оно ломает сообщения вида {"text":"","attachment_ids":[...]}.
|
||||
|
||||
ALTER TABLE messages
|
||||
DROP CONSTRAINT IF EXISTS messages_text_check;
|
||||
|
||||
ALTER TABLE messages
|
||||
ADD CONSTRAINT messages_text_check CHECK (
|
||||
(char_length(text) >= 1 AND char_length(text) <= 4000)
|
||||
OR
|
||||
(char_length(text) = 0 AND cardinality(attachment_ids) > 0)
|
||||
);
|
||||
@@ -0,0 +1,62 @@
|
||||
-- LAB 5: очередь заданий, transactional outbox, реестр failed.
|
||||
--
|
||||
-- jobs — оркестрация обработки: попытки, lease, backoff, финальная ошибка.
|
||||
-- outbox — намерение опубликовать сообщение в брокер, записанное в той же
|
||||
-- транзакции, что и данные; relay читает и публикует (закрытие
|
||||
-- разрыва COMMIT -> publish).
|
||||
-- job_failures — реестр failed (DLQ) для оператора.
|
||||
--
|
||||
-- Состояние для клиента живёт в attachments.status (queued/processing/ready/failed).
|
||||
|
||||
CREATE TABLE IF NOT EXISTS jobs (
|
||||
id UUID PRIMARY KEY,
|
||||
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
|
||||
status TEXT NOT NULL DEFAULT 'queued',
|
||||
attempt INTEGER NOT NULL DEFAULT 0,
|
||||
max_attempts INTEGER NOT NULL DEFAULT 5,
|
||||
next_attempt_at TIMESTAMPTZ,
|
||||
lease_id TEXT,
|
||||
lease_expires_at TIMESTAMPTZ,
|
||||
error_code TEXT,
|
||||
error_message TEXT,
|
||||
pipeline_version INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_jobs_attachment ON jobs (attachment_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_jobs_claimable ON jobs (status, next_attempt_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_jobs_stuck ON jobs (status, lease_expires_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS outbox (
|
||||
id UUID PRIMARY KEY,
|
||||
aggregate_type TEXT NOT NULL,
|
||||
aggregate_id UUID NOT NULL,
|
||||
event_type TEXT NOT NULL,
|
||||
payload JSONB NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
published_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_outbox_unpublished
|
||||
ON outbox (created_at)
|
||||
WHERE published_at IS NULL;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS job_failures (
|
||||
id UUID PRIMARY KEY,
|
||||
job_id UUID NOT NULL,
|
||||
attachment_id UUID NOT NULL,
|
||||
error_code TEXT NOT NULL,
|
||||
error_message TEXT,
|
||||
attempt INTEGER NOT NULL,
|
||||
failed_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_job_failures_attachment ON job_failures (attachment_id);
|
||||
|
||||
-- LAB 5: версия pipeline и время старта обработки для наблюдаемости.
|
||||
-- LAB 5: варианты, версия pipeline и время старта обработки.
|
||||
ALTER TABLE attachments
|
||||
ADD COLUMN IF NOT EXISTS variants JSONB NOT NULL DEFAULT '[]',
|
||||
ADD COLUMN IF NOT EXISTS pipeline_version INTEGER NOT NULL DEFAULT 1,
|
||||
ADD COLUMN IF NOT EXISTS processing_started_at TIMESTAMPTZ;
|
||||
@@ -0,0 +1,717 @@
|
||||
// Package store — слой доступа к данным lab2+lab4.
|
||||
// PostgreSQL = источник истины (пользователи, чаты, участники, сообщения, сессии,
|
||||
// метаданные вложений).
|
||||
// Redis = опциональный кэш (сессии + история в треке 5): при его потере
|
||||
// деградируем в SQL, а не отказываем.
|
||||
// S3-совместимое хранилище = источник истины для БАЙТОВ вложений (лаба 4).
|
||||
//
|
||||
// ВСЕ запросы параметризованы ($1, $2, ...): значения никогда не конкатенируются
|
||||
// в текст SQL — это защита от SQL-инъекций.
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mtusi-messenger/internal/model"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"golang.org/x/crypto/scrypt"
|
||||
)
|
||||
|
||||
// Sentinel-ошибки: store НЕ ЗНАЕТ про HTTP; хендлеры маппят флажки в статусы.
|
||||
var (
|
||||
ErrNotFound = errors.New("not found") // объекта нет ИЛИ он чужой
|
||||
ErrUsernameTaken = errors.New("username taken") // unique-ограничение
|
||||
ErrInvalidCursor = errors.New("invalid cursor") // битая/чужая закладка
|
||||
ErrInvalidLogin = errors.New("invalid credentials") // неверный пароль ИЛИ неизвестный user (намеренно одно!)
|
||||
ErrBadMembers = errors.New("invalid member_ids") // неизвестный участник / вызывающий не в списке
|
||||
ErrIdempotencyConflict = errors.New("idempotency conflict") // тот же ключ, но другое тело
|
||||
)
|
||||
|
||||
// Store — доступ к PostgreSQL (+ опциональный Redis) + S3-хранилище (лаба 4).
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool // ограниченный пул соединений (уровень 4)
|
||||
rdb *redis.Client // nil = режим деградации без кэша
|
||||
s3 *S3Client // приватное S3-совместимое хранилище (лаба 4)
|
||||
sessionTTL time.Duration // из SESSION_TTL_SECONDS
|
||||
cacheMode string // "off" | "naive" | "versioned"; дефолт versioned (трек 5)
|
||||
log *slog.Logger
|
||||
sf *SingleFlight // stampede-защита кэша истории (трек 5)
|
||||
}
|
||||
|
||||
// New собирает Store. s3 может быть nil в случае недоступности — тогда все
|
||||
// операции с вложениями вернут ErrNotFound/503 (хендлеры маппят IsS3Unavailable).
|
||||
func New(pool *pgxpool.Pool, rdb *redis.Client, s3 *S3Client, sessionTTLSeconds, cacheMode string, log *slog.Logger) *Store {
|
||||
ttl := 3600
|
||||
if v, err := strconv.Atoi(sessionTTLSeconds); err == nil && v > 0 {
|
||||
ttl = v
|
||||
}
|
||||
if cacheMode == "" {
|
||||
cacheMode = "versioned"
|
||||
}
|
||||
return &Store{
|
||||
pool: pool,
|
||||
rdb: rdb,
|
||||
s3: s3,
|
||||
sessionTTL: time.Duration(ttl) * time.Second,
|
||||
cacheMode: cacheMode,
|
||||
log: log,
|
||||
sf: NewSingleFlight(),
|
||||
}
|
||||
}
|
||||
|
||||
// Ping — живость БД; используется в /health/ready: БД мертва => 503.
|
||||
func (s *Store) Ping(ctx context.Context) error { return s.pool.Ping(ctx) }
|
||||
|
||||
// ─────────────── Курсор и пагинация (перенесено из lab1 без изменений) ───────────────
|
||||
|
||||
type Cursor struct {
|
||||
Scope string `json:"s"` // чей ресурс: id чата или id пользователя
|
||||
TS time.Time `json:"t"` // время записи-закладки
|
||||
ID string `json:"i"` // id записи-закладки
|
||||
}
|
||||
|
||||
func EncodeCursor(c Cursor) string {
|
||||
b, _ := json.Marshal(c)
|
||||
return base64.RawURLEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
func DecodeCursor(s string) (Cursor, error) {
|
||||
var c Cursor
|
||||
b, err := base64.RawURLEncoding.DecodeString(s)
|
||||
if err != nil {
|
||||
return c, ErrInvalidCursor
|
||||
}
|
||||
if err := json.Unmarshal(b, &c); err != nil {
|
||||
return c, ErrInvalidCursor
|
||||
}
|
||||
if c.Scope == "" || c.ID == "" || c.TS.IsZero() {
|
||||
return c, ErrInvalidCursor
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func lessPair(ai time.Time, aid string, bi time.Time, bid string) bool {
|
||||
if !ai.Equal(bi) {
|
||||
return ai.Before(bi)
|
||||
}
|
||||
return aid < bid
|
||||
}
|
||||
|
||||
// paginate — дженерик листания для списков, собранных в памяти (список чатов).
|
||||
// История сообщений листается НА СТОРОНЕ SQL (см. ListMessages).
|
||||
func paginate[T any](all []T, limit int, cur *Cursor, key func(T) (time.Time, string)) ([]T, bool) {
|
||||
start := 0
|
||||
if cur != nil {
|
||||
start = sort.Search(len(all), func(i int) bool {
|
||||
t, id := key(all[i])
|
||||
return lessPair(cur.TS, cur.ID, t, id)
|
||||
})
|
||||
}
|
||||
rest := all[start:]
|
||||
if len(rest) > limit {
|
||||
return rest[:limit], true
|
||||
}
|
||||
return rest, false
|
||||
}
|
||||
|
||||
// ─────────────── Пароли: KDF scrypt ───────────────
|
||||
|
||||
const (
|
||||
scryptN = 32768 // 2^15
|
||||
scryptR = 8
|
||||
scryptP = 1
|
||||
scryptKeyLen = 32
|
||||
saltLen = 16
|
||||
)
|
||||
|
||||
func HashPassword(password string) (string, error) {
|
||||
salt := make([]byte, saltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
h, err := scrypt.Key([]byte(password), salt, scryptN, scryptR, scryptP, scryptKeyLen)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
enc := base64.RawStdEncoding.EncodeToString
|
||||
return fmt.Sprintf("scrypt$%d$%d$%d$%s$%s", scryptN, scryptR, scryptP, enc(salt), enc(h)), nil
|
||||
}
|
||||
|
||||
func VerifyPassword(password, encoded string) bool {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[0] != "scrypt" {
|
||||
return false
|
||||
}
|
||||
N, e1 := strconv.Atoi(parts[1])
|
||||
r, e2 := strconv.Atoi(parts[2])
|
||||
p, e3 := strconv.Atoi(parts[3])
|
||||
if e1 != nil || e2 != nil || e3 != nil {
|
||||
return false
|
||||
}
|
||||
salt, e4 := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
want, e5 := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if e4 != nil || e5 != nil {
|
||||
return false
|
||||
}
|
||||
got, err := scrypt.Key([]byte(password), salt, N, r, p, len(want))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return subtle.ConstantTimeCompare(want, got) == 1
|
||||
}
|
||||
|
||||
// isUniqueViolation — SQLSTATE 23505: нарушение UNIQUE (гонка регистрации).
|
||||
func isUniqueViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23505"
|
||||
}
|
||||
|
||||
// ─────────────── Пользователи ───────────────
|
||||
|
||||
func (s *Store) CreateUser(ctx context.Context, username, displayName, password string) (*model.User, error) {
|
||||
hash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
u := &model.User{ID: uuid.NewString(), Username: username, DisplayName: displayName, CreatedAt: model.NowTS()}
|
||||
_, err = s.pool.Exec(ctx,
|
||||
`INSERT INTO users (id, username, display_name, password_hash, created_at) VALUES ($1, $2, $3, $4, $5)`,
|
||||
u.ID, u.Username, u.DisplayName, hash, u.CreatedAt.Time)
|
||||
if err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
return nil, ErrUsernameTaken
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
const userCols = `id, username, display_name, created_at`
|
||||
|
||||
func (s *Store) User(ctx context.Context, id string) (*model.User, error) {
|
||||
var u model.User
|
||||
var createdAt time.Time
|
||||
err := s.pool.QueryRow(ctx, `SELECT `+userCols+` FROM users WHERE id = $1`, id).
|
||||
Scan(&u.ID, &u.Username, &u.DisplayName, &createdAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
u.CreatedAt = model.Timestamp{Time: createdAt.UTC()}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
func (s *Store) UserByCredentials(ctx context.Context, username, password string) (*model.User, error) {
|
||||
var u model.User
|
||||
var createdAt time.Time
|
||||
var hash string
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT `+userCols+`, password_hash FROM users WHERE username = $1`, username).
|
||||
Scan(&u.ID, &u.Username, &u.DisplayName, &createdAt, &hash)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrInvalidLogin
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !VerifyPassword(password, hash) {
|
||||
return nil, ErrInvalidLogin
|
||||
}
|
||||
u.CreatedAt = model.Timestamp{Time: createdAt.UTC()}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
// ─────────────── Сессии ───────────────
|
||||
|
||||
func (s *Store) CreateSession(ctx context.Context, userID string) (string, time.Time, error) {
|
||||
raw := make([]byte, 32)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
token := base64.RawURLEncoding.EncodeToString(raw)
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
expiresAt := time.Now().UTC().Add(s.sessionTTL)
|
||||
_, err := s.pool.Exec(ctx,
|
||||
`INSERT INTO sessions (token_hash, user_id, expires_at) VALUES ($1, $2, $3)`,
|
||||
hash[:], userID, expiresAt)
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
s.cacheSessionPut(ctx, hash, userID, expiresAt)
|
||||
return token, expiresAt, nil
|
||||
}
|
||||
|
||||
func (s *Store) SessionUser(ctx context.Context, token string) (*model.User, error) {
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
if userID, ok := s.cacheSessionGet(ctx, hash); ok {
|
||||
return s.User(ctx, userID)
|
||||
}
|
||||
var userID string
|
||||
var expiresAt time.Time
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT user_id, expires_at FROM sessions WHERE token_hash = $1`, hash[:]).
|
||||
Scan(&userID, &expiresAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if time.Now().UTC().After(expiresAt) {
|
||||
_, _ = s.pool.Exec(ctx, `DELETE FROM sessions WHERE token_hash = $1`, hash[:])
|
||||
s.cacheSessionDel(ctx, hash)
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
s.cacheSessionPut(ctx, hash, userID, expiresAt)
|
||||
return s.User(ctx, userID)
|
||||
}
|
||||
|
||||
func (s *Store) RevokeSession(ctx context.Context, token string) error {
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
if _, err := s.pool.Exec(ctx, `DELETE FROM sessions WHERE token_hash = $1`, hash[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
if s.rdb == nil {
|
||||
return nil
|
||||
}
|
||||
var err error
|
||||
for attempt := 1; attempt <= 3; attempt++ {
|
||||
if err = s.cacheSessionDel(ctx, hash); err == nil {
|
||||
return nil
|
||||
}
|
||||
s.log.Warn("redis DEL failed on logout, retrying", "attempt", attempt, "error", err.Error())
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
return fmt.Errorf("session cache invalidation failed after retries: %w", err)
|
||||
}
|
||||
|
||||
// ─────────────── Чаты ───────────────
|
||||
|
||||
func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []string, callerID string) (*model.Chat, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
rows, err := tx.Query(ctx, `SELECT id FROM users WHERE id = ANY($1)`, memberIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
found := make(map[string]bool, len(memberIDs))
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
found[id] = true
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(found) != len(memberIDs) {
|
||||
return nil, ErrBadMembers
|
||||
}
|
||||
if !found[callerID] {
|
||||
return nil, ErrBadMembers
|
||||
}
|
||||
chat := &model.Chat{ID: uuid.NewString(), Title: title, MemberIDs: memberIDs, CreatedAt: model.NowTS()}
|
||||
if _, err := tx.Exec(ctx,
|
||||
`INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`,
|
||||
chat.ID, chat.Title, chat.CreatedAt.Time); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := tx.Exec(ctx,
|
||||
`INSERT INTO chat_members (chat_id, user_id) SELECT $1, unnest($2::uuid[])`,
|
||||
chat.ID, memberIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *Store) ChatForUser(ctx context.Context, chatID, userID string) (*model.Chat, error) {
|
||||
var c model.Chat
|
||||
var createdAt time.Time
|
||||
var members []string
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT c.id, c.title, c.created_at, (SELECT array_agg(cm.user_id) FROM chat_members cm WHERE cm.chat_id = c.id) FROM chats c WHERE c.id = $1 AND EXISTS (SELECT 1 FROM chat_members cm WHERE cm.chat_id = c.id AND cm.user_id = $2)`,
|
||||
chatID, userID).Scan(&c.ID, &c.Title, &createdAt, &members)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.CreatedAt = model.Timestamp{Time: createdAt.UTC()}
|
||||
c.MemberIDs = members
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListChats(ctx context.Context, userID string, limit int, cur *Cursor) ([]*model.Chat, bool, error) {
|
||||
rows, err := s.pool.Query(ctx,
|
||||
`SELECT c.id, c.title, c.created_at, array_agg(cm.user_id) FROM chats c JOIN chat_members cm ON cm.chat_id = c.id WHERE c.id IN (SELECT chat_id FROM chat_members WHERE user_id = $1) GROUP BY c.id ORDER BY c.created_at, c.id`, userID)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
defer rows.Close()
|
||||
all := make([]*model.Chat, 0, 8)
|
||||
for rows.Next() {
|
||||
var c model.Chat
|
||||
var createdAt time.Time
|
||||
var members []string
|
||||
if err := rows.Scan(&c.ID, &c.Title, &createdAt, &members); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
c.CreatedAt = model.Timestamp{Time: createdAt.UTC()}
|
||||
c.MemberIDs = members
|
||||
all = append(all, &c)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
items, more := paginate(all, limit, cur, func(c *model.Chat) (time.Time, string) {
|
||||
return c.CreatedAt.Time, c.ID
|
||||
})
|
||||
return items, more, nil
|
||||
}
|
||||
|
||||
// ─────────────── Сообщения ───────────────
|
||||
// CreateMessage — идемпотентная отправка сообщения (Lab 3) + привязка вложений (Lab 4).
|
||||
// Область идемпотентности: (chat_id, sender_id, idempotency_key).
|
||||
// attachmentIDs проверяются на принадлежность чату в той же транзакции.
|
||||
func (s *Store) CreateMessage(
|
||||
ctx context.Context,
|
||||
chatID, senderID, text string,
|
||||
attachmentIDs []string,
|
||||
idempotencyKey string,
|
||||
) (*model.Message, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
// 1. Проверка членства в чате
|
||||
var one int
|
||||
err = tx.QueryRow(ctx,
|
||||
`SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`,
|
||||
chatID, senderID).Scan(&one)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 2. Проверка принадлежности вложений ЭТОМУ чату.
|
||||
// Все вложения должны существовать и принадлежать chatID; чужое/неизвестное — 404.
|
||||
if len(attachmentIDs) > 0 {
|
||||
rows, err := tx.Query(ctx,
|
||||
`SELECT id FROM attachments WHERE id = ANY($1) AND chat_id = $2`,
|
||||
attachmentIDs, chatID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
found := make(map[string]bool, len(attachmentIDs))
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
found[id] = true
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(found) != len(attachmentIDs) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Пытаемся вставить сообщение. Если ключ уже есть — игнорируем (DO NOTHING)
|
||||
m := &model.Message{
|
||||
ID: uuid.NewString(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: model.NowTS(),
|
||||
AttachmentIDs: attachmentIDs,
|
||||
}
|
||||
var insertedID string
|
||||
err = tx.QueryRow(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at, idempotency_key, attachment_ids)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
ON CONFLICT (chat_id, sender_id, idempotency_key) DO NOTHING
|
||||
RETURNING id
|
||||
`, m.ID, m.ChatID, m.SenderID, m.Text, m.CreatedAt.Time, idempotencyKey, attachmentIDs).Scan(&insertedID)
|
||||
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 4. Если вернулось ErrNoRows, значит сработал ON CONFLICT DO NOTHING
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
var existing model.Message
|
||||
var createdAt time.Time
|
||||
var existingAttIDs []string
|
||||
err = tx.QueryRow(ctx, `
|
||||
SELECT id, chat_id, sender_id, text, created_at, attachment_ids
|
||||
FROM messages
|
||||
WHERE chat_id = $1 AND sender_id = $2 AND idempotency_key = $3
|
||||
`, chatID, senderID, idempotencyKey).Scan(
|
||||
&existing.ID, &existing.ChatID, &existing.SenderID, &existing.Text, &createdAt, &existingAttIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Сравниваем тело (текст + вложения). Любое отличие — конфликт 409.
|
||||
if existing.Text != text || !sameStringSet(existingAttIDs, attachmentIDs) {
|
||||
return nil, ErrIdempotencyConflict
|
||||
}
|
||||
existing.CreatedAt = model.Timestamp{Time: createdAt.UTC()}
|
||||
existing.AttachmentIDs = existingAttIDs
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &existing, nil
|
||||
}
|
||||
|
||||
// 5. Успешная вставка
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if s.cacheMode == "versioned" {
|
||||
s.bumpChatVersion(ctx, chatID)
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// sameStringSet — сравнение двух срезов строк как множеств.
|
||||
func sameStringSet(a, b []string) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
m := make(map[string]struct{}, len(a))
|
||||
for _, v := range a {
|
||||
m[v] = struct{}{}
|
||||
}
|
||||
for _, v := range b {
|
||||
if _, ok := m[v]; !ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Store) ListMessages(ctx context.Context, chatID string, limit int, cur *Cursor) ([]*model.Message, bool, error) {
|
||||
cursorJSON := EncodeCursorJSON(cur)
|
||||
useCache := s.rdb != nil && s.cacheMode != "off"
|
||||
version := int64(0)
|
||||
if useCache && s.cacheMode == "versioned" {
|
||||
version = s.ChatVersion(ctx, chatID)
|
||||
}
|
||||
key := HistoryCacheKey(chatID, version, cursorJSON, limit)
|
||||
if useCache {
|
||||
if items, hasMore, ok := s.CacheHistoryGet(ctx, key); ok {
|
||||
s.log.Info("cache_hit", "chat_id", chatID, "mode", s.cacheMode, "cursor", cursorJSON)
|
||||
return items, hasMore, nil
|
||||
}
|
||||
}
|
||||
type pageResult struct {
|
||||
items []*model.Message
|
||||
hasMore bool
|
||||
}
|
||||
fetch := func() (any, error) {
|
||||
s.log.Info("sql_list_messages", "chat_id", chatID, "cursor", cursorJSON, "limit", limit)
|
||||
q := `SELECT id, chat_id, sender_id, text, created_at, attachment_ids FROM messages WHERE chat_id = $1`
|
||||
args := []any{chatID}
|
||||
if cur != nil {
|
||||
q += ` AND (created_at, id) > ($2, $3)`
|
||||
args = append(args, cur.TS, cur.ID)
|
||||
}
|
||||
q += ` ORDER BY created_at, id LIMIT $` + strconv.Itoa(len(args)+1)
|
||||
args = append(args, limit+1)
|
||||
rows, err := s.pool.Query(ctx, q, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := make([]*model.Message, 0, limit)
|
||||
for rows.Next() {
|
||||
var m model.Message
|
||||
var createdAt time.Time
|
||||
var attIDs []string
|
||||
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &createdAt, &attIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m.CreatedAt = model.Timestamp{Time: createdAt.UTC()}
|
||||
if attIDs == nil {
|
||||
attIDs = []string{}
|
||||
}
|
||||
m.AttachmentIDs = attIDs
|
||||
items = append(items, &m)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
more := len(items) > limit
|
||||
if more {
|
||||
items = items[:limit]
|
||||
}
|
||||
return pageResult{items: items, hasMore: more}, nil
|
||||
}
|
||||
var res any
|
||||
var err error
|
||||
if useCache && s.cacheMode == "versioned" {
|
||||
res, err = s.sf.Do(key, fetch)
|
||||
} else {
|
||||
res, err = fetch()
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
pr := res.(pageResult)
|
||||
if useCache {
|
||||
s.CacheHistoryPut(ctx, key, pr.items, pr.hasMore)
|
||||
}
|
||||
return pr.items, pr.hasMore, nil
|
||||
}
|
||||
|
||||
// ─────────────── Вложения (лаба 4) ───────────────
|
||||
|
||||
// CreateAttachment — вставка метаданных в БД. Вызывается после успешного
|
||||
// PUT в S3. При ошибке хендлер компенсирует — удаляет объект из S3.
|
||||
func (s *Store) CreateAttachment(ctx context.Context, att *model.Attachment) error {
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO attachments
|
||||
(id, chat_id, owner_id, filename, content_type, size_bytes, sha256, s3_key, status, error_code, created_at, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
|
||||
`,
|
||||
att.ID, att.ChatID, att.OwnerID, att.Filename, att.ContentType,
|
||||
att.SizeBytes, att.SHA256, att.S3Key, att.Status, att.ErrorCode,
|
||||
att.CreatedAt.Time, att.UpdatedAt.Time)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetAttachmentForUser — метаданные вложения с проверкой членства в чате.
|
||||
// Посторонний получает ErrNotFound (404) — не раскрываем существование объекта.
|
||||
// GetAttachmentForUser — метаданные вложения с проверкой членства в чате.
|
||||
// Посторонний получает ErrNotFound (404) — не раскрываем существование объекта.
|
||||
// LAB 5: возвращает фактические status/variants/error_code через общий scanAttachment,
|
||||
// чтобы список колонок был в одном месте (attachCols) и не разъезжался с воркером.
|
||||
func (s *Store) GetAttachmentForUser(ctx context.Context, attachmentID, userID string) (*model.Attachment, error) {
|
||||
return scanAttachment(s.pool.QueryRow(ctx, `SELECT`+attachCols+`
|
||||
FROM attachments a
|
||||
WHERE a.id = $1
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM chat_members cm
|
||||
WHERE cm.chat_id = a.chat_id AND cm.user_id = $2
|
||||
)`, attachmentID, userID))
|
||||
}
|
||||
|
||||
// ValidateAttachmentsForChat — проверка, что все attachmentIDs существуют и
|
||||
// принадлежат именно этому чату. Вызывается перед сохранением сообщения.
|
||||
// Если хоть один ID не прошёл — ErrNotFound (чужой объект = как будто нет).
|
||||
func (s *Store) ValidateAttachmentsForChat(ctx context.Context, chatID string, ids []string) error {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
rows, err := s.pool.Query(ctx,
|
||||
`SELECT id FROM attachments WHERE id = ANY($1) AND chat_id = $2`,
|
||||
ids, chatID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
found := make(map[string]bool, len(ids))
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return err
|
||||
}
|
||||
found[id] = true
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(found) != len(ids) {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ─────────────── Делегаты S3 (лаба 4) ───────────────
|
||||
|
||||
// PutObject — кладёт байты в приватный S3-бакет.
|
||||
// Ошибки маппятся хендлером в 503 через IsS3Unavailable.
|
||||
func (s *Store) PutObject(ctx context.Context, key string, data []byte, contentType string) error {
|
||||
if s.s3 == nil {
|
||||
return errors.New("s3 client not configured")
|
||||
}
|
||||
return s.s3.PutObject(ctx, key, data, contentType)
|
||||
}
|
||||
|
||||
// GetObject — скачивает байты из S3.
|
||||
func (s *Store) GetObject(ctx context.Context, key string) ([]byte, error) {
|
||||
if s.s3 == nil {
|
||||
return nil, errors.New("s3 client not configured")
|
||||
}
|
||||
return s.s3.GetObject(ctx, key)
|
||||
}
|
||||
|
||||
// DeleteObject — удаляет объект. Используется для компенсации, если INSERT
|
||||
// метаданных в БД упал после успешного S3 PUT.
|
||||
func (s *Store) DeleteObject(ctx context.Context, key string) error {
|
||||
if s.s3 == nil {
|
||||
return nil
|
||||
}
|
||||
return s.s3.DeleteObject(ctx, key)
|
||||
}
|
||||
|
||||
// IsUnavailable — «БД недоступна» (пул закрыт, таймаут, ошибка подключения).
|
||||
func IsUnavailable(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
var connErr *pgconn.ConnectError
|
||||
var netErr net.Error
|
||||
if errors.As(err, &connErr) {
|
||||
return true
|
||||
}
|
||||
if errors.As(err, &netErr) && netErr.Timeout() {
|
||||
return true
|
||||
}
|
||||
errStr := err.Error()
|
||||
return strings.Contains(errStr, "connection refused") ||
|
||||
strings.Contains(errStr, "connection reset") ||
|
||||
strings.Contains(errStr, "pool closed") ||
|
||||
strings.Contains(errStr, "acquire timeout") ||
|
||||
strings.Contains(errStr, "no connection")
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
// Package store, queue.go — брокер Redis Streams для заданий обработки (лаба 5).
|
||||
//
|
||||
// Почему Redis Streams, а не Pub/Sub: поток хранит сообщения (durable при AOF),
|
||||
// consumer group даёт at-least-once доставку и явный ack, XAUTOCLAIM возвращает
|
||||
// сообщения упавшего потребителя. В очередь идут только ID (jobs.schema.json).
|
||||
//
|
||||
// LAB 6: Publish создаёт producer span и инжектирует W3C trace context
|
||||
// (traceparent/tracestate) в поля сообщения, чтобы worker продолжил трассу.
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"mtusi-messenger/internal/model"
|
||||
)
|
||||
|
||||
const (
|
||||
// QueueStreamKey — имя потока заданий.
|
||||
QueueStreamKey = "messenger:attachment-jobs"
|
||||
// QueueGroup — consumer group worker'ов.
|
||||
QueueGroup = "workers"
|
||||
// queueMaxLen — приблизительный потолок длины потока (защита от разрастания).
|
||||
queueMaxLen = 10000
|
||||
)
|
||||
|
||||
// Queue — обёртка над Redis Streams.
|
||||
type Queue struct {
|
||||
rdb *redis.Client
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
// NewQueue — Redis-хук ставится ОДИН РАЗ в main (rdb.AddHook), чтобы не
|
||||
// получить дублирующиеся spans на каждой команде.
|
||||
func NewQueue(rdb *redis.Client, log *slog.Logger) *Queue {
|
||||
return &Queue{rdb: rdb, log: log}
|
||||
}
|
||||
|
||||
// Ensure — идемпотентное создание потока и consumer group.
|
||||
func (q *Queue) Ensure(ctx context.Context) error {
|
||||
err := q.rdb.XGroupCreateMkStream(ctx, QueueStreamKey, QueueGroup, "0").Err()
|
||||
if err != nil && !strings.Contains(err.Error(), "BUSYGROUP") {
|
||||
return fmt.Errorf("create consumer group: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// InjectTraceContext сохраняет W3C trace context из ctx в поля сообщения.
|
||||
// Вызывается там, где сообщение кладётся в outbox (upload, retry, reaper),
|
||||
// чтобы трасса инициатора дожила до момента публикации.
|
||||
func InjectTraceContext(ctx context.Context, msg *model.JobMessage) {
|
||||
carrier := propagation.MapCarrier{}
|
||||
otel.GetTextMapPropagator().Inject(ctx, carrier)
|
||||
msg.Traceparent = carrier.Get("traceparent")
|
||||
msg.Tracestate = carrier.Get("tracestate")
|
||||
}
|
||||
|
||||
// Publish — добавить сообщение в поток (publisher confirm = успех XADD).
|
||||
// LAB 6: восстанавливаем контекст инициатора из полей сообщения, создаём
|
||||
// producer span как его дочерний, затем инжектируем СВОЙ контекст для worker.
|
||||
func (q *Queue) Publish(ctx context.Context, msg model.JobMessage) (string, error) {
|
||||
in := propagation.MapCarrier{}
|
||||
if msg.Traceparent != "" {
|
||||
in.Set("traceparent", msg.Traceparent)
|
||||
}
|
||||
if msg.Tracestate != "" {
|
||||
in.Set("tracestate", msg.Tracestate)
|
||||
}
|
||||
ctx = otel.GetTextMapPropagator().Extract(ctx, in)
|
||||
|
||||
ctx, span := otel.Tracer("messenger-queue").Start(ctx, "queue.publish",
|
||||
trace.WithSpanKind(trace.SpanKindProducer),
|
||||
trace.WithAttributes(
|
||||
attribute.String("messaging.system", "redis_streams"),
|
||||
attribute.String("messaging.destination", QueueStreamKey),
|
||||
attribute.String("messaging.operation", "publish"),
|
||||
attribute.String("job.id", msg.JobID),
|
||||
attribute.String("job.type", msg.Type),
|
||||
attribute.Int("job.attempt", msg.Attempt),
|
||||
),
|
||||
)
|
||||
defer span.End()
|
||||
|
||||
out := propagation.MapCarrier{}
|
||||
otel.GetTextMapPropagator().Inject(ctx, out)
|
||||
msg.Traceparent = out.Get("traceparent")
|
||||
msg.Tracestate = out.Get("tracestate")
|
||||
|
||||
b, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
return "", fmt.Errorf("marshal job message: %w", err)
|
||||
}
|
||||
id, err := q.rdb.XAdd(ctx, &redis.XAddArgs{
|
||||
Stream: QueueStreamKey,
|
||||
MaxLen: queueMaxLen,
|
||||
Approx: true,
|
||||
Values: map[string]any{"payload": string(b)},
|
||||
}).Result()
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
return "", fmt.Errorf("xadd: %w", err)
|
||||
}
|
||||
span.SetAttributes(attribute.String("messaging.message.id", id))
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// Consume — читать новые сообщения группы (BLOCK, COUNT 1: ограниченный prefetch).
|
||||
func (q *Queue) Consume(ctx context.Context, consumer string, block time.Duration) ([]redis.XMessage, error) {
|
||||
res, err := q.rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
|
||||
Group: QueueGroup,
|
||||
Consumer: consumer,
|
||||
Streams: []string{QueueStreamKey, ">"},
|
||||
Count: 1,
|
||||
Block: block,
|
||||
}).Result()
|
||||
if err == redis.Nil {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("xreadgroup: %w", err)
|
||||
}
|
||||
var out []redis.XMessage
|
||||
for _, s := range res {
|
||||
out = append(out, s.Messages...)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Ack — подтвердить устойчивую обработку (после COMMIT результата в БД).
|
||||
func (q *Queue) Ack(ctx context.Context, msgID string) error {
|
||||
return q.rdb.XAck(ctx, QueueStreamKey, QueueGroup, msgID).Err()
|
||||
}
|
||||
|
||||
// ReclaimStale — забрать сообщения, которые держит упавший потребитель.
|
||||
// Второе возвращаемое значение XAutoClaim — курсор следующей страницы PEL;
|
||||
// игнорируем, т.к. периодический цикл сканирует PEL с "0-0" малыми порциями.
|
||||
func (q *Queue) ReclaimStale(ctx context.Context, consumer string, minIdle time.Duration) ([]redis.XMessage, error) {
|
||||
msgs, _, err := q.rdb.XAutoClaim(ctx, &redis.XAutoClaimArgs{
|
||||
Stream: QueueStreamKey,
|
||||
Group: QueueGroup,
|
||||
Consumer: consumer,
|
||||
MinIdle: minIdle,
|
||||
Start: "0-0",
|
||||
Count: 4,
|
||||
}).Result()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("xautoclaim: %w", err)
|
||||
}
|
||||
return msgs, nil
|
||||
}
|
||||
|
||||
// QueuePendingStats — глубина и возраст неподтверждённых (не acked) сообщений.
|
||||
// XLEN не используем: acked сообщения остаются в потоке до обрезки MAXLEN,
|
||||
// поэтому реальная «очередь» — это pending из XPENDING.
|
||||
// QueuePendingStats — фактический backlog очереди.
|
||||
// Глубина = lag (сообщения, которые группа ещё НЕ прочитала) +
|
||||
// pending (прочитанные, но не подтверждённые ack). Ранее считали только
|
||||
// pending через XPENDING — это не видело очередь при мёртвом worker'е,
|
||||
// потому что сообщения ещё никем не были прочитаны.
|
||||
// QueuePendingStats — фактический backlog очереди.
|
||||
// Глубина = lag (сообщения, которые группа ещё НЕ прочитала) +
|
||||
// pending (прочитанные, но не подтверждённые ack). Ранее считали только
|
||||
// pending через XPENDING — это не видело очередь при мёртвом worker'е,
|
||||
// потому что сообщения ещё никем не были прочитаны.
|
||||
type QueuePendingStats struct {
|
||||
Count int64
|
||||
OldestAgeSeconds float64
|
||||
}
|
||||
|
||||
// PendingStats — backlog группы и возраст старейшего НЕобработанного сообщения.
|
||||
// Возраст = минимум из (a) старейшего pending entry и (b) первого непрочитанного
|
||||
// сообщения стрима (идёт сразу за last-delivered-id группы).
|
||||
func (q *Queue) PendingStats(ctx context.Context) (QueuePendingStats, error) {
|
||||
var st QueuePendingStats
|
||||
|
||||
groups, err := q.rdb.XInfoGroups(ctx, QueueStreamKey).Result()
|
||||
if err != nil {
|
||||
// Поток или группа ещё не созданы — очереди нет, это не ошибка.
|
||||
if strings.Contains(err.Error(), "NOGROUP") || strings.Contains(err.Error(), "no such key") {
|
||||
return st, nil
|
||||
}
|
||||
return st, fmt.Errorf("xinfo groups: %w", err)
|
||||
}
|
||||
|
||||
var lag int64
|
||||
var lastDelivered string
|
||||
for _, g := range groups {
|
||||
if g.Name != QueueGroup {
|
||||
continue
|
||||
}
|
||||
if g.Lag > 0 { // lag может быть -1, когда Redis не может оценить
|
||||
lag = g.Lag
|
||||
}
|
||||
lastDelivered = g.LastDeliveredID
|
||||
st.Count += g.Pending
|
||||
}
|
||||
st.Count += lag
|
||||
if st.Count == 0 {
|
||||
return st, nil
|
||||
}
|
||||
|
||||
var oldestMS int64
|
||||
consider := func(ms int64) {
|
||||
if ms > 0 && (oldestMS == 0 || ms < oldestMS) {
|
||||
oldestMS = ms
|
||||
}
|
||||
}
|
||||
|
||||
// (a) старейший pending entry. В go-redis v9: XPending.Lower (не Min).
|
||||
if p, perr := q.rdb.XPending(ctx, QueueStreamKey, QueueGroup).Result(); perr == nil && p.Count > 0 && p.Lower != "" {
|
||||
if ms, ok := parseStreamMS(p.Lower); ok {
|
||||
consider(ms)
|
||||
}
|
||||
}
|
||||
// (b) первое непрочитанное сообщение (сразу за last-delivered-id)
|
||||
if lag > 0 && lastDelivered != "" {
|
||||
msgs, rerr := q.rdb.XRangeN(ctx, QueueStreamKey, nextStreamID(lastDelivered), "+", 1).Result()
|
||||
if rerr == nil && len(msgs) == 1 {
|
||||
if ms, ok := parseStreamMS(msgs[0].ID); ok {
|
||||
consider(ms)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if oldestMS > 0 {
|
||||
age := float64(time.Now().UnixMilli()-oldestMS) / 1000.0
|
||||
if age < 0 {
|
||||
age = 0
|
||||
}
|
||||
st.OldestAgeSeconds = age
|
||||
}
|
||||
return st, nil
|
||||
}
|
||||
|
||||
// parseStreamMS извлекает миллисекундную часть id вида "<ms>-<seq>".
|
||||
func parseStreamMS(id string) (int64, bool) {
|
||||
msPart, _, _ := strings.Cut(id, "-")
|
||||
ms, err := strconv.ParseInt(msPart, 10, 64)
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
return ms, true
|
||||
}
|
||||
|
||||
// nextStreamID возвращает id, следующий за данным (для XRANGE от границы чтения).
|
||||
func nextStreamID(id string) string {
|
||||
msPart, seqPart, found := strings.Cut(id, "-")
|
||||
if !found {
|
||||
return "-"
|
||||
}
|
||||
ms, err1 := strconv.ParseInt(msPart, 10, 64)
|
||||
seq, err2 := strconv.ParseInt(seqPart, 10, 64)
|
||||
if err1 != nil || err2 != nil {
|
||||
return "-"
|
||||
}
|
||||
return fmt.Sprintf("%d-%d", ms, seq+1)
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// attachmentIDFromKey — извлекает attachment_id из object key лабы 5.
|
||||
// Форматы: staging/{chat}/{att} и {chat}/{att}/{variant|original}.
|
||||
func attachmentIDFromKey(key string) (string, bool) {
|
||||
parts := strings.Split(key, "/")
|
||||
if len(parts) != 3 {
|
||||
return "", false
|
||||
}
|
||||
if parts[0] == "staging" {
|
||||
return parts[2], true
|
||||
}
|
||||
return parts[1], true
|
||||
}
|
||||
|
||||
// RunReconcile — сверка S3 ↔ PostgreSQL (лаба 5).
|
||||
//
|
||||
// Известным считается объект, чей attachment_id присутствует в таблице
|
||||
// attachments (независимо от статуса). Исключение: staging-объект вложения
|
||||
// в терминальном failed — он больше не нужен и удаляется.
|
||||
//
|
||||
// Осиротевшие объекты (attachment_id отсутствует в БД) удаляются только старше
|
||||
// grace period: это защищает гонку «объект создан, метаданные дописываются».
|
||||
func RunReconcile(ctx context.Context, pool *pgxpool.Pool, s3 *S3Client, grace time.Duration, log *slog.Logger) error {
|
||||
if s3 == nil {
|
||||
return fmt.Errorf("reconcile: s3 client not configured")
|
||||
}
|
||||
|
||||
rows, err := pool.Query(ctx, `SELECT id, status FROM attachments`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reconcile: query attachments: %w", err)
|
||||
}
|
||||
known := make(map[string]string)
|
||||
for rows.Next() {
|
||||
var id, status string
|
||||
if err := rows.Scan(&id, &status); err != nil {
|
||||
rows.Close()
|
||||
return fmt.Errorf("reconcile: scan: %w", err)
|
||||
}
|
||||
known[id] = status
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return fmt.Errorf("reconcile: rows err: %w", err)
|
||||
}
|
||||
|
||||
objs, err := s3.ListObjectsInfo(ctx, "")
|
||||
if err != nil {
|
||||
return fmt.Errorf("reconcile: list objects: %w", err)
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
var deleted, skippedYoung, skippedUnknown int
|
||||
for _, o := range objs {
|
||||
attID, ok := attachmentIDFromKey(o.Key)
|
||||
if !ok {
|
||||
skippedUnknown++
|
||||
log.Info("reconcile skip unknown key format", "key", o.Key)
|
||||
continue
|
||||
}
|
||||
status, inDB := known[attID]
|
||||
if inDB {
|
||||
// staging у failed-вложения больше не нужен.
|
||||
if status == "failed" && strings.HasPrefix(o.Key, "staging/") {
|
||||
if err := s3.DeleteObject(ctx, o.Key); err != nil {
|
||||
log.Warn("reconcile delete failed staging", "key", o.Key, "error", err.Error())
|
||||
continue
|
||||
}
|
||||
deleted++
|
||||
log.Info("reconcile deleted failed staging", "key", o.Key)
|
||||
}
|
||||
continue
|
||||
}
|
||||
age := now.Sub(o.LastModified.UTC())
|
||||
if age < grace {
|
||||
skippedYoung++
|
||||
log.Info("reconcile skip young orphan",
|
||||
"key", o.Key,
|
||||
"age_seconds", int(age.Seconds()),
|
||||
"grace_seconds", int(grace.Seconds()))
|
||||
continue
|
||||
}
|
||||
if err := s3.DeleteObject(ctx, o.Key); err != nil {
|
||||
log.Warn("reconcile delete failed", "key", o.Key, "error", err.Error())
|
||||
continue
|
||||
}
|
||||
deleted++
|
||||
log.Info("reconcile deleted orphan", "key", o.Key, "age_seconds", int(age.Seconds()))
|
||||
}
|
||||
|
||||
log.Info("reconcile complete",
|
||||
"objects_in_bucket", len(objs),
|
||||
"known_attachments", len(known),
|
||||
"deleted", deleted,
|
||||
"skipped_young", skippedYoung,
|
||||
"skipped_unknown_format", skippedUnknown,
|
||||
"grace_seconds", int(grace.Seconds()))
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// Package store, redisotel.go — Redis-инструментация через go-redis Hook (лаба 6).
|
||||
//
|
||||
// Создаёт db client spans для каждой Redis-команды (XADD, XREADGROUP, XACK,
|
||||
// XAUTOCLAIM, GET, SET и т.д.) с атрибутами db.system, db.operation,
|
||||
// db.statement. Работает как в API (producer), так и в worker (consumer).
|
||||
//
|
||||
// Почему собственная реализация: пакет otelredis был удалён из contrib в
|
||||
// последних релизах; ручная реализация стабильна и не зависит от внешних
|
||||
// breaking changes.
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// RedisTracerHook возвращает go-redis Hook для OTel-инструментации.
|
||||
// Используется в API и worker для создания db client spans.
|
||||
func RedisTracerHook() redis.Hook { return redisTracerHook{} }
|
||||
|
||||
type redisTracerHook struct{}
|
||||
|
||||
// DialHook — go-redis v9: next возвращает net.Conn, а не redis.Conn.
|
||||
// Мы не оборачиваем dial в span (он происходит один раз на соединение),
|
||||
// просто пробрасываем вызов.
|
||||
func (redisTracerHook) DialHook(next redis.DialHook) redis.DialHook {
|
||||
return func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
return next(ctx, network, addr)
|
||||
}
|
||||
}
|
||||
|
||||
// ProcessHook — создаём span для каждой Redis-команды.
|
||||
func (redisTracerHook) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
|
||||
return func(ctx context.Context, cmd redis.Cmder) error {
|
||||
tracer := otel.Tracer("messenger-redis")
|
||||
cmdName := strings.ToUpper(cmd.Name())
|
||||
ctx, span := tracer.Start(ctx, "redis "+cmdName,
|
||||
trace.WithSpanKind(trace.SpanKindClient),
|
||||
trace.WithAttributes(
|
||||
attribute.String("db.system", "redis"),
|
||||
attribute.String("db.operation", cmdName),
|
||||
attribute.String("db.statement", truncateStmt(cmd.String(), 512)),
|
||||
),
|
||||
)
|
||||
err := next(ctx, cmd)
|
||||
if err != nil && err != redis.Nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
}
|
||||
span.End()
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// ProcessPipelineHook — пайплайны проходят как есть (каждая команда внутри
|
||||
// пайплайна всё равно будет обработана ProcessHook, если он активен).
|
||||
func (redisTracerHook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook {
|
||||
return func(ctx context.Context, cmds []redis.Cmder) error {
|
||||
return next(ctx, cmds)
|
||||
}
|
||||
}
|
||||
|
||||
// truncateStmt обрезает длинные statements для атрибутов span, чтобы не
|
||||
// раздувать хранилище трасс большими XADD-payload.
|
||||
func truncateStmt(s string, maxLen int) string {
|
||||
if len(s) <= maxLen {
|
||||
return s
|
||||
}
|
||||
return s[:maxLen] + "..."
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
// Package store, s3.go — клиент приватного S3-совместимого хранилища (лаба 4).
|
||||
//
|
||||
// Разделение данных:
|
||||
// - Источник истины для БАЙТОВ — это хранилище.
|
||||
// - Источник истины для МЕТАДАННЫХ — PostgreSQL (таблица attachments).
|
||||
//
|
||||
// Ключ объекта (s3_key) назначает сервер и НЕ раскрывает клиенту.
|
||||
// Бакет приватный: анонимного доступа нет, скачивание только через
|
||||
// авторизованный API с проверкой членства в чате. Приватный бакет сам по себе
|
||||
// НЕ заменяет эту проверку (см. handlers.go).
|
||||
package store
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
// s3Timeout — максимальное время на одну операцию с хранилищем.
|
||||
// При недоступном хранилище клиент быстро получает ошибку, и загрузка/скачивание
|
||||
// честно возвращают 503, а не висят до таймаута клиента.
|
||||
const s3Timeout = 30 * time.Second
|
||||
|
||||
// S3Client — обёртка над MinIO/S3 с фиксированным приватным бакетом.
|
||||
type S3Client struct {
|
||||
client *minio.Client
|
||||
bucket string
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
// NewS3Client создаёт клиент.
|
||||
// - endpoint: "host:port" без схемы, например "minio:9000";
|
||||
// - useSSL: false для локального стенда по HTTP.
|
||||
//
|
||||
// Уровень 4: "API использует отдельные S3 credentials с ограниченными правами".
|
||||
// Эти креды читаются из переменных окружения (см. main.go, compose.yaml) и не
|
||||
// коммитятся в репозиторий.
|
||||
func NewS3Client(endpoint, accessKey, secretKey, bucket string, useSSL bool, log *slog.Logger) (*S3Client, error) {
|
||||
c, err := minio.New(endpoint, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(accessKey, secretKey, ""),
|
||||
Secure: useSSL,
|
||||
BucketLookup: minio.BucketLookupPath,
|
||||
Region: "us-east-1",
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("init s3 client: %w", err)
|
||||
}
|
||||
return &S3Client{client: c, bucket: bucket, log: log}, nil
|
||||
}
|
||||
|
||||
// EnsureBucket — идемпотентный бутстрап приватного бакета.
|
||||
// Вызывается при старте; повторный вызов безопасен (существующий бакет не
|
||||
// пересоздаётся). Уровень 4: "Bucket bootstrap идемпотентен".
|
||||
func (s *S3Client) EnsureBucket(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s3Timeout)
|
||||
defer cancel()
|
||||
ok, err := s.client.BucketExists(ctx, s.bucket)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check bucket: %w", err)
|
||||
}
|
||||
if ok {
|
||||
s.log.Info("s3 bucket already exists", "bucket", s.bucket)
|
||||
return nil
|
||||
}
|
||||
if err := s.client.MakeBucket(ctx, s.bucket, minio.MakeBucketOptions{}); err != nil {
|
||||
return fmt.Errorf("create bucket: %w", err)
|
||||
}
|
||||
s.log.Info("s3 bucket created", "bucket", s.bucket)
|
||||
return nil
|
||||
}
|
||||
|
||||
// PutObject — положить байты в бакет. Используется в загрузке вложения.
|
||||
// Ошибка маппится хендлером в 503 (хранилище недоступно).
|
||||
func (s *S3Client) PutObject(ctx context.Context, key string, data []byte, contentType string) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s3Timeout)
|
||||
defer cancel()
|
||||
_, err := s.client.PutObject(ctx, s.bucket, key, bytes.NewReader(data), int64(len(data)), minio.PutObjectOptions{
|
||||
ContentType: contentType,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("s3 put object: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetObject — скачать байты. Используется в скачивании вложения.
|
||||
// Сначала проверяем существование (чтобы отличить "объект не найден" от сетевой
|
||||
// ошибки), затем читаем. Ошибка маппится хендлером в 503 или 404.
|
||||
func (s *S3Client) GetObject(ctx context.Context, key string) ([]byte, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s3Timeout)
|
||||
defer cancel()
|
||||
if _, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{}); err != nil {
|
||||
return nil, fmt.Errorf("s3 stat object: %w", err)
|
||||
}
|
||||
obj, err := s.client.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("s3 get object: %w", err)
|
||||
}
|
||||
defer obj.Close()
|
||||
data, err := io.ReadAll(obj)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("s3 read object: %w", err)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// DeleteObject — удалить объект. Используется для компенсации, если запись
|
||||
// метаданных в БД не удалась после успешного S3 PUT (механизм согласованности
|
||||
// уровня 4), а также в reconciler для очистки осиротевших объектов.
|
||||
func (s *S3Client) DeleteObject(ctx context.Context, key string) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s3Timeout)
|
||||
defer cancel()
|
||||
if err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}); err != nil {
|
||||
return fmt.Errorf("s3 delete object: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListKeys — перечислить все ключи объектов с префиксом ("" = все).
|
||||
// Используется в reconciler (уровень 4) для поиска осиротевших объектов:
|
||||
// объектов в хранилище, у которых нет метаданных в БД.
|
||||
// Результат ограничен по времени (см. context.WithTimeout), но НЕ по количеству —
|
||||
// для учебной лабы этого достаточно; в отчёте зафиксируешь ограничение.
|
||||
func (s *S3Client) ListKeys(ctx context.Context, prefix string) ([]string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s3Timeout)
|
||||
defer cancel()
|
||||
var keys []string
|
||||
for obj := range s.client.ListObjects(ctx, s.bucket, minio.ListObjectsOptions{Prefix: prefix, Recursive: true}) {
|
||||
if obj.Err != nil {
|
||||
return nil, fmt.Errorf("s3 list objects: %w", obj.Err)
|
||||
}
|
||||
keys = append(keys, obj.Key)
|
||||
}
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
// IsS3Unavailable — эвристика "хранилище недоступно" для маппинга в 503.
|
||||
// Аналог IsUnavailable для PostgreSQL: сетевые ошибки и таймауты считаем
|
||||
// недоступностью, а не ошибкой клиента.
|
||||
func IsS3Unavailable(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return true
|
||||
}
|
||||
msg := err.Error()
|
||||
return strings.Contains(msg, "connection refused") ||
|
||||
strings.Contains(msg, "connection reset") ||
|
||||
strings.Contains(msg, "no such host") ||
|
||||
strings.Contains(msg, "timeout") ||
|
||||
strings.Contains(msg, "i/o timeout") ||
|
||||
strings.Contains(msg, "dial tcp")
|
||||
}
|
||||
|
||||
// ObjectInfo — ключ и время изменения объекта. Нужно reconcile, чтобы
|
||||
// отличать «осиротевший давно» от «создан секунду назад, метаданные дописываются».
|
||||
type ObjectInfo struct {
|
||||
Key string
|
||||
LastModified time.Time
|
||||
}
|
||||
|
||||
// ListObjectsInfo — перечислить объекты с ключом и временем изменения.
|
||||
// Используется RunReconcile (уровень 4) для поиска осиротевших объектов.
|
||||
func (s *S3Client) ListObjectsInfo(ctx context.Context, prefix string) ([]ObjectInfo, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s3Timeout)
|
||||
defer cancel()
|
||||
var out []ObjectInfo
|
||||
for obj := range s.client.ListObjects(ctx, s.bucket, minio.ListObjectsOptions{Prefix: prefix, Recursive: true}) {
|
||||
if obj.Err != nil {
|
||||
return nil, fmt.Errorf("s3 list objects: %w", obj.Err)
|
||||
}
|
||||
out = append(out, ObjectInfo{Key: obj.Key, LastModified: obj.LastModified})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
// Package worker, pipeline.go — генерация вариантов изображения (лаба 5).
|
||||
//
|
||||
// thumbnail : JPEG, вписан в 256x256 БЕЗ увеличения, EXIF orientation учтён,
|
||||
//
|
||||
// альфа-канал сведён на белый фон.
|
||||
//
|
||||
// crop : JPEG, центральный квадрат 128x128 (для малых изображений
|
||||
//
|
||||
// допускается увеличение, иначе квадрат не собрать).
|
||||
//
|
||||
// optimized : WebP, вписан в 1280x1280 БЕЗ увеличения, EXIF не сохраняется.
|
||||
//
|
||||
// Память ограничена потолком пикселей (40 Мп), время — дедлайном задания
|
||||
// в worker.go. Декодирование одно, варианты строятся из одного кадра.
|
||||
package worker
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"io"
|
||||
|
||||
"github.com/disintegration/imaging"
|
||||
)
|
||||
|
||||
const (
|
||||
thumbMax = 256
|
||||
cropSize = 128
|
||||
optMax = 1280
|
||||
jpegQuality = 80
|
||||
webpQuality = 80
|
||||
maxPixels = 40_000_000
|
||||
)
|
||||
|
||||
var errTooManyPixels = errors.New("image exceeds pixel limit")
|
||||
|
||||
// variantOut — готовый байтовый вариант с фактическими размерми.
|
||||
type variantOut struct {
|
||||
Name string
|
||||
ContentType string
|
||||
Data []byte
|
||||
Width int
|
||||
Height int
|
||||
}
|
||||
|
||||
// buildVariants декодирует оригинал один раз и строит три варианта.
|
||||
func buildVariants(src io.Reader) ([]variantOut, error) {
|
||||
img, err := imaging.Decode(src, imaging.AutoOrientation(true))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b := img.Bounds()
|
||||
if int64(b.Dx())*int64(b.Dy()) > maxPixels {
|
||||
return nil, errTooManyPixels
|
||||
}
|
||||
|
||||
out := make([]variantOut, 0, 3)
|
||||
|
||||
// thumbnail
|
||||
thumb := fitNoUpscale(img, thumbMax, thumbMax)
|
||||
thumb = flattenOnWhite(thumb)
|
||||
buf := &bytes.Buffer{}
|
||||
if err := imaging.Encode(buf, thumb, imaging.JPEG, imaging.JPEGQuality(jpegQuality)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, variantOut{
|
||||
Name: "thumbnail", ContentType: "image/jpeg",
|
||||
Data: buf.Bytes(), Width: thumb.Bounds().Dx(), Height: thumb.Bounds().Dy(),
|
||||
})
|
||||
|
||||
// crop
|
||||
side := b.Dx()
|
||||
if b.Dy() < side {
|
||||
side = b.Dy()
|
||||
}
|
||||
square := imaging.CropCenter(img, side, side)
|
||||
cropped := flattenOnWhite(imaging.Resize(square, cropSize, cropSize, imaging.Lanczos))
|
||||
buf = &bytes.Buffer{}
|
||||
if err := imaging.Encode(buf, cropped, imaging.JPEG, imaging.JPEGQuality(jpegQuality)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, variantOut{
|
||||
Name: "crop", ContentType: "image/jpeg",
|
||||
Data: buf.Bytes(), Width: cropSize, Height: cropSize,
|
||||
})
|
||||
|
||||
// optimized
|
||||
opt := fitNoUpscale(img, optMax, optMax)
|
||||
buf = &bytes.Buffer{}
|
||||
if err := encodeWebp(buf, opt, webpQuality); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, variantOut{
|
||||
Name: "optimized", ContentType: "image/webp",
|
||||
Data: buf.Bytes(), Width: opt.Bounds().Dx(), Height: opt.Bounds().Dy(),
|
||||
})
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// fitNoUpscale вписывает в бокс, но никогда не увеличивает малые изображения.
|
||||
func fitNoUpscale(img image.Image, mw, mh int) image.Image {
|
||||
b := img.Bounds()
|
||||
if b.Dx() <= mw && b.Dy() <= mh {
|
||||
return img
|
||||
}
|
||||
return imaging.Fit(img, mw, mh, imaging.Lanczos)
|
||||
}
|
||||
|
||||
// flattenOnWhite сводит альфа-канал на белый фон.
|
||||
|
||||
func flattenOnWhite(img image.Image) image.Image {
|
||||
b := img.Bounds()
|
||||
white := image.NewRGBA(b)
|
||||
draw.Draw(white, b, image.NewUniform(color.White), image.Point{}, draw.Src)
|
||||
draw.Draw(white, b, img, b.Min, draw.Over)
|
||||
return white
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//go:build cgo
|
||||
|
||||
package worker
|
||||
|
||||
import (
|
||||
"image"
|
||||
"io"
|
||||
|
||||
"github.com/chai2010/webp"
|
||||
)
|
||||
|
||||
// encodeWebp — lossy WebP через libwebp (только в cgo-сборке, т.е. в Docker).
|
||||
func encodeWebp(w io.Writer, img image.Image, quality float32) error {
|
||||
return webp.Encode(w, img, &webp.Options{Lossless: false, Quality: quality})
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//go:build !cgo
|
||||
|
||||
package worker
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"image"
|
||||
"io"
|
||||
)
|
||||
|
||||
// encodeWebp — заглушка для локальных сборок без cgo.
|
||||
// Воркер выполняется только в Docker, где cgo включён.
|
||||
func encodeWebp(w io.Writer, img image.Image, quality float32) error {
|
||||
return errors.New("webp encoding requires cgo build (run inside Docker)")
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
// Package worker, worker.go — цикл обработки заданий (лаба 5 + лаба 6).
|
||||
//
|
||||
// consume -> claim(lease) -> process -> complete/fail/retry -> ack.
|
||||
// ack только ПОСЛЕ COMMIT результата в БД (at-least-once без потери эффекта).
|
||||
// Упавшего потребителя подхватывает XAUTOCLAIM; зависшую аренду снимает
|
||||
// ReapExpiredLeases. Отложенные повторы публикует EnqueueDueRetries.
|
||||
//
|
||||
// LAB 6: handle создаёт consumer span, извлекая W3C trace context
|
||||
// (traceparent/tracestate) из полей сообщения. Consumer span становится
|
||||
// дочерним к producer span, созданному API при publish: сквозная цепочка
|
||||
// upload → publish → consume → S3/DB.
|
||||
//
|
||||
// LAB 6: все значимые логи пишутся через *Context-методы slog, чтобы
|
||||
// trace_id/span_id автоматически попадали в stdout-JSON и OTLP-логи.
|
||||
//
|
||||
// ВАЖНО про импорты: go.opentelemetry.io/otel (алиас otel) даёт Tracer/
|
||||
// propagator; приложения-метрики живут в mtusi-messenger/internal/otel
|
||||
// (алиас appotel). Смешивать префиксы нельзя.
|
||||
package worker
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"math"
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"mtusi-messenger/internal/model"
|
||||
appotel "mtusi-messenger/internal/otel"
|
||||
"mtusi-messenger/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
jobTimeout = 60 * time.Second // лимит времени одной обработки
|
||||
consumeBlock = 2 * time.Second
|
||||
reclaimIdle = store.LeaseTTL + 30*time.Second // не перехватывать живую обработку
|
||||
housekeepEvery = 5 * time.Second
|
||||
backoffBase = 500 * time.Millisecond
|
||||
backoffCap = 8 * time.Second
|
||||
)
|
||||
|
||||
// Worker — потребитель очереди заданий.
|
||||
type Worker struct {
|
||||
st *store.Store
|
||||
q *store.Queue
|
||||
log *slog.Logger
|
||||
name string
|
||||
}
|
||||
|
||||
// New — конструктор БЕЗ rdb: Redis-хук ставится один раз в main (rdb.AddHook),
|
||||
// поэтому worker не знает про redis-клиент напрямую.
|
||||
func New(st *store.Store, q *store.Queue, log *slog.Logger) *Worker {
|
||||
return &Worker{st: st, q: q, log: log, name: "worker-" + uuid.NewString()[:8]}
|
||||
}
|
||||
|
||||
// Run — основной цикл. Завершается по отмене контекста (graceful stop).
|
||||
func (w *Worker) Run(ctx context.Context) error {
|
||||
if err := w.q.Ensure(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
w.log.Info("worker started", "consumer", w.name)
|
||||
hk := time.NewTicker(housekeepEvery)
|
||||
defer hk.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
w.log.Info("worker stopping")
|
||||
return nil
|
||||
case <-hk.C:
|
||||
w.housekeep(appotel.SuppressTracing(ctx))
|
||||
default:
|
||||
}
|
||||
|
||||
// LAB 6: пустой XREADGROUP BLOCK 2s — служебная операция,
|
||||
// не бизнес-трасса. Подавляем корень, чтобы не засорять Tempo
|
||||
// ~30 опросами в минуту на каждый consumer.
|
||||
consumeCtx := appotel.SuppressTracing(ctx)
|
||||
msgs, err := w.q.Consume(consumeCtx, w.name, consumeBlock)
|
||||
if err != nil {
|
||||
w.log.Warn("consume error", "error", err.Error())
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
continue
|
||||
}
|
||||
for _, m := range msgs {
|
||||
w.handle(ctx, m)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// housekeep — возврат сообщений упавших потребителей, снятие истёкших аренд
|
||||
// и публикация отложенных повторов, у которых настал срок.
|
||||
func (w *Worker) housekeep(ctx context.Context) {
|
||||
msgs, err := w.q.ReclaimStale(ctx, w.name, reclaimIdle)
|
||||
if err == nil {
|
||||
for _, m := range msgs {
|
||||
w.handle(ctx, m)
|
||||
}
|
||||
} else {
|
||||
w.log.Warn("reclaim stale", "error", err.Error())
|
||||
}
|
||||
|
||||
n, err := w.st.ReapExpiredLeases(ctx)
|
||||
if err != nil {
|
||||
w.log.Warn("reap leases", "error", err.Error())
|
||||
} else if n > 0 {
|
||||
w.log.Info("reaped expired leases", "count", n)
|
||||
}
|
||||
|
||||
d, err := w.st.EnqueueDueRetries(ctx)
|
||||
if err != nil {
|
||||
w.log.Warn("enqueue due retries", "error", err.Error())
|
||||
} else if d > 0 {
|
||||
w.log.Info("enqueued due retries", "count", d)
|
||||
}
|
||||
}
|
||||
|
||||
// handle — обработка одного сообщения очереди.
|
||||
func (w *Worker) handle(parent context.Context, m redis.XMessage) {
|
||||
raw, ok := m.Values["payload"].(string)
|
||||
if !ok {
|
||||
w.handleInvalidMessage(parent, m, "message without payload", nil)
|
||||
return
|
||||
}
|
||||
var msg model.JobMessage
|
||||
if err := json.Unmarshal([]byte(raw), &msg); err != nil {
|
||||
w.handleInvalidMessage(parent, m, "bad job message", err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(parent, jobTimeout)
|
||||
defer cancel()
|
||||
|
||||
// ─── LAB 6: consumer span с извлечением W3C trace context ───────────
|
||||
carrier := propagation.MapCarrier{}
|
||||
if msg.Traceparent != "" {
|
||||
carrier.Set("traceparent", msg.Traceparent)
|
||||
}
|
||||
if msg.Tracestate != "" {
|
||||
carrier.Set("tracestate", msg.Tracestate)
|
||||
}
|
||||
ctx = otel.GetTextMapPropagator().Extract(ctx, carrier)
|
||||
|
||||
ctx, span := otel.Tracer("messenger-worker").Start(ctx, "attachment.process",
|
||||
trace.WithSpanKind(trace.SpanKindConsumer),
|
||||
trace.WithAttributes(
|
||||
attribute.String("messaging.system", "redis_streams"),
|
||||
attribute.String("messaging.destination", store.QueueStreamKey),
|
||||
attribute.String("messaging.operation", "process"),
|
||||
attribute.String("messaging.message.id", m.ID),
|
||||
attribute.String("job.id", msg.JobID),
|
||||
attribute.String("attachment.id", msg.AttachmentID),
|
||||
attribute.Int("job.attempt", msg.Attempt),
|
||||
attribute.String("worker.name", w.name),
|
||||
),
|
||||
)
|
||||
defer span.End()
|
||||
// ─── /LAB 6 ─────────────────────────────────────────────────────────
|
||||
|
||||
// persistCtx сохраняет trace context, но не отменяется по jobTimeout.
|
||||
// Через него фиксируем терминальные результаты и ack, чтобы не потерять
|
||||
// их, если обработка уже превысила дедлайн.
|
||||
persistCtx := context.WithoutCancel(ctx)
|
||||
|
||||
claim, err := w.st.ClaimJob(ctx, msg.JobID, msg.Attempt, uuid.NewString(), time.Now().Add(store.LeaseTTL))
|
||||
if err != nil {
|
||||
w.log.WarnContext(ctx, "claim failed",
|
||||
"job", msg.JobID,
|
||||
"attachment", msg.AttachmentID,
|
||||
"attempt", msg.Attempt,
|
||||
"error", err.Error(),
|
||||
)
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, "claim_failed")
|
||||
return // без ack: сообщение вернётся через PEL
|
||||
}
|
||||
|
||||
if claim == nil {
|
||||
// Либо терминальное состояние (повтор после готовности), либо живая аренда.
|
||||
att, aerr := w.st.GetAttachmentInternal(ctx, msg.AttachmentID)
|
||||
if aerr == nil && (att.Status == model.StatusReady || att.Status == model.StatusFailed) {
|
||||
w.log.InfoContext(ctx, "job already terminal, acking duplicate",
|
||||
"job", msg.JobID,
|
||||
"attachment", msg.AttachmentID,
|
||||
"status", att.Status,
|
||||
)
|
||||
_ = w.q.Ack(persistCtx, m.ID) // идемпотентный no-op
|
||||
span.SetAttributes(attribute.String("job.outcome", "duplicate_terminal"))
|
||||
return
|
||||
}
|
||||
w.log.InfoContext(ctx, "claim skipped: live lease or attachment not terminal",
|
||||
"job", msg.JobID,
|
||||
"attachment", msg.AttachmentID,
|
||||
)
|
||||
span.SetAttributes(attribute.String("job.outcome", "skipped_live_lease"))
|
||||
return
|
||||
}
|
||||
|
||||
w.log.InfoContext(ctx, "job claimed",
|
||||
"job", msg.JobID,
|
||||
"attachment", claim.AttachmentID,
|
||||
"attempt", claim.Attempt,
|
||||
"pipeline_version", claim.PipelineVersion,
|
||||
)
|
||||
|
||||
// LAB 6: saturation worker + замер длительности обработки.
|
||||
appotel.SetWorkerBusy(1)
|
||||
start := time.Now()
|
||||
perr := w.process(ctx, claim)
|
||||
dur := time.Since(start).Seconds()
|
||||
appotel.SetWorkerBusy(0)
|
||||
|
||||
if perr != nil {
|
||||
span.RecordError(perr)
|
||||
span.SetStatus(codes.Error, errorCode(perr))
|
||||
} else {
|
||||
span.SetStatus(codes.Ok, "")
|
||||
span.SetAttributes(attribute.String("job.outcome", "success"))
|
||||
}
|
||||
|
||||
switch {
|
||||
case perr == nil:
|
||||
appotel.RecordJobProcessed(ctx, msg.Type, "success", "", dur)
|
||||
_ = w.q.Ack(persistCtx, m.ID)
|
||||
|
||||
case isPermanent(perr):
|
||||
span.SetAttributes(
|
||||
attribute.String("job.outcome", "permanent_failure"),
|
||||
attribute.String("job.error_code", errorCode(perr)),
|
||||
)
|
||||
appotel.RecordJobProcessed(ctx, msg.Type, "permanent_failure", errorCode(perr), dur)
|
||||
|
||||
// Терминальный отказ: staging больше не нужен, убираем best-effort.
|
||||
if att, aerr := w.st.GetAttachmentInternal(persistCtx, claim.AttachmentID); aerr == nil {
|
||||
_ = w.st.DeleteObject(persistCtx, store.StagingKey(att.ChatID, att.ID))
|
||||
}
|
||||
if ferr := w.st.FailJob(persistCtx, claim.AttachmentID, errorCode(perr), perr.Error()); ferr != nil {
|
||||
w.log.WarnContext(persistCtx, "fail job persist failed",
|
||||
"job", msg.JobID,
|
||||
"attachment", claim.AttachmentID,
|
||||
"error_code", errorCode(perr),
|
||||
"error", ferr.Error(),
|
||||
)
|
||||
return // без ack: попробуем ещё раз зафиксировать отказ
|
||||
}
|
||||
w.log.InfoContext(persistCtx, "job failed permanently",
|
||||
"job", msg.JobID,
|
||||
"attachment", claim.AttachmentID,
|
||||
"error_code", errorCode(perr),
|
||||
)
|
||||
_ = w.q.Ack(persistCtx, m.ID)
|
||||
|
||||
default: // временная ошибка: retry с backoff+jitter либо финальный отказ
|
||||
if claim.Attempt < store.DefaultMaxAttempts {
|
||||
span.SetAttributes(
|
||||
attribute.String("job.outcome", "retry_scheduled"),
|
||||
attribute.String("job.error_code", "transient_error"),
|
||||
)
|
||||
next := time.Now().Add(backoff(claim.Attempt))
|
||||
if ok, rerr := w.st.ScheduleRetry(persistCtx, claim.AttachmentID, next, "transient_error"); rerr != nil || !ok {
|
||||
w.log.WarnContext(persistCtx, "schedule retry failed",
|
||||
"job", msg.JobID,
|
||||
"attachment", claim.AttachmentID,
|
||||
"attempt", claim.Attempt,
|
||||
"error", rerr,
|
||||
)
|
||||
} else {
|
||||
appotel.RecordJobProcessed(ctx, msg.Type, "retry_scheduled", "transient_error", dur)
|
||||
w.log.InfoContext(persistCtx, "job retry scheduled",
|
||||
"job", msg.JobID,
|
||||
"attachment", claim.AttachmentID,
|
||||
"attempt", claim.Attempt,
|
||||
"next_attempt_at", next.UTC().Format(time.RFC3339Nano),
|
||||
)
|
||||
}
|
||||
} else {
|
||||
span.SetAttributes(
|
||||
attribute.String("job.outcome", "retry_exhausted"),
|
||||
attribute.String("job.error_code", "retry_exhausted"),
|
||||
)
|
||||
if ferr := w.st.FailJob(persistCtx, claim.AttachmentID, "retry_exhausted", perr.Error()); ferr != nil {
|
||||
w.log.WarnContext(persistCtx, "fail exhausted job persist failed",
|
||||
"job", msg.JobID,
|
||||
"attachment", claim.AttachmentID,
|
||||
"attempt", claim.Attempt,
|
||||
"error", ferr.Error(),
|
||||
)
|
||||
return
|
||||
}
|
||||
appotel.RecordJobProcessed(ctx, msg.Type, "retry_exhausted", "retry_exhausted", dur)
|
||||
w.log.InfoContext(persistCtx, "job retry exhausted",
|
||||
"job", msg.JobID,
|
||||
"attachment", claim.AttachmentID,
|
||||
"attempt", claim.Attempt,
|
||||
)
|
||||
}
|
||||
_ = w.q.Ack(persistCtx, m.ID) // намерение о повторе уже durable в outbox
|
||||
}
|
||||
}
|
||||
|
||||
// handleInvalidMessage — нечитаемое сообщение очереди.
|
||||
// LAB 6: отдельный span, чтобы даже такие логи имели trace_id/span_id.
|
||||
func (w *Worker) handleInvalidMessage(parent context.Context, m redis.XMessage, message string, err error) {
|
||||
ctx, span := otel.Tracer("messenger-worker").Start(parent, "attachment.process.invalid",
|
||||
trace.WithSpanKind(trace.SpanKindConsumer),
|
||||
trace.WithAttributes(
|
||||
attribute.String("messaging.system", "redis_streams"),
|
||||
attribute.String("messaging.destination", store.QueueStreamKey),
|
||||
attribute.String("messaging.operation", "process"),
|
||||
attribute.String("messaging.message.id", m.ID),
|
||||
attribute.String("worker.name", w.name),
|
||||
),
|
||||
)
|
||||
defer span.End()
|
||||
|
||||
span.SetStatus(codes.Error, "invalid_message")
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
}
|
||||
|
||||
args := []any{"id", m.ID, "worker", w.name}
|
||||
if err != nil {
|
||||
args = append(args, "error", err.Error())
|
||||
}
|
||||
w.log.ErrorContext(ctx, message, args...)
|
||||
|
||||
// Нечитаемое сообщение не должно блокировать очередь.
|
||||
_ = w.q.Ack(context.WithoutCancel(ctx), m.ID)
|
||||
}
|
||||
|
||||
// process — конвейер: staging -> варианты -> финальные объекты -> COMMIT.
|
||||
func (w *Worker) process(ctx context.Context, c *store.ClaimedJob) error {
|
||||
att, err := w.st.GetAttachmentInternal(ctx, c.AttachmentID)
|
||||
if err != nil {
|
||||
return permanentErr{code: "attachment_missing", err: err}
|
||||
}
|
||||
|
||||
// LAB 6: атрибуты вложения на текущем span для поиска в Tempo.
|
||||
trace.SpanFromContext(ctx).SetAttributes(
|
||||
attribute.String("attachment.chat_id", att.ChatID),
|
||||
attribute.String("attachment.owner_id", att.OwnerID),
|
||||
attribute.Int64("attachment.size_bytes", att.SizeBytes),
|
||||
attribute.String("attachment.content_type", att.ContentType),
|
||||
attribute.String("attachment.sha256", att.SHA256),
|
||||
)
|
||||
|
||||
stagingKey := store.StagingKey(att.ChatID, att.ID)
|
||||
data, err := w.st.GetObject(ctx, stagingKey)
|
||||
if err != nil {
|
||||
return transientErr{err} // хранилище недоступно
|
||||
}
|
||||
if sum := sha256.Sum256(data); hex.EncodeToString(sum[:]) != att.SHA256 {
|
||||
return permanentErr{code: "checksum_mismatch"}
|
||||
}
|
||||
|
||||
vars, err := buildVariants(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return permanentErr{code: "invalid_image", err: err}
|
||||
}
|
||||
|
||||
for _, v := range vars {
|
||||
key := store.VariantKey(att.ChatID, att.ID, v.Name)
|
||||
if err := w.st.PutObject(ctx, key, v.Data, v.ContentType); err != nil {
|
||||
return transientErr{err}
|
||||
}
|
||||
}
|
||||
// Финальный оригинал публикуется ПОСЛЕ вариантов.
|
||||
if err := w.st.PutObject(ctx, att.S3Key, data, att.ContentType); err != nil {
|
||||
return transientErr{err}
|
||||
}
|
||||
|
||||
mvars := make([]model.Variant, 0, len(vars))
|
||||
for _, v := range vars {
|
||||
s := sha256.Sum256(v.Data)
|
||||
mvars = append(mvars, model.Variant{
|
||||
Name: v.Name, ContentType: v.ContentType,
|
||||
SizeBytes: int64(len(v.Data)), Width: v.Width, Height: v.Height,
|
||||
SHA256: hex.EncodeToString(s[:]),
|
||||
})
|
||||
}
|
||||
if err := w.st.CompleteJob(ctx, att.ID, mvars); err != nil {
|
||||
return transientErr{err}
|
||||
}
|
||||
|
||||
// LAB 6: end-to-end задержка от durable acceptance до публикации ready.
|
||||
appotel.RecordTimeToReady(ctx, time.Since(att.CreatedAt.Time).Seconds())
|
||||
|
||||
// Staging удаляется ТОЛЬКО после COMMIT результата.
|
||||
_ = w.st.DeleteObject(ctx, stagingKey)
|
||||
|
||||
w.log.InfoContext(ctx, "job completed",
|
||||
"attachment", att.ID,
|
||||
"attempt", c.Attempt,
|
||||
"variants", len(mvars),
|
||||
)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ─────────────── классификация ошибок и backoff ───────────────
|
||||
|
||||
type permanentErr struct {
|
||||
code string
|
||||
err error
|
||||
}
|
||||
|
||||
func (e permanentErr) Error() string {
|
||||
if e.err != nil {
|
||||
return e.code + ": " + e.err.Error()
|
||||
}
|
||||
return e.code
|
||||
}
|
||||
|
||||
type transientErr struct{ err error }
|
||||
|
||||
func (e transientErr) Error() string { return "transient: " + e.err.Error() }
|
||||
|
||||
func isPermanent(err error) bool {
|
||||
var p permanentErr
|
||||
return errors.As(err, &p)
|
||||
}
|
||||
|
||||
func errorCode(err error) string {
|
||||
var p permanentErr
|
||||
if errors.As(err, &p) {
|
||||
return p.code
|
||||
}
|
||||
return "processing_error"
|
||||
}
|
||||
|
||||
// backoff — экспоненциальная задержка с потолком и jitter ±25%,
|
||||
// чтобы повторы не выстраивались в синхронную волну.
|
||||
func backoff(attempt int) time.Duration {
|
||||
d := float64(backoffBase) * math.Pow(2, float64(attempt-1))
|
||||
if d > float64(backoffCap) {
|
||||
d = float64(backoffCap)
|
||||
}
|
||||
jitter := 0.75 + rand.Float64()*0.5
|
||||
return time.Duration(d * jitter)
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Track 1 bench: матрица нагрузка x размер истории для in-memory store.
|
||||
Только stdlib. Пример:
|
||||
python student-tests/bench.py --label before --container mtusi-messenger-lab1
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
import http.client
|
||||
import json
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self, host, port, user_id=None):
|
||||
self.host, self.port, self.user_id = host, port, user_id
|
||||
self.conn = None
|
||||
|
||||
def _ensure(self):
|
||||
if self.conn is None:
|
||||
self.conn = http.client.HTTPConnection(self.host, self.port, timeout=30)
|
||||
|
||||
def request(self, method, path, body=None):
|
||||
headers = {}
|
||||
data = None
|
||||
if body is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
data = json.dumps(body).encode()
|
||||
if self.user_id:
|
||||
headers["X-User-Id"] = self.user_id
|
||||
for attempt in (0, 1):
|
||||
try:
|
||||
self._ensure()
|
||||
self.conn.request(method, path, body=data, headers=headers)
|
||||
resp = self.conn.getresponse()
|
||||
payload = resp.read()
|
||||
return resp.status, (json.loads(payload) if payload else None)
|
||||
except Exception:
|
||||
self.conn = None
|
||||
if attempt:
|
||||
raise
|
||||
time.sleep(0.05)
|
||||
|
||||
|
||||
class Phase:
|
||||
def __init__(self):
|
||||
self.lock = threading.Lock()
|
||||
self.lat = []
|
||||
self.errors = 0
|
||||
self.requests = 0
|
||||
|
||||
def add(self, ms, ok):
|
||||
with self.lock:
|
||||
self.lat.append(ms)
|
||||
self.requests += 1
|
||||
if not ok:
|
||||
self.errors += 1
|
||||
|
||||
def row(self):
|
||||
with self.lock:
|
||||
lat = sorted(self.lat)
|
||||
n = len(lat)
|
||||
if n == 0:
|
||||
return 0, 0, 0, 0
|
||||
def p(q):
|
||||
return lat[min(n - 1, int((q * n) // 100))]
|
||||
return n, p(50), p(95), p(99)
|
||||
|
||||
|
||||
class RssSampler:
|
||||
def __init__(self, container, interval=2.0):
|
||||
self.container, self.interval = container, interval
|
||||
self.samples = []
|
||||
self.stop = threading.Event()
|
||||
self.th = threading.Thread(target=self._run, daemon=True)
|
||||
|
||||
def _run(self):
|
||||
while not self.stop.is_set():
|
||||
try:
|
||||
out = subprocess.run(
|
||||
["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}", self.container],
|
||||
capture_output=True, text=True, timeout=10).stdout.strip().splitlines()
|
||||
if out:
|
||||
self.samples.append(parse_mib(out[0].split("/")[0].strip()))
|
||||
except Exception:
|
||||
pass
|
||||
self.stop.wait(self.interval)
|
||||
|
||||
def start(self):
|
||||
self.th.start()
|
||||
return self
|
||||
|
||||
def finish(self):
|
||||
self.stop.set()
|
||||
self.th.join(timeout=5)
|
||||
if not self.samples:
|
||||
return 0.0, 0.0
|
||||
return sum(self.samples) / len(self.samples), max(self.samples)
|
||||
|
||||
|
||||
def parse_mib(s):
|
||||
s = s.strip()
|
||||
if s.endswith("GiB"):
|
||||
return float(s[:-3]) * 1024
|
||||
if s.endswith("MiB"):
|
||||
return float(s[:-3])
|
||||
if s.endswith("KiB"):
|
||||
return float(s[:-4]) / 1024
|
||||
return 0.0
|
||||
|
||||
|
||||
def run_phase(host, port, clients, duration, op):
|
||||
ph = Phase()
|
||||
deadline = time.perf_counter() + duration
|
||||
|
||||
def worker(idx):
|
||||
c = Client(host, port, op_user(idx))
|
||||
while time.perf_counter() < deadline:
|
||||
t0 = time.perf_counter()
|
||||
ok = op(c, idx)
|
||||
ph.add((time.perf_counter() - t0) * 1000.0, ok)
|
||||
|
||||
threads = [threading.Thread(target=worker, args=(i,)) for i in range(clients)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
return ph
|
||||
|
||||
|
||||
USERS = []
|
||||
|
||||
|
||||
def op_user(idx):
|
||||
return USERS[idx % len(USERS)]
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--label", required=True)
|
||||
ap.add_argument("--container", default="mtusi-messenger-lab1")
|
||||
ap.add_argument("--sizes", default="10000,50000,150000")
|
||||
ap.add_argument("--clients", default="8,32,96")
|
||||
ap.add_argument("--duration", type=float, default=10.0)
|
||||
ap.add_argument("--out", default="student-tests/results")
|
||||
args = ap.parse_args()
|
||||
|
||||
hostport = args.base_url.split("://")[-1].split("/")
|
||||
host, _, port = hostport[0].partition(":")
|
||||
port = int(port or 80)
|
||||
sizes = [int(x) for x in args.sizes.split(",")]
|
||||
clients = [int(x) for x in args.clients.split(",")]
|
||||
os_makedirs(args.out)
|
||||
|
||||
admin = Client(host, port)
|
||||
global USERS
|
||||
n_users = max(clients)
|
||||
for i in range(n_users):
|
||||
st, body = admin.request("POST", "/api/v1/users",
|
||||
{"username": "b" + uuid.uuid4().hex[:12], "display_name": "Bench"})
|
||||
assert st == 201, (st, body)
|
||||
USERS.append(body["id"])
|
||||
|
||||
admin.user_id = USERS[0] # <-- ДОБАВИТЬ ЭТУ СТРОКУ: чаты создаёт участник
|
||||
|
||||
st, chat = admin.request("POST", "/api/v1/chats",
|
||||
{"title": "bench", "member_ids": USERS})
|
||||
assert st == 201, (st, chat)
|
||||
chat_id = chat["id"]
|
||||
st, chat2 = admin.request("POST", "/api/v1/chats",
|
||||
{"title": "bench-writes", "member_ids": USERS})
|
||||
assert st == 201
|
||||
chat2_id = chat2["id"]
|
||||
|
||||
rows = []
|
||||
have = 0
|
||||
for H in sizes:
|
||||
# досеиваем историю до H (кумулятивно, экономим время)
|
||||
if H > have:
|
||||
seed(host, port, chat_id, H - have)
|
||||
have = H
|
||||
for C in clients:
|
||||
print(f"[{args.label}] read H={H} C={C} ...", flush=True)
|
||||
rss = RssSampler(args.container).start()
|
||||
ph = run_phase(host, port, C, args.duration, make_read_op(chat_id))
|
||||
avg, mx = rss.finish()
|
||||
n, p50, p95, p99 = ph.row()
|
||||
rows.append([args.label, "read", H, C, args.duration, n, ph.errors,
|
||||
round(n / args.duration, 1), p50, p95, p99, round(avg, 1), round(mx, 1)])
|
||||
for C in clients:
|
||||
print(f"[{args.label}] write C={C} ...", flush=True)
|
||||
rss = RssSampler(args.container).start()
|
||||
ph = run_phase(host, port, C, args.duration, make_write_op(chat2_id))
|
||||
avg, mx = rss.finish()
|
||||
n, p50, p95, p99 = ph.row()
|
||||
rows.append([args.label, "write", 0, C, args.duration, n, ph.errors,
|
||||
round(n / args.duration, 1), p50, p95, p99, round(avg, 1), round(mx, 1)])
|
||||
|
||||
path = f"{args.out}/{args.label}.csv"
|
||||
with open(path, "w", newline="", encoding="utf-8") as f:
|
||||
w = csv.writer(f)
|
||||
w.writerow(["label", "phase", "history", "clients", "duration_s", "requests",
|
||||
"errors", "rps", "p50_ms", "p95_ms", "p99_ms", "rss_avg_mib", "rss_max_mib"])
|
||||
w.writerows(rows)
|
||||
print(f"saved {path}")
|
||||
|
||||
|
||||
def os_makedirs(p):
|
||||
import os
|
||||
os.makedirs(p, exist_ok=True)
|
||||
|
||||
|
||||
def seed(host, port, chat_id, count):
|
||||
threads_n = 16
|
||||
per = count // threads_n
|
||||
lock = threading.Lock()
|
||||
state = {"done": 0, "errors": 0}
|
||||
t0 = time.perf_counter()
|
||||
|
||||
def worker(idx):
|
||||
c = Client(host, port, USERS[0])
|
||||
for j in range(per):
|
||||
st, _ = c.request("POST", f"/api/v1/chats/{chat_id}/messages",
|
||||
{"text": f"seed-{idx}-{j}"})
|
||||
with lock:
|
||||
state["done"] += 1
|
||||
if st != 201:
|
||||
state["errors"] += 1
|
||||
|
||||
threads = [threading.Thread(target=worker, args=(i,)) for i in range(threads_n)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
dt = time.perf_counter() - t0
|
||||
print(f" seeded {state['done']} msgs in {dt:.1f}s "
|
||||
f"({state['done']/dt:.0f} rps, errors={state['errors']})", flush=True)
|
||||
|
||||
|
||||
def make_read_op(chat_id):
|
||||
cursors = {}
|
||||
|
||||
def op(c, idx):
|
||||
cur = cursors.get(idx)
|
||||
path = f"/api/v1/chats/{chat_id}/messages?limit=50"
|
||||
if cur:
|
||||
path += "&cursor=" + cur
|
||||
st, body = c.request("GET", path)
|
||||
if st != 200:
|
||||
cursors[idx] = None
|
||||
return False
|
||||
cursors[idx] = body.get("next_cursor")
|
||||
return True
|
||||
|
||||
return op
|
||||
|
||||
|
||||
def make_write_op(chat_id):
|
||||
counter = {"i": 0}
|
||||
lock = threading.Lock()
|
||||
|
||||
def op(c, idx):
|
||||
with lock:
|
||||
counter["i"] += 1
|
||||
i = counter["i"]
|
||||
st, _ = c.request("POST", f"/api/v1/chats/{chat_id}/messages", {"text": f"w{i}"})
|
||||
return st == 201
|
||||
|
||||
return op
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,229 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Трек 5: согласованность кэша истории. Фазы (переключаются bat-ом через CACHE_MODE):
|
||||
off — baseline: кэша нет. 32 конкурентных холодных чтения = ~32 SQL
|
||||
(демонстрация cache stampede «до»), 100 последовательных чтений = 100 SQL,
|
||||
latency p50/p95/p99 «до».
|
||||
naive — кэш БЕЗ инвалидации версией: ожидаем НАБЛЮДАТЬ stale read
|
||||
(запись не видна из тёплого кэша). Это демонстрация проблемы согласованности.
|
||||
versioned — защищённый кэш: read-after-write OK; 32 конкурентных холодных чтения
|
||||
схлопываются single-flight'ом в 1 SQL (защита от stampede «после»);
|
||||
100 тёплых чтений обслуживает кэш (sql<=2), latency «после».
|
||||
recovery — restart redis: сессия и read-after-write корректны, кэш перестраивается.
|
||||
Запуск: scripts/cache_demo.bat (сам переключает CACHE_MODE и перезапускает api).
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
FAILURES = []
|
||||
BASE = "http://localhost:8080"
|
||||
PASSWORD = "Example-only-not-a-real-secret-123"
|
||||
READS = 100 # последовательных чтений для SQL-счётчика и latency
|
||||
STAMPEDE = 32 # конкурентных холодных чтений
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
if not cond:
|
||||
FAILURES.append(name)
|
||||
print(f"[{'PASS' if cond else 'FAIL'}] {name}" + (f" -- {detail}" if not cond and detail else ""))
|
||||
|
||||
|
||||
def sh(cmd):
|
||||
subprocess.run(cmd, shell=True, check=True, capture_output=True)
|
||||
|
||||
|
||||
def req(method, path, body=None, token=None, basic=None):
|
||||
headers, data = {}, None
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
headers["Content-Type"] = "application/json"
|
||||
if token:
|
||||
headers["Authorization"] = "Bearer " + token
|
||||
if basic:
|
||||
headers["Authorization"] = "Basic " + base64.b64encode(basic.encode()).decode()
|
||||
r = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(r, timeout=30) as resp:
|
||||
payload = resp.read().decode()
|
||||
return resp.status, (json.loads(payload) if payload else None)
|
||||
except urllib.error.HTTPError as e:
|
||||
payload = e.read().decode()
|
||||
try:
|
||||
return e.code, json.loads(payload)
|
||||
except ValueError:
|
||||
return e.code, None
|
||||
|
||||
|
||||
def wait_ready(timeout=90, want=200):
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
st, _ = req("GET", "/health/ready")
|
||||
if st == want:
|
||||
return True
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def register_login():
|
||||
uname = "t5" + uuid.uuid4().hex[:10]
|
||||
st, _ = req("POST", "/api/v1/users", {"username": uname, "display_name": "T5", "password": PASSWORD})
|
||||
assert st == 201, st
|
||||
st, sess = req("POST", "/api/v1/auth/sessions", basic=f"{uname}:{PASSWORD}")
|
||||
assert st == 201, st
|
||||
return sess["token"], sess["user"]["id"]
|
||||
|
||||
|
||||
def setup_chat(token, uid, n):
|
||||
st, chat = req("POST", "/api/v1/chats",
|
||||
{"title": "track5-" + uuid.uuid4().hex[:8], "member_ids": [uid]}, token=token)
|
||||
assert st == 201, st
|
||||
for i in range(n):
|
||||
st, _ = req("POST", f"/api/v1/chats/{chat['id']}/messages",
|
||||
{"text": f"t5-{i:03d}"}, token=token)
|
||||
assert st == 201, st
|
||||
return chat
|
||||
|
||||
|
||||
def read_page(token, chat_id):
|
||||
st, body = req("GET", f"/api/v1/chats/{chat_id}/messages?limit=50", token=token)
|
||||
assert st == 200, (st, body)
|
||||
return body
|
||||
|
||||
|
||||
def sql_count(since_unix, chat_id):
|
||||
out = subprocess.run(f"docker compose logs api --since {since_unix}",
|
||||
shell=True, capture_output=True, text=True).stdout
|
||||
return sum(1 for line in out.splitlines()
|
||||
if "sql_list_messages" in line and chat_id in line)
|
||||
|
||||
|
||||
def concurrent_burst(token, chat_id):
|
||||
"""32 конкурентных холодных чтения через barrier; возвращает число SQL-запросов."""
|
||||
since = str(int(time.time()))
|
||||
barrier = threading.Barrier(STAMPEDE)
|
||||
|
||||
def reader():
|
||||
barrier.wait()
|
||||
read_page(token, chat_id)
|
||||
|
||||
ts = [threading.Thread(target=reader) for _ in range(STAMPEDE)]
|
||||
for t in ts:
|
||||
t.start()
|
||||
for t in ts:
|
||||
t.join()
|
||||
return sql_count(since, chat_id)
|
||||
|
||||
|
||||
def pctl(xs):
|
||||
xs = sorted(xs)
|
||||
n = len(xs)
|
||||
|
||||
def p(q):
|
||||
return xs[min(n - 1, int(q * n // 100))]
|
||||
|
||||
return round(p(50), 2), round(p(95), 2), round(p(99), 2)
|
||||
|
||||
|
||||
def phase_off():
|
||||
token, uid = register_login()
|
||||
chat = setup_chat(token, uid, 5)
|
||||
# Stampede БЕЗ кэша: каждый из 32 конкурентных читателей идёт в SQL.
|
||||
n_burst = concurrent_burst(token, chat["id"])
|
||||
check("off: concurrent cold reads -> each hits SQL (stampede without cache)",
|
||||
n_burst >= STAMPEDE // 2, f"sql={n_burst} clients={STAMPEDE}")
|
||||
# Baseline: каждое последовательное чтение = SQL.
|
||||
since = str(int(time.time()))
|
||||
lats = []
|
||||
for _ in range(READS):
|
||||
t0 = time.perf_counter()
|
||||
read_page(token, chat["id"])
|
||||
lats.append((time.perf_counter() - t0) * 1000)
|
||||
n = sql_count(since, chat["id"])
|
||||
check("off: every read hits SQL", n >= READS * 0.9, f"sql={n} reads={READS}")
|
||||
p50, p95, p99 = pctl(lats)
|
||||
print(f"RESULT mode=off reads={READS} sql={n} stampede_sql={n_burst} p50={p50} p95={p95} p99={p99}")
|
||||
|
||||
|
||||
def phase_naive():
|
||||
token, uid = register_login()
|
||||
# Stale read: тёплый кэш + запись + повторное чтение.
|
||||
chat = setup_chat(token, uid, 2)
|
||||
read_page(token, chat["id"]) # прогрев кэша
|
||||
req("POST", f"/api/v1/chats/{chat['id']}/messages", {"text": "stale-probe"}, token=token)
|
||||
page = read_page(token, chat["id"])
|
||||
visible = any(m["text"] == "stale-probe" for m in page["items"])
|
||||
check("naive: stale read OBSERVED (cache returned old page after write)", not visible,
|
||||
f"visible={visible}")
|
||||
print(f"RESULT mode=naive stale_observed={not visible}")
|
||||
|
||||
|
||||
def phase_versioned():
|
||||
token, uid = register_login()
|
||||
# Read-after-write: запись видна сразу даже при тёплом кэше.
|
||||
chat = setup_chat(token, uid, 2)
|
||||
read_page(token, chat["id"])
|
||||
req("POST", f"/api/v1/chats/{chat['id']}/messages", {"text": "stale-probe"}, token=token)
|
||||
page = read_page(token, chat["id"])
|
||||
visible = any(m["text"] == "stale-probe" for m in page["items"])
|
||||
check("versioned: read-after-write OK (no stale)", visible)
|
||||
# Stampede ПОД защитой: single-flight схлопывает 32 холодных чтения в 1 SQL.
|
||||
chat2 = setup_chat(token, uid, 5)
|
||||
n_burst = concurrent_burst(token, chat2["id"])
|
||||
check("versioned: single-flight -> exactly 1 SQL on cold key", n_burst == 1,
|
||||
f"sql={n_burst} clients={STAMPEDE}")
|
||||
# Тёплые чтения обслуживает кэш.
|
||||
since = str(int(time.time()))
|
||||
lats = []
|
||||
for _ in range(READS):
|
||||
t0 = time.perf_counter()
|
||||
read_page(token, chat["id"])
|
||||
lats.append((time.perf_counter() - t0) * 1000)
|
||||
n = sql_count(since, chat["id"])
|
||||
check("versioned: warm reads served from cache", n <= 2, f"sql={n} reads={READS}")
|
||||
p50, p95, p99 = pctl(lats)
|
||||
print(f"RESULT mode=versioned reads={READS} sql={n} stampede_sql={n_burst} p50={p50} p95={p95} p99={p99}")
|
||||
|
||||
|
||||
def phase_recovery():
|
||||
token, uid = register_login()
|
||||
chat = setup_chat(token, uid, 3)
|
||||
read_page(token, chat["id"])
|
||||
sh("docker compose restart redis")
|
||||
check("recovery: api ready after redis restart", wait_ready(90, 200))
|
||||
st, _ = req("GET", "/api/v1/users/me", token=token)
|
||||
check("recovery: session still valid (source of truth = postgres)", st == 200, str(st))
|
||||
since = str(int(time.time()))
|
||||
page = read_page(token, chat["id"])
|
||||
check("recovery: history readable after cache loss", len(page["items"]) == 3)
|
||||
req("POST", f"/api/v1/chats/{chat['id']}/messages", {"text": "after-restart"}, token=token)
|
||||
page = read_page(token, chat["id"])
|
||||
check("recovery: read-after-write OK with rebuilt cache",
|
||||
any(m["text"] == "after-restart" for m in page["items"]))
|
||||
n = sql_count(since, chat["id"])
|
||||
check("recovery: cache rebuilds (1 sql for 2 reads)", n == 1, f"sql={n}")
|
||||
print(f"RESULT mode=recovery sql_after_restart={n}")
|
||||
|
||||
|
||||
def main():
|
||||
global BASE
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default=BASE)
|
||||
ap.add_argument("--phase", required=True, choices=["off", "naive", "versioned", "recovery"])
|
||||
a = ap.parse_args()
|
||||
BASE = a.base_url
|
||||
{"off": phase_off, "naive": phase_naive,
|
||||
"versioned": phase_versioned, "recovery": phase_recovery}[a.phase]()
|
||||
if FAILURES:
|
||||
print(f"PHASE {a.phase} FAILED: {FAILURES}")
|
||||
raise SystemExit(1)
|
||||
print(f"PHASE {a.phase} DONE")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,50 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Сравнение двух label'ов: python student-tests/compare.py --before before --after after"""
|
||||
import argparse
|
||||
import csv
|
||||
|
||||
|
||||
def load(path):
|
||||
d = {}
|
||||
with open(path, newline="", encoding="utf-8") as f:
|
||||
for r in csv.DictReader(f):
|
||||
d[(r["phase"], r["history"], r["clients"])] = r
|
||||
return d
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--before", required=True)
|
||||
ap.add_argument("--after", required=True)
|
||||
ap.add_argument("--results", default="student-tests/results")
|
||||
ap.add_argument("--out", default="student-tests/results/summary.md")
|
||||
args = ap.parse_args()
|
||||
|
||||
b = load(f"{args.results}/{args.before}.csv")
|
||||
a = load(f"{args.results}/{args.after}.csv")
|
||||
lines = [f"# Трек 1: сравнение `{args.before}` → `{args.after}`", ""]
|
||||
|
||||
for phase in ("read", "write"):
|
||||
keys = sorted(k for k in b if k[0] == phase and k in a)
|
||||
if not keys:
|
||||
continue
|
||||
lines.append(f"## Фаза `{phase}`")
|
||||
lines.append("")
|
||||
lines.append("| H | C | rps до | rps после | Δ rps | p95 до | p95 после | p99 до | p99 после | RSS max до | RSS max после |")
|
||||
lines.append("|---|---|---|---|---|---|---|---|---|---|---|")
|
||||
for k in keys:
|
||||
rb, ra = b[k], a[k]
|
||||
dr = (float(ra["rps"]) - float(rb["rps"])) / float(rb["rps"]) * 100 if float(rb["rps"]) else 0
|
||||
lines.append(f"| {k[1]} | {k[2]} | {rb['rps']} | {ra['rps']} | {dr:+.0f}% | "
|
||||
f"{rb['p95_ms']} | {ra['p95_ms']} | {rb['p99_ms']} | {ra['p99_ms']} | "
|
||||
f"{rb['rss_max_mib']} | {ra['rss_max_mib']} |")
|
||||
lines.append("")
|
||||
|
||||
with open(args.out, "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(lines) + "\n")
|
||||
print("\n".join(lines))
|
||||
print(f"\nsaved {args.out}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,117 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка expiry при коротком SESSION_TTL_SECONDS (стенд поднят скриптом).
|
||||
|
||||
Устойчивость к медленному старту после перезапуска api:
|
||||
- заголовки ищем в lower-case (Go шлёт "Www-Authenticate", а не "WWW-Authenticate");
|
||||
- логин повторяется, пока на сессии не останется достаточный запас времени,
|
||||
иначе «свежий» запрос ловил 401 из-за гонки времени при очень коротком TTL.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
BASE = "http://localhost:8080"
|
||||
PASSWORD = "Example-only-not-a-real-secret-123"
|
||||
FAILURES = []
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
if not cond:
|
||||
FAILURES.append(name)
|
||||
print(f"[{'PASS' if cond else 'FAIL'}] {name}" + (f" -- {detail}" if not cond and detail else ""))
|
||||
|
||||
|
||||
def _lower_headers(headers):
|
||||
"""Ключи заголовков в нижнем регистре: регистр присылки не важен."""
|
||||
return {k.lower(): v for k, v in headers.items()}
|
||||
|
||||
|
||||
def www_auth(hdr):
|
||||
return hdr.get("www-authenticate", "")
|
||||
|
||||
|
||||
def req(method, path, body=None, token=None, basic=None):
|
||||
headers, data = {}, None
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
headers["Content-Type"] = "application/json"
|
||||
if token:
|
||||
headers["Authorization"] = "Bearer " + token
|
||||
if basic:
|
||||
headers["Authorization"] = "Basic " + base64.b64encode(basic.encode()).decode()
|
||||
r = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(r, timeout=10) as resp:
|
||||
p = resp.read().decode()
|
||||
return resp.status, _lower_headers(resp.headers), (json.loads(p) if p else None)
|
||||
except urllib.error.HTTPError as e:
|
||||
p = e.read().decode()
|
||||
try:
|
||||
return e.code, _lower_headers(e.headers), json.loads(p)
|
||||
except ValueError:
|
||||
return e.code, _lower_headers(e.headers), None
|
||||
|
||||
|
||||
def seconds_left(sess):
|
||||
"""Сколько секунд осталось до истечения — по expires_at из ответа сервера."""
|
||||
exp = datetime.fromisoformat(sess["expires_at"].replace("Z", "+00:00"))
|
||||
return (exp - datetime.now(timezone.utc)).total_seconds()
|
||||
|
||||
|
||||
def login_fresh(uname, min_left=1.5, attempts=5):
|
||||
"""Логин с повторами, пока на сессии не останется >= min_left секунд.
|
||||
Защита от медленных первых запросов сразу после перезапуска контейнера."""
|
||||
sess = None
|
||||
for i in range(attempts):
|
||||
st, _, sess = req("POST", "/api/v1/auth/sessions", basic=f"{uname}:{PASSWORD}")
|
||||
assert st == 201, f"login failed: {st} {sess}"
|
||||
if seconds_left(sess) >= min_left:
|
||||
return sess
|
||||
time.sleep(0.3)
|
||||
return sess # последний вариант, даже если запас мал
|
||||
|
||||
|
||||
def main():
|
||||
global BASE
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default=BASE)
|
||||
BASE = ap.parse_args().base_url
|
||||
|
||||
uname = "exp" + uuid.uuid4().hex[:10]
|
||||
st, _, body = req("POST", "/api/v1/users",
|
||||
{"username": uname, "display_name": "EX", "password": PASSWORD})
|
||||
assert st == 201, f"register failed: {st} {body}"
|
||||
|
||||
sess = login_fresh(uname)
|
||||
check("login 201 with short TTL", True)
|
||||
token = sess["token"]
|
||||
|
||||
# Свежий токен обязан работать сразу после логина.
|
||||
st, _, _ = req("GET", "/api/v1/users/me", token=token)
|
||||
check("fresh token 200", st == 200, str(st))
|
||||
|
||||
# Ждём гарантированного истечения: реальный остаток + 1 с запаса.
|
||||
wait = seconds_left(sess) + 1.0
|
||||
time.sleep(max(wait, 0.5))
|
||||
|
||||
st, hdr, _ = req("GET", "/api/v1/users/me", token=token)
|
||||
check("expired token -> 401", st == 401, str(st))
|
||||
check("expired WWW-Authenticate Bearer", www_auth(hdr).startswith("Bearer"),
|
||||
f"got {www_auth(hdr)!r}")
|
||||
|
||||
st, _, _ = req("POST", "/api/v1/auth/sessions", basic=f"{uname}:{PASSWORD}")
|
||||
check("re-login after expiry 201", st == 201)
|
||||
|
||||
if FAILURES:
|
||||
print(f"FAILED {len(FAILURES)}: {FAILURES}")
|
||||
raise SystemExit(1)
|
||||
print("EXPIRY CHECKS PASSED")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,10 @@
|
||||
-- План запроса keyset-пагинации истории: первая страница (курсор = начало времён).
|
||||
-- Ожидаем WITH index: Limit -> Index Scan using messages_history_idx
|
||||
-- Ожидаем WITHOUT index: Limit -> Sort -> Seq Scan on messages
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = :'chat'
|
||||
AND (created_at, id) > ('2020-01-01T00:00:00+00', '00000000-0000-0000-0000-000000000000')
|
||||
ORDER BY created_at, id
|
||||
LIMIT 51;
|
||||
@@ -0,0 +1,143 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Уровень 4: деградация при потере сервисов.
|
||||
Redis down -> API обслуживает запросы через SQL (200), логи warn.
|
||||
Postgres down -> /health/ready 503 и защищённые запросы 503 (не 200, не «аноним доверен»).
|
||||
Запуск из корня репозитория:
|
||||
python student-tests/failover_tests.py --base-url http://localhost:8080
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
FAILURES = []
|
||||
BASE = "http://localhost:8080"
|
||||
PASSWORD = "Example-only-not-a-real-secret-123"
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
if not cond:
|
||||
FAILURES.append(name)
|
||||
print(f"[{'PASS' if cond else 'FAIL'}] {name}" + (f" -- {detail}" if not cond and detail else ""))
|
||||
|
||||
|
||||
def sh(cmd):
|
||||
subprocess.run(cmd, shell=True, check=True, capture_output=True)
|
||||
|
||||
|
||||
def req(method, path, body=None, token=None, basic=None):
|
||||
headers, data = {}, None
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
headers["Content-Type"] = "application/json"
|
||||
if token:
|
||||
headers["Authorization"] = "Bearer " + token
|
||||
if basic:
|
||||
headers["Authorization"] = "Basic " + base64.b64encode(basic.encode()).decode()
|
||||
r = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(r, timeout=10) as resp:
|
||||
payload = resp.read().decode()
|
||||
return resp.status, (json.loads(payload) if payload else None)
|
||||
except urllib.error.HTTPError as e:
|
||||
payload = e.read().decode()
|
||||
try:
|
||||
return e.code, json.loads(payload)
|
||||
except ValueError:
|
||||
return e.code, None
|
||||
|
||||
|
||||
def wait_ready(timeout=60, want=200):
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
st, _ = req("GET", "/health/ready")
|
||||
if st == want:
|
||||
return True
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
global BASE
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default=BASE)
|
||||
BASE = ap.parse_args().base_url
|
||||
|
||||
# Создаём пользователя
|
||||
uname = "fo" + uuid.uuid4().hex[:10] # без дефиса
|
||||
st, body = req("POST", "/api/v1/users", {"username": uname, "display_name": "FO", "password": PASSWORD})
|
||||
print(f"DEBUG register: {st} {body}")
|
||||
assert st == 201, f"register failed: {st} {body}"
|
||||
|
||||
st, sess = req("POST", "/api/v1/auth/sessions", basic=f"{uname}:{PASSWORD}")
|
||||
print(f"DEBUG login: {st} {sess}")
|
||||
assert st == 201, f"login failed: {st} {sess}"
|
||||
token = sess["token"]
|
||||
|
||||
# Узнаём свой id через /me
|
||||
me_st, me = req("GET", "/api/v1/users/me", token=token)
|
||||
print(f"DEBUG /me: {me_st} {me}")
|
||||
assert me_st == 200, f"/me failed: {me_st} {me}"
|
||||
|
||||
# Создаём чат с самим собой
|
||||
st, chat = req("POST", "/api/v1/chats", {"title": "failover", "member_ids": [me["id"]]}, token=token)
|
||||
print(f"DEBUG create chat: {st} {chat}")
|
||||
assert st == 201, f"create chat failed: {st} {chat}"
|
||||
|
||||
# ── Redis down: деградация в SQL, не отказ ──
|
||||
sh("docker compose stop redis")
|
||||
time.sleep(2)
|
||||
st, _ = req("GET", "/health/ready")
|
||||
check("redis down: ready stays 200 (cache optional)", st == 200, str(st))
|
||||
st, _ = req("GET", "/api/v1/users/me", token=token)
|
||||
check("redis down: auth via postgres 200", st == 200, str(st))
|
||||
st, _ = req("POST", f"/api/v1/chats/{chat['id']}/messages", {"text": "during redis outage"}, token=token)
|
||||
check("redis down: write 201", st == 201, str(st))
|
||||
st, _ = req("GET", f"/api/v1/chats/{chat['id']}/messages?limit=10", token=token)
|
||||
check("redis down: read 200", st == 200, str(st))
|
||||
sh("docker compose start redis")
|
||||
check("redis back: ready 200", wait_ready(60, 200))
|
||||
|
||||
# ── Postgres down: ограниченные ошибки, аноним не доверен ──
|
||||
sh("docker compose stop postgres")
|
||||
check("postgres down: ready becomes 503", wait_ready(60, 503))
|
||||
st, _ = req("GET", "/api/v1/users/me", token=token)
|
||||
check("postgres down: protected request 503 (not 200/401)", st == 503, str(st))
|
||||
st, _ = req("GET", "/api/v1/users/me")
|
||||
check("postgres down: anonymous still 401", st == 401, str(st))
|
||||
sh("docker compose start postgres")
|
||||
check("postgres back: ready 200", wait_ready(90, 200))
|
||||
st, _ = req("GET", "/api/v1/users/me", token=token)
|
||||
check("postgres back: same session valid 200", st == 200, str(st))
|
||||
|
||||
# ── Logout при сбое Redis: никаких «тихих» 204, оставляющих токен живым ──
|
||||
st, sess2 = req("POST", "/api/v1/auth/sessions", basic=f"{uname}:{PASSWORD}")
|
||||
assert st == 201, f"second login failed: {st} {sess2}"
|
||||
token2 = sess2["token"]
|
||||
|
||||
sh("docker compose stop redis")
|
||||
time.sleep(2)
|
||||
st, _ = req("DELETE", "/api/v1/auth/sessions/current", token=token2)
|
||||
check("redis down: logout returns 503, not silent 204", st == 503, str(st))
|
||||
st, _ = req("GET", "/api/v1/users/me", token=token2)
|
||||
check("redis down: token already revoked in postgres -> 401", st == 401, str(st))
|
||||
|
||||
sh("docker compose start redis")
|
||||
check("redis back (2): ready 200", wait_ready(60, 200))
|
||||
st, _ = req("DELETE", "/api/v1/auth/sessions/current", token=token2)
|
||||
check("redis back: logout retry 204 (DEL confirmed)", st == 204, str(st))
|
||||
st, _ = req("GET", "/api/v1/users/me", token=token2)
|
||||
check("after retry logout: token still 401", st == 401, str(st))
|
||||
|
||||
if FAILURES:
|
||||
print(f"FAILED {len(FAILURES)}: {FAILURES}")
|
||||
raise SystemExit(1)
|
||||
print("ALL FAILOVER TESTS PASSED")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,145 @@
|
||||
#!/usr/bin/env python3
|
||||
"""LAB 6: генератор нагрузки для демо и защиты. Только stdlib.
|
||||
|
||||
Создаёт пользователей и чаты, шлёт сообщения (Idempotency-Key обязателен по
|
||||
контракту lab3), опционально загружает вложения (202) и ждёт ready.
|
||||
Печатает сводку: запросы, коды ответов, RPS, p50/p95/p99.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
PNG = base64.b64decode(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJg=="
|
||||
)
|
||||
|
||||
_lock = threading.Lock()
|
||||
_lat = []
|
||||
_codes = {}
|
||||
|
||||
|
||||
def call(base, method, path, token=None, basic=None, obj=None, raw=None, ctype=None, idem=None):
|
||||
headers = {}
|
||||
data = None
|
||||
if obj is not None:
|
||||
data = json.dumps(obj).encode()
|
||||
headers["Content-Type"] = "application/json"
|
||||
if raw is not None:
|
||||
data = raw
|
||||
headers["Content-Type"] = ctype or "application/octet-stream"
|
||||
if token:
|
||||
headers["Authorization"] = "Bearer " + token
|
||||
if basic:
|
||||
import base64 as b64
|
||||
pair = f"{basic[0]}:{basic[1]}".encode()
|
||||
headers["Authorization"] = "Basic " + b64.b64encode(pair).decode()
|
||||
if idem:
|
||||
headers["Idempotency-Key"] = idem
|
||||
req = urllib.request.Request(base + path, data=data, headers=headers, method=method)
|
||||
t0 = time.perf_counter()
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as r:
|
||||
status, body = r.status, r.read()
|
||||
except urllib.error.HTTPError as e:
|
||||
status, body = e.code, e.read()
|
||||
dt = time.perf_counter() - t0
|
||||
with _lock:
|
||||
_lat.append(dt)
|
||||
_codes[status] = _codes.get(status, 0) + 1
|
||||
return status, body
|
||||
|
||||
|
||||
def jbody(b):
|
||||
try:
|
||||
return json.loads(b)
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def pct(v, p):
|
||||
if not v:
|
||||
return 0.0
|
||||
v = sorted(v)
|
||||
k = max(0, min(len(v) - 1, int(round(p * (len(v) - 1)))))
|
||||
return v[k]
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base", default="http://localhost:8080")
|
||||
ap.add_argument("--users", type=int, default=2)
|
||||
ap.add_argument("--messages", type=int, default=30)
|
||||
ap.add_argument("--attachments", type=int, default=1)
|
||||
ap.add_argument("--concurrency", type=int, default=8)
|
||||
ap.add_argument("--poll-ready", action="store_true")
|
||||
a = ap.parse_args()
|
||||
|
||||
t0 = time.perf_counter()
|
||||
jobs = []
|
||||
for u in range(a.users):
|
||||
name = f"load{int(time.time())}-{u}"
|
||||
st, _ = call(a.base, "POST", "/api/v1/users",
|
||||
obj={"username": name, "display_name": name, "password": "load-pass-1"})
|
||||
if st not in (201, 409):
|
||||
print(f"[skip] register {st}")
|
||||
continue
|
||||
st, b = call(a.base, "POST", "/api/v1/auth/sessions", basic=(name, "load-pass-1"))
|
||||
tok = jbody(b).get("token")
|
||||
if not tok:
|
||||
print(f"[skip] login {st}")
|
||||
continue
|
||||
st, b = call(a.base, "POST", "/api/v1/chats", token=tok,
|
||||
obj={"title": f"load chat {u}", "member_ids": []})
|
||||
chat = jbody(b).get("id")
|
||||
if not chat:
|
||||
st, b = call(a.base, "POST", "/api/v1/chats", token=tok, obj={"title": f"load chat {u}"})
|
||||
chat = jbody(b).get("id")
|
||||
if not chat:
|
||||
print(f"[skip] chat {st}")
|
||||
continue
|
||||
with ThreadPoolExecutor(a.concurrency) as ex:
|
||||
futs = [ex.submit(call, a.base, "POST", f"/api/v1/chats/{chat}/messages", token=tok,
|
||||
obj={"text": f"load msg {i}", "attachment_ids": []},
|
||||
idem=str(uuid.uuid4()))
|
||||
for i in range(a.messages)]
|
||||
for f in futs:
|
||||
f.result()
|
||||
for _ in range(a.attachments):
|
||||
st, b = call(a.base, "POST", f"/api/v1/chats/{chat}/attachments",
|
||||
token=tok, raw=PNG, ctype="image/png")
|
||||
att = jbody(b).get("id")
|
||||
if att and a.poll_ready:
|
||||
jobs.append((tok, att))
|
||||
|
||||
def poll(job):
|
||||
tok, att = job
|
||||
deadline = time.time() + 60
|
||||
while time.time() < deadline:
|
||||
st, b = call(a.base, "GET", f"/api/v1/attachments/{att}", token=tok)
|
||||
if jbody(b).get("status") == "ready":
|
||||
return True
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
if jobs:
|
||||
with ThreadPoolExecutor(max(1, len(jobs))) as ex:
|
||||
oks = list(ex.map(poll, jobs))
|
||||
print(f"attachments ready: {sum(oks)}/{len(jobs)}")
|
||||
|
||||
dur = time.perf_counter() - t0
|
||||
with _lock:
|
||||
lat, codes = list(_lat), dict(_codes)
|
||||
total = len(lat)
|
||||
print(f"requests={total} wall={dur:.1f}s rps={total / dur:.1f}")
|
||||
print("status_codes=", codes)
|
||||
print(f"latency_ms p50={pct(lat, .5) * 1000:.1f} p95={pct(lat, .95) * 1000:.1f} p99={pct(lat, .99) * 1000:.1f}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,24 @@
|
||||
# Трек 1: сравнение `before` → `after`
|
||||
|
||||
## Фаза `read`
|
||||
|
||||
| H | C | rps до | rps после | Δ rps | p95 до | p95 после | p99 до | p99 после | RSS max до | RSS max после |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| 10000 | 32 | 2317.8 | 3020.1 | +30% | 21.274199985782616 | 20.00600000610575 | 26.18879999499768 | 25.65840000170283 | 23.4 | 15.5 |
|
||||
| 10000 | 8 | 1801.8 | 3074.2 | +71% | 6.358900005579926 | 3.886999998940155 | 7.281500002136454 | 4.761800009873696 | 15.2 | 13.8 |
|
||||
| 10000 | 96 | 2181.6 | 2964.9 | +36% | 82.42629999585915 | 63.01610000082292 | 111.98879999574274 | 82.43429999856744 | 26.8 | 17.1 |
|
||||
| 150000 | 32 | 193.7 | 2807.4 | +1349% | 228.64050000498537 | 21.50559998699464 | 269.6471999952337 | 27.85779999976512 | 158.0 | 64.6 |
|
||||
| 150000 | 8 | 132.5 | 2741.9 | +1969% | 79.64959999662824 | 4.394600007799454 | 89.75159999681637 | 5.48490000073798 | 86.7 | 64.1 |
|
||||
| 150000 | 96 | 198.9 | 2739.8 | +1277% | 717.6964999962365 | 68.98559999535792 | 1624.148500006413 | 89.6325999929104 | 338.8 | 66.1 |
|
||||
| 50000 | 32 | 634.7 | 2902.8 | +357% | 79.3132999970112 | 20.84120000654366 | 96.15100000519305 | 26.748899996164255 | 68.8 | 29.5 |
|
||||
| 50000 | 8 | 436.7 | 2818.5 | +545% | 26.245999993989244 | 4.248600002028979 | 34.15639999730047 | 5.172299992409535 | 36.5 | 29.1 |
|
||||
| 50000 | 96 | 685.8 | 2842.3 | +314% | 350.77499999897555 | 65.7708999933675 | 623.8148999982513 | 86.68810001108795 | 120.9 | 31.8 |
|
||||
|
||||
## Фаза `write`
|
||||
|
||||
| H | C | rps до | rps после | Δ rps | p95 до | p95 после | p99 до | p99 после | RSS max до | RSS max после |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| 0 | 32 | 3254.3 | 3129.9 | -4% | 18.110699995304458 | 18.42429999669548 | 22.875099995872006 | 23.47979998739902 | 85.5 | 79.8 |
|
||||
| 0 | 8 | 3021.2 | 2970.7 | -2% | 4.0160999924410135 | 4.090300004463643 | 4.905399997369386 | 4.8944000009214506 | 225.0 | 68.5 |
|
||||
| 0 | 96 | 3173.5 | 3057.3 | -4% | 56.61030000192113 | 57.44370000320487 | 73.07939999736845 | 74.52429999830201 | 98.3 | 91.9 |
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Студенческие тесты lab2 (Bearer-аутентификация). Одна команда:
|
||||
python student-tests/run_tests.py --base-url http://localhost:8080
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import threading
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
FAILURES = []
|
||||
BASE = "http://localhost:8080"
|
||||
PASSWORD = "Example-only-not-a-real-secret-123" # 38 code points: в диапазоне 12..128
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
if not cond:
|
||||
FAILURES.append(name)
|
||||
print(f"[{'PASS' if cond else 'FAIL'}] {name}" + (f" -- {detail}" if not cond and detail else ""))
|
||||
|
||||
|
||||
def _lower_headers(headers):
|
||||
"""Ключи заголовков в нижнем регистре.
|
||||
Go шлёт WWW-Authenticate как "Www-Authenticate" (каноническая MIME-форма),
|
||||
а dict(headers) сохраняет регистр как пришёл. Чтобы тест не зависел от
|
||||
регистра, всегда ищем заголовки в lower-case."""
|
||||
return {k.lower(): v for k, v in headers.items()}
|
||||
|
||||
|
||||
def www_auth(hdr):
|
||||
"""Значение WWW-Authenticate независимо от регистра ключа."""
|
||||
return hdr.get("www-authenticate", "")
|
||||
|
||||
|
||||
def req(method, path, body=None, raw=None, token=None, basic=None,
|
||||
ctype="application/json", extra_headers=None):
|
||||
headers, data = {}, None
|
||||
if raw is not None:
|
||||
data, headers["Content-Type"] = raw.encode("utf-8"), ctype
|
||||
elif body is not None:
|
||||
data, headers["Content-Type"] = json.dumps(body, ensure_ascii=False).encode("utf-8"), ctype
|
||||
if token:
|
||||
headers["Authorization"] = "Bearer " + token
|
||||
if basic:
|
||||
headers["Authorization"] = "Basic " + base64.b64encode(basic.encode("utf-8")).decode("ascii")
|
||||
if extra_headers:
|
||||
headers.update(extra_headers)
|
||||
r = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(r, timeout=30) as resp:
|
||||
payload = resp.read().decode("utf-8")
|
||||
return resp.status, _lower_headers(resp.headers), (json.loads(payload) if payload else None)
|
||||
except urllib.error.HTTPError as e:
|
||||
payload = e.read().decode("utf-8")
|
||||
try:
|
||||
return e.code, _lower_headers(e.headers), json.loads(payload)
|
||||
except ValueError:
|
||||
return e.code, _lower_headers(e.headers), None
|
||||
|
||||
|
||||
def register(username=None, password=PASSWORD, display="Тест Юникод ✓"):
|
||||
username = username or "u" + uuid.uuid4().hex[:12]
|
||||
return req("POST", "/api/v1/users",
|
||||
{"username": username, "display_name": display, "password": password})
|
||||
|
||||
|
||||
def login(username, password=PASSWORD):
|
||||
return req("POST", "/api/v1/auth/sessions", basic=f"{username}:{password}")
|
||||
|
||||
|
||||
def main():
|
||||
global BASE
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default=BASE)
|
||||
BASE = ap.parse_args().base_url
|
||||
|
||||
# ── health и номерки ──
|
||||
st, hdr, body = req("GET", "/health/live")
|
||||
check("health live 200", st == 200 and body == {"status": "ok"})
|
||||
check("X-Request-Id present", bool(hdr.get("x-request-id")))
|
||||
st, _, body = req("GET", "/health/ready")
|
||||
check("health ready 200", st == 200 and body == {"status": "ok"})
|
||||
|
||||
# ── валидация регистрации ──
|
||||
st, _, _ = req("POST", "/api/v1/users", raw='{"username": "abc",')
|
||||
check("malformed JSON -> 400", st == 400)
|
||||
st, _, _ = req("POST", "/api/v1/users",
|
||||
{"username": "extrafield1", "display_name": "x", "password": PASSWORD, "junk": 1})
|
||||
check("extra field -> 400", st == 400)
|
||||
st, _, _ = req("POST", "/api/v1/users", {"username": "BadName", "display_name": "x", "password": PASSWORD})
|
||||
check("username pattern -> 400", st == 400)
|
||||
st, _, _ = req("POST", "/api/v1/users", {"username": "wsname1", "display_name": " ", "password": PASSWORD})
|
||||
check("whitespace display_name -> 400", st == 400)
|
||||
st, _, _ = req("POST", "/api/v1/users", {"username": "shortpw1", "display_name": "x", "password": "short"})
|
||||
check("password < 12 -> 400", st == 400)
|
||||
st, _, _ = req("POST", "/api/v1/users", {"username": "longpw1", "display_name": "x", "password": "x" * 129})
|
||||
check("password > 128 -> 400", st == 400)
|
||||
st, _, _ = req("POST", "/api/v1/users", {"username": "wspw1", "display_name": "x", "password": " "})
|
||||
check("whitespace password -> 400", st == 400)
|
||||
|
||||
st, _, alice = register()
|
||||
check("register 201", st == 201)
|
||||
check("no password/hash in User response",
|
||||
isinstance(alice, dict) and "password" not in alice and "password_hash" not in alice)
|
||||
st2, _, _ = register(username=alice["username"])
|
||||
check("duplicate username -> 409", st2 == 409)
|
||||
|
||||
# ── вход: неверные/неизвестные/успех ──
|
||||
st, hdr, _ = login(alice["username"], "Wrong-" + PASSWORD)
|
||||
check("wrong password -> 401", st == 401)
|
||||
check("wrong password WWW-Authenticate Basic", www_auth(hdr).startswith("Basic"),
|
||||
f"got {www_auth(hdr)!r}")
|
||||
st, hdr, _ = login("nosuchuser" + uuid.uuid4().hex[:6])
|
||||
check("unknown user -> 401 same shape",
|
||||
st == 401 and www_auth(hdr).startswith("Basic"), f"got {www_auth(hdr)!r}")
|
||||
st, _, sess = login(alice["username"])
|
||||
check("login 201 session", st == 201 and sess["token_type"] == "Bearer" and len(sess["token"]) >= 32)
|
||||
check("session has expires_at and user", "expires_at" in sess and "user" in sess)
|
||||
token_a = sess["token"]
|
||||
|
||||
_, _, bob = register(); _, _, sess_b = login(bob["username"]); token_b = sess_b["token"]
|
||||
_, _, carol = register(); _, _, sess_c = login(carol["username"]); token_c = sess_c["token"]
|
||||
|
||||
# ── правила аутентификации lab2 ──
|
||||
st, hdr, _ = req("GET", "/api/v1/users/me")
|
||||
check("no auth -> 401 + Bearer header",
|
||||
st == 401 and www_auth(hdr).startswith("Bearer"), f"got {www_auth(hdr)!r}")
|
||||
st, _, _ = req("GET", "/api/v1/users/me", extra_headers={"X-User-Id": alice["id"]})
|
||||
check("X-User-Id ignored -> 401", st == 401)
|
||||
st, hdr, _ = req("GET", "/api/v1/users/me", basic=f"{alice['username']}:{PASSWORD}")
|
||||
check("Basic on business endpoint -> 401 Bearer",
|
||||
st == 401 and www_auth(hdr).startswith("Bearer"), f"got {www_auth(hdr)!r}")
|
||||
st, _, _ = req("GET", "/api/v1/users/me", token="not-a-valid-token")
|
||||
check("garbage Bearer -> 401", st == 401)
|
||||
st, _, me = req("GET", "/api/v1/users/me", token=token_a)
|
||||
check("me with Bearer 200", st == 200 and me["id"] == alice["id"])
|
||||
|
||||
# ── чаты и доступ ──
|
||||
st, _, chat = req("POST", "/api/v1/chats",
|
||||
{"title": "Проект по ВНП", "member_ids": [alice["id"], bob["id"]]}, token=token_a)
|
||||
check("create chat 201", st == 201)
|
||||
cid = chat["id"]
|
||||
st, _, _ = req("GET", f"/api/v1/chats/{cid}", token=token_c)
|
||||
check("outsider GET chat -> 404", st == 404)
|
||||
st, _, _ = req("POST", f"/api/v1/chats/{cid}/messages", {"text": "hi"}, token=token_c)
|
||||
check("outsider POST message -> 404", st == 404)
|
||||
st, _, body = req("GET", "/api/v1/chats", token=token_c)
|
||||
check("outsider list hides foreign chat", st == 200 and all(c["id"] != cid for c in body["items"]))
|
||||
|
||||
# ── валидация сообщений ──
|
||||
st, _, _ = req("POST", f"/api/v1/chats/{cid}/messages", {"text": ""}, token=token_a)
|
||||
check("empty text -> 400", st == 400)
|
||||
st, _, _ = req("POST", f"/api/v1/chats/{cid}/messages", {"text": " \n "}, token=token_a)
|
||||
check("whitespace text -> 400", st == 400)
|
||||
st, _, _ = req("POST", f"/api/v1/chats/{cid}/messages", {"text": "x" * 4001}, token=token_a)
|
||||
check("text > 4000 -> 400", st == 400)
|
||||
text = "Привет, Боб! 🚀 Ünïcödé ✓"
|
||||
st, _, msg = req("POST", f"/api/v1/chats/{cid}/messages", {"text": text}, token=token_a)
|
||||
check("unicode round-trip exact", st == 201 and msg["text"] == text)
|
||||
|
||||
# ── пагинация ──
|
||||
for i in range(24):
|
||||
req("POST", f"/api/v1/chats/{cid}/messages", {"text": f"msg-{i:02d}"}, token=token_b)
|
||||
hist, cursor, pages = [], None, 0
|
||||
while True:
|
||||
q = f"/api/v1/chats/{cid}/messages?limit=10" + (f"&cursor={cursor}" if cursor else "")
|
||||
st, _, page = req("GET", q, token=token_b)
|
||||
pages += 1
|
||||
hist.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if not cursor:
|
||||
break
|
||||
ids = [m["id"] for m in hist]
|
||||
check("25 msgs -> 3 pages, no repeats", pages == 3 and len(ids) == 25 and len(set(ids)) == 25)
|
||||
pairs = [(m["created_at"], m["id"]) for m in hist]
|
||||
bad = [i for i in range(len(pairs) - 1) if pairs[i] > pairs[i + 1]]
|
||||
check("history ordered by (created_at, id)", not bad, f"{len(bad)} inversions")
|
||||
|
||||
st, _, chat2 = req("POST", "/api/v1/chats",
|
||||
{"title": "other", "member_ids": [alice["id"], bob["id"]]}, token=token_a)
|
||||
req("POST", f"/api/v1/chats/{chat2['id']}/messages", {"text": "o1"}, token=token_a)
|
||||
req("POST", f"/api/v1/chats/{chat2['id']}/messages", {"text": "o2"}, token=token_a)
|
||||
_, _, p2 = req("GET", f"/api/v1/chats/{chat2['id']}/messages?limit=1", token=token_a)
|
||||
st, _, _ = req("GET", f"/api/v1/chats/{cid}/messages?limit=10&cursor={p2['next_cursor']}", token=token_a)
|
||||
check("cursor from another chat -> 400", st == 400)
|
||||
ok = True
|
||||
for v in ("0", "101", "abc"):
|
||||
st, _, _ = req("GET", f"/api/v1/chats/{cid}/messages?limit={v}", token=token_a)
|
||||
ok = ok and st == 400
|
||||
check("limit 0/101/abc -> 400", ok)
|
||||
|
||||
# ── logout и отзыв ──
|
||||
_, _, sess_b2 = login(bob["username"])
|
||||
token_b2 = sess_b2["token"]
|
||||
st, _, _ = req("DELETE", "/api/v1/auth/sessions/current", token=token_b2)
|
||||
check("logout -> 204", st == 204)
|
||||
st, _, _ = req("GET", "/api/v1/users/me", token=token_b2)
|
||||
check("revoked token -> 401", st == 401)
|
||||
st, _, _ = req("GET", "/api/v1/users/me", token=token_b)
|
||||
check("other session of same user still valid", st == 200)
|
||||
|
||||
# ── гонка регистрации: UNIQUE-ограничение (имя БЕЗ дефиса: маска username) ──
|
||||
race_name = "race" + uuid.uuid4().hex[:10]
|
||||
results, lock = [], threading.Lock()
|
||||
def racer():
|
||||
s, _, _ = register(username=race_name)
|
||||
with lock:
|
||||
results.append(s)
|
||||
ts = [threading.Thread(target=racer) for _ in range(10)]
|
||||
for t in ts: t.start()
|
||||
for t in ts: t.join()
|
||||
check("race registration: one 201, rest 409",
|
||||
results.count(201) == 1 and results.count(409) == 9, str(results))
|
||||
|
||||
# ── rollback составной операции ──
|
||||
_, _, before = req("GET", "/api/v1/chats", token=token_a)
|
||||
n_before = len(before["items"])
|
||||
st, _, _ = req("POST", "/api/v1/chats",
|
||||
{"title": "rollback-probe", "member_ids": [alice["id"], str(uuid.uuid4())]}, token=token_a)
|
||||
check("chat with unknown member -> 400", st == 400)
|
||||
_, _, after = req("GET", "/api/v1/chats", token=token_a)
|
||||
check("rollback: no partial chat",
|
||||
len(after["items"]) == n_before and all(c["title"] != "rollback-probe" for c in after["items"]))
|
||||
|
||||
# ── конкурентные записи ──
|
||||
errs = []
|
||||
def writer(idx):
|
||||
for j in range(10):
|
||||
s, _, _ = req("POST", f"/api/v1/chats/{cid}/messages", {"text": f"c{idx}-{j}"}, token=token_b)
|
||||
if s != 201:
|
||||
errs.append((idx, j, s))
|
||||
ts = [threading.Thread(target=writer, args=(i,)) for i in range(10)]
|
||||
for t in ts: t.start()
|
||||
for t in ts: t.join()
|
||||
check("100 concurrent sends all 201", not errs, str(errs[:5]))
|
||||
items, cur = [], None
|
||||
while True:
|
||||
q = f"/api/v1/chats/{cid}/messages?limit=100" + (f"&cursor={cur}" if cur else "")
|
||||
st, _, page = req("GET", q, token=token_b)
|
||||
items.extend(page["items"])
|
||||
cur = page["next_cursor"]
|
||||
if not cur:
|
||||
break
|
||||
expected = {f"c{i}-{j}" for i in range(10) for j in range(10)}
|
||||
got = {m["text"] for m in items}
|
||||
check("exactly 100 unique concurrent messages", expected <= got and len(got & expected) == 100)
|
||||
|
||||
# ── прочее контрактное ──
|
||||
st, _, _ = req("POST", "/api/v1/users",
|
||||
raw='{"username":"cttest1","display_name":"x","password":"' + PASSWORD + '"}',
|
||||
ctype="text/plain")
|
||||
check("wrong Content-Type -> 415", st == 415)
|
||||
st, _, body = req("GET", "/nope")
|
||||
check("unknown route -> 404 envelope", st == 404 and body and body["error"]["code"] == "not_found")
|
||||
|
||||
if FAILURES:
|
||||
print(f"FAILED {len(FAILURES)}: {FAILURES}")
|
||||
raise SystemExit(1)
|
||||
print("ALL STUDENT TESTS PASSED")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,7 @@
|
||||
-- Сев 10 000 сообщений в существующий чат.
|
||||
-- Переменные psql: :chat и :sender (передаются через -v chat=... -v sender=...).
|
||||
-- created_at разносим в прошлое по секунде на сообщение, чтобы ключ
|
||||
-- (created_at, id) был плотным и реалистичным для keyset-пагинации.
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT gen_random_uuid(), :'chat', :'sender', 'seed-' || g, now() - make_interval(secs => g)
|
||||
FROM generate_series(1, 10000) AS g;
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
# LAB 6: Tempo — хранилище трасс. Local backend, OTLP receivers.
|
||||
# Порт 3200 — query API (Grafana datasource), 4317/4318 — приём OTLP.
|
||||
|
||||
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:
|
||||
max_block_duration: 5m
|
||||
|
||||
compactor:
|
||||
compaction:
|
||||
block_retention: 24h
|
||||
|
||||
storage:
|
||||
trace:
|
||||
backend: local
|
||||
wal:
|
||||
path: /var/tempo/wal
|
||||
local:
|
||||
path: /var/tempo/blocks
|
||||
|
||||
usage_report:
|
||||
reporting_enabled: false
|
||||
Reference in New Issue
Block a user