ЛР 5 — БВТ2303 — Вейнмайер — на 5 #35
@@ -18,3 +18,5 @@ __pycache__
|
||||
node_modules
|
||||
evidence
|
||||
.DS_Store
|
||||
bin
|
||||
experiments
|
||||
|
||||
+16
-1
@@ -7,7 +7,7 @@ SESSION_TTL_SECONDS=3600
|
||||
# Choose credentials locally. File paths contain no secret values.
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
SESSION_STORE=postgres
|
||||
SESSION_STORE=redis
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
API_REPLICAS=2
|
||||
IDEMPOTENCY_TTL_SECONDS=86400
|
||||
@@ -20,6 +20,21 @@ MAX_UPLOAD_BYTES=10485760
|
||||
MAX_IMAGE_PIXELS=40000000
|
||||
BROKER_URL_FILE=/run/secrets/broker_url
|
||||
WORKER_CONCURRENCY=2
|
||||
# Мягкий лимит кучи Go в worker (≈75% WORKER_MEMORY)
|
||||
WORKER_GOMEMLIMIT=560MiB
|
||||
JOB_MAX_ATTEMPTS=5
|
||||
JOB_TIMEOUT_SECONDS=60
|
||||
STAGING_RETENTION_SECONDS=86400
|
||||
# Graceful shutdown: after SIGTERM readiness=503 for DRAIN_DELAY, then Shutdown up to SHUTDOWN_TIMEOUT.
|
||||
DRAIN_DELAY=3s
|
||||
SHUTDOWN_TIMEOUT=8s
|
||||
# Reconciler (PostgreSQL <-> S3): background pass interval and safe grace period.
|
||||
RECONCILE_INTERVAL=10m
|
||||
RECONCILE_GRACE=1h
|
||||
# Pipeline (lab5): published version, retry backoff (exponential with jitter), WebP quality, memory budget.
|
||||
PIPELINE_VERSION=1
|
||||
RETRY_BASE_DELAY=2s
|
||||
RETRY_MAX_DELAY=60s
|
||||
WEBP_QUALITY=80
|
||||
WORKER_PIXEL_BUDGET=60000000
|
||||
WORKER_REPLICAS=1
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
# Реальный прогон Docker-стенда lab5 на GitHub-hosted runner.
|
||||
# Нужен потому, что на машине разработки нет аппаратной виртуализации для Docker Desktop.
|
||||
# Все результаты — настоящие прогоны; публикуются в ветку lab5-results.
|
||||
name: lab5 stand
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [lab5]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: lab5-stand-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
PYTHONUTF8: "1"
|
||||
|
||||
jobs:
|
||||
# Unit-тесты и интеграционный fault-injection pipeline (трек 5) на настоящем PostgreSQL.
|
||||
go-tests:
|
||||
name: Go unit + интеграционный fault-injection
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16.4-alpine
|
||||
env:
|
||||
POSTGRES_USER: it
|
||||
POSTGRES_PASSWORD: it
|
||||
POSTGRES_DB: postgres
|
||||
ports: ["5432:5432"]
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U it" --health-interval 2s --health-timeout 2s --health-retries 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
- name: cwebp для теста варианта optimized
|
||||
run: sudo apt-get update -qq && sudo apt-get install -y -qq webp > /dev/null && cwebp -version
|
||||
- name: go test
|
||||
env:
|
||||
TEST_DATABASE_URL: postgres://it:it@localhost:5432/postgres?sslmode=disable
|
||||
run: |
|
||||
mkdir -p evidence/track2
|
||||
go test ./... -count=1 2>&1 | tee evidence/go_test.txt
|
||||
go test ./internal/worker/ -run Pipeline -count=1 -v 2>&1 | grep -E '^(=== RUN|--- |PASS|FAIL|ok)|FAULT INJECTION|duplicate|lease|stale|noop|attempt failed|early delivery' \
|
||||
| tee evidence/track2/pipeline_fault_injection.txt
|
||||
go test ./internal/imaging/ -run OptimizedWebP -count=1 -v 2>&1 | tee evidence/webp_test.txt
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: evidence-go
|
||||
path: evidence/
|
||||
|
||||
stand:
|
||||
name: Стенд — ${{ matrix.part }}
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 50
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
part: [base, files, pipeline, track2]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- name: Секреты и запуск стенда
|
||||
shell: bash
|
||||
run: |
|
||||
set -o pipefail
|
||||
mkdir -p evidence
|
||||
chmod +x scripts/*.sh infra/s3/init.sh
|
||||
sh scripts/init-secrets.sh
|
||||
docker compose --env-file .env config --quiet
|
||||
for img in $(docker compose config --images | sort -u | grep -v -- '-api:local'); do
|
||||
if docker pull -q "$img" > /dev/null 2>> evidence/pull_${{ matrix.part }}.log; then echo "ok $img"; else echo "FAIL $img"; fi
|
||||
done | tee -a evidence/pull_${{ matrix.part }}.log
|
||||
docker compose --env-file .env build 2>&1 | tail -30 > evidence/build_${{ matrix.part }}.log
|
||||
docker compose --env-file .env up -d --wait 2>&1 | tee evidence/up_${{ matrix.part }}.log
|
||||
- name: make check + доказательства (${{ matrix.part }})
|
||||
run: |
|
||||
make check PYTHON=python
|
||||
PYTHON=python sh scripts/collect-evidence.sh ${{ matrix.part }}
|
||||
- name: Окружение runner
|
||||
if: always()
|
||||
run: |
|
||||
mkdir -p evidence
|
||||
{ nproc; free -m; docker version --format '{{.Server.Version}}'; docker compose version; } > evidence/runner_${{ matrix.part }}.txt
|
||||
docker compose ps -a > evidence/docker_ps_final_${{ matrix.part }}.txt || true
|
||||
docker compose logs --no-color --tail 300 > evidence/compose_logs_${{ matrix.part }}.log 2>&1 || true
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: evidence-${{ matrix.part }}
|
||||
path: evidence/
|
||||
|
||||
publish:
|
||||
name: Публикация результатов в ветку lab5-results
|
||||
needs: [go-tests, stand]
|
||||
if: always()
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: collected
|
||||
- name: Commit в lab5-results
|
||||
run: |
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git checkout -q --orphan lab5-results
|
||||
git rm -rf -q .
|
||||
{ echo "source_commit=${{ github.sha }}"
|
||||
echo "run=${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
|
||||
echo "go_tests=${{ needs.go-tests.result }}"
|
||||
echo "stand=${{ needs.stand.result }}"; } > collected/RUN.txt
|
||||
cp -r collected/. .
|
||||
rm -rf collected
|
||||
git add -A
|
||||
git commit -q -m "results for ${{ github.sha }}"
|
||||
git push -f origin lab5-results
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
# ============================================================
|
||||
# Stage 1: builder — компилируем статический бинарник
|
||||
# ============================================================
|
||||
FROM golang:1.26-alpine@sha256:27f2d3b83cfc5803c8078f8e730af0f7c431bf067afaec8f60a36fb763187cba AS builder
|
||||
|
||||
WORKDIR /src
|
||||
|
||||
# Сначала манифесты зависимостей — кэшируем слой.
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
# Затем исходники.
|
||||
COPY . .
|
||||
|
||||
# Статический бинарник с оптимизациями:
|
||||
# CGO_ENABLED=0 — статическая линковка (не требует libc)
|
||||
# -ldflags="-s -w" — убираем отладочную информацию
|
||||
# -trimpath — убираем пути сборки из бинарника
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build \
|
||||
-ldflags="-s -w" \
|
||||
-trimpath \
|
||||
-o /out/ \
|
||||
./cmd/api ./cmd/reconcile ./cmd/pipeline
|
||||
|
||||
# ============================================================
|
||||
# Stage 2: runtime — минимальный образ только с бинарником
|
||||
# ============================================================
|
||||
FROM alpine:3.20@sha256:d9e853e87e55526f6b2917df91a2115c36dd7c696a35be12163d44e6e2a4b6bc
|
||||
|
||||
# ca-certificates — для HTTPS в lab2+
|
||||
# tzdata — для корректной работы с временными зонами
|
||||
# libwebp-tools — cwebp для варианта optimized (WebP) в worker.
|
||||
RUN apk --no-cache add ca-certificates tzdata libwebp-tools
|
||||
|
||||
# Непривилегированный пользователь (UID/GID 1001).
|
||||
RUN addgroup -g 1001 -S appgroup && \
|
||||
adduser -u 1001 -S appuser -G appgroup
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Копируем бинарник и сразу выставляем владельца.
|
||||
COPY --from=builder --chown=appuser:appgroup /out/api /app/api
|
||||
# reconcile — сверка PostgreSQL и S3 (сервис reconciler и ручной запуск).
|
||||
COPY --from=builder --chown=appuser:appgroup /out/reconcile /app/reconcile
|
||||
# pipeline — worker, relay (outbox) и операторские команды (replay, failed, reprocess).
|
||||
COPY --from=builder --chown=appuser:appgroup /out/pipeline /app/pipeline
|
||||
|
||||
# Переключаемся на непривилегированного пользователя.
|
||||
USER 1001:1001
|
||||
|
||||
# Информативно: какой порт слушает приложение.
|
||||
EXPOSE 8080
|
||||
|
||||
# Healthcheck: readiness (БД + Redis + не в режиме drain).
|
||||
HEALTHCHECK --interval=5s --timeout=2s --start-period=5s --retries=3 \
|
||||
CMD wget --spider -q http://localhost:8080/health/ready || exit 1
|
||||
|
||||
# Exec-форма CMD — критично для доставки SIGTERM в приложение.
|
||||
CMD ["/app/api"]
|
||||
@@ -4,7 +4,7 @@ CA_FILE ?=
|
||||
ACTION_SCRIPT ?=
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
|
||||
.PHONY: help check validate test load test-persistence test-failover
|
||||
.PHONY: help check validate test load test-persistence test-failover up down test-files test-pipeline test-faults failed replay evidence
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@@ -28,3 +28,33 @@ test-persistence:
|
||||
test-failover:
|
||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
|
||||
$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
# --- Студенческие цели (lab5) ---
|
||||
up:
|
||||
sh scripts/init-secrets.sh
|
||||
docker compose --env-file .env up -d --build --wait
|
||||
|
||||
down:
|
||||
docker compose --env-file .env stop
|
||||
|
||||
test-files:
|
||||
$(PYTHON) student-tests/attachments_negative.py --base-url "$(BASE_URL)"
|
||||
|
||||
# Сценарии pipeline на стенде: make test-pipeline SCENARIO=demo (список — student-tests/pipeline_ops.py)
|
||||
SCENARIO ?= demo
|
||||
test-pipeline:
|
||||
$(PYTHON) student-tests/pipeline_ops.py $(SCENARIO) --base-url "$(BASE_URL)"
|
||||
|
||||
# Интеграционный fault-injection pipeline (трек 5); нужен PostgreSQL: TEST_DATABASE_URL=postgres://...
|
||||
test-faults:
|
||||
go test ./internal/worker/ -run Pipeline -count=1 -v
|
||||
|
||||
failed:
|
||||
docker compose run --rm --no-deps -T --entrypoint /app/pipeline relay failed
|
||||
|
||||
# make replay ID=<attachment_id>
|
||||
replay:
|
||||
docker compose run --rm --no-deps -T --entrypoint /app/pipeline relay replay $(ID) --actor operator
|
||||
|
||||
evidence:
|
||||
sh scripts/collect-evidence.sh all
|
||||
|
||||
@@ -1,37 +1,230 @@
|
||||
# Отчёт — лабораторная 5
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор, группа: Вейнмайер Андрей Андреевич, БВТ2303
|
||||
- Целевая оценка: 5 (уровни 3, 4 и трек 2 «Доказанная идемпотентность pipeline»)
|
||||
- Commit/PR: ветка `solution/bvt2303-weinmaier` в https://gitea.privcloud.tech/WeinmaierAndrew/mtusi2026lab5, PR в mtusi2026/mtusi2026lab5
|
||||
- Основа: собственная lab4 (PR mtusi2026/mtusi2026lab4#56) — S3-вложения, reconciler; через неё lab3 (балансировка, идемпотентность, failover)
|
||||
- Использованные источники:
|
||||
- Контракт: contracts/openapi.json, contracts/README.md, contracts/attachment-states.md, contracts/jobs.schema.json
|
||||
- Библиотеки: github.com/rabbitmq/amqp091-go v1.16.0, github.com/jackc/pgx/v5, github.com/minio/minio-go/v7, github.com/redis/go-redis/v9, golang.org/x/image (CatmullRom, x/draw), golang.org/x/sync/semaphore; `cwebp` из libwebp-tools
|
||||
- Документация: RabbitMQ — reliability, publisher confirms и consumer acknowledgements, quorum queues (`x-delivery-limit`, dead lettering); PostgreSQL — `SELECT … FOR UPDATE SKIP LOCKED`; Go — `GOMEMLIMIT` (runtime/debug); EXIF 2.32 (тег Orientation 0x0112)
|
||||
- Помощь ИИ: ИИ-ассистент использовался при реализации и отладке; все результаты ниже — реальные прогоны, ссылки на них приведены.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
### Версии
|
||||
|
||||
| Компонент | Образ |
|
||||
| --- | --- |
|
||||
| API, relay, worker, reconciler | golang:1.26-alpine → alpine:3.20 (закреплены по digest в Dockerfile) + `libwebp-tools`; один образ, бинарники `/app/api`, `/app/pipeline`, `/app/reconcile` |
|
||||
| Broker | `rabbitmq:4.0.9-alpine` (по digest), quorum queues, volume `rabbitmq_data` |
|
||||
| S3 | `bitnamilegacy/minio:2025.4.22@sha256:50cec18a…` (MinIO RELEASE.2025-04-22), bootstrap `bitnamilegacy/minio-client:2025.4.16@sha256:8a86e441…` |
|
||||
| LB / БД / сессии | haproxy:3.0.5-alpine, postgres:16.4-alpine, redis:7.4.1-alpine (digest в `evidence/images.txt`) |
|
||||
| Миграции | migrate/migrate:v4.17.0 |
|
||||
|
||||
Официальные образы `minio/minio` и `minio/mc` недоступны на Docker Hub и quay.io (проверено в lab4), поэтому использована сборка Bitnami того же релиза, закреплённая по digest.
|
||||
|
||||
Prerequisites: Docker с Compose v2, Python 3.9+, POSIX shell (Linux/macOS/WSL или Git Bash); для `make test-faults` — Go 1.26 и PostgreSQL.
|
||||
|
||||
### Команды
|
||||
|
||||
```sh
|
||||
sh scripts/init-secrets.sh # .env и secrets/ (пароли PostgreSQL, Redis, S3, RabbitMQ генерируются, не печатаются)
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env up -d --build --wait # postgres, redis, s3, rabbitmq → migrate, s3-init → api×2, relay, worker, reconciler → lb
|
||||
make test # публичный smoke lab5 (202 → ready → thumbnail)
|
||||
make test-pipeline SCENARIO=demo # демонстрация уровня 3 (worker остановлен → … → ready)
|
||||
make test-pipeline SCENARIO=outbox-gap # и crash-effect, crash-commit, broker-restart, transient, failed-replay, limits, versions
|
||||
make test-files # негативный набор вложений (lab4)
|
||||
make failed # реестр failed jobs
|
||||
make replay ID=<attachment_id> # явный replay failed job (с аудитом)
|
||||
TEST_DATABASE_URL=postgres://… make test-faults # трек 2: fault-injection pipeline на реальном PostgreSQL
|
||||
sh scripts/collect-evidence.sh all # все доказательства в evidence/
|
||||
```
|
||||
|
||||
Остановка без потери данных: `docker compose --env-file .env stop` (worker получает SIGTERM, дорабатывает текущие задания до 70 s). Намеренное удаление учебных данных: `docker compose --env-file .env down -v` (удаляет `pg_data`, `redis_data`, `s3_data`, `rabbitmq_data`).
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab4, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
```
|
||||
клиент ──► lb (HAProxy, 127.0.0.1:8080) ──► api × 2
|
||||
│ 1. intent (uploading) ─────────────► postgres
|
||||
│ 2. потоковый PUT s/{chat}/{id} ────► s3 (staging)
|
||||
│ 3. tx: queued + jobs + outbox ─────► postgres
|
||||
└ 4. 202 queued
|
||||
relay ── outbox (FOR UPDATE SKIP LOCKED) ── publish + confirm ──► rabbitmq: attachment.process (quorum)
|
||||
│ │ x-delivery-limit 10 → attachment.dead
|
||||
└ sweeper lease, очистка staging ▼
|
||||
worker (prefetch = WORKER_CONCURRENCY) ── claim lease ── варианты v/{chat}/{id}/p{ver}/… ──► s3
|
||||
── Copy s/ → o/ ── tx: variants + ready + job done ──► postgres
|
||||
── ack ── удалить staging
|
||||
reconciler (lab4) — сверка всего bucket; ключи pipeline (staging, variant) учитывает
|
||||
```
|
||||
|
||||
**Источник истины — PostgreSQL.** Broker — только канал доставки «разбудить worker по job_id»: в сообщении `{job_id, attachment_id, pipeline_version}`, без байтов и credentials. Потерянное или дублированное сообщение не меняет результат: состояние job и lease в БД.
|
||||
|
||||
**Перенесено из lab4:** всё — вложения, потоковая загрузка с SHA-256 и структурной проверкой, лимиты 10 MiB / 40 Мпикс, права S3, reconciler, failover и идемпотентность lab3.
|
||||
|
||||
**Новое в lab5:**
|
||||
|
||||
1. **Модель** ([0005_pipeline.up.sql](migrations/0005_pipeline.up.sql)): статусы `uploading|queued|processing|ready|failed|missing`, `error_code`, `pipeline_version` (опубликованная версия), `staging_key`; таблицы `jobs` (`UNIQUE(attachment_id, pipeline_version)` — ключ идемпотентности, `state`, `attempt/max_attempts`, `next_attempt_at`, `lease_until/lease_owner`, `last_error`), `outbox`, `attachment_variants` (`PK(attachment_id, pipeline_version, name)`, `object_key UNIQUE`), `job_events` (аудит). Ready-вложения lab4 получают job бэкфиллом.
|
||||
2. **Upload → 202** ([attachment.go](internal/service/attachment.go)): после проверки байтов одна транзакция переводит вложение в `queued` и вставляет job и outbox-строку. 202 возвращается только после COMMIT, когда оригинал уже в S3 (staging), а намерение обработки — в PostgreSQL.
|
||||
3. **Transactional outbox** ([pipeline.go](internal/repository/postgres/pipeline.go) `PublishDue`, [cmd/pipeline](cmd/pipeline/main.go) `relay`): relay берёт строки `FOR UPDATE SKIP LOCKED`, публикует с **publisher confirm** и помечает `published_at` только после confirm. Падение между confirm и пометкой даёт повторную публикацию; её поглощает worker.
|
||||
4. **Worker** ([worker.go](internal/worker/worker.go)): manual ack, `prefetch = WORKER_CONCURRENCY` (2). `Claim` — атомарный захват lease с fencing (`lease_owner` + `attempt`). Исходы: Claimed / AlreadyDone (ack дубля) / Busy (lease жив — ack, восстановление через sweeper) / NotDue (ранняя доставка) / Terminal. Heartbeat продлевает lease каждые `lease/3`. Обработка: чтение staging по ключу из БД, сверка SHA-256, пиксельный семафор, декодирование, 3 варианта по детерминированным ключам, `CopyObject` s/ → o/. `Complete` в одной транзакции: варианты `ON CONFLICT DO NOTHING`, `ready` только если `pipeline_version` вложения меньше версии job, job → done. Затем ack, затем удаление staging.
|
||||
5. **Ошибки и повторы:** постоянные (`invalid_image`, `checksum_mismatch`, `source_missing`, `too_large`) сразу дают `failed` без повторов; временные — повтор с экспоненциальным backoff и jitter (`[d/2, d]`, `d = min(2s·2^(n-1), 60s)`) через `outbox.available_at`; после `JOB_MAX_ATTEMPTS=5` — `failed` / `retry_exhausted`. Сообщение в broker при повторе ack-ается, новое публикует relay в срок — broker не держит таймеры. `x-delivery-limit 10` + DLX `attachment.dead` ловят «ядовитые» сообщения, которые роняют worker раньше, чем тот успевает записать решение.
|
||||
6. **Replay** (`pipeline replay <id>`): разрешён только для `failed` job, сбрасывает попытки и пишет `job_events(replay, actor)`; для `done` отказ (`replay_refused`). Повторная обработка готового вложения — только новой версией (`pipeline reprocess <id> --version N`).
|
||||
7. **Варианты** ([imaging.go](internal/imaging/imaging.go)): `thumbnail` — JPEG q85, вписан в 256×256 без увеличения, EXIF orientation применён, alpha на белый, размеры вниз (320×200 → 256×160); `crop` — JPEG q85, центр 128×128; `optimized` — WebP (`cwebp -q 80 -m 4 -metadata none`), вписан в 1280 без увеличения. Пиксели перекодируются из декодированного изображения, поэтому EXIF/ICC не переносятся. Все кодировщики детерминированы. Pipeline v2 — q92 для JPEG.
|
||||
8. **Ограничения worker:** байты ≤10 MiB и ≤40 Мпикс проверяются ещё при upload (lab4); в worker — пиксельный семафор `WORKER_PIXEL_BUDGET=60M` на процесс, timeout задания `JOB_TIMEOUT_SECONDS=60` (он же lease), лимит контейнера 768M и `GOMEMLIMIT=560MiB`, cwebp под `CommandContext`.
|
||||
9. **Lease и sweeper:** relay каждые 5 s возвращает `processing` с истёкшим lease в очередь (событие `lease_expired_requeued`). Ack от «зависшего» worker после этого не испортит результат: его `Complete` отвергается fencing-ом (`LostLease`).
|
||||
10. **Очистка staging:** только после фиксации `ready`/`failed` и ack (воркер удаляет сразу, relay раз в минуту дочищает остатки старше `STAGING_RETENTION_SECONDS`).
|
||||
11. **API:** `GET` метаданных показывает `queued|processing|ready|failed` (у ready — варианты, у failed — `error_code`); `content` до ready — 409; прикрепить к сообщению можно `queued/processing/ready`, `failed/missing` — 409.
|
||||
|
||||
**Соответствие .env.example:** все переменные контракта (`BROKER_URL_FILE`, `WORKER_CONCURRENCY`, `JOB_MAX_ATTEMPTS`, `JOB_TIMEOUT_SECONDS`, `STAGING_RETENTION_SECONDS`) читаются в [config.go](internal/config/config.go); добавлены `PIPELINE_VERSION`, `RETRY_BASE_DELAY`, `RETRY_MAX_DELAY`, `WEBP_QUALITY`, `WORKER_PIXEL_BUDGET`, `WORKER_REPLICAS`, `WORKER_GOMEMLIMIT`; из lab4 — S3, reconciler, drain.
|
||||
|
||||
## Где запускался стенд
|
||||
|
||||
На машине разработки нет аппаратной виртуализации для Docker Desktop, поэтому Docker-проверки выполнены на **GitHub-hosted runner** workflow [.github/workflows/lab5-stand.yml](.github/workflows/lab5-stand.yml): job `go-tests` (unit + интеграционный fault-injection с сервисом PostgreSQL, WebP через настоящий cwebp) и четыре независимых стенда параллельно (`base`, `files`, `pipeline`, `track2`) — тот же compose.yaml и те же скрипты. Runner: 2 vCPU, 8 GB, Docker 28.0.4, Compose v2.38.2.
|
||||
|
||||
Итоговый прогон: https://github.com/CharaWein/2026_lab3/actions/runs/42642251603 (commit 1289df3, `go_tests=success`, `stand=success`). Все файлы в `evidence/` — из него. Предыдущие прогоны той же ветки нашли ошибки, исправленные ниже.
|
||||
|
||||
## Исправления, найденные тестами
|
||||
|
||||
| Что показал тест | Причина | Исправление |
|
||||
| --- | --- | --- |
|
||||
| интеграционный тест: ранняя повторная доставка обрабатывалась до `next_attempt_at` | в условии NotDue был допуск 1 s | строгое `next_attempt_at > now` |
|
||||
| `transient`: отказа S3 не было — worker сразу всё обработал | `docker compose start worker` поднимает и зависимости (worker → s3-init → s3) | сценарий останавливает/запускает контейнеры напрямую (`docker stop/start`) |
|
||||
| `broker-restart`, `demo`: очередь сразу после рестарта RabbitMQ пустая | quorum-очередь ещё выбирает лидера и восстанавливает журнал | ожидание до 30 s; дополнительно проверка `outbox.publish_attempts == 1`, чтобы сообщение не оказалось переотправленным из outbox |
|
||||
| первый прогон: один упавший сценарий оставил worker остановленным, остаток job съел одноразовый fault следующего сценария | нет изоляции сценариев | каждый сценарий начинает с `drain()` (очередь и jobs пусты), восстанавливает сервисы в `finally`; fault-сценарии проверяют, что crash действительно был (restarts ≥ 1) |
|
||||
| `limits` (прогон 4): анонимная память worker 759.9 из 768 MiB при трёх 6000×6000, OOM не было, но запаса нет | GC Go с `GOGC=100` позволяет куче расти до ~2× живого объёма; живой объём одного изображения ≈ 137 MiB RGBA + ~245 MiB временного буфера CatmullRom при масштабировании до 1280 | лишняя копия непрозрачного RGBA при декодировании убрана; `GOMEMLIMIT=560MiB` (≈75% лимита) — повторный замер ниже |
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
### Уровень 3
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл |
|
||||
| --- | --- | --- | --- |
|
||||
| Минимум lab4 сохранён, upload 201 → 202 | `make test`; регрессии lab3/lab4; негативный набор | `PASS: lab5 public API scenario`; 28 случаев загрузки без 5xx; failover, persistence, идемпотентность — PASS | evidence/smoke.txt, regressions.txt, files/attachments_negative.txt |
|
||||
| 202 только после устойчивого приёма оригинала и job | код + `demo`: после 202 перезапущены API и RabbitMQ | job дожил (`outbox published=1`, в очереди 1 сообщение) и стал ready | evidence/pipeline/demo.json |
|
||||
| Отдельные broker и worker; durable, at least once, ack после эффекта | compose.yaml; `crash-commit` | rabbitmq, relay, worker в стенде; worker убит после COMMIT до ack → повторная доставка, `redelivery_acked_as_noop: true`, attempt 1 | evidence/docker_ps.txt, pipeline/crash-commit.json |
|
||||
| Недоступность worker не включает синхронный resize | `demo` | при остановленном worker upload 202 `queued`, content 409, другие сообщения работают | evidence/pipeline/demo.json |
|
||||
| Состояния queued/processing/ready/failed в API; оригинал неизменен; thumbnail по контракту | `make test`, `demo`, `failed-replay` | ready: thumbnail 256×160 (из 320×200), SHA-256 оригинала совпал; failed с `error_code=checksum_mismatch` | evidence/smoke.txt, pipeline/demo.json, failed-replay.json |
|
||||
| Ограниченный retry (5), финальное failed с безопасным error_code | `JOB_MAX_ATTEMPTS=5`; Go-тест `RetryExhausted` | после 5 временных ошибок `failed`/`retry_exhausted`, без деталей исключения | evidence/go_test.txt, track2/pipeline_fault_injection.txt |
|
||||
| Повтор job не создаёт второго набора вариантов | все сценарии проверяют инварианты | `objects_per_version: {"1": 3}` во всех сценариях, включая повторы и дубли | evidence/pipeline/*.json |
|
||||
| Демонстрация: worker stop → 202 → сообщение → restart API → start worker → ready | `make test-pipeline SCENARIO=demo` | таймлайн ниже; ready через 2.4 s после старта worker | evidence/pipeline/demo.json |
|
||||
| Принятое задание переживает рестарт broker с volume | `broker-restart` | сообщение подтверждено broker (`published_at` выставлен после publisher confirm; `rabbitmqctl` до рестарта показал 0 — счётчик quorum-очереди обновляется с задержкой), после рестарта в очереди 1; `publish_attempts=1` — то же сообщение, не переотправка; ready | evidence/pipeline/broker-restart.json |
|
||||
|
||||
**Таймлайн `demo`** (attachment 977aa698…): worker остановлен → upload 202 queued → сообщение 201 с queued-вложением → content 409, другие сообщения OK → API и RabbitMQ перезапущены (volumes сохранены), outbox опубликован → в очереди `attachment.process: 1` → worker запущен → ready за 2.4 s; события job `enqueued, claimed, done`.
|
||||
|
||||
### Уровень 4
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл |
|
||||
| --- | --- | --- | --- |
|
||||
| crop 128×128 и optimized WebP по контракту; параметры качества и метаданных | `demo`, `limits`; unit-тесты imaging | crop 128×128, optimized 320×200 WebP (2 462 байта из PNG 111 817); для 6000×6000 — 256×256, 128×128, 1280×1280; WebP-тест с настоящим cwebp — PASS | evidence/pipeline/demo.json, limits.json, go_test.txt, webp_test.txt |
|
||||
| Невалидные/огромные изображения ограничены по bytes, пикселям, времени и памяти worker | негативный набор + `limits` | 413/415 при загрузке; worker: пиксельный семафор, lease/timeout 60 s, лимит 768M, GOMEMLIMIT; результаты ниже | evidence/files/attachments_negative.txt, pipeline/limits.json |
|
||||
| Разрыв PostgreSQL ↔ broker закрыт outbox; crash между COMMIT и publish | `outbox-gap` | relay остановлен: строка outbox не опубликована (1), после старта relay — ready. Crash relay после confirm до пометки: relay перезапущен (1 раз), сообщение пришло дважды, job выполнен один раз (attempt 1), 3 объекта | evidence/pipeline/outbox-gap.json |
|
||||
| Backoff с jitter, постоянные/временные ошибки | `transient` (S3 остановлен) и `failed-replay` | временная: 3 попытки, паузы 1.553 s и 2.758 s (окна [1, 2] и [2, 4] s), затем ready; постоянная (`checksum_mismatch`) — сразу failed, без повторов | evidence/pipeline/transient.json, failed-replay.json |
|
||||
| DLQ/реестр failed, безопасный replay; повтор не исполняет дубль успешной job | `failed-replay` | failed в реестре (`make failed`), replay → ready; повторный replay — `conflict: job is done, only failed jobs can be replayed`; события `…,failed,replay,claimed,done,replay_refused`; в DLQ 1 сообщение | evidence/pipeline/failed-replay.json |
|
||||
| Остановка worker после записи объекта, до ack | `crash-effect` (`FAULT_POINTS=worker.after_side_effect`) | worker упал после записи вариантов до COMMIT; lease истёк → sweeper вернул job → попытка 2 перезаписала те же ключи; ready за 19.6 s; объектов 3 | evidence/pipeline/crash-effect.json |
|
||||
| Timeout/lease для зависшего processing | `crash-effect`; Go-тест `LostLeaseFencing` | `lease_expired_requeued` в событиях; «проснувшийся» старый worker получил `LostLease`, его результат не записан | evidence/pipeline/crash-effect.json, track2/pipeline_fault_injection.txt |
|
||||
| Ограниченная конкуренция/prefetch | `WORKER_CONCURRENCY=2` = prefetch; пиксельный семафор | 3 параллельных 6000×6000 обработаны без OOM за 5.4 s (ниже) | evidence/pipeline/limits.json |
|
||||
| Очистка staging после безопасной фиксации | Go-тесты; `make failed` | staging удаляется после ready/failed и ack; при replay failed проверяется, что staging ещё на месте | evidence/go_test.txt |
|
||||
|
||||
**Память worker на огромных изображениях** (`limits`: 3 параллельных PNG 6000×6000 = 36 Мпикс, файл 119 755 байт; лимит контейнера 768 MiB; RGBA одного изображения 137.3 MiB):
|
||||
|
||||
| Прогон | GOMEMLIMIT | Все 3 ready, s | Анонимная память max, MiB | memory.peak (с page cache), MiB | OOM kill |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 4 (до исправления) | нет | 15.6 | 759.9 | 768.0 (= лимит) | 0 |
|
||||
| 5 (итоговый) | 560MiB | 5.4 | 570.3 | 576.4 | 0 |
|
||||
|
||||
Пиксельный бюджет 60 Мпикс пропускает одно изображение 36 Мпикс за раз (вес `min(px, budget)`, два дали бы 72 M), поэтому три задания при `WORKER_CONCURRENCY=2` выполняются последовательно по декодированию. Без GOMEMLIMIT куча Go (`GOGC=100`) росла почти до лимита контейнера, и время уходило на reclaim страниц; с мягким лимитом GC собирает раньше, пик анонимной памяти ≈ GOMEMLIMIT, запас до лимита контейнера ~200 MiB, обработка в 2.9 раза быстрее. Живой объём одного изображения — ≈137 MiB RGBA + до ~245 MiB временного буфера CatmullRom при масштабировании до 1280 (оценка по размеру буфера, отдельно не профилировалась). Изображения больше 40 Мпикс отклоняются ещё при upload (413). Данные `limits` по прогону 4 — из сохранённого результата того прогона (https://github.com/CharaWein/2026_lab3/actions/runs/42640758312), в `evidence/` — итоговый прогон 5.
|
||||
|
||||
## Трек 5.2: доказанная идемпотентность pipeline
|
||||
|
||||
### Гипотеза
|
||||
|
||||
At-least-once доставка + ключ идемпотентности `(attachment_id, pipeline_version)` + lease с fencing + детерминированные ключи и байты вариантов + монотонная публикация версии дают **эффективно-однократный результат**: при любом дубле, переупорядочении и падении до/после side effect (1) ни одна принятая (202) задача не теряется, (2) у вложения не появляется второго набора вариантов одной версии, (3) результат новой версии никогда не перезаписывается старой.
|
||||
|
||||
### Инварианты
|
||||
|
||||
| # | Инвариант | Как проверяется |
|
||||
| --- | --- | --- |
|
||||
| I1 | ≤ 1 варианта на `(attachment, version, name)` | PK + явный запрос после каждого шага |
|
||||
| I2 | `ready` ⇒ опубликованная версия ≥ 1, её 3 варианта в БД, объекты в S3 совпадают по размеру и SHA-256 | сравнение БД ↔ S3 |
|
||||
| I3 | `ready` ⇒ оригинал в `o/`, байты равны принятым (SHA-256 из ответа 202) | чтение объекта |
|
||||
| I4 | после sweeper нет `processing` с истёкшим lease | запрос по `jobs` |
|
||||
| I5 | опубликованная версия не уменьшается | история версий в сценарии |
|
||||
| L | каждая job с 202 достигает `done` или `failed` (нет потерь) | состояние job в конце каждого сценария |
|
||||
|
||||
### Методика
|
||||
|
||||
1. **Интеграционный fault-injection** ([pipeline_integration_test.go](internal/worker/pipeline_integration_test.go)): настоящий PostgreSQL (отдельная БД на тест, все миграции), настоящий код `Claim/Complete/PublishDue/Sweep/Replay` и `Worker.Handle`; S3 и broker заменены детерминированными двойниками (in-memory store, сообщения передаются вручную, что позволяет точно задать порядок и дубли). Падения — точки `Fault()` в коде, превращённые в panic с кодом выхода. После каждого шага `checkInvariants`.
|
||||
2. **Стенд** ([pipeline_ops.py](student-tests/pipeline_ops.py)): те же точки отказа на настоящих процессах через `FAULT_POINTS` (`worker.after_side_effect`, `worker.after_commit`, `relay.after_publish`) — процесс завершается `os.Exit(137)` один раз, Docker перезапускает его; сценарий проверяет число рестартов, события `job_events` и инварианты по БД и S3.
|
||||
|
||||
| Сценарий | Внедрение | Проверка |
|
||||
| --- | --- | --- |
|
||||
| HappyPathAndDuplicate | то же сообщение после done | AlreadyDone → ack, объектов 3 |
|
||||
| ConcurrentDuplicateIsBusy | дубль при живом lease другого worker | Busy → ack без работы; восстановление — sweeper |
|
||||
| CrashAfterSideEffectBeforeCommit | crash после записи объектов до COMMIT | повтор перезаписал **те же** ключи, новых объектов нет |
|
||||
| CrashAfterCommitBeforeAck | crash после COMMIT до ack | повторная доставка — no-op |
|
||||
| RelayCrashAfterPublishDuplicates | crash relay после confirm до пометки | 2 публикации, 1 выполнение |
|
||||
| VersionReorderAndStaleJob | v2 обработана раньше v1; v1 приходит позже; v1 фиксируется после публикации v3 | v1 не перезаписывает v2/v3 (`NewerPublished`), I5 |
|
||||
| LostLeaseFencing | worker A «завис», lease истёк, B завершил, A «проснулся» | `Complete` A → `LostLease` |
|
||||
| TransientRetryWithBackoff | временная ошибка S3, ранняя повторная доставка | NotDue; повтор после backoff |
|
||||
| PermanentFailureAndReplay | порча staging (checksum) | failed без повторов; replay done запрещён, failed — разрешён |
|
||||
| RetryExhausted | 5 временных ошибок | failed / `retry_exhausted` |
|
||||
|
||||
### Результаты
|
||||
|
||||
**Go fault-injection:** 10 из 10 PASS на CI (evidence/track2/pipeline_fault_injection.txt) и локально; ни в одном шаге не нарушен I1–I5, все job завершились (L).
|
||||
|
||||
**Стенд** — все инварианты выполнены в каждом сценарии:
|
||||
|
||||
| Сценарий | Внедрение на стенде | Наблюдение |
|
||||
| --- | --- | --- |
|
||||
| crash-effect | worker `os.Exit` после записи вариантов | рестартов 1, attempt 2, события `enqueued, claimed, lease_expired_requeued, claimed, done`, ready за 19.6 s (≈ lease 15 s сценария + обработка), объектов `{"1": 3}` |
|
||||
| crash-commit | worker `os.Exit` после COMMIT до ack | рестартов 1, attempt 1, повторная доставка ack-нута как no-op |
|
||||
| outbox-gap | relay `os.Exit` после confirm | рестартов 1, worker получил сообщение дважды, attempt 1, объектов 3 |
|
||||
| broker-restart | рестарт RabbitMQ с job в очереди | сообщение сохранилось, `publish_attempts=1` |
|
||||
| versions | v1 → ready; `reprocess --version 2`; затем повторно доставлены **устаревшая v1 и дубль v2** | thumbnail v1 `4462c506…`, v2 `254bbafb…`; после устаревшей v1 и дубля v2 — по-прежнему `254bbafb…`, `pipeline_version=2`, объектов `{"1": 3, "2": 3}` — старая версия не перезаписала новую и не размножилась |
|
||||
| failed-replay | порча staging | failed → replay → ready; повторный replay отклонён |
|
||||
|
||||
Гипотеза подтверждена в пределах внедрённых отказов: потерь принятых задач нет, дублей вариантов нет, перезаписи новой версии старой нет.
|
||||
|
||||
### Почему это не exactly-once доставка
|
||||
|
||||
- **Доставка** остаётся at-least-once: сценарии прямо показывают дубли (relay после confirm опубликовал сообщение повторно, worker получил его дважды; после crash до ack broker доставил снова). Exactly-once между PostgreSQL, S3 и RabbitMQ без распределённой транзакции невозможен: всегда есть момент «эффект сделан, подтверждение не записано».
|
||||
- Однократным является **наблюдаемый результат**, и то при условиях: детерминированные кодировщики (одинаковые байты при повторе), детерминированные ключи, идемпотентный `CopyObject`, условная фиксация в БД. Side effect в S3 при повторе **выполняется повторно** (перезапись теми же байтами) — это не «один раз», а «одинаково».
|
||||
- Fencing защищает БД, но не S3: «зависший» worker со старым lease может перезаписать объект варианта после того, как новый уже зафиксирован. Это безопасно только потому, что байты той же версии идентичны; другая версия пишет в другой префикс `p{ver}`.
|
||||
|
||||
### Ограничения трека
|
||||
|
||||
- В Go-тестах broker и S3 — двойники: проверена логика протокола, а не свойства RabbitMQ/MinIO; эти свойства проверены отдельно на стенде (broker-restart, crash-*).
|
||||
- Точки отказа выбраны вручную (3 на стенде, больше в тестах); перебора всех точек прерывания и model checking нет. Падения на сети (частичная запись в S3, разрыв TCP посреди confirm) отдельно не внедрялись.
|
||||
- Детерминизм WebP зависит от версии libwebp: при обновлении cwebp между попытками байты одной версии могут отличаться (результат корректен, но I2 по SHA-256 сравнивается с метаданными последней фиксации). Версия cwebp закреплена образом.
|
||||
- Часы: lease и `next_attempt_at` вычисляются по времени PostgreSQL, поэтому расхождение часов worker не влияет; паузы GC/VM дольше lease приводят к повтору (безопасно, но дорого).
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| Worker остановлен, upload | 202 queued, остальное работает | 202, content 409, сообщения работают | ready через 2.4 s после старта worker; 0 потерь |
|
||||
| Рестарт API + RabbitMQ с job в очереди | job не теряется | в очереди 1, ready | 0 потерь |
|
||||
| Worker crash после side effect | повтор с теми же ключами | attempt 2, 3 объекта | 19.6 s (lease) |
|
||||
| Worker crash после COMMIT | дубль — no-op | attempt 1 | — |
|
||||
| Relay остановлен / crash после confirm | outbox догоняет; дубль поглощается | ready; 2 доставки, 1 выполнение | 0 потерь |
|
||||
| S3 остановлен на время обработки | повторы с backoff | 3 попытки, паузы 1.6 s / 2.8 s, ready | после старта S3 |
|
||||
| S3 остановлен при upload | быстрый 503 | 503 за 0.12 s, текст и readiness OK, брошенных намерений 0 | сразу |
|
||||
| PostgreSQL замер посреди upload (45 s) | не 202 | 504 клиенту, намерение и staging удалены | 0 «queued без байтов» |
|
||||
| Остановка каждой API-реплики под нагрузкой | 0 ошибок | 0 из 18 698 запросов, 0 потерь подтверждённых записей и 0 дублей | возврат в LB за 5.9 / 6.3 s |
|
||||
| Rolling update API под нагрузкой (90 s) | 0 ошибок | 0 из 34 917, 387 RPS, p50 / p95 / p99 = 7.1 / 19.9 / 97.8 ms | замена 26 s |
|
||||
| Failover lab4 (×2) | данные и сессия целы | PASS, 141 и 130 записей, 0 ошибок | восстановление записи 3.37 / 4.08 s |
|
||||
|
||||
Нагрузочные цифры — closed loop, 4 клиента, без повторов, один runner 2 vCPU; задержки только по успешным запросам.
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
- SPOF: один узел RabbitMQ (quorum-очередь с одним членом — durability на диске, без репликации), PostgreSQL, MinIO, LB, хост. Выдерживаются: остановка worker, relay, API-реплики, рестарт broker с volume, временный отказ S3.
|
||||
- Relay — один процесс; при нескольких копиях корректность сохраняется (`SKIP LOCKED`), но порядок публикации не гарантируется (порядок и не нужен — job независимы).
|
||||
- Upload не идемпотентен (контракт не требует ключа): повтор клиента после 504 создаёт второе вложение.
|
||||
- Модель памяти worker грубая: семафор считает декодированные пиксели, а временный буфер масштабирования (≈ 32 байта × 1280 × высоту) не учитывается; запас дают GOMEMLIMIT и лимит контейнера. Следующий шаг — учитывать буфер в весе семафора или масштабировать в два прохода.
|
||||
- DLQ наполняется только при многократном падении worker на одном сообщении (`x-delivery-limit`); решения о failed принимаются в БД, и реестр `make failed` — основной.
|
||||
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/config"
|
||||
"github.com/charawein/mtusi2026lab5/internal/repository/postgres"
|
||||
redisrepo "github.com/charawein/mtusi2026lab5/internal/repository/redis"
|
||||
"github.com/charawein/mtusi2026lab5/internal/service"
|
||||
"github.com/charawein/mtusi2026lab5/internal/storage"
|
||||
transporthttp "github.com/charawein/mtusi2026lab5/internal/transport/http"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cfg := config.Load()
|
||||
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: cfg.LogLevel}))
|
||||
slog.SetDefault(logger)
|
||||
|
||||
if cfg.DatabaseURL == "" {
|
||||
slog.Error("DATABASE_URL_FILE is not set or empty")
|
||||
os.Exit(1)
|
||||
}
|
||||
if cfg.CacheURL == "" {
|
||||
slog.Error("CACHE_URL_FILE is not set or empty")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
pool, err := postgres.NewPool(ctx, cfg.DatabaseURL, cfg.DBPoolMax)
|
||||
cancel()
|
||||
if err != nil {
|
||||
slog.Error("connect to postgres", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
rctx, rcancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
redisClient, err := redisrepo.NewClient(rctx, cfg.CacheURL)
|
||||
rcancel()
|
||||
if err != nil {
|
||||
slog.Error("connect to redis", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer redisClient.Close()
|
||||
|
||||
if cfg.S3AccessKey == "" || cfg.S3SecretKey == "" {
|
||||
slog.Error("S3_ACCESS_KEY_ID_FILE / S3_SECRET_ACCESS_KEY_FILE are not set or empty")
|
||||
os.Exit(1)
|
||||
}
|
||||
store, err := storage.NewS3(cfg.S3Endpoint, cfg.S3Region, cfg.S3Bucket, cfg.S3AccessKey, cfg.S3SecretKey)
|
||||
if err != nil {
|
||||
slog.Error("s3 client", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
userRepo := postgres.NewUserRepository(pool)
|
||||
chatRepo := postgres.NewChatRepository(pool)
|
||||
msgRepo := postgres.NewMessageRepository(pool)
|
||||
sessRepo := redisrepo.NewSessionRepository(redisClient)
|
||||
|
||||
userSvc := service.NewUserService(userRepo)
|
||||
chatSvc := service.NewChatService(chatRepo, userRepo)
|
||||
|
||||
var msgCache *redisrepo.MessageCache
|
||||
if cfg.CacheEnabled {
|
||||
msgCache = redisrepo.NewMessageCache(redisClient, cfg.CacheInvalidation)
|
||||
}
|
||||
msgSvc := service.NewMessageService(msgRepo, chatRepo, msgCache, cfg.IdempotencyTTL)
|
||||
|
||||
attSvc := service.NewAttachmentService(postgres.NewAttachmentRepository(pool), chatRepo, store,
|
||||
cfg.MaxUploadBytes, cfg.MaxImagePixels, cfg.PipelineVersion, cfg.JobMaxAttempts)
|
||||
authSvc := service.NewAuthService(userRepo, sessRepo, cfg.SessionTTL())
|
||||
|
||||
// draining выставляется по SIGTERM: /health/ready начинает отвечать 503,
|
||||
// LB исключает реплику, и только затем закрывается listener.
|
||||
var draining atomic.Bool
|
||||
router := transporthttp.NewRouter(userSvc, chatSvc, msgSvc, attSvc, authSvc, pool, redisClient, cfg.InstanceID, &draining)
|
||||
|
||||
// Очистка просроченных ключей идемпотентности. Запрос идемпотентен,
|
||||
// поэтому параллельный запуск на всех репликах безопасен.
|
||||
cleanupCtx, cleanupStop := context.WithCancel(context.Background())
|
||||
defer cleanupStop()
|
||||
go func() {
|
||||
t := time.NewTicker(time.Hour)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-cleanupCtx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
ctx, cancel := context.WithTimeout(cleanupCtx, 30*time.Second)
|
||||
if n, err := msgRepo.DeleteExpiredKeys(ctx, cfg.IdempotencyTTL); err != nil {
|
||||
slog.Warn("idempotency cleanup failed", "err", err)
|
||||
} else if n > 0 {
|
||||
slog.Info("idempotency keys expired", "deleted", n)
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: cfg.Addr(),
|
||||
Handler: router,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
// Загрузка до 10 MiB должна уложиться в ReadTimeout; медленный клиент
|
||||
// дольше не держит соединение и память.
|
||||
ReadTimeout: 30 * time.Second,
|
||||
WriteTimeout: 35 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
|
||||
// Внутренний endpoint метрик для экспериментов (трек 1). Порт не публикуется
|
||||
// и не проксируется LB: читается только через docker exec внутри контейнера.
|
||||
internalSrv := &http.Server{
|
||||
Addr: cfg.InternalAddr,
|
||||
Handler: transporthttp.NewInternalStatsHandler(pool, cfg),
|
||||
ReadHeaderTimeout: 2 * time.Second,
|
||||
}
|
||||
go func() {
|
||||
if err := internalSrv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
slog.Warn("internal stats server failed", "err", err)
|
||||
}
|
||||
}()
|
||||
defer internalSrv.Close()
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
slog.Info("server starting", "addr", cfg.Addr(), "instance_id", cfg.InstanceID)
|
||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
errCh <- err
|
||||
}
|
||||
}()
|
||||
|
||||
sigCtx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||||
defer stop()
|
||||
|
||||
select {
|
||||
case err := <-errCh:
|
||||
slog.Error("server failed", "err", err)
|
||||
os.Exit(1)
|
||||
case <-sigCtx.Done():
|
||||
slog.Info("shutdown signal received, draining", "delay", cfg.DrainDelay)
|
||||
}
|
||||
|
||||
// Перестаём быть ready и даём LB время заметить это (inter*fall у HAProxy),
|
||||
// продолжая обслуживать уже направленные к нам запросы.
|
||||
draining.Store(true)
|
||||
time.Sleep(cfg.DrainDelay)
|
||||
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||
slog.Error("graceful shutdown failed", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
slog.Info("server stopped")
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
// Command pipeline — асинхронная обработка вложений (lab5).
|
||||
//
|
||||
// pipeline worker потребитель broker (сервис worker)
|
||||
// pipeline relay outbox → broker, возврат истёкших lease, очистка staging
|
||||
// pipeline failed реестр failed-заданий (JSON)
|
||||
// pipeline replay <attachment_id> [--version N] [--actor NAME] явный повтор failed
|
||||
// pipeline reprocess <attachment_id> --version N работа новой версии (трек 5)
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/broker"
|
||||
"github.com/charawein/mtusi2026lab5/internal/config"
|
||||
"github.com/charawein/mtusi2026lab5/internal/imaging"
|
||||
"github.com/charawein/mtusi2026lab5/internal/repository/postgres"
|
||||
"github.com/charawein/mtusi2026lab5/internal/storage"
|
||||
"github.com/charawein/mtusi2026lab5/internal/worker"
|
||||
)
|
||||
|
||||
func main() {
|
||||
slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, nil)))
|
||||
if len(os.Args) < 2 {
|
||||
fmt.Fprintln(os.Stderr, "usage: pipeline worker|relay|failed|replay|reprocess")
|
||||
os.Exit(2)
|
||||
}
|
||||
cfg := config.Load()
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||||
defer stop()
|
||||
|
||||
pool, err := postgres.NewPool(ctx, cfg.DatabaseURL, int32(cfg.WorkerConcurrency+4))
|
||||
if err != nil {
|
||||
slog.Error("connect to postgres", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer pool.Close()
|
||||
repo := postgres.NewPipelineRepository(pool)
|
||||
|
||||
switch os.Args[1] {
|
||||
case "worker":
|
||||
os.Exit(runWorker(ctx, cfg, repo))
|
||||
case "relay":
|
||||
os.Exit(runRelay(ctx, cfg, repo))
|
||||
case "failed":
|
||||
jobs, err := repo.FailedJobs(ctx, 200)
|
||||
if err != nil {
|
||||
slog.Error("failed jobs", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
out, _ := json.MarshalIndent(jobs, "", " ")
|
||||
fmt.Println(string(out))
|
||||
case "replay", "reprocess":
|
||||
fs := flag.NewFlagSet(os.Args[1], flag.ExitOnError)
|
||||
version := fs.Int("version", cfg.PipelineVersion, "pipeline version")
|
||||
actor := fs.String("actor", "operator", "who requested the replay (audit)")
|
||||
if len(os.Args) < 3 {
|
||||
fmt.Fprintln(os.Stderr, "attachment_id required")
|
||||
os.Exit(2)
|
||||
}
|
||||
_ = fs.Parse(os.Args[3:])
|
||||
var jobID string
|
||||
if os.Args[1] == "replay" {
|
||||
jobID, err = repo.Replay(ctx, os.Args[2], *version, *actor)
|
||||
} else {
|
||||
jobID, err = repo.Reprocess(ctx, os.Args[2], *version, cfg.JobMaxAttempts)
|
||||
}
|
||||
out, _ := json.Marshal(map[string]any{"command": os.Args[1], "attachment_id": os.Args[2], "version": *version,
|
||||
"job_id": jobID, "ok": err == nil, "error": errString(err)})
|
||||
fmt.Println(string(out))
|
||||
if err != nil {
|
||||
os.Exit(3)
|
||||
}
|
||||
default:
|
||||
fmt.Fprintln(os.Stderr, "unknown command", os.Args[1])
|
||||
os.Exit(2)
|
||||
}
|
||||
}
|
||||
|
||||
func errString(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
return err.Error()
|
||||
}
|
||||
|
||||
func faultPoints() map[string]bool {
|
||||
m := map[string]bool{}
|
||||
for _, p := range strings.Split(os.Getenv("FAULT_POINTS"), ",") {
|
||||
if p = strings.TrimSpace(p); p != "" {
|
||||
m[p] = true
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func newStore(cfg config.Config) storage.Store {
|
||||
store, err := storage.NewS3(cfg.S3Endpoint, cfg.S3Region, cfg.S3Bucket, cfg.S3AccessKey, cfg.S3SecretKey)
|
||||
if err != nil {
|
||||
slog.Error("s3 client", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return store
|
||||
}
|
||||
|
||||
func runWorker(ctx context.Context, cfg config.Config, repo *postgres.PipelineRepository) int {
|
||||
host, _ := os.Hostname()
|
||||
owner := fmt.Sprintf("%s:%d", host, os.Getpid())
|
||||
w := worker.New(repo, newStore(cfg), imaging.CWebP, worker.Config{
|
||||
Owner: owner, Lease: cfg.JobTimeout, JobTimeout: cfg.JobTimeout,
|
||||
MaxBytes: cfg.MaxUploadBytes, MaxPixels: cfg.MaxImagePixels, PixelBudget: cfg.PixelBudget,
|
||||
WebPQuality: cfg.WebPQuality, RetryBase: cfg.RetryBaseDelay, RetryMax: cfg.RetryMaxDelay,
|
||||
FaultPoints: faultPoints(), FaultDir: os.TempDir(), DeleteStaging: true,
|
||||
})
|
||||
slog.Info("worker starting", "owner", owner, "concurrency", cfg.WorkerConcurrency, "lease", cfg.JobTimeout)
|
||||
backoff := time.Second
|
||||
for ctx.Err() == nil {
|
||||
cons, deliveries, err := broker.NewConsumer(cfg.BrokerURL, cfg.WorkerConcurrency, "worker-"+owner)
|
||||
if err != nil {
|
||||
slog.Warn("broker unavailable, retrying", "err", err, "in", backoff)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(backoff):
|
||||
}
|
||||
backoff = min(backoff*2, 30*time.Second)
|
||||
continue
|
||||
}
|
||||
backoff = time.Second
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < cfg.WorkerConcurrency; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for d := range deliveries {
|
||||
switch w.Handle(context.WithoutCancel(ctx), d.Body) {
|
||||
case worker.Ack:
|
||||
_ = d.Ack(false)
|
||||
case worker.Requeue:
|
||||
time.Sleep(time.Second)
|
||||
_ = d.Nack(false, true)
|
||||
case worker.Reject:
|
||||
_ = d.Nack(false, false) // → DLX attachment.dead
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
// Graceful: прекращаем получать новые сообщения, дорабатываем текущие.
|
||||
slog.Info("shutdown: cancel consumer, finishing in-flight jobs")
|
||||
cons.Cancel("worker-" + owner)
|
||||
done := make(chan struct{})
|
||||
go func() { wg.Wait(); close(done) }()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(cfg.JobTimeout):
|
||||
slog.Warn("shutdown timeout: unacked jobs will be redelivered")
|
||||
}
|
||||
cons.Close()
|
||||
return 0
|
||||
case <-waitAll(&wg):
|
||||
slog.Warn("broker connection lost, reconnecting")
|
||||
cons.Close()
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func waitAll(wg *sync.WaitGroup) <-chan struct{} {
|
||||
ch := make(chan struct{})
|
||||
go func() { wg.Wait(); close(ch) }()
|
||||
return ch
|
||||
}
|
||||
|
||||
func runRelay(ctx context.Context, cfg config.Config, repo *postgres.PipelineRepository) int {
|
||||
store := newStore(cfg)
|
||||
points := faultPoints()
|
||||
afterPublish := func() { worker.Fault(points, os.TempDir(), "relay.after_publish", os.Exit) }
|
||||
var pub *broker.Publisher
|
||||
defer func() {
|
||||
if pub != nil {
|
||||
pub.Close()
|
||||
}
|
||||
}()
|
||||
tPublish := time.NewTicker(300 * time.Millisecond)
|
||||
tSweep := time.NewTicker(5 * time.Second)
|
||||
tClean := time.NewTicker(time.Minute)
|
||||
defer tPublish.Stop()
|
||||
defer tSweep.Stop()
|
||||
defer tClean.Stop()
|
||||
slog.Info("relay starting")
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return 0
|
||||
case <-tPublish.C:
|
||||
if pub == nil || pub.Closed() {
|
||||
p, err := broker.NewPublisher(cfg.BrokerURL)
|
||||
if err != nil {
|
||||
slog.Warn("broker unavailable; outbox keeps messages", "err", err)
|
||||
continue
|
||||
}
|
||||
pub = p
|
||||
}
|
||||
for {
|
||||
n, err := repo.PublishDue(ctx, 100, func(c context.Context, m postgres.OutboxMessage) error {
|
||||
return pub.Publish(c, m.JobID, m.Payload)
|
||||
}, afterPublish)
|
||||
if err != nil {
|
||||
slog.Warn("outbox publish failed; will retry", "err", err)
|
||||
break
|
||||
}
|
||||
if n > 0 {
|
||||
slog.Info("outbox published", "messages", n)
|
||||
}
|
||||
if n < 100 {
|
||||
break
|
||||
}
|
||||
}
|
||||
case <-tSweep.C:
|
||||
if n, err := repo.SweepExpiredLeases(ctx); err != nil {
|
||||
slog.Warn("lease sweep failed", "err", err)
|
||||
} else if n > 0 {
|
||||
slog.Warn("expired leases requeued", "jobs", n)
|
||||
}
|
||||
case <-tClean.C:
|
||||
cleanStaging(ctx, cfg, repo, store)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// cleanStaging удаляет staging после безопасной публикации (ready, ≥10 мин назад —
|
||||
// fallback, если worker не удалил сразу) и у failed старше STAGING_RETENTION.
|
||||
func cleanStaging(ctx context.Context, cfg config.Config, repo *postgres.PipelineRepository, store storage.Store) {
|
||||
cands, err := repo.StagingToClean(ctx, 10*time.Minute, cfg.StagingRetention, 200)
|
||||
if err != nil {
|
||||
slog.Warn("staging cleanup query failed", "err", err)
|
||||
return
|
||||
}
|
||||
for _, c := range cands {
|
||||
if err := store.Delete(ctx, c.Key); err != nil && !errors.Is(err, storage.ErrNotFound) {
|
||||
slog.Warn("staging delete failed", "key", c.Key, "err", err)
|
||||
continue
|
||||
}
|
||||
_ = repo.ClearStaging(ctx, c.AttachmentID, c.Key)
|
||||
}
|
||||
if len(cands) > 0 {
|
||||
slog.Info("staging cleaned", "objects", len(cands))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
// Command reconcile сверяет PostgreSQL и S3 и безопасно убирает расхождения.
|
||||
//
|
||||
// reconcile # dry-run, grace 1h, отчёт JSON в stdout
|
||||
// reconcile --apply # исправить
|
||||
// reconcile --apply --interval 10m # фоновый режим (сервис reconciler в compose)
|
||||
//
|
||||
// Grace period должен быть больше максимальной длительности загрузки
|
||||
// (ReadTimeout 30 s + PUT) с запасом на расхождение часов; значения < 5m
|
||||
// разрешены только с --unsafe-short-grace (для тестов).
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/config"
|
||||
"github.com/charawein/mtusi2026lab5/internal/reconcile"
|
||||
"github.com/charawein/mtusi2026lab5/internal/repository/postgres"
|
||||
"github.com/charawein/mtusi2026lab5/internal/storage"
|
||||
)
|
||||
|
||||
func main() {
|
||||
apply := flag.Bool("apply", false, "apply fixes (default: dry-run, report only)")
|
||||
grace := flag.Duration("grace", time.Hour, "do not touch objects/intents/quarantine younger than this")
|
||||
unsafe := flag.Bool("unsafe-short-grace", false, "allow grace < 5m (tests only)")
|
||||
interval := flag.Duration("interval", 0, "repeat every interval (0 = run once)")
|
||||
flag.Parse()
|
||||
|
||||
slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stderr, nil)))
|
||||
if *grace < 5*time.Minute && !*unsafe {
|
||||
fmt.Fprintln(os.Stderr, "grace < 5m is unsafe: in-flight uploads could be deleted; pass --unsafe-short-grace for tests")
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
cfg := config.Load()
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||||
defer stop()
|
||||
|
||||
pool, err := postgres.NewPool(ctx, cfg.DatabaseURL, 4)
|
||||
if err != nil {
|
||||
slog.Error("connect to postgres", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer pool.Close()
|
||||
store, err := storage.NewS3(cfg.S3Endpoint, cfg.S3Region, cfg.S3Bucket, cfg.S3AccessKey, cfg.S3SecretKey)
|
||||
if err != nil {
|
||||
slog.Error("s3 client", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
repo := postgres.NewAttachmentRepository(pool)
|
||||
|
||||
runOnce := func() int {
|
||||
unlock, ok, err := repo.TryLock(ctx)
|
||||
if err != nil {
|
||||
slog.Error("advisory lock", "err", err)
|
||||
return 1
|
||||
}
|
||||
if !ok {
|
||||
slog.Warn("another reconciler is running, skipping this pass")
|
||||
return 3
|
||||
}
|
||||
defer unlock()
|
||||
var now time.Time
|
||||
if err := pool.QueryRow(ctx, `SELECT now()`).Scan(&now); err != nil {
|
||||
slog.Error("db time", "err", err)
|
||||
return 1
|
||||
}
|
||||
rep, err := reconcile.Run(ctx, repo, store, reconcile.Options{
|
||||
Prefix: "", Grace: *grace, Apply: *apply, Now: now, // весь bucket: a/, s/, o/, v/
|
||||
})
|
||||
out, _ := json.Marshal(rep)
|
||||
fmt.Println(string(out))
|
||||
if err != nil {
|
||||
slog.Error("reconcile pass failed", "err", err)
|
||||
return 1
|
||||
}
|
||||
slog.Info("reconcile pass done", "dry_run", rep.DryRun, "found", rep.Found, "fixed", rep.Fixed,
|
||||
"rows", rep.RowsScanned, "objects", rep.ObjectsScanned, "ms", rep.DurationMS)
|
||||
if len(rep.Errors) > 0 {
|
||||
return 4
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
if *interval <= 0 {
|
||||
os.Exit(runOnce())
|
||||
}
|
||||
t := time.NewTicker(*interval)
|
||||
defer t.Stop()
|
||||
for {
|
||||
runOnce()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
+324
@@ -0,0 +1,324 @@
|
||||
# Lab5: клиент → HAProxy → API × N → PostgreSQL (данные, метаданные, jobs, outbox), Redis (сессии, кэш),
|
||||
# приватный S3 (MinIO: staging s/, оригиналы o/, варианты v/).
|
||||
# relay: outbox → RabbitMQ (publisher confirms); worker: RabbitMQ → варианты → S3 + PostgreSQL.
|
||||
# Запуск: scripts/init-secrets.sh && docker compose --env-file .env up -d --build --wait
|
||||
name: mtusi2026lab5
|
||||
|
||||
x-api-env: &api-env
|
||||
APP_HOST: ${APP_HOST:-0.0.0.0}
|
||||
APP_PORT: ${APP_PORT:-8080}
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
SESSION_STORE: ${SESSION_STORE:-redis}
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
CACHE_URL_FILE: /run/secrets/cache_url
|
||||
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
|
||||
DRAIN_DELAY: ${DRAIN_DELAY:-3s}
|
||||
SHUTDOWN_TIMEOUT: ${SHUTDOWN_TIMEOUT:-8s}
|
||||
DB_POOL_MAX: ${DB_POOL_MAX:-20}
|
||||
CACHE_INVALIDATION: ${CACHE_INVALIDATION:-version}
|
||||
S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:9000}
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key
|
||||
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
|
||||
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
|
||||
PIPELINE_VERSION: ${PIPELINE_VERSION:-1}
|
||||
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
|
||||
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
|
||||
WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2}
|
||||
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400}
|
||||
WEBP_QUALITY: ${WEBP_QUALITY:-80}
|
||||
WORKER_PIXEL_BUDGET: ${WORKER_PIXEL_BUDGET:-60000000}
|
||||
RETRY_BASE_DELAY: ${RETRY_BASE_DELAY:-2s}
|
||||
RETRY_MAX_DELAY: ${RETRY_MAX_DELAY:-60s}
|
||||
|
||||
services:
|
||||
lb:
|
||||
image: haproxy:3.0.5-alpine
|
||||
ports:
|
||||
- "127.0.0.1:${LB_PORT:-8080}:8080"
|
||||
- "127.0.0.1:${LB_STATS_PORT:-8404}:8404"
|
||||
environment:
|
||||
LB_BALANCE: ${LB_BALANCE:-roundrobin}
|
||||
volumes:
|
||||
- ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
networks: [front]
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "${LB_CPUS:-0.50}", memory: 128M }
|
||||
|
||||
api:
|
||||
build: .
|
||||
image: mtusi2026lab5-api:local
|
||||
# Без container_name и без ports: реплики доступны только через lb.
|
||||
environment: *api-env
|
||||
secrets: [database_url, cache_url, s3_access_key_id, s3_secret_access_key]
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
s3-init:
|
||||
condition: service_completed_successfully
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--spider", "-q", "http://localhost:8080/health/ready"]
|
||||
interval: 5s
|
||||
timeout: 2s
|
||||
retries: 3
|
||||
start_period: 5s
|
||||
# DRAIN_DELAY + SHUTDOWN_TIMEOUT < stop_grace_period, иначе SIGKILL оборвёт запросы.
|
||||
stop_grace_period: 15s
|
||||
restart: unless-stopped
|
||||
networks: [front, back]
|
||||
deploy:
|
||||
replicas: ${API_REPLICAS:-2}
|
||||
resources:
|
||||
limits: { cpus: "${API_CPUS:-0.50}", memory: "${API_MEMORY:-256M}" }
|
||||
|
||||
# Однократные миграции до старта API: реплики не гоняются за схему.
|
||||
migrate:
|
||||
image: migrate/migrate:v4.17.0
|
||||
volumes:
|
||||
- ./migrations:/migrations:ro
|
||||
secrets: [database_url]
|
||||
entrypoint: ["/bin/sh", "-c", "exec migrate -path /migrations -database \"$$(cat /run/secrets/database_url)\" up"]
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
restart: "no"
|
||||
networks: [back]
|
||||
|
||||
postgres:
|
||||
image: postgres:16.4-alpine
|
||||
command: ["postgres", "-c", "max_connections=${PG_MAX_CONNECTIONS:-100}"]
|
||||
environment:
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
|
||||
POSTGRES_DB: messenger
|
||||
secrets: [postgres_password]
|
||||
volumes:
|
||||
- pg_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
restart: unless-stopped
|
||||
networks: [back]
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "${PG_CPUS:-1.00}", memory: "${PG_MEMORY:-512M}" }
|
||||
|
||||
redis:
|
||||
image: redis:7.4.1-alpine
|
||||
command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec"]
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
restart: unless-stopped
|
||||
networks: [back]
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "${REDIS_CPUS:-0.50}", memory: 256M }
|
||||
|
||||
# S3-совместимое хранилище байтов вложений: MinIO RELEASE.2025-04-22T22-12-26Z.
|
||||
# Официальные образы minio/minio убраны из Docker Hub и quay.io (проверено в CI),
|
||||
# поэтому используется сборка Bitnami того же релиза, закреплённая по digest.
|
||||
# Порты не публикуются, консоль выключена (MINIO_BROWSER=off): доступ только из сети back.
|
||||
s3:
|
||||
image: bitnamilegacy/minio:2025.4.22@sha256:50cec18ac4184af4671a78aedd5554942c8ae105d51a465fa82037949046da01
|
||||
entrypoint: ["/bin/bash", "-c"]
|
||||
command:
|
||||
- export MINIO_ROOT_USER="$$(cat /run/secrets/s3_root_user)" MINIO_ROOT_PASSWORD="$$(cat /run/secrets/s3_root_password)"; exec /opt/bitnami/minio/bin/minio server /bitnami/minio/data --address :9000
|
||||
environment:
|
||||
MINIO_BROWSER: "off"
|
||||
secrets: [s3_root_user, s3_root_password]
|
||||
volumes:
|
||||
- s3_data:/bitnami/minio/data
|
||||
healthcheck:
|
||||
# Без curl в образе: HTTP/1.1-запрос к /minio/health/live через /dev/tcp и read (только bash).
|
||||
test: ["CMD", "bash", "-c", "exec 3<>/dev/tcp/127.0.0.1/9000 && printf 'GET /minio/health/live HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n' >&3 && read -r line <&3 && [[ $$line == *' 200 '* ]]"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
restart: unless-stopped
|
||||
networks: [back]
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "${S3_CPUS:-0.50}", memory: 512M }
|
||||
|
||||
# Идемпотентный bootstrap: приватный bucket, политика и отдельный пользователь
|
||||
# API с правами только на этот bucket. Root-учётка есть только у s3 и s3-init.
|
||||
s3-init:
|
||||
image: bitnamilegacy/minio-client:2025.4.16@sha256:8a86e441decf053093c5977d49290298295f850c7843652f93e970ab15871dd1
|
||||
entrypoint: ["/bin/sh", "/init/init.sh"]
|
||||
environment:
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
PATH: /opt/bitnami/minio-client/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
||||
MC_CONFIG_DIR: /tmp/.mc
|
||||
secrets: [s3_root_user, s3_root_password, s3_access_key_id, s3_secret_access_key]
|
||||
volumes:
|
||||
- ./infra/s3:/init:ro
|
||||
depends_on:
|
||||
s3:
|
||||
condition: service_healthy
|
||||
restart: "no"
|
||||
networks: [back]
|
||||
|
||||
# Сверка PostgreSQL и S3: брошенные загрузки, сироты, потерянные объекты.
|
||||
# Безопасный grace period 1h; одновременно работает один экземпляр (advisory lock).
|
||||
reconciler:
|
||||
image: mtusi2026lab5-api:local
|
||||
entrypoint: ["/app/reconcile", "--apply", "--interval", "${RECONCILE_INTERVAL:-10m}", "--grace", "${RECONCILE_GRACE:-1h}"]
|
||||
environment:
|
||||
<<: *api-env
|
||||
CACHE_URL_FILE: "" # Redis reconciler не нужен
|
||||
secrets: [database_url, s3_access_key_id, s3_secret_access_key]
|
||||
# HTTP не обслуживает, поэтому вместо HEALTHCHECK образа API — проверка, что
|
||||
# процесс reconcile жив (нужна и для docker compose up --wait).
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pgrep -x reconcile >/dev/null || pidof reconcile >/dev/null"]
|
||||
interval: 10s
|
||||
timeout: 3s
|
||||
retries: 3
|
||||
start_period: 5s
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
s3-init:
|
||||
condition: service_completed_successfully
|
||||
restart: unless-stopped
|
||||
networks: [back]
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "0.25", memory: 128M }
|
||||
|
||||
# Broker: quorum-очереди на диске (volume), без management UI, порты не публикуются.
|
||||
# Пользователь и пароль — из secret rabbitmq.conf (guest отключён вне localhost).
|
||||
rabbitmq:
|
||||
image: rabbitmq:4.0.9-alpine
|
||||
hostname: rabbitmq # имя узла фиксировано: данные в volume привязаны к нему
|
||||
secrets:
|
||||
- source: rabbitmq_conf
|
||||
target: /etc/rabbitmq/conf.d/20-credentials.conf
|
||||
volumes:
|
||||
- rabbitmq_data:/var/lib/rabbitmq
|
||||
healthcheck:
|
||||
test: ["CMD", "rabbitmq-diagnostics", "-q", "check_port_connectivity"]
|
||||
interval: 5s
|
||||
timeout: 10s
|
||||
retries: 20
|
||||
start_period: 10s
|
||||
restart: unless-stopped
|
||||
networks: [back]
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "0.50", memory: 512M }
|
||||
|
||||
# Relay: публикует transactional outbox с publisher confirms, возвращает в очередь
|
||||
# работу с истёкшим lease, чистит staging. Не зависит от доступности API.
|
||||
relay:
|
||||
image: mtusi2026lab5-api:local
|
||||
entrypoint: ["/app/pipeline", "relay"]
|
||||
environment:
|
||||
<<: *api-env
|
||||
CACHE_URL_FILE: ""
|
||||
BROKER_URL_FILE: /run/secrets/broker_url
|
||||
FAULT_POINTS: ${RELAY_FAULT_POINTS:-}
|
||||
secrets: [database_url, s3_access_key_id, s3_secret_access_key, broker_url]
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pgrep -x pipeline >/dev/null || pidof pipeline >/dev/null"]
|
||||
interval: 10s
|
||||
timeout: 3s
|
||||
retries: 3
|
||||
start_period: 5s
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
s3-init:
|
||||
condition: service_completed_successfully
|
||||
rabbitmq:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
networks: [back]
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "0.25", memory: 128M }
|
||||
|
||||
# Worker: отдельный процесс; prefetch = WORKER_CONCURRENCY, lease = JOB_TIMEOUT_SECONDS,
|
||||
# память ограничена контейнером и пиксельным бюджетом. SIGTERM → дорабатывает текущие задания.
|
||||
worker:
|
||||
image: mtusi2026lab5-api:local
|
||||
entrypoint: ["/app/pipeline", "worker"]
|
||||
environment:
|
||||
<<: *api-env
|
||||
CACHE_URL_FILE: ""
|
||||
BROKER_URL_FILE: /run/secrets/broker_url
|
||||
FAULT_POINTS: ${WORKER_FAULT_POINTS:-}
|
||||
# Мягкий лимит кучи Go ≈ 75% лимита контейнера: без него GC (GOGC=100) даёт куче
|
||||
# расти до ~2× живого объёма, и пик подходил вплотную к 768M (замер прогона 4).
|
||||
GOMEMLIMIT: ${WORKER_GOMEMLIMIT:-560MiB}
|
||||
secrets: [database_url, s3_access_key_id, s3_secret_access_key, broker_url]
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pgrep -x pipeline >/dev/null || pidof pipeline >/dev/null"]
|
||||
interval: 10s
|
||||
timeout: 3s
|
||||
retries: 3
|
||||
start_period: 5s
|
||||
stop_grace_period: 70s
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
s3-init:
|
||||
condition: service_completed_successfully
|
||||
rabbitmq:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
networks: [back]
|
||||
deploy:
|
||||
replicas: ${WORKER_REPLICAS:-1}
|
||||
resources:
|
||||
limits: { cpus: "${WORKER_CPUS:-1.00}", memory: "${WORKER_MEMORY:-768M}" }
|
||||
|
||||
networks:
|
||||
# front: lb ↔ api; back: api ↔ хранилища и broker. LB не видит БД, S3 и broker.
|
||||
front:
|
||||
back:
|
||||
|
||||
secrets:
|
||||
postgres_password:
|
||||
file: ./secrets/postgres_password
|
||||
database_url:
|
||||
file: ./secrets/database_url
|
||||
cache_url:
|
||||
file: ./secrets/cache_url
|
||||
s3_root_user:
|
||||
file: ./secrets/s3_root_user
|
||||
s3_root_password:
|
||||
file: ./secrets/s3_root_password
|
||||
s3_access_key_id:
|
||||
file: ./secrets/s3_access_key_id
|
||||
s3_secret_access_key:
|
||||
file: ./secrets/s3_secret_access_key
|
||||
rabbitmq_conf:
|
||||
file: ./secrets/rabbitmq.conf
|
||||
broker_url:
|
||||
file: ./secrets/broker_url
|
||||
|
||||
volumes:
|
||||
rabbitmq_data:
|
||||
s3_data:
|
||||
pg_data:
|
||||
redis_data:
|
||||
@@ -3,3 +3,7 @@
|
||||
Храните небольшие обезличенные результаты: команды и stdout проверок, JSON/CSV агрегатов нагрузки, EXPLAIN, dashboard JSON, текст разбора отказа. Укажите дату, commit, аппаратные лимиты и профиль нагрузки.
|
||||
|
||||
Не добавляйте .env, session tokens, cookies, приватные ключи, credentials, реальные сообщения, raw dumps и signed URLs. Для скриншотов скрывайте секреты. Большие логи/бинарные traces сохраняйте отдельно по правилам преподавателя; одного скриншота без методики недостаточно.
|
||||
|
||||
## Этот каталог (lab5)
|
||||
|
||||
Источник всех файлов — итоговый прогон https://github.com/CharaWein/2026_lab3/actions/runs/42642251603, commit 1289df3 (`RUN.txt`), 2026-11-09, GitHub-hosted runner 2 vCPU / 8 GB, Docker 28.0.4, Compose v2.38.2 (`runner_*.txt`). Четыре независимых стенда: base (корень каталога), files (`files/`), pipeline (`pipeline/`), track2 (`track2/`); Go-тесты — `go_test.txt`, `webp_test.txt`, `track2/pipeline_fault_injection.txt`. Полные логи compose и сборки остались в артефактах прогона и сюда не копировались.
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
source_commit=1289df31b164f918788b81710a19622bd131deab
|
||||
run=https://github.com/CharaWein/2026_lab3/actions/runs/42642251603
|
||||
go_tests=success
|
||||
stand=success
|
||||
@@ -0,0 +1,13 @@
|
||||
2026-11-09T15:14:12Z
|
||||
Docker Compose version v2.38.2
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab5-api-1 mtusi2026lab5-api:local "/app/api" api 17 seconds ago Up 7 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab5-api-2 mtusi2026lab5-api:local "/app/api" api 17 seconds ago Up 8 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab5-lb-1 haproxy:3.0.5-alpine "docker-entrypoint.s…" lb 17 seconds ago Up 1 second 127.0.0.1:8080->8080/tcp, 127.0.0.1:8404->8404/tcp
|
||||
mtusi2026lab5-postgres-1 postgres:16.4-alpine "docker-entrypoint.s…" postgres 17 seconds ago Up 16 seconds (healthy) 5432/tcp
|
||||
mtusi2026lab5-rabbitmq-1 rabbitmq:4.0.9-alpine "docker-entrypoint.s…" rabbitmq 17 seconds ago Up 16 seconds (healthy) 4369/tcp, 5671-5672/tcp, 15691-15692/tcp, 25672/tcp
|
||||
mtusi2026lab5-reconciler-1 mtusi2026lab5-api:local "/app/reconcile --ap…" reconciler 17 seconds ago Up 7 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab5-redis-1 redis:7.4.1-alpine "docker-entrypoint.s…" redis 17 seconds ago Up 16 seconds (healthy) 6379/tcp
|
||||
mtusi2026lab5-relay-1 mtusi2026lab5-api:local "/app/pipeline relay" relay 17 seconds ago Up 8 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab5-s3-1 bitnamilegacy/minio:2025.4.22@sha256:50cec18ac4184af4671a78aedd5554942c8ae105d51a465fa82037949046da01 "/bin/bash -c 'expor…" s3 17 seconds ago Up 16 seconds (healthy) 9000-9001/tcp
|
||||
mtusi2026lab5-worker-1 mtusi2026lab5-api:local "/app/pipeline worker" worker 17 seconds ago Up 7 seconds (healthy) 8080/tcp
|
||||
@@ -0,0 +1,13 @@
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab5-api-3 mtusi2026lab5-api:local "/app/api" api About a minute ago Up About a minute (healthy) 8080/tcp
|
||||
mtusi2026lab5-api-4 mtusi2026lab5-api:local "/app/api" api About a minute ago Up About a minute (healthy) 8080/tcp
|
||||
mtusi2026lab5-lb-1 haproxy:3.0.5-alpine "docker-entrypoint.s…" lb 5 minutes ago Up 3 minutes 127.0.0.1:8080->8080/tcp, 127.0.0.1:8404->8404/tcp
|
||||
mtusi2026lab5-migrate-1 migrate/migrate:v4.17.0 "/bin/sh -c 'exec mi…" migrate 5 minutes ago Exited (0) 3 minutes ago
|
||||
mtusi2026lab5-postgres-1 postgres:16.4-alpine "docker-entrypoint.s…" postgres 5 minutes ago Up 3 minutes (healthy) 5432/tcp
|
||||
mtusi2026lab5-rabbitmq-1 rabbitmq:4.0.9-alpine "docker-entrypoint.s…" rabbitmq 5 minutes ago Up 3 minutes (healthy) 4369/tcp, 5671-5672/tcp, 15691-15692/tcp, 25672/tcp
|
||||
mtusi2026lab5-reconciler-1 mtusi2026lab5-api:local "/app/reconcile --ap…" reconciler 5 minutes ago Up 3 minutes (healthy) 8080/tcp
|
||||
mtusi2026lab5-redis-1 redis:7.4.1-alpine "docker-entrypoint.s…" redis 5 minutes ago Up 3 minutes (healthy) 6379/tcp
|
||||
mtusi2026lab5-relay-1 mtusi2026lab5-api:local "/app/pipeline relay" relay 5 minutes ago Up 3 minutes (healthy) 8080/tcp
|
||||
mtusi2026lab5-s3-1 bitnamilegacy/minio:2025.4.22@sha256:50cec18ac4184af4671a78aedd5554942c8ae105d51a465fa82037949046da01 "/bin/bash -c 'expor…" s3 5 minutes ago Up 3 minutes (healthy) 9000-9001/tcp
|
||||
mtusi2026lab5-s3-init-1 bitnamilegacy/minio-client:2025.4.16@sha256:8a86e441decf053093c5977d49290298295f850c7843652f93e970ab15871dd1 "/bin/sh /init/init.…" s3-init 5 minutes ago Exited (0) 3 minutes ago
|
||||
mtusi2026lab5-worker-1 mtusi2026lab5-api:local "/app/pipeline worker" worker 5 minutes ago Up 3 minutes (healthy) 8080/tcp
|
||||
@@ -0,0 +1,13 @@
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab5-api-1 mtusi2026lab5-api:local "/app/api" api 2 minutes ago Up 12 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab5-api-2 mtusi2026lab5-api:local "/app/api" api 2 minutes ago Up 12 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab5-lb-1 haproxy:3.0.5-alpine "docker-entrypoint.s…" lb 2 minutes ago Up 2 minutes 127.0.0.1:8080->8080/tcp, 127.0.0.1:8404->8404/tcp
|
||||
mtusi2026lab5-migrate-1 migrate/migrate:v4.17.0 "/bin/sh -c 'exec mi…" migrate 2 minutes ago Exited (0) 11 seconds ago
|
||||
mtusi2026lab5-postgres-1 postgres:16.4-alpine "docker-entrypoint.s…" postgres 2 minutes ago Up 2 minutes (healthy) 5432/tcp
|
||||
mtusi2026lab5-rabbitmq-1 rabbitmq:4.0.9-alpine "docker-entrypoint.s…" rabbitmq 2 minutes ago Up 2 minutes (healthy) 4369/tcp, 5671-5672/tcp, 15691-15692/tcp, 25672/tcp
|
||||
mtusi2026lab5-reconciler-1 mtusi2026lab5-api:local "/app/reconcile --ap…" reconciler 2 minutes ago Up 2 minutes (healthy) 8080/tcp
|
||||
mtusi2026lab5-redis-1 redis:7.4.1-alpine "docker-entrypoint.s…" redis 2 minutes ago Up 2 minutes (healthy) 6379/tcp
|
||||
mtusi2026lab5-relay-1 mtusi2026lab5-api:local "/app/pipeline relay" relay 2 minutes ago Up 2 minutes (healthy) 8080/tcp
|
||||
mtusi2026lab5-s3-1 bitnamilegacy/minio:2025.4.22@sha256:50cec18ac4184af4671a78aedd5554942c8ae105d51a465fa82037949046da01 "/bin/bash -c 'expor…" s3 2 minutes ago Up About a minute (healthy) 9000-9001/tcp
|
||||
mtusi2026lab5-s3-init-1 bitnamilegacy/minio-client:2025.4.16@sha256:8a86e441decf053093c5977d49290298295f850c7843652f93e970ab15871dd1 "/bin/sh /init/init.…" s3-init 2 minutes ago Exited (0) 10 seconds ago
|
||||
mtusi2026lab5-worker-1 mtusi2026lab5-api:local "/app/pipeline worker" worker 2 minutes ago Up 2 minutes (healthy) 8080/tcp
|
||||
@@ -0,0 +1,13 @@
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab5-api-1 mtusi2026lab5-api:local "/app/api" api 3 minutes ago Up 2 minutes (healthy) 8080/tcp
|
||||
mtusi2026lab5-api-2 mtusi2026lab5-api:local "/app/api" api 3 minutes ago Up 2 minutes (healthy) 8080/tcp
|
||||
mtusi2026lab5-lb-1 haproxy:3.0.5-alpine "docker-entrypoint.s…" lb 3 minutes ago Up 3 minutes 127.0.0.1:8080->8080/tcp, 127.0.0.1:8404->8404/tcp
|
||||
mtusi2026lab5-migrate-1 migrate/migrate:v4.17.0 "/bin/sh -c 'exec mi…" migrate 3 minutes ago Exited (0) 27 seconds ago
|
||||
mtusi2026lab5-postgres-1 postgres:16.4-alpine "docker-entrypoint.s…" postgres 3 minutes ago Up 3 minutes (healthy) 5432/tcp
|
||||
mtusi2026lab5-rabbitmq-1 rabbitmq:4.0.9-alpine "docker-entrypoint.s…" rabbitmq 3 minutes ago Up 59 seconds (healthy) 4369/tcp, 5671-5672/tcp, 15691-15692/tcp, 25672/tcp
|
||||
mtusi2026lab5-reconciler-1 mtusi2026lab5-api:local "/app/reconcile --ap…" reconciler 3 minutes ago Up 3 minutes (healthy) 8080/tcp
|
||||
mtusi2026lab5-redis-1 redis:7.4.1-alpine "docker-entrypoint.s…" redis 3 minutes ago Up 3 minutes (healthy) 6379/tcp
|
||||
mtusi2026lab5-relay-1 mtusi2026lab5-api:local "/app/pipeline relay" relay 2 minutes ago Up 2 minutes (healthy) 8080/tcp
|
||||
mtusi2026lab5-s3-1 bitnamilegacy/minio:2025.4.22@sha256:50cec18ac4184af4671a78aedd5554942c8ae105d51a465fa82037949046da01 "/bin/bash -c 'expor…" s3 3 minutes ago Up 36 seconds (healthy) 9000-9001/tcp
|
||||
mtusi2026lab5-s3-init-1 bitnamilegacy/minio-client:2025.4.16@sha256:8a86e441decf053093c5977d49290298295f850c7843652f93e970ab15871dd1 "/bin/sh /init/init.…" s3-init 3 minutes ago Exited (0) 26 seconds ago
|
||||
mtusi2026lab5-worker-1 mtusi2026lab5-api:local "/app/pipeline worker" worker About a minute ago Up 12 seconds (healthy) 8080/tcp
|
||||
@@ -0,0 +1,13 @@
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab5-api-1 mtusi2026lab5-api:local "/app/api" api About a minute ago Up About a minute (healthy) 8080/tcp
|
||||
mtusi2026lab5-api-2 mtusi2026lab5-api:local "/app/api" api About a minute ago Up About a minute (healthy) 8080/tcp
|
||||
mtusi2026lab5-lb-1 haproxy:3.0.5-alpine "docker-entrypoint.s…" lb About a minute ago Up 54 seconds 127.0.0.1:8080->8080/tcp, 127.0.0.1:8404->8404/tcp
|
||||
mtusi2026lab5-migrate-1 migrate/migrate:v4.17.0 "/bin/sh -c 'exec mi…" migrate About a minute ago Exited (0) About a minute ago
|
||||
mtusi2026lab5-postgres-1 postgres:16.4-alpine "docker-entrypoint.s…" postgres About a minute ago Up About a minute (healthy) 5432/tcp
|
||||
mtusi2026lab5-rabbitmq-1 rabbitmq:4.0.9-alpine "docker-entrypoint.s…" rabbitmq About a minute ago Up About a minute (healthy) 4369/tcp, 5671-5672/tcp, 15691-15692/tcp, 25672/tcp
|
||||
mtusi2026lab5-reconciler-1 mtusi2026lab5-api:local "/app/reconcile --ap…" reconciler About a minute ago Up About a minute (healthy) 8080/tcp
|
||||
mtusi2026lab5-redis-1 redis:7.4.1-alpine "docker-entrypoint.s…" redis About a minute ago Up About a minute (healthy) 6379/tcp
|
||||
mtusi2026lab5-relay-1 mtusi2026lab5-api:local "/app/pipeline relay" relay About a minute ago Up 53 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab5-s3-1 bitnamilegacy/minio:2025.4.22@sha256:50cec18ac4184af4671a78aedd5554942c8ae105d51a465fa82037949046da01 "/bin/bash -c 'expor…" s3 About a minute ago Up About a minute (healthy) 9000-9001/tcp
|
||||
mtusi2026lab5-s3-init-1 bitnamilegacy/minio-client:2025.4.16@sha256:8a86e441decf053093c5977d49290298295f850c7843652f93e970ab15871dd1 "/bin/sh /init/init.…" s3-init About a minute ago Exited (0) About a minute ago
|
||||
mtusi2026lab5-worker-1 mtusi2026lab5-api:local "/app/pipeline worker" worker About a minute ago Up 53 seconds (healthy) 8080/tcp
|
||||
@@ -0,0 +1,10 @@
|
||||
mtusi2026lab5-api-4 0.05% 7.82MiB / 256MiB
|
||||
mtusi2026lab5-api-3 0.07% 7.984MiB / 256MiB
|
||||
mtusi2026lab5-lb-1 0.09% 8.594MiB / 128MiB
|
||||
mtusi2026lab5-relay-1 0.16% 4.051MiB / 128MiB
|
||||
mtusi2026lab5-reconciler-1 0.01% 3.809MiB / 128MiB
|
||||
mtusi2026lab5-worker-1 0.00% 3.102MiB / 768MiB
|
||||
mtusi2026lab5-s3-1 0.02% 334.1MiB / 512MiB
|
||||
mtusi2026lab5-postgres-1 24.21% 82.02MiB / 512MiB
|
||||
mtusi2026lab5-rabbitmq-1 43.18% 68.2MiB / 512MiB
|
||||
mtusi2026lab5-redis-1 0.39% 4.438MiB / 256MiB
|
||||
@@ -0,0 +1,10 @@
|
||||
mtusi2026lab5-lb-1 0.09% 8.531MiB / 128MiB
|
||||
mtusi2026lab5-relay-1 0.11% 4.016MiB / 128MiB
|
||||
mtusi2026lab5-reconciler-1 0.00% 3.664MiB / 128MiB
|
||||
mtusi2026lab5-api-2 0.07% 13.44MiB / 256MiB
|
||||
mtusi2026lab5-worker-1 85.87% 141.1MiB / 768MiB
|
||||
mtusi2026lab5-api-1 0.05% 14.41MiB / 256MiB
|
||||
mtusi2026lab5-rabbitmq-1 0.24% 83.23MiB / 512MiB
|
||||
mtusi2026lab5-s3-1 9.12% 441MiB / 512MiB
|
||||
mtusi2026lab5-postgres-1 0.68% 79.43MiB / 512MiB
|
||||
mtusi2026lab5-redis-1 0.49% 3.633MiB / 256MiB
|
||||
@@ -0,0 +1,10 @@
|
||||
mtusi2026lab5-worker-1 0.00% 530.2MiB / 768MiB
|
||||
mtusi2026lab5-relay-1 0.15% 4.234MiB / 128MiB
|
||||
mtusi2026lab5-lb-1 0.12% 8.016MiB / 128MiB
|
||||
mtusi2026lab5-api-2 0.07% 135.2MiB / 256MiB
|
||||
mtusi2026lab5-reconciler-1 0.00% 3.68MiB / 128MiB
|
||||
mtusi2026lab5-api-1 0.05% 134.6MiB / 256MiB
|
||||
mtusi2026lab5-rabbitmq-1 0.17% 67.86MiB / 512MiB
|
||||
mtusi2026lab5-redis-1 0.29% 3.859MiB / 256MiB
|
||||
mtusi2026lab5-s3-1 1.84% 336MiB / 512MiB
|
||||
mtusi2026lab5-postgres-1 3.09% 55.77MiB / 512MiB
|
||||
@@ -0,0 +1,10 @@
|
||||
mtusi2026lab5-lb-1 0.20% 8.262MiB / 128MiB
|
||||
mtusi2026lab5-relay-1 0.23% 3.301MiB / 128MiB
|
||||
mtusi2026lab5-reconciler-1 0.00% 3.664MiB / 128MiB
|
||||
mtusi2026lab5-api-1 0.08% 134.1MiB / 256MiB
|
||||
mtusi2026lab5-worker-1 0.00% 7.043MiB / 768MiB
|
||||
mtusi2026lab5-api-2 0.09% 134.4MiB / 256MiB
|
||||
mtusi2026lab5-postgres-1 0.21% 55.47MiB / 512MiB
|
||||
mtusi2026lab5-rabbitmq-1 50.81% 134.4MiB / 512MiB
|
||||
mtusi2026lab5-s3-1 0.02% 404.3MiB / 512MiB
|
||||
mtusi2026lab5-redis-1 3.70% 3.344MiB / 256MiB
|
||||
@@ -0,0 +1,8 @@
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 141, "failed_attempts": 0, "first_recovery_seconds": 3.367}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
-- контейнеры api после stop-one:
|
||||
mtusi2026lab5-api-1 61f9abf05f85 Up 30 seconds (healthy)
|
||||
mtusi2026lab5-api-2 95a4d5c06533 Exited (0) 12 seconds ago
|
||||
mtusi2026lab5-api-1 Up 38 seconds (healthy)
|
||||
mtusi2026lab5-api-2 Up 6 seconds (healthy)
|
||||
@@ -0,0 +1,8 @@
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 130, "failed_attempts": 0, "first_recovery_seconds": 4.083}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
-- контейнеры api после stop-one:
|
||||
mtusi2026lab5-api-1 61f9abf05f85 Up 55 seconds (healthy)
|
||||
mtusi2026lab5-api-2 95a4d5c06533 Exited (0) 11 seconds ago
|
||||
mtusi2026lab5-api-1 Up About a minute (healthy)
|
||||
mtusi2026lab5-api-2 Up 6 seconds (healthy)
|
||||
@@ -0,0 +1,64 @@
|
||||
{
|
||||
"concurrency": 4,
|
||||
"replicas": 2,
|
||||
"total": {
|
||||
"seconds": 53.17,
|
||||
"ok": 18698,
|
||||
"errors": 0,
|
||||
"ok_rps": 351.7
|
||||
},
|
||||
"confirmed_writes": 9350,
|
||||
"stored_messages": 9352,
|
||||
"duplicates": 0,
|
||||
"lost_confirmed": 0,
|
||||
"per_replica": [
|
||||
{
|
||||
"target_instance": "61f9abf05f85",
|
||||
"docker_stop_seconds": 3.54,
|
||||
"before": {
|
||||
"seconds": 5.0,
|
||||
"ok": 1072,
|
||||
"errors": 0,
|
||||
"ok_rps": 214.4
|
||||
},
|
||||
"during_stop_and_observe": {
|
||||
"seconds": 15.0,
|
||||
"ok": 5318,
|
||||
"errors": 0,
|
||||
"ok_rps": 354.5
|
||||
},
|
||||
"errors_after_stop": 0,
|
||||
"recovery_seconds": 0.0,
|
||||
"target_last_served_after_stop_seconds": 0.91,
|
||||
"other_instances_after": [
|
||||
"95a4d5c06533"
|
||||
],
|
||||
"restore_healthy_seconds": 5.92,
|
||||
"restore_serving_via_lb_seconds": 5.92
|
||||
},
|
||||
{
|
||||
"target_instance": "95a4d5c06533",
|
||||
"docker_stop_seconds": 4.33,
|
||||
"before": {
|
||||
"seconds": 5.0,
|
||||
"ok": 1737,
|
||||
"errors": 0,
|
||||
"ok_rps": 347.4
|
||||
},
|
||||
"during_stop_and_observe": {
|
||||
"seconds": 15.0,
|
||||
"ok": 5541,
|
||||
"errors": 0,
|
||||
"ok_rps": 369.4
|
||||
},
|
||||
"errors_after_stop": 0,
|
||||
"recovery_seconds": 0.0,
|
||||
"target_last_served_after_stop_seconds": 0.95,
|
||||
"other_instances_after": [
|
||||
"61f9abf05f85"
|
||||
],
|
||||
"restore_healthy_seconds": 6.28,
|
||||
"restore_serving_via_lb_seconds": 6.28
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
ok.png image/png 106 -> 202
|
||||
ok.jpg image/jpeg 900 -> 202
|
||||
%D1%84%D0%BE%D1%82%D0%BE%20%F0%9F%98%80. image/png 106 -> 202
|
||||
params.png image/png; charset=binary 106 -> 202
|
||||
near-limit.png image/png 10288524 -> 202
|
||||
too-big.png (Content-Length) image/png 10485761 -> 413
|
||||
too-big-chunked.png (no Content-Length) image/png 11534336 -> 413
|
||||
bomb.png image/png 66 -> 413
|
||||
over-pixels.png image/png 66 -> 413
|
||||
truncated.png image/png 53 -> 415
|
||||
corrupt.png image/png 106 -> 415
|
||||
truncated.jpg image/jpeg 898 -> 415
|
||||
mime-swap.png image/jpeg 106 -> 415
|
||||
mime-swap.jpg image/png 900 -> 415
|
||||
text.png image/png 23 -> 415
|
||||
gif.gif image/gif 14 -> 415
|
||||
ctype-missing.png application/octet-stream 106 -> 415
|
||||
empty.png image/png 0 -> 415
|
||||
short-data.png image/png 68 -> 415
|
||||
..%2Fetc%2Fpasswd image/png 106 -> 400
|
||||
a%5Cb.png image/png 106 -> 400
|
||||
nul%00.png image/png 106 -> 400
|
||||
bell%07.png image/png 106 -> 400
|
||||
%20%20%20 image/png 106 -> 400
|
||||
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx image/png 106 -> 400
|
||||
image/png 106 -> 400
|
||||
eve.png image/png 106 -> 404
|
||||
foreign.png image/png 106 -> 202
|
||||
PASS: attachment negative suite (28 upload cases, no 5xx)
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"scenario": "db-gap",
|
||||
"result": {
|
||||
"client_status": 504,
|
||||
"seconds": 53.4,
|
||||
"after_gap": {
|
||||
"row_status": "uploading",
|
||||
"staging_objects": 1
|
||||
},
|
||||
"final": {
|
||||
"row_status": "none"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"scenario": "failover",
|
||||
"result": {
|
||||
"uploaded_by": "136ebad5f66d",
|
||||
"downloaded_by": [
|
||||
"2426fcb77065"
|
||||
],
|
||||
"sha256": "9cd8ae086706327908419e4e9782e8ed003310802f9381e4f8776a81079460e5",
|
||||
"stopped_container": "136ebad5f66d"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"scenario": "interrupt",
|
||||
"result": {
|
||||
"sent_bytes": 1048576,
|
||||
"declared_bytes": 4192910,
|
||||
"rows_after": 0,
|
||||
"objects_after": 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"scenario": "memory",
|
||||
"result": {
|
||||
"file_bytes": 10187085,
|
||||
"runs": [
|
||||
{
|
||||
"parallel": 10,
|
||||
"ok": 10,
|
||||
"failed": [],
|
||||
"max_seconds": 2.3,
|
||||
"baseline_peak_mib": {
|
||||
"136ebad5f66d": 8.1,
|
||||
"2426fcb77065": 8.1
|
||||
},
|
||||
"peak_mib": {
|
||||
"136ebad5f66d": 32.2,
|
||||
"2426fcb77065": 18.2
|
||||
},
|
||||
"payload_total_mib": 97.2,
|
||||
"max_peak_growth_mib": 24.2
|
||||
},
|
||||
{
|
||||
"parallel": 20,
|
||||
"ok": 20,
|
||||
"failed": [],
|
||||
"max_seconds": 3.34,
|
||||
"baseline_peak_mib": {
|
||||
"136ebad5f66d": 7.4,
|
||||
"2426fcb77065": 7.8
|
||||
},
|
||||
"peak_mib": {
|
||||
"136ebad5f66d": 49.9,
|
||||
"2426fcb77065": 43.8
|
||||
},
|
||||
"payload_total_mib": 194.3,
|
||||
"max_peak_growth_mib": 42.5
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"scenario": "s3-outage",
|
||||
"result": {
|
||||
"upload_status_during_outage": 503,
|
||||
"upload_error_seconds": 0.12,
|
||||
"download_status_during_outage": 503,
|
||||
"metadata_during_outage": "ready",
|
||||
"text_message_during_outage": 201,
|
||||
"readiness_during_outage": 200,
|
||||
"intents_left": 0,
|
||||
"upload_after_recovery": "queued"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"scenario": "security",
|
||||
"result": {
|
||||
"anonymous_get": "403",
|
||||
"anonymous_list": "403",
|
||||
"api_key_own_bucket": "allowed",
|
||||
"api_key_make_bucket": "denied",
|
||||
"api_key_admin": "denied",
|
||||
"api_key_visible_buckets": [
|
||||
"messenger-attachments"
|
||||
],
|
||||
"bootstrap_runs": [
|
||||
0,
|
||||
0
|
||||
],
|
||||
"objects_before_after": [
|
||||
40,
|
||||
40
|
||||
],
|
||||
"s3_published_ports": "9000-9001/tcp"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
? github.com/charawein/mtusi2026lab5/cmd/api [no test files]
|
||||
? github.com/charawein/mtusi2026lab5/cmd/pipeline [no test files]
|
||||
? github.com/charawein/mtusi2026lab5/cmd/reconcile [no test files]
|
||||
? github.com/charawein/mtusi2026lab5/internal/broker [no test files]
|
||||
? github.com/charawein/mtusi2026lab5/internal/config [no test files]
|
||||
? github.com/charawein/mtusi2026lab5/internal/domain [no test files]
|
||||
ok github.com/charawein/mtusi2026lab5/internal/imagecheck 0.025s
|
||||
ok github.com/charawein/mtusi2026lab5/internal/imaging 0.693s
|
||||
ok github.com/charawein/mtusi2026lab5/internal/reconcile 0.008s
|
||||
? github.com/charawein/mtusi2026lab5/internal/repository [no test files]
|
||||
? github.com/charawein/mtusi2026lab5/internal/repository/postgres [no test files]
|
||||
? github.com/charawein/mtusi2026lab5/internal/repository/redis [no test files]
|
||||
ok github.com/charawein/mtusi2026lab5/internal/service 0.022s
|
||||
? github.com/charawein/mtusi2026lab5/internal/storage [no test files]
|
||||
? github.com/charawein/mtusi2026lab5/internal/transport/http [no test files]
|
||||
? github.com/charawein/mtusi2026lab5/internal/transport/http/middleware [no test files]
|
||||
? github.com/charawein/mtusi2026lab5/internal/transport/httputil [no test files]
|
||||
ok github.com/charawein/mtusi2026lab5/internal/worker 5.974s
|
||||
? github.com/charawein/mtusi2026lab5/student-tests/genfixtures [no test files]
|
||||
@@ -0,0 +1,88 @@
|
||||
{
|
||||
"rounds": 10,
|
||||
"parallel_per_round": 16,
|
||||
"distinct_instances_seen": 2,
|
||||
"duplicates_found": 0,
|
||||
"per_round": [
|
||||
{
|
||||
"round": 0,
|
||||
"requests": 16,
|
||||
"status_201": 16,
|
||||
"distinct_messages": 1,
|
||||
"stored": 1,
|
||||
"instances": 2
|
||||
},
|
||||
{
|
||||
"round": 1,
|
||||
"requests": 16,
|
||||
"status_201": 16,
|
||||
"distinct_messages": 1,
|
||||
"stored": 1,
|
||||
"instances": 2
|
||||
},
|
||||
{
|
||||
"round": 2,
|
||||
"requests": 16,
|
||||
"status_201": 16,
|
||||
"distinct_messages": 1,
|
||||
"stored": 1,
|
||||
"instances": 2
|
||||
},
|
||||
{
|
||||
"round": 3,
|
||||
"requests": 16,
|
||||
"status_201": 16,
|
||||
"distinct_messages": 1,
|
||||
"stored": 1,
|
||||
"instances": 2
|
||||
},
|
||||
{
|
||||
"round": 4,
|
||||
"requests": 16,
|
||||
"status_201": 16,
|
||||
"distinct_messages": 1,
|
||||
"stored": 1,
|
||||
"instances": 2
|
||||
},
|
||||
{
|
||||
"round": 5,
|
||||
"requests": 16,
|
||||
"status_201": 16,
|
||||
"distinct_messages": 1,
|
||||
"stored": 1,
|
||||
"instances": 2
|
||||
},
|
||||
{
|
||||
"round": 6,
|
||||
"requests": 16,
|
||||
"status_201": 16,
|
||||
"distinct_messages": 1,
|
||||
"stored": 1,
|
||||
"instances": 2
|
||||
},
|
||||
{
|
||||
"round": 7,
|
||||
"requests": 16,
|
||||
"status_201": 16,
|
||||
"distinct_messages": 1,
|
||||
"stored": 1,
|
||||
"instances": 2
|
||||
},
|
||||
{
|
||||
"round": 8,
|
||||
"requests": 16,
|
||||
"status_201": 16,
|
||||
"distinct_messages": 1,
|
||||
"stored": 1,
|
||||
"instances": 2
|
||||
},
|
||||
{
|
||||
"round": 9,
|
||||
"requests": 16,
|
||||
"status_201": 16,
|
||||
"distinct_messages": 1,
|
||||
"stored": 1,
|
||||
"instances": 2
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
bitnamilegacy/minio-client:2025.4.16@sha256:8a86e441decf053093c5977d49290298295f850c7843652f93e970ab15871dd1 bitnamilegacy/minio-client@sha256:8a86e441decf053093c5977d49290298295f850c7843652f93e970ab15871dd1
|
||||
bitnamilegacy/minio:2025.4.22@sha256:50cec18ac4184af4671a78aedd5554942c8ae105d51a465fa82037949046da01 bitnamilegacy/minio@sha256:50cec18ac4184af4671a78aedd5554942c8ae105d51a465fa82037949046da01
|
||||
haproxy:3.0.5-alpine haproxy@sha256:43a2591a6a62a41dd22edb4452880e9c70de489fbd7c54ffb52d035cccbfe949
|
||||
migrate/migrate:v4.17.0 migrate/migrate@sha256:4d017c6fb5997127093648cab09e63d377997125c3d3dcca18e5d1c847da49fa
|
||||
mtusi2026lab5-api:local
|
||||
local-build
|
||||
postgres:16.4-alpine postgres@sha256:5660c2cbfea50c7a9127d17dc4e48543eedd3d7a41a595a2dfa572471e37e64c
|
||||
rabbitmq:4.0.9-alpine rabbitmq@sha256:0a09ddfd00a1ef2e58f497d731e9b2814ef3bebb3668069185c54d085352d2b9
|
||||
redis:7.4.1-alpine redis@sha256:c1e88455c85225310bbea54816e9c3f4b5295815e6dbf80c34d40afc6df28275
|
||||
@@ -0,0 +1,2 @@
|
||||
61f9abf05f85 10
|
||||
95a4d5c06533 10
|
||||
@@ -0,0 +1,24 @@
|
||||
-- до:
|
||||
mtusi2026lab5-api-1 Up About a minute (healthy)
|
||||
mtusi2026lab5-api-2 Up 6 seconds (healthy)
|
||||
mtusi2026lab5-lb-1 Up 57 seconds
|
||||
mtusi2026lab5-postgres-1 Up About a minute (healthy)
|
||||
mtusi2026lab5-rabbitmq-1 Up About a minute (healthy)
|
||||
mtusi2026lab5-reconciler-1 Up About a minute (healthy)
|
||||
mtusi2026lab5-redis-1 Up About a minute (healthy)
|
||||
mtusi2026lab5-relay-1 Up About a minute (healthy)
|
||||
mtusi2026lab5-s3-1 Up About a minute (healthy)
|
||||
mtusi2026lab5-worker-1 Up About a minute (healthy)
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
-- после:
|
||||
mtusi2026lab5-api-1 Up 6 seconds (healthy)
|
||||
mtusi2026lab5-api-2 Up 6 seconds (healthy)
|
||||
mtusi2026lab5-lb-1 Up Less than a second
|
||||
mtusi2026lab5-postgres-1 Up 17 seconds (healthy)
|
||||
mtusi2026lab5-rabbitmq-1 Up 16 seconds (healthy)
|
||||
mtusi2026lab5-reconciler-1 Up 6 seconds (healthy)
|
||||
mtusi2026lab5-redis-1 Up 17 seconds (healthy)
|
||||
mtusi2026lab5-relay-1 Up 6 seconds (healthy)
|
||||
mtusi2026lab5-s3-1 Up 17 seconds (healthy)
|
||||
mtusi2026lab5-worker-1 Up 6 seconds (healthy)
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"scenario": "broker-restart",
|
||||
"result": {
|
||||
"attachment_id": "41928433-0d5c-4179-a23e-1e962bded4e2",
|
||||
"queue_before_restart": {
|
||||
"attachment.dead": 0,
|
||||
"attachment.process": 0
|
||||
},
|
||||
"queue_after_restart": {
|
||||
"attachment.dead": 0,
|
||||
"attachment.process": 1
|
||||
},
|
||||
"outbox_publish_attempts": 1,
|
||||
"invariants": {
|
||||
"status": "ready",
|
||||
"published_version": 1,
|
||||
"objects_per_version": {
|
||||
"1": 3
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"scenario": "crash-commit",
|
||||
"result": {
|
||||
"attachment_id": "b79d51ac-bd5f-4ebf-b7b2-0372638e289f",
|
||||
"job_id": "9679d789-9782-4965-847b-88ae26653ecc",
|
||||
"worker_restarts": 1,
|
||||
"attempt": 1,
|
||||
"redelivery_acked_as_noop": true,
|
||||
"invariants": {
|
||||
"status": "ready",
|
||||
"published_version": 1,
|
||||
"objects_per_version": {
|
||||
"1": 3
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"scenario": "crash-effect",
|
||||
"result": {
|
||||
"attachment_id": "6a4a5622-45fb-4af7-9603-d310130fb69e",
|
||||
"job_id": "8c912c85-5398-4aae-881b-ddc9c3789d15",
|
||||
"worker_restarts": 1,
|
||||
"attempt": 2,
|
||||
"seconds_to_ready": 19.6,
|
||||
"events": "enqueued,claimed,lease_expired_requeued,claimed,done",
|
||||
"invariants": {
|
||||
"status": "ready",
|
||||
"published_version": 1,
|
||||
"objects_per_version": {
|
||||
"1": 3
|
||||
}
|
||||
},
|
||||
"variants": {
|
||||
"thumbnail": [
|
||||
256,
|
||||
160
|
||||
],
|
||||
"crop": [
|
||||
128,
|
||||
128
|
||||
],
|
||||
"optimized": [
|
||||
320,
|
||||
200
|
||||
],
|
||||
"optimized_bytes": 2462,
|
||||
"original_bytes": 111817
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"scenario": "demo",
|
||||
"result": {
|
||||
"attachment_id": "3e265d26-04d0-40ad-9626-1a0fc6e4f9fd",
|
||||
"job_id": "52e255df-61a1-46a1-a90c-e00184ef8a59",
|
||||
"job_state": "done",
|
||||
"attempt": 1,
|
||||
"timeline": [
|
||||
"worker stopped",
|
||||
"upload 202 queued id=3e265d26-04d0-40ad-9626-1a0fc6e4f9fd",
|
||||
"message 201 with queued attachment",
|
||||
"content 409, other messages OK",
|
||||
"api and rabbitmq restarted (volumes kept), outbox published=1",
|
||||
"rabbitmq queues after restart: {'attachment.dead': 0, 'attachment.process': 1}",
|
||||
"worker started → ready in 2.4 s"
|
||||
],
|
||||
"variants": {
|
||||
"thumbnail": [
|
||||
256,
|
||||
160
|
||||
],
|
||||
"crop": [
|
||||
128,
|
||||
128
|
||||
],
|
||||
"optimized": [
|
||||
320,
|
||||
200
|
||||
],
|
||||
"optimized_bytes": 2462,
|
||||
"original_bytes": 111817
|
||||
},
|
||||
"invariants": {
|
||||
"status": "ready",
|
||||
"published_version": 1,
|
||||
"objects_per_version": {
|
||||
"1": 3
|
||||
}
|
||||
},
|
||||
"events": "enqueued,claimed,done"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"scenario": "failed-replay",
|
||||
"result": {
|
||||
"attachment_id": "a778211f-1990-469c-8134-16dc71b7932b",
|
||||
"failed_error_code": "checksum_mismatch",
|
||||
"content_while_failed": 409,
|
||||
"attach_failed_to_message": 409,
|
||||
"registry_listed": true,
|
||||
"replay": {
|
||||
"attachment_id": "a778211f-1990-469c-8134-16dc71b7932b",
|
||||
"command": "replay",
|
||||
"error": "",
|
||||
"job_id": "473811d7-02f9-4994-9acb-d67d396b9453",
|
||||
"ok": true,
|
||||
"version": 1
|
||||
},
|
||||
"replay_after_success": {
|
||||
"attachment_id": "a778211f-1990-469c-8134-16dc71b7932b",
|
||||
"command": "replay",
|
||||
"error": "conflict: job is done, only failed jobs can be replayed",
|
||||
"job_id": "473811d7-02f9-4994-9acb-d67d396b9453",
|
||||
"ok": false,
|
||||
"version": 1
|
||||
},
|
||||
"final_status": "ready",
|
||||
"events": "enqueued,claimed,failed,replay,claimed,done,replay_refused",
|
||||
"dlq_messages": 1,
|
||||
"invariants": {
|
||||
"status": "ready",
|
||||
"published_version": 1,
|
||||
"objects_per_version": {
|
||||
"1": 3
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"scenario": "limits",
|
||||
"result": {
|
||||
"image": "6000x6000 PNG (119755 bytes)",
|
||||
"parallel_uploads": 3,
|
||||
"seconds_all_ready": 5.4,
|
||||
"worker_anon_memory_max_mib": 570.3,
|
||||
"worker_memory_peak_incl_page_cache_mib": 576.4,
|
||||
"oom_kill_events": 0,
|
||||
"go_memlimit": "560MiB",
|
||||
"oom_events": 0,
|
||||
"worker_memory_limit_mib": 768.0,
|
||||
"pixel_budget": 60000000,
|
||||
"decoded_rgba_per_image_mib": 137.3,
|
||||
"variant_sizes": {
|
||||
"thumbnail": [
|
||||
256,
|
||||
256
|
||||
],
|
||||
"crop": [
|
||||
128,
|
||||
128
|
||||
],
|
||||
"optimized": [
|
||||
1280,
|
||||
1280
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"scenario": "outbox-gap",
|
||||
"result": {
|
||||
"relay_down_then_up": {
|
||||
"attachment_id": "adff70ba-9cda-450a-88a2-9c7827ed4022",
|
||||
"unpublished_while_relay_down": 1,
|
||||
"then": "ready"
|
||||
},
|
||||
"relay_crash_after_confirm": {
|
||||
"attachment_id": "c55e34c1-e4b8-4b6d-b48b-9038a1a920c9",
|
||||
"relay_restarts": 1,
|
||||
"outbox_publish_attempts": 1,
|
||||
"worker_saw_message_twice": true,
|
||||
"job_attempt": 1,
|
||||
"invariants": {
|
||||
"status": "ready",
|
||||
"published_version": 1,
|
||||
"objects_per_version": {
|
||||
"1": 3
|
||||
}
|
||||
}
|
||||
},
|
||||
"events": "enqueued,claimed,done"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"scenario": "transient",
|
||||
"result": {
|
||||
"attachment_id": "13448df8-cb13-4b9a-9227-73182d6c84bc",
|
||||
"attempts": 3,
|
||||
"final_status": "ready",
|
||||
"retry_details": "processing_failed; next_attempt=2 in 1.553s | processing_failed; next_attempt=3 in 2.758s",
|
||||
"events": "enqueued,claimed,retry_scheduled,claimed,retry_scheduled,claimed,done",
|
||||
"invariants": {
|
||||
"status": "ready",
|
||||
"published_version": 1,
|
||||
"objects_per_version": {
|
||||
"1": 3
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
worker-1 | {"time":"2026-11-09T15:15:46.619759171Z","level":"INFO","msg":"worker starting","owner":"18d147720c4c:1","concurrency":2,"lease":60000000000}
|
||||
worker-1 | {"time":"2026-11-09T15:16:10.212884822Z","level":"INFO","msg":"worker starting","owner":"18d147720c4c:1","concurrency":2,"lease":60000000000}
|
||||
worker-1 | {"time":"2026-11-09T15:16:18.342232549Z","level":"INFO","msg":"worker starting","owner":"18d147720c4c:1","concurrency":2,"lease":60000000000}
|
||||
worker-1 | {"time":"2026-11-09T15:16:18.87701229Z","level":"WARN","msg":"attempt failed","job_id":"db189a01-f03c-4451-bde1-232b101fc886","attachment_id":"13448df8-cb13-4b9a-9227-73182d6c84bc","version":1,"attempt":1,"code":"processing_failed","final":false,"backoff":1552880322}
|
||||
worker-1 | {"time":"2026-11-09T15:16:20.857991266Z","level":"WARN","msg":"attempt failed","job_id":"db189a01-f03c-4451-bde1-232b101fc886","attachment_id":"13448df8-cb13-4b9a-9227-73182d6c84bc","version":1,"attempt":2,"code":"processing_failed","final":false,"backoff":2758454067}
|
||||
worker-1 | {"time":"2026-11-09T15:16:31.988478744Z","level":"INFO","msg":"worker starting","owner":"18d147720c4c:1","concurrency":2,"lease":60000000000}
|
||||
worker-1 | {"time":"2026-11-09T15:16:32.017138291Z","level":"WARN","msg":"attempt failed","job_id":"473811d7-02f9-4994-9acb-d67d396b9453","attachment_id":"a778211f-1990-469c-8134-16dc71b7932b","version":1,"attempt":1,"code":"checksum_mismatch","final":true,"backoff":1371991185}
|
||||
worker-1 | {"time":"2026-11-09T15:16:34.957981424Z","level":"ERROR","msg":"invalid job message, dead-lettering","err":null}
|
||||
worker-1 | {"time":"2026-11-09T15:16:45.821308891Z","level":"INFO","msg":"worker starting","owner":"18d147720c4c:1","concurrency":2,"lease":60000000000}
|
||||
relay-1 | {"time":"2026-11-09T15:15:21.358127392Z","level":"WARN","msg":"expired leases requeued","jobs":1}
|
||||
@@ -0,0 +1,3 @@
|
||||
PASS: whitespace-only password rejected with 400 (3 variants)
|
||||
PASS: Redis ACL -incr: message visible on every next read (3 in history)
|
||||
PASS: Redis ACL -incr -del -unlink -scan: message visible on every next read (4 in history)
|
||||
@@ -0,0 +1,92 @@
|
||||
-- до:
|
||||
mtusi2026lab5-api-1 61f9abf05f85 Up About a minute (healthy)
|
||||
mtusi2026lab5-api-2 95a4d5c06533 Up About a minute (healthy)
|
||||
#1 [internal] load local bake definitions
|
||||
#1 reading from stdin 380B done
|
||||
#1 DONE 0.0s
|
||||
|
||||
#2 [internal] load build definition from Dockerfile
|
||||
#2 transferring dockerfile: 2.84kB done
|
||||
#2 DONE 0.0s
|
||||
|
||||
#3 [internal] load metadata for docker.io/library/alpine:3.20@sha256:d9e853e87e55526f6b2917df91a2115c36dd7c696a35be12163d44e6e2a4b6bc
|
||||
#3 DONE 0.0s
|
||||
|
||||
#4 [internal] load metadata for docker.io/library/golang:1.26-alpine@sha256:27f2d3b83cfc5803c8078f8e730af0f7c431bf067afaec8f60a36fb763187cba
|
||||
#4 DONE 0.0s
|
||||
|
||||
#5 [internal] load .dockerignore
|
||||
#5 transferring context: 212B done
|
||||
#5 DONE 0.0s
|
||||
|
||||
#6 [builder 1/6] FROM docker.io/library/golang:1.26-alpine@sha256:27f2d3b83cfc5803c8078f8e730af0f7c431bf067afaec8f60a36fb763187cba
|
||||
#6 DONE 0.0s
|
||||
|
||||
#7 [stage-1 1/7] FROM docker.io/library/alpine:3.20@sha256:d9e853e87e55526f6b2917df91a2115c36dd7c696a35be12163d44e6e2a4b6bc
|
||||
#7 DONE 0.0s
|
||||
|
||||
#8 [internal] load build context
|
||||
#8 transferring context: 7.33kB 0.0s done
|
||||
#8 DONE 0.0s
|
||||
|
||||
#9 [stage-1 4/7] WORKDIR /app
|
||||
#9 CACHED
|
||||
|
||||
#10 [builder 6/6] RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -trimpath -o /out/ ./cmd/api ./cmd/reconcile ./cmd/pipeline
|
||||
#10 CACHED
|
||||
|
||||
#11 [builder 5/6] COPY . .
|
||||
#11 CACHED
|
||||
|
||||
#12 [builder 3/6] COPY go.mod go.sum ./
|
||||
#12 CACHED
|
||||
|
||||
#13 [builder 2/6] WORKDIR /src
|
||||
#13 CACHED
|
||||
|
||||
#14 [stage-1 3/7] RUN addgroup -g 1001 -S appgroup && adduser -u 1001 -S appuser -G appgroup
|
||||
#14 CACHED
|
||||
|
||||
#15 [stage-1 6/7] COPY --from=builder --chown=appuser:appgroup /out/reconcile /app/reconcile
|
||||
#15 CACHED
|
||||
|
||||
#16 [stage-1 5/7] COPY --from=builder --chown=appuser:appgroup /out/api /app/api
|
||||
#16 CACHED
|
||||
|
||||
#17 [builder 4/6] RUN go mod download
|
||||
#17 CACHED
|
||||
|
||||
#18 [stage-1 2/7] RUN apk --no-cache add ca-certificates tzdata libwebp-tools
|
||||
#18 CACHED
|
||||
|
||||
#19 [stage-1 7/7] COPY --from=builder --chown=appuser:appgroup /out/pipeline /app/pipeline
|
||||
#19 CACHED
|
||||
|
||||
#20 exporting to image
|
||||
#20 exporting layers done
|
||||
#20 writing image sha256:6564857c5a6a93ceafc1af85ee252d7333f47c4b265f20864686582701e278cc done
|
||||
#20 naming to docker.io/library/mtusi2026lab5-api:local done
|
||||
#20 DONE 0.0s
|
||||
|
||||
#21 resolving provenance for metadata file
|
||||
#21 DONE 0.0s
|
||||
api Built
|
||||
Container mtusi2026lab5-postgres-1 Running
|
||||
no change
|
||||
Container mtusi2026lab5-api-1 Running
|
||||
Container mtusi2026lab5-api-2 Running
|
||||
Container mtusi2026lab5-api-3 Creating
|
||||
Container mtusi2026lab5-api-3 Created
|
||||
Container mtusi2026lab5-api-3 Starting
|
||||
Container mtusi2026lab5-api-3 Started
|
||||
replaced /mtusi2026lab5-api-1
|
||||
Container mtusi2026lab5-api-2 Running
|
||||
Container mtusi2026lab5-api-3 Running
|
||||
Container mtusi2026lab5-api-4 Creating
|
||||
Container mtusi2026lab5-api-4 Created
|
||||
Container mtusi2026lab5-api-4 Starting
|
||||
Container mtusi2026lab5-api-4 Started
|
||||
replaced /mtusi2026lab5-api-2
|
||||
mtusi2026lab5-api-3 01c220dc06f7 mtusi2026lab5-api:local Up 22 seconds (healthy)
|
||||
mtusi2026lab5-api-4 f75e5c7061b9 mtusi2026lab5-api:local Up 11 seconds (healthy)
|
||||
-- замена заняла 26 s (внутри 90 s нагрузки)
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 5,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 90.0,
|
||||
"elapsed_seconds": 90.141,
|
||||
"concurrency": 4,
|
||||
"successful_requests": 34917,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 387.359,
|
||||
"successful_latency_ms": {
|
||||
"p50": 7.079,
|
||||
"p95": 19.94,
|
||||
"p99": 97.821
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
2
|
||||
total used free shared buff/cache available
|
||||
Mem: 7932 1565 3068 105 3719 6367
|
||||
Swap: 3071 0 3071
|
||||
28.0.4
|
||||
Docker Compose version v2.38.2
|
||||
@@ -0,0 +1,6 @@
|
||||
2
|
||||
total used free shared buff/cache available
|
||||
Mem: 7931 1934 3100 83 3295 5997
|
||||
Swap: 3071 191 2880
|
||||
28.0.4
|
||||
Docker Compose version v2.38.2
|
||||
@@ -0,0 +1,6 @@
|
||||
2
|
||||
total used free shared buff/cache available
|
||||
Mem: 7932 2465 2649 82 3214 5466
|
||||
Swap: 3071 0 3071
|
||||
28.0.4
|
||||
Docker Compose version v2.38.2
|
||||
@@ -0,0 +1,6 @@
|
||||
2
|
||||
total used free shared buff/cache available
|
||||
Mem: 7932 1881 3233 87 3219 6050
|
||||
Swap: 3071 0 3071
|
||||
28.0.4
|
||||
Docker Compose version v2.38.2
|
||||
@@ -0,0 +1 @@
|
||||
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -0,0 +1,36 @@
|
||||
=== RUN TestPipelineHappyPathAndDuplicate
|
||||
2026/11/09 15:13:04 INFO duplicate delivery of finished job: ack without work job_id=fc293796-cf32-49a0-a708-89eca552acf3 attachment_id=cb9791cf-9bb9-417f-948d-97b164242742 version=1
|
||||
--- PASS: TestPipelineHappyPathAndDuplicate (1.42s)
|
||||
=== RUN TestPipelineConcurrentDuplicateIsBusy
|
||||
2026/11/09 15:13:04 INFO job leased by another worker: ack duplicate job_id=5561990b-d348-4de0-844a-57074a5fe9a7 attachment_id=e0b35bf6-3778-4d63-b2f8-2d73761d5b8e version=1 owner=slow-worker
|
||||
--- PASS: TestPipelineConcurrentDuplicateIsBusy (0.28s)
|
||||
=== RUN TestPipelineCrashAfterSideEffectBeforeCommit
|
||||
2026/11/09 15:13:04 WARN FAULT INJECTION: crashing point=worker.after_side_effect
|
||||
2026/11/09 15:13:04 INFO job leased by another worker: ack duplicate job_id=37d3dbca-5672-419c-8460-2f3846a2ebfb attachment_id=33092dec-9b0b-4251-a4f0-420eeec15083 version=1 owner=w-20ea9c
|
||||
--- PASS: TestPipelineCrashAfterSideEffectBeforeCommit (1.42s)
|
||||
=== RUN TestPipelineCrashAfterCommitBeforeAck
|
||||
2026/11/09 15:13:05 WARN FAULT INJECTION: crashing point=worker.after_commit
|
||||
2026/11/09 15:13:05 INFO duplicate delivery of finished job: ack without work job_id=e33999f9-533f-49b2-aeb3-b7374878d542 attachment_id=a3f65fa0-f9de-410d-a922-5ba2c5cf2a27 version=1
|
||||
--- PASS: TestPipelineCrashAfterCommitBeforeAck (0.19s)
|
||||
=== RUN TestPipelineRelayCrashAfterPublishDuplicates
|
||||
2026/11/09 15:13:06 INFO duplicate delivery of finished job: ack without work job_id=7cadd5dd-4407-4954-94f1-6f98ef486540 attachment_id=e695d363-76f9-4271-8351-ec267e7e38b8 version=1
|
||||
--- PASS: TestPipelineRelayCrashAfterPublishDuplicates (0.20s)
|
||||
=== RUN TestPipelineVersionReorderAndStaleJob
|
||||
2026/11/09 15:13:06 INFO duplicate delivery of finished job: ack without work job_id=aef7a9de-888b-4564-b9ca-115205c124c0 attachment_id=e074a46b-5a13-447d-9d30-ce341d39328e version=1
|
||||
--- PASS: TestPipelineVersionReorderAndStaleJob (0.23s)
|
||||
=== RUN TestPipelineLostLeaseFencing
|
||||
--- PASS: TestPipelineLostLeaseFencing (0.62s)
|
||||
=== RUN TestPipelineTransientRetryWithBackoff
|
||||
2026/11/09 15:13:07 WARN attempt failed job_id=2f7db8b4-7645-4ee2-89a3-283fa4bbdaf5 attachment_id=69640927-26c8-429d-8df6-1b8d1ff7747e version=1 attempt=1 code=processing_failed final=false backoff=179.128211ms
|
||||
2026/11/09 15:13:07 INFO early delivery before backoff: ack, outbox will redeliver job_id=2f7db8b4-7645-4ee2-89a3-283fa4bbdaf5 attachment_id=69640927-26c8-429d-8df6-1b8d1ff7747e version=1
|
||||
--- PASS: TestPipelineTransientRetryWithBackoff (0.70s)
|
||||
=== RUN TestPipelinePermanentFailureAndReplay
|
||||
2026/11/09 15:13:07 WARN attempt failed job_id=c7f78be9-bec0-4071-b831-ea9cee524926 attachment_id=31ef119f-9ac0-468d-9bab-b3889f36a50c version=1 attempt=1 code=checksum_mismatch final=true backoff=122.679132ms
|
||||
--- PASS: TestPipelinePermanentFailureAndReplay (0.23s)
|
||||
=== RUN TestPipelineRetryExhausted
|
||||
2026/11/09 15:13:08 WARN attempt failed job_id=76ec00b8-d064-4c14-83ce-ecc692f7c122 attachment_id=e38fd780-4d74-41f2-9e9f-07d849bfecae version=1 attempt=1 code=processing_failed final=false backoff=169.957589ms
|
||||
2026/11/09 15:13:08 WARN attempt failed job_id=76ec00b8-d064-4c14-83ce-ecc692f7c122 attachment_id=e38fd780-4d74-41f2-9e9f-07d849bfecae version=1 attempt=2 code=processing_failed final=false backoff=395.104417ms
|
||||
2026/11/09 15:13:08 WARN attempt failed job_id=76ec00b8-d064-4c14-83ce-ecc692f7c122 attachment_id=e38fd780-4d74-41f2-9e9f-07d849bfecae version=1 attempt=3 code=processing_failed final=true backoff=204.467236ms
|
||||
--- PASS: TestPipelineRetryExhausted (1.55s)
|
||||
PASS
|
||||
ok github.com/charawein/mtusi2026lab5/internal/worker 6.829s
|
||||
@@ -0,0 +1,327 @@
|
||||
{
|
||||
"injected": {
|
||||
"orphan_old": 1,
|
||||
"orphan_fresh": 1,
|
||||
"deleted_objects": 3,
|
||||
"resized_object": 1,
|
||||
"stale_intents": 2,
|
||||
"inflight_intent": 1
|
||||
},
|
||||
"dry_run_found": {
|
||||
"orphan_object": 1,
|
||||
"stale_intent": 2,
|
||||
"missing_object": 3,
|
||||
"size_mismatch": 1
|
||||
},
|
||||
"dry_run_state_changed": false,
|
||||
"apply_found": {
|
||||
"orphan_object": 1,
|
||||
"stale_intent": 2,
|
||||
"missing_object": 3,
|
||||
"size_mismatch": 1
|
||||
},
|
||||
"second_apply_actions": 0,
|
||||
"restored": 1,
|
||||
"after_grace": {
|
||||
"purge_missing": 2,
|
||||
"orphan_object": 1
|
||||
},
|
||||
"never_deleted": [
|
||||
"fresh orphan (until grace)",
|
||||
"in-flight intent",
|
||||
"referenced quarantined row",
|
||||
"healthy rows"
|
||||
],
|
||||
"reports": {
|
||||
"dry_run": {
|
||||
"dry_run": true,
|
||||
"grace_seconds": 8,
|
||||
"cutoff": "2026-11-09T15:14:39.888516Z",
|
||||
"duration_ms": 13,
|
||||
"rows_scanned": 34,
|
||||
"objects_scanned": 32,
|
||||
"consistent": 27,
|
||||
"found": {
|
||||
"missing_object": 3,
|
||||
"orphan_object": 1,
|
||||
"size_mismatch": 1,
|
||||
"stale_intent": 2
|
||||
},
|
||||
"fixed": {},
|
||||
"skipped": {
|
||||
"fresh_intent": 1,
|
||||
"fresh_object": 1
|
||||
},
|
||||
"calls": {
|
||||
"db_haskey": 1,
|
||||
"s3_list_pages": 1,
|
||||
"s3_stat": 3
|
||||
},
|
||||
"heap_alloc_mb": 1.5885543823242188,
|
||||
"wait_ms": {
|
||||
"db_stream": 0,
|
||||
"s3_list": 10
|
||||
},
|
||||
"errors": [],
|
||||
"items": [
|
||||
{
|
||||
"kind": "orphan_object",
|
||||
"key": "a/6eec5843-381a-4c64-9326-6af6e2903da5/5beb6f1f-49c0-4a4c-a311-ac1cdf4b3b5e",
|
||||
"action": "would_delete_object",
|
||||
"detail": "size=5000 modified=2026-11-09T15:14:36Z"
|
||||
},
|
||||
{
|
||||
"kind": "stale_intent",
|
||||
"key": "a/6eec5843-381a-4c64-9326-6af6e2903da5/a8a32b50-8441-4b4e-9063-4764a103caa8",
|
||||
"attachment_id": "a8a32b50-8441-4b4e-9063-4764a103caa8",
|
||||
"action": "would_delete_object_and_intent",
|
||||
"detail": "updated_at=2026-11-09T14:44:36Z"
|
||||
},
|
||||
{
|
||||
"kind": "stale_intent",
|
||||
"key": "a/6eec5843-381a-4c64-9326-6af6e2903da5/c9464366-e6d7-4978-9da9-543477aeb7b6",
|
||||
"attachment_id": "c9464366-e6d7-4978-9da9-543477aeb7b6",
|
||||
"action": "would_delete_intent",
|
||||
"detail": "updated_at=2026-11-09T14:44:37Z"
|
||||
},
|
||||
{
|
||||
"kind": "missing_object",
|
||||
"key": "o/6eec5843-381a-4c64-9326-6af6e2903da5/021fb513-0410-4b13-8390-44b8b853699a",
|
||||
"attachment_id": "021fb513-0410-4b13-8390-44b8b853699a",
|
||||
"action": "would_quarantine"
|
||||
},
|
||||
{
|
||||
"kind": "size_mismatch",
|
||||
"key": "o/6eec5843-381a-4c64-9326-6af6e2903da5/6b861791-d77e-4b28-9e47-b952d412faea",
|
||||
"attachment_id": "6b861791-d77e-4b28-9e47-b952d412faea",
|
||||
"action": "would_quarantine",
|
||||
"detail": "db=21584 s3=777"
|
||||
},
|
||||
{
|
||||
"kind": "missing_object",
|
||||
"key": "o/6eec5843-381a-4c64-9326-6af6e2903da5/b53b858c-6782-4c33-a773-30481aac1354",
|
||||
"attachment_id": "b53b858c-6782-4c33-a773-30481aac1354",
|
||||
"action": "would_quarantine"
|
||||
},
|
||||
{
|
||||
"kind": "missing_object",
|
||||
"key": "o/6eec5843-381a-4c64-9326-6af6e2903da5/d40a2bcb-2243-4a30-8af6-79d07600b3c4",
|
||||
"attachment_id": "d40a2bcb-2243-4a30-8af6-79d07600b3c4",
|
||||
"action": "would_quarantine"
|
||||
}
|
||||
]
|
||||
},
|
||||
"apply": {
|
||||
"dry_run": false,
|
||||
"grace_seconds": 8,
|
||||
"cutoff": "2026-11-09T15:14:40.968289Z",
|
||||
"duration_ms": 21,
|
||||
"rows_scanned": 34,
|
||||
"objects_scanned": 32,
|
||||
"consistent": 27,
|
||||
"found": {
|
||||
"missing_object": 3,
|
||||
"orphan_object": 1,
|
||||
"size_mismatch": 1,
|
||||
"stale_intent": 2
|
||||
},
|
||||
"fixed": {
|
||||
"missing_object": 3,
|
||||
"orphan_object": 1,
|
||||
"size_mismatch": 1,
|
||||
"stale_intent": 2
|
||||
},
|
||||
"skipped": {
|
||||
"fresh_intent": 1,
|
||||
"fresh_object": 1
|
||||
},
|
||||
"calls": {
|
||||
"db_delete": 2,
|
||||
"db_haskey": 1,
|
||||
"db_update": 4,
|
||||
"s3_delete": 2,
|
||||
"s3_list_pages": 1,
|
||||
"s3_stat": 3
|
||||
},
|
||||
"heap_alloc_mb": 1.6164779663085938,
|
||||
"wait_ms": {
|
||||
"db_stream": 0,
|
||||
"s3_list": 9
|
||||
},
|
||||
"errors": [],
|
||||
"items": [
|
||||
{
|
||||
"kind": "orphan_object",
|
||||
"key": "a/6eec5843-381a-4c64-9326-6af6e2903da5/5beb6f1f-49c0-4a4c-a311-ac1cdf4b3b5e",
|
||||
"action": "delete_object",
|
||||
"detail": "size=5000 modified=2026-11-09T15:14:36Z"
|
||||
},
|
||||
{
|
||||
"kind": "stale_intent",
|
||||
"key": "a/6eec5843-381a-4c64-9326-6af6e2903da5/a8a32b50-8441-4b4e-9063-4764a103caa8",
|
||||
"attachment_id": "a8a32b50-8441-4b4e-9063-4764a103caa8",
|
||||
"action": "delete_object_and_intent",
|
||||
"detail": "updated_at=2026-11-09T14:44:36Z"
|
||||
},
|
||||
{
|
||||
"kind": "stale_intent",
|
||||
"key": "a/6eec5843-381a-4c64-9326-6af6e2903da5/c9464366-e6d7-4978-9da9-543477aeb7b6",
|
||||
"attachment_id": "c9464366-e6d7-4978-9da9-543477aeb7b6",
|
||||
"action": "delete_intent",
|
||||
"detail": "updated_at=2026-11-09T14:44:37Z"
|
||||
},
|
||||
{
|
||||
"kind": "missing_object",
|
||||
"key": "o/6eec5843-381a-4c64-9326-6af6e2903da5/021fb513-0410-4b13-8390-44b8b853699a",
|
||||
"attachment_id": "021fb513-0410-4b13-8390-44b8b853699a",
|
||||
"action": "quarantine"
|
||||
},
|
||||
{
|
||||
"kind": "size_mismatch",
|
||||
"key": "o/6eec5843-381a-4c64-9326-6af6e2903da5/6b861791-d77e-4b28-9e47-b952d412faea",
|
||||
"attachment_id": "6b861791-d77e-4b28-9e47-b952d412faea",
|
||||
"action": "quarantine",
|
||||
"detail": "db=21584 s3=777"
|
||||
},
|
||||
{
|
||||
"kind": "missing_object",
|
||||
"key": "o/6eec5843-381a-4c64-9326-6af6e2903da5/b53b858c-6782-4c33-a773-30481aac1354",
|
||||
"attachment_id": "b53b858c-6782-4c33-a773-30481aac1354",
|
||||
"action": "quarantine"
|
||||
},
|
||||
{
|
||||
"kind": "missing_object",
|
||||
"key": "o/6eec5843-381a-4c64-9326-6af6e2903da5/d40a2bcb-2243-4a30-8af6-79d07600b3c4",
|
||||
"attachment_id": "d40a2bcb-2243-4a30-8af6-79d07600b3c4",
|
||||
"action": "quarantine"
|
||||
}
|
||||
]
|
||||
},
|
||||
"second_apply": {
|
||||
"dry_run": false,
|
||||
"grace_seconds": 8,
|
||||
"cutoff": "2026-11-09T15:14:42.325414Z",
|
||||
"duration_ms": 22,
|
||||
"rows_scanned": 32,
|
||||
"objects_scanned": 30,
|
||||
"consistent": 27,
|
||||
"found": {},
|
||||
"fixed": {},
|
||||
"skipped": {
|
||||
"fresh_intent": 1,
|
||||
"fresh_missing": 4,
|
||||
"fresh_object": 1
|
||||
},
|
||||
"calls": {
|
||||
"s3_list_pages": 1
|
||||
},
|
||||
"heap_alloc_mb": 1.4375228881835938,
|
||||
"wait_ms": {
|
||||
"db_stream": 0,
|
||||
"s3_list": 20
|
||||
},
|
||||
"errors": [],
|
||||
"items": []
|
||||
},
|
||||
"restore": {
|
||||
"dry_run": false,
|
||||
"grace_seconds": 8,
|
||||
"cutoff": "2026-11-09T15:14:43.601474Z",
|
||||
"duration_ms": 15,
|
||||
"rows_scanned": 32,
|
||||
"objects_scanned": 31,
|
||||
"consistent": 27,
|
||||
"found": {
|
||||
"restored": 1
|
||||
},
|
||||
"fixed": {
|
||||
"restored": 1
|
||||
},
|
||||
"skipped": {
|
||||
"fresh_intent": 1,
|
||||
"fresh_missing": 3,
|
||||
"fresh_object": 1
|
||||
},
|
||||
"calls": {
|
||||
"db_update": 1,
|
||||
"s3_list_pages": 1
|
||||
},
|
||||
"heap_alloc_mb": 1.5108413696289062,
|
||||
"wait_ms": {
|
||||
"db_stream": 3,
|
||||
"s3_list": 7
|
||||
},
|
||||
"errors": [],
|
||||
"items": [
|
||||
{
|
||||
"kind": "restored",
|
||||
"key": "o/6eec5843-381a-4c64-9326-6af6e2903da5/021fb513-0410-4b13-8390-44b8b853699a",
|
||||
"attachment_id": "021fb513-0410-4b13-8390-44b8b853699a",
|
||||
"action": "set_ready"
|
||||
}
|
||||
]
|
||||
},
|
||||
"after_grace": {
|
||||
"dry_run": false,
|
||||
"grace_seconds": 8,
|
||||
"cutoff": "2026-11-09T15:14:53.061655Z",
|
||||
"duration_ms": 22,
|
||||
"rows_scanned": 32,
|
||||
"objects_scanned": 31,
|
||||
"consistent": 28,
|
||||
"found": {
|
||||
"orphan_object": 1,
|
||||
"purge_missing": 2,
|
||||
"stale_intent": 1
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_object": 1,
|
||||
"purge_missing": 2,
|
||||
"stale_intent": 1
|
||||
},
|
||||
"skipped": {
|
||||
"referenced_missing_kept": 1
|
||||
},
|
||||
"calls": {
|
||||
"db_delete": 3,
|
||||
"db_haskey": 1,
|
||||
"db_referenced": 3,
|
||||
"s3_delete": 2,
|
||||
"s3_list_pages": 1
|
||||
},
|
||||
"heap_alloc_mb": 1.580108642578125,
|
||||
"wait_ms": {
|
||||
"db_stream": 1,
|
||||
"s3_list": 9
|
||||
},
|
||||
"errors": [],
|
||||
"items": [
|
||||
{
|
||||
"kind": "orphan_object",
|
||||
"key": "a/6eec5843-381a-4c64-9326-6af6e2903da5/1686dbee-6d75-4a67-b324-e695a2a6cf12",
|
||||
"action": "delete_object",
|
||||
"detail": "size=3000 modified=2026-11-09T15:14:46Z"
|
||||
},
|
||||
{
|
||||
"kind": "stale_intent",
|
||||
"key": "a/6eec5843-381a-4c64-9326-6af6e2903da5/e7243526-a98a-4d95-bceb-4f686ed7eabf",
|
||||
"attachment_id": "e7243526-a98a-4d95-bceb-4f686ed7eabf",
|
||||
"action": "delete_object_and_intent",
|
||||
"detail": "updated_at=2026-11-09T15:14:46Z"
|
||||
},
|
||||
{
|
||||
"kind": "purge_missing",
|
||||
"key": "o/6eec5843-381a-4c64-9326-6af6e2903da5/6b861791-d77e-4b28-9e47-b952d412faea",
|
||||
"attachment_id": "6b861791-d77e-4b28-9e47-b952d412faea",
|
||||
"action": "delete_row"
|
||||
},
|
||||
{
|
||||
"kind": "purge_missing",
|
||||
"key": "o/6eec5843-381a-4c64-9326-6af6e2903da5/b53b858c-6782-4c33-a773-30481aac1354",
|
||||
"attachment_id": "b53b858c-6782-4c33-a773-30481aac1354",
|
||||
"action": "delete_row"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"scenario": "versions",
|
||||
"result": {
|
||||
"attachment_id": "e38fdc85-0525-4f1d-b045-343c4749286b",
|
||||
"v1_thumbnail_sha": "4462c506c73f692d1a8da1f5a5d217bf29e7c7af0fe19f2c03a021055c8751fe",
|
||||
"v2_thumbnail_sha": "254bbafb2e117b40b37de23cd9fd6f3da12eff9a4e07e143c199e4c33b3fa30d",
|
||||
"after_stale_v1_and_dup_v2": "254bbafb2e117b40b37de23cd9fd6f3da12eff9a4e07e143c199e4c33b3fa30d",
|
||||
"published_version": 2,
|
||||
"jobs": {
|
||||
"v1": {
|
||||
"state": "done",
|
||||
"attempt": 1,
|
||||
"events": "enqueued,claimed,done"
|
||||
},
|
||||
"v2": {
|
||||
"state": "done",
|
||||
"attempt": 1,
|
||||
"events": "enqueued,claimed,done"
|
||||
}
|
||||
},
|
||||
"invariants": {
|
||||
"status": "ready",
|
||||
"published_version": 2,
|
||||
"objects_per_version": {
|
||||
"1": 3,
|
||||
"2": 3
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
=== RUN TestOptimizedWebP
|
||||
--- PASS: TestOptimizedWebP (0.39s)
|
||||
PASS
|
||||
ok github.com/charawein/mtusi2026lab5/internal/imaging 0.401s
|
||||
@@ -0,0 +1,37 @@
|
||||
module github.com/charawein/mtusi2026lab5
|
||||
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgx/v5 v5.11.0
|
||||
github.com/minio/minio-go/v7 v7.4.1
|
||||
github.com/rabbitmq/amqp091-go v1.16.0
|
||||
github.com/redis/go-redis/v9 v9.23.0
|
||||
golang.org/x/crypto v0.58.0
|
||||
golang.org/x/image v0.47.0
|
||||
golang.org/x/sync v0.25.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // 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.19.2 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 // indirect
|
||||
github.com/klauspost/crc32 v1.3.0 // indirect
|
||||
github.com/minio/crc64nvme v1.1.1 // indirect
|
||||
github.com/minio/md5-simd v1.1.2 // indirect
|
||||
github.com/philhofer/fwd v1.2.0 // indirect
|
||||
github.com/rs/xid v1.6.0 // indirect
|
||||
github.com/tinylib/msgp v1.6.4 // indirect
|
||||
github.com/zeebo/xxh3 v1.1.0 // indirect
|
||||
go.uber.org/atomic v1.12.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
golang.org/x/net v0.60.0 // indirect
|
||||
golang.org/x/sys v0.49.0 // indirect
|
||||
golang.org/x/text v0.43.0 // indirect
|
||||
gopkg.in/ini.v1 v1.67.3 // indirect
|
||||
)
|
||||
@@ -0,0 +1,83 @@
|
||||
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/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
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/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/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.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
|
||||
github.com/jackc/pgx/v5 v5.11.0/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.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8=
|
||||
github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
|
||||
github.com/klauspost/crc32 v1.3.0 h1:sSmTt3gUt81RP655XGZPElI0PelVTZ6YwCRnPSupoFM=
|
||||
github.com/klauspost/crc32 v1.3.0/go.mod h1:D7kQaZhnkX/Y0tstFGf8VUzv2UofNGqCjnC3zdHB0Hw=
|
||||
github.com/minio/crc64nvme v1.1.1 h1:8dwx/Pz49suywbO+auHCBpCtlW1OfpcLN7wYgVR6wAI=
|
||||
github.com/minio/crc64nvme v1.1.1/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg=
|
||||
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.4.1 h1:PtU/zIOfQRWZ+QydXAZysc+xZYHdG+BBR4Z6TUvy73w=
|
||||
github.com/minio/minio-go/v7 v7.4.1/go.mod h1:nQnQi7zTfXR4lREtYXZQWqo5aw0Rqv+ZqCGrTORygRk=
|
||||
github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM=
|
||||
github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rabbitmq/amqp091-go v1.16.0 h1:1O8oQqnj9hLACoo6CVMgn57z2pLWXvgemhh4GsquV+Y=
|
||||
github.com/rabbitmq/amqp091-go v1.16.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s=
|
||||
github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0=
|
||||
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/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
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.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
github.com/tinylib/msgp v1.6.4 h1:mOwYbyYDLPj35mkA2BjjYejgJk9BuHxDdvRnb6v2ZcQ=
|
||||
github.com/tinylib/msgp v1.6.4/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA=
|
||||
github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ=
|
||||
github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=
|
||||
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
|
||||
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
|
||||
go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE=
|
||||
go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk=
|
||||
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.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
|
||||
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
|
||||
golang.org/x/image v0.47.0 h1:za/8gVz++PPZqmZJBNSISICN5Rrj5zixP/8K++fgmqo=
|
||||
golang.org/x/image v0.47.0/go.mod h1:IkN5o4A7vq55vXN8FWjjnhg9Rs2GOtffqsSi9mWAKYE=
|
||||
golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU=
|
||||
golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
|
||||
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
||||
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/ini.v1 v1.67.3 h1:iM9Lhz5MRSGhHVGGwCuzG9KO8PoirCXj/m/qTmOJJQw=
|
||||
gopkg.in/ini.v1 v1.67.3/go.mod h1:x/cyOwCgZqOkJoDIJ3c1KNHMo10+nLGAhh+kn3Zizss=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,59 @@
|
||||
# HAProxy — единственная публичная точка входа (lab3).
|
||||
# Backend-адреса берутся из встроенного DNS Docker (service name "api"),
|
||||
# поэтому масштабирование/пересоздание реплик не требует перезапуска LB.
|
||||
|
||||
global
|
||||
log stdout format raw local0 info
|
||||
maxconn 2048
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
option httplog
|
||||
option dontlognull
|
||||
timeout connect 2s
|
||||
timeout client 30s
|
||||
timeout server 15s
|
||||
timeout http-request 10s
|
||||
timeout queue 5s
|
||||
# Повтор только при ошибке установки соединения (запрос ещё не отправлен),
|
||||
# поэтому неидемпотентные POST /users, /chats не дублируются.
|
||||
retries 2
|
||||
retry-on conn-failure
|
||||
option redispatch 1
|
||||
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
resolve_retries 3
|
||||
timeout resolve 1s
|
||||
timeout retry 1s
|
||||
# Как долго держать последний ответ DNS при ошибке/пропаже записи.
|
||||
hold valid 5s
|
||||
hold other 5s
|
||||
hold refused 5s
|
||||
hold nx 2s
|
||||
hold timeout 5s
|
||||
hold obsolete 2s
|
||||
accepted_payload_size 8192
|
||||
|
||||
frontend public
|
||||
bind :8080
|
||||
default_backend api
|
||||
|
||||
backend api
|
||||
# roundrobin по умолчанию; leastconn — вариант для эксперимента трека 1 (env LB_BALANCE).
|
||||
balance "${LB_BALANCE}"
|
||||
# Активная проверка готовности: 503 во время drain или без БД/Redis.
|
||||
option httpchk
|
||||
http-check send meth GET uri /health/ready
|
||||
http-check expect status 200
|
||||
# Период проверки 1s, исключение после 2 неудач (~2s), возврат после 2 успехов.
|
||||
default-server check inter 1s fastinter 500ms downinter 1s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr none
|
||||
# До 8 слотов под реплики сервиса api; лишние слоты остаются в MAINT.
|
||||
server-template api 8 api:8080
|
||||
|
||||
frontend stats
|
||||
bind :8404
|
||||
stats enable
|
||||
stats uri /stats
|
||||
stats refresh 2s
|
||||
Executable
+35
@@ -0,0 +1,35 @@
|
||||
#!/bin/sh
|
||||
# Идемпотентный bootstrap MinIO: повторный запуск ничего не ломает и не стирает данные.
|
||||
# 1. приватный bucket (anonymous access: none);
|
||||
# 2. политика messenger-api: только Get/Put/Delete объектов и List этого bucket;
|
||||
# 3. отдельный пользователь API с этой политикой (root-ключ API не получает).
|
||||
# Секреты читаются из /run/secrets и не печатаются.
|
||||
set -eu
|
||||
: "${S3_BUCKET:?}"
|
||||
ROOT_USER=$(cat /run/secrets/s3_root_user)
|
||||
ROOT_PASS=$(cat /run/secrets/s3_root_password)
|
||||
API_KEY=$(cat /run/secrets/s3_access_key_id)
|
||||
API_SECRET=$(cat /run/secrets/s3_secret_access_key)
|
||||
|
||||
mc alias set local http://s3:9000 "$ROOT_USER" "$ROOT_PASS" >/dev/null
|
||||
mc mb --ignore-existing "local/$S3_BUCKET"
|
||||
mc anonymous set none "local/$S3_BUCKET" >/dev/null
|
||||
|
||||
cat > /tmp/messenger-api.json <<EOF
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{"Effect": "Allow", "Action": ["s3:GetBucketLocation", "s3:ListBucket"],
|
||||
"Resource": ["arn:aws:s3:::$S3_BUCKET"]},
|
||||
{"Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
|
||||
"Resource": ["arn:aws:s3:::$S3_BUCKET/*"]}
|
||||
]
|
||||
}
|
||||
EOF
|
||||
mc admin policy create local messenger-api /tmp/messenger-api.json >/dev/null
|
||||
# user add для существующего пользователя обновляет секрет — повтор безопасен.
|
||||
mc admin user add local "$API_KEY" "$API_SECRET" >/dev/null
|
||||
if ! mc admin policy entities local --user "$API_KEY" 2>/dev/null | grep -q messenger-api; then
|
||||
mc admin policy attach local messenger-api --user "$API_KEY" >/dev/null
|
||||
fi
|
||||
echo "s3 bootstrap ok: bucket=$S3_BUCKET private, api user with messenger-api policy"
|
||||
@@ -0,0 +1,164 @@
|
||||
// Package broker — RabbitMQ для заданий обработки вложений.
|
||||
//
|
||||
// Топология (объявляется идемпотентно при каждом подключении):
|
||||
//
|
||||
// exchange attachments (direct, durable) ──process──► queue attachment.process
|
||||
// quorum-очередь (реплицируемый журнал на диске), x-delivery-limit=10:
|
||||
// сообщение, которое 10 раз вернулось без ack (poison), уходит в DLX
|
||||
// exchange attachments.dlx (fanout, durable) ──► queue attachment.dead (реестр «мёртвых»)
|
||||
//
|
||||
// Publisher confirm подтверждает, что broker устойчиво ПРИНЯЛ сообщение (записал
|
||||
// в quorum-журнал); consumer ack подтверждает, что worker устойчиво ОБРАБОТАЛ его.
|
||||
// Это разные границы: между ними сообщение может быть доставлено несколько раз.
|
||||
package broker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
const (
|
||||
Exchange = "attachments"
|
||||
RoutingKey = "process"
|
||||
Queue = "attachment.process"
|
||||
DeadExchange = "attachments.dlx"
|
||||
DeadQueue = "attachment.dead"
|
||||
DeliveryLimit = 10
|
||||
)
|
||||
|
||||
// Declare объявляет топологию; повторный вызов с теми же аргументами — no-op.
|
||||
func Declare(ch *amqp.Channel) error {
|
||||
if err := ch.ExchangeDeclare(Exchange, "direct", true, false, false, false, nil); err != nil {
|
||||
return fmt.Errorf("declare exchange: %w", err)
|
||||
}
|
||||
if err := ch.ExchangeDeclare(DeadExchange, "fanout", true, false, false, false, nil); err != nil {
|
||||
return fmt.Errorf("declare dlx: %w", err)
|
||||
}
|
||||
if _, err := ch.QueueDeclare(DeadQueue, true, false, false, false, amqp.Table{"x-queue-type": "quorum"}); err != nil {
|
||||
return fmt.Errorf("declare dead queue: %w", err)
|
||||
}
|
||||
if err := ch.QueueBind(DeadQueue, "", DeadExchange, false, nil); err != nil {
|
||||
return fmt.Errorf("bind dead queue: %w", err)
|
||||
}
|
||||
args := amqp.Table{
|
||||
"x-queue-type": "quorum",
|
||||
"x-dead-letter-exchange": DeadExchange,
|
||||
"x-delivery-limit": int32(DeliveryLimit),
|
||||
}
|
||||
if _, err := ch.QueueDeclare(Queue, true, false, false, false, args); err != nil {
|
||||
return fmt.Errorf("declare queue: %w", err)
|
||||
}
|
||||
if err := ch.QueueBind(Queue, RoutingKey, Exchange, false, nil); err != nil {
|
||||
return fmt.Errorf("bind queue: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Publisher публикует с publisher confirms.
|
||||
type Publisher struct {
|
||||
conn *amqp.Connection
|
||||
ch *amqp.Channel
|
||||
}
|
||||
|
||||
func NewPublisher(url string) (*Publisher, error) {
|
||||
conn, err := amqp.DialConfig(url, amqp.Config{Heartbeat: 10 * time.Second, Properties: amqp.Table{"connection_name": "relay"}})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("dial broker: %w", err)
|
||||
}
|
||||
ch, err := conn.Channel()
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err := Declare(ch); err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err := ch.Confirm(false); err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("enable confirms: %w", err)
|
||||
}
|
||||
return &Publisher{conn: conn, ch: ch}, nil
|
||||
}
|
||||
|
||||
func (p *Publisher) Closed() bool { return p.conn.IsClosed() || p.ch.IsClosed() }
|
||||
|
||||
func (p *Publisher) Close() { _ = p.conn.Close() }
|
||||
|
||||
// Publish отправляет persistent-сообщение и ждёт confirm (ack от broker).
|
||||
// nack или таймаут — ошибка: outbox не помечается опубликованным.
|
||||
func (p *Publisher) Publish(ctx context.Context, messageID string, body []byte) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
dc, err := p.ch.PublishWithDeferredConfirmWithContext(ctx, Exchange, RoutingKey, true, false, amqp.Publishing{
|
||||
ContentType: "application/json",
|
||||
DeliveryMode: amqp.Persistent,
|
||||
MessageId: messageID,
|
||||
Timestamp: time.Now(),
|
||||
Type: "attachment.process.v1",
|
||||
Body: body,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("publish: %w", err)
|
||||
}
|
||||
ok, err := dc.WaitContext(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("publish confirm: %w", err)
|
||||
}
|
||||
if !ok {
|
||||
return errors.New("publish nacked by broker")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Consumer — подписка с ручным ack и prefetch.
|
||||
type Consumer struct {
|
||||
conn *amqp.Connection
|
||||
ch *amqp.Channel
|
||||
}
|
||||
|
||||
func NewConsumer(url string, prefetch int, name string) (*Consumer, <-chan amqp.Delivery, error) {
|
||||
conn, err := amqp.DialConfig(url, amqp.Config{Heartbeat: 10 * time.Second, Properties: amqp.Table{"connection_name": name}})
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("dial broker: %w", err)
|
||||
}
|
||||
ch, err := conn.Channel()
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
if err := Declare(ch); err != nil {
|
||||
conn.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
// prefetch = максимум неподтверждённых сообщений у этого worker:
|
||||
// ограничивает конкуренцию и не даёт одному worker забрать всю очередь.
|
||||
if err := ch.Qos(prefetch, 0, false); err != nil {
|
||||
conn.Close()
|
||||
return nil, nil, fmt.Errorf("qos: %w", err)
|
||||
}
|
||||
deliveries, err := ch.Consume(Queue, name, false, false, false, false, nil)
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return nil, nil, fmt.Errorf("consume: %w", err)
|
||||
}
|
||||
return &Consumer{conn: conn, ch: ch}, deliveries, nil
|
||||
}
|
||||
|
||||
// Cancel прекращает получение новых сообщений; неподтверждённые вернутся в очередь.
|
||||
func (c *Consumer) Cancel(name string) { _ = c.ch.Cancel(name, false) }
|
||||
|
||||
func (c *Consumer) Close() { _ = c.conn.Close() }
|
||||
|
||||
// Ping проверяет соединение (для readiness/heartbeat-проверок).
|
||||
func Ping(url string) error {
|
||||
conn, err := amqp.DialConfig(url, amqp.Config{Heartbeat: 10 * time.Second})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return conn.Close()
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Host string
|
||||
Port string
|
||||
Env string
|
||||
SessionTTLSeconds int
|
||||
DatabaseURL string
|
||||
CacheURL string
|
||||
SessionStore string
|
||||
LogLevel slog.Level
|
||||
ShutdownTimeout time.Duration
|
||||
CacheEnabled bool
|
||||
InstanceID string
|
||||
IdempotencyTTL time.Duration
|
||||
DrainDelay time.Duration
|
||||
DBPoolMax int32
|
||||
CacheInvalidation string
|
||||
InternalAddr string
|
||||
S3Endpoint string
|
||||
S3Region string
|
||||
S3Bucket string
|
||||
S3AccessKey string
|
||||
S3SecretKey string
|
||||
MaxUploadBytes int64
|
||||
MaxImagePixels int64
|
||||
// Pipeline (lab5)
|
||||
BrokerURL string
|
||||
PipelineVersion int
|
||||
JobMaxAttempts int
|
||||
JobTimeout time.Duration
|
||||
WorkerConcurrency int
|
||||
StagingRetention time.Duration
|
||||
WebPQuality int
|
||||
PixelBudget int64
|
||||
RetryBaseDelay time.Duration
|
||||
RetryMaxDelay time.Duration
|
||||
}
|
||||
|
||||
func Load() Config {
|
||||
return Config{
|
||||
Host: getEnv("APP_HOST", "0.0.0.0"),
|
||||
Port: getEnv("APP_PORT", "8080"),
|
||||
Env: getEnv("APP_ENV", "lab"),
|
||||
SessionTTLSeconds: getInt("SESSION_TTL_SECONDS", 3600),
|
||||
DatabaseURL: readSecretFile("DATABASE_URL_FILE"),
|
||||
CacheURL: readSecretFile("CACHE_URL_FILE"),
|
||||
SessionStore: getEnv("SESSION_STORE", "postgres"),
|
||||
LogLevel: parseLevel(getEnv("LOG_LEVEL", "info")),
|
||||
ShutdownTimeout: parseDuration(getEnv("SHUTDOWN_TIMEOUT", "8s")),
|
||||
CacheEnabled: getEnv("CACHE_ENABLED", "true") == "true",
|
||||
InstanceID: instanceID(),
|
||||
IdempotencyTTL: time.Duration(getInt("IDEMPOTENCY_TTL_SECONDS", 86400)) * time.Second,
|
||||
DrainDelay: parseDuration(getEnv("DRAIN_DELAY", "3s")),
|
||||
DBPoolMax: int32(max(1, getInt("DB_POOL_MAX", 20))),
|
||||
CacheInvalidation: getEnv("CACHE_INVALIDATION", "version"),
|
||||
InternalAddr: getEnv("INTERNAL_ADDR", ":9090"),
|
||||
S3Endpoint: getEnv("S3_ENDPOINT", "http://s3:9000"),
|
||||
S3Region: getEnv("S3_REGION", "us-east-1"),
|
||||
S3Bucket: getEnv("S3_BUCKET", "messenger-attachments"),
|
||||
S3AccessKey: readSecretFile("S3_ACCESS_KEY_ID_FILE"),
|
||||
S3SecretKey: readSecretFile("S3_SECRET_ACCESS_KEY_FILE"),
|
||||
MaxUploadBytes: int64(getInt("MAX_UPLOAD_BYTES", 10*1024*1024)),
|
||||
MaxImagePixels: int64(getInt("MAX_IMAGE_PIXELS", 40_000_000)),
|
||||
BrokerURL: readSecretFile("BROKER_URL_FILE"),
|
||||
PipelineVersion: max(1, getInt("PIPELINE_VERSION", 1)),
|
||||
JobMaxAttempts: max(1, getInt("JOB_MAX_ATTEMPTS", 5)),
|
||||
JobTimeout: time.Duration(max(5, getInt("JOB_TIMEOUT_SECONDS", 60))) * time.Second,
|
||||
WorkerConcurrency: max(1, getInt("WORKER_CONCURRENCY", 2)),
|
||||
StagingRetention: time.Duration(max(60, getInt("STAGING_RETENTION_SECONDS", 86400))) * time.Second,
|
||||
WebPQuality: min(100, max(1, getInt("WEBP_QUALITY", 80))),
|
||||
PixelBudget: int64(max(1_000_000, getInt("WORKER_PIXEL_BUDGET", 60_000_000))),
|
||||
RetryBaseDelay: parseDuration(getEnv("RETRY_BASE_DELAY", "2s")),
|
||||
RetryMaxDelay: parseDuration(getEnv("RETRY_MAX_DELAY", "60s")),
|
||||
}
|
||||
}
|
||||
|
||||
// instanceID — идентификатор реплики для X-Instance-Id. По умолчанию hostname,
|
||||
// который в Docker равен короткому ID контейнера: так stop-one.sh однозначно
|
||||
// находит контейнер. В lab7 его заменит непрозрачный alias.
|
||||
func instanceID() string {
|
||||
if v := os.Getenv("INSTANCE_ID"); v != "" {
|
||||
return v
|
||||
}
|
||||
if h, err := os.Hostname(); err == nil && h != "" {
|
||||
return h
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
func (c Config) SessionTTL() time.Duration {
|
||||
return time.Duration(c.SessionTTLSeconds) * time.Second
|
||||
}
|
||||
|
||||
func (c Config) Addr() string { return c.Host + ":" + c.Port }
|
||||
|
||||
func getEnv(key, def string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func getInt(key string, def int) int {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil {
|
||||
return n
|
||||
}
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func readSecretFile(envKey string) string {
|
||||
path := os.Getenv(envKey)
|
||||
if path == "" {
|
||||
return ""
|
||||
}
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
slog.Warn("secret file not readable", "path", path, "err", err)
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(string(b))
|
||||
}
|
||||
|
||||
func parseLevel(s string) slog.Level {
|
||||
var l slog.Level
|
||||
if err := l.UnmarshalText([]byte(s)); err != nil {
|
||||
return slog.LevelInfo
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
func parseDuration(s string) time.Duration {
|
||||
d, err := time.ParseDuration(s)
|
||||
if err != nil {
|
||||
return 8 * time.Second
|
||||
}
|
||||
return d
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
AttachmentUploading = "uploading" // внутреннее намерение до 202, клиенту не видно
|
||||
AttachmentQueued = "queued"
|
||||
AttachmentProcessing = "processing"
|
||||
AttachmentReady = "ready"
|
||||
AttachmentFailed = "failed"
|
||||
AttachmentMissing = "missing" // карантин reconciler
|
||||
)
|
||||
|
||||
// Variant — результат обработки одной версии pipeline.
|
||||
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"`
|
||||
ObjectKey string `json:"-"`
|
||||
PipelineVersion int `json:"-"`
|
||||
}
|
||||
|
||||
// Attachment — метаданные вложения. Ключи S3 никогда не уходят клиенту.
|
||||
type Attachment struct {
|
||||
ID string
|
||||
ChatID string
|
||||
OwnerID string
|
||||
Filename string
|
||||
ObjectKey string // текущее место оригинала: staging до ready, конечный prefix после
|
||||
StagingKey string // staging-объект, пока он не удалён после публикации
|
||||
Status string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
SHA256 string
|
||||
ErrorCode string
|
||||
PipelineVersion int // версия, чей результат опубликован (0 — ещё нет)
|
||||
Variants []Variant
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// MarshalJSON — представление по контракту: queued/processing/ready/failed,
|
||||
// варианты текущей опубликованной версии, error_code только у failed.
|
||||
func (a Attachment) MarshalJSON() ([]byte, error) {
|
||||
variants := a.Variants
|
||||
if variants == nil {
|
||||
variants = []Variant{}
|
||||
}
|
||||
var errCode *string
|
||||
if a.Status == AttachmentFailed && a.ErrorCode != "" {
|
||||
ec := a.ErrorCode
|
||||
errCode = &ec
|
||||
}
|
||||
return json.Marshal(struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Status string `json:"status"`
|
||||
Variants []Variant `json:"variants"`
|
||||
ErrorCode *string `json:"error_code"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}{
|
||||
ID: a.ID, ChatID: a.ChatID, OwnerID: a.OwnerID, Filename: a.Filename,
|
||||
ContentType: a.ContentType, SizeBytes: a.SizeBytes, SHA256: a.SHA256,
|
||||
Status: a.Status, Variants: variants, ErrorCode: errCode,
|
||||
CreatedAt: a.CreatedAt.UTC().Truncate(time.Second).Format(time.RFC3339),
|
||||
UpdatedAt: a.UpdatedAt.UTC().Truncate(time.Second).Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
|
||||
// Job — сообщение broker по contracts/jobs.schema.json. Только ID и служебные
|
||||
// поля: ни байтов, ни URL, ни credentials.
|
||||
type Job 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"`
|
||||
Traceparent string `json:"traceparent,omitempty"`
|
||||
}
|
||||
|
||||
const JobType = "attachment.process.v1"
|
||||
@@ -0,0 +1,30 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Chat struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func (c Chat) MarshalJSON() ([]byte, error) {
|
||||
type Alias Chat
|
||||
members := c.MemberIDs
|
||||
if members == nil {
|
||||
members = []string{}
|
||||
}
|
||||
return json.Marshal(&struct {
|
||||
Alias
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}{
|
||||
Alias: Alias(c),
|
||||
MemberIDs: members,
|
||||
CreatedAt: c.CreatedAt.UTC().Truncate(time.Second).Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Message struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
// AttachmentIDs — в порядке отправки; всегда массив (пустой, если вложений нет).
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
func (m Message) MarshalJSON() ([]byte, error) {
|
||||
type Alias Message
|
||||
if m.AttachmentIDs == nil {
|
||||
m.AttachmentIDs = []string{}
|
||||
}
|
||||
return json.Marshal(&struct {
|
||||
Alias
|
||||
CreatedAt string `json:"created_at"`
|
||||
}{
|
||||
Alias: Alias(m),
|
||||
CreatedAt: m.CreatedAt.UTC().Truncate(time.Second).Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
type Session struct {
|
||||
Token string `json:"token"`
|
||||
UserID string `json:"-"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
CreatedAt time.Time `json:"-"`
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// MarshalJSON форматирует CreatedAt в RFC3339 без микросекунд.
|
||||
func (u User) MarshalJSON() ([]byte, error) {
|
||||
type Alias User
|
||||
return json.Marshal(&struct {
|
||||
Alias
|
||||
CreatedAt string `json:"created_at"`
|
||||
}{
|
||||
Alias: Alias(u),
|
||||
CreatedAt: u.CreatedAt.UTC().Truncate(time.Second).Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,592 @@
|
||||
// Package imagecheck потоково проверяет PNG/JPEG без декодирования пикселей.
|
||||
//
|
||||
// Проверка идёт по мере чтения (используется параллельно с PUT в S3), память
|
||||
// O(1) от размера изображения: размеры берутся из заголовка (IHDR/SOF) и
|
||||
// сравниваются с лимитом до чтения тела; PNG — CRC каждого chunk, длина
|
||||
// распакованного IDAT-потока (zlib → io.Discard) и байт фильтра каждой строки,
|
||||
// JPEG — структура сегментов и маркер EOI. «Заведомо повреждённые» файлы
|
||||
// (обрыв, битый CRC, мусор вместо данных, чужой формат) дают ErrInvalid,
|
||||
// слишком большие по пикселям — ErrTooLarge.
|
||||
package imagecheck
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash/crc32"
|
||||
"io"
|
||||
)
|
||||
|
||||
const (
|
||||
PNG = "image/png"
|
||||
JPEG = "image/jpeg"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalid = errors.New("invalid or unsupported image")
|
||||
ErrTooLarge = errors.New("image dimensions exceed limit")
|
||||
)
|
||||
|
||||
var pngSignature = []byte("\x89PNG\r\n\x1a\n")
|
||||
|
||||
// Sniff определяет формат по первым байтам (не по заголовку Content-Type клиента).
|
||||
func Sniff(head []byte) (string, bool) {
|
||||
switch {
|
||||
case bytes.HasPrefix(head, pngSignature):
|
||||
return PNG, true
|
||||
case len(head) >= 3 && head[0] == 0xFF && head[1] == 0xD8 && head[2] == 0xFF:
|
||||
return JPEG, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// Result — что удалось узнать при проверке.
|
||||
type Result struct {
|
||||
Format string
|
||||
Width int
|
||||
Height int
|
||||
}
|
||||
|
||||
// Validate читает r до конца и проверяет изображение формата format.
|
||||
// maxPixels ограничивает width*height. Хвост после конца изображения
|
||||
// дочитывается и игнорируется, чтобы не блокировать писателя.
|
||||
func Validate(r io.Reader, format string, maxPixels int64) (Result, error) {
|
||||
br := bufio.NewReaderSize(r, 32*1024)
|
||||
var res Result
|
||||
var err error
|
||||
switch format {
|
||||
case PNG:
|
||||
res, err = validatePNG(br, maxPixels)
|
||||
case JPEG:
|
||||
res, err = validateJPEG(br, maxPixels)
|
||||
default:
|
||||
return Result{}, ErrInvalid
|
||||
}
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
_, _ = io.Copy(io.Discard, br)
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func invalid(format string, args ...any) error {
|
||||
return fmt.Errorf("%w: %s", ErrInvalid, fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
// --- PNG ---
|
||||
|
||||
func channels(colorType byte) (int, bool) {
|
||||
switch colorType {
|
||||
case 0:
|
||||
return 1, true // grayscale
|
||||
case 2:
|
||||
return 3, true // RGB
|
||||
case 3:
|
||||
return 1, true // palette
|
||||
case 4:
|
||||
return 2, true // gray + alpha
|
||||
case 6:
|
||||
return 4, true // RGBA
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func validBitDepth(colorType, depth byte) bool {
|
||||
switch colorType {
|
||||
case 0:
|
||||
return depth == 1 || depth == 2 || depth == 4 || depth == 8 || depth == 16
|
||||
case 3:
|
||||
return depth == 1 || depth == 2 || depth == 4 || depth == 8
|
||||
case 2, 4, 6:
|
||||
return depth == 8 || depth == 16
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// pngRowLen — длина одной отсканированной строки прохода: 1 байт фильтра +
|
||||
// данные пикселей.
|
||||
func pngRowLen(pw, bitsPerPixel int64) int64 {
|
||||
return 1 + (pw*bitsPerPixel+7)/8
|
||||
}
|
||||
|
||||
// expectedRaw — длина распакованного потока IDAT: строки с байтом фильтра.
|
||||
func expectedRaw(w, h int64, bitsPerPixel int64, interlaced bool) int64 {
|
||||
if !interlaced {
|
||||
return h * pngRowLen(w, bitsPerPixel)
|
||||
}
|
||||
passes := [7][4]int64{{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 {
|
||||
if w <= p[0] || h <= p[1] {
|
||||
continue
|
||||
}
|
||||
pw := (w - p[0] + p[2] - 1) / p[2]
|
||||
ph := (h - p[1] + p[3] - 1) / p[3]
|
||||
total += ph * pngRowLen(pw, bitsPerPixel)
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
// pngRows — итератор по (pw, ph) проходов Adam7 или единственного прохода.
|
||||
// Используется, чтобы валидировать байт фильтра каждой строки, не зная
|
||||
// заранее, как разбивается распакованный поток на проходы.
|
||||
type pngPass struct {
|
||||
pw, ph int64
|
||||
}
|
||||
|
||||
func pngPasses(w, h int64, interlaced bool) []pngPass {
|
||||
if !interlaced {
|
||||
return []pngPass{{w, h}}
|
||||
}
|
||||
coords := [7][4]int64{{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}}
|
||||
out := make([]pngPass, 0, len(coords))
|
||||
for _, p := range coords {
|
||||
if w <= p[0] || h <= p[1] {
|
||||
continue
|
||||
}
|
||||
pw := (w - p[0] + p[2] - 1) / p[2]
|
||||
ph := (h - p[1] + p[3] - 1) / p[3]
|
||||
out = append(out, pngPass{pw, ph})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type pngChunk struct {
|
||||
length uint32
|
||||
typ [4]byte
|
||||
}
|
||||
|
||||
func readChunkHeader(br *bufio.Reader) (pngChunk, error) {
|
||||
var hdr [8]byte
|
||||
if _, err := io.ReadFull(br, hdr[:]); err != nil {
|
||||
return pngChunk{}, invalid("truncated chunk header")
|
||||
}
|
||||
c := pngChunk{length: binary.BigEndian.Uint32(hdr[:4])}
|
||||
copy(c.typ[:], hdr[4:])
|
||||
if c.length > 1<<31-1 {
|
||||
return c, invalid("chunk too long")
|
||||
}
|
||||
for _, b := range c.typ {
|
||||
if !((b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z')) {
|
||||
return c, invalid("bad chunk type")
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// readChunkData читает тело chunk в dst (если не nil) и проверяет CRC.
|
||||
func readChunkData(br *bufio.Reader, c pngChunk, dst io.Writer) error {
|
||||
h := crc32.NewIEEE()
|
||||
h.Write(c.typ[:])
|
||||
w := io.Writer(h)
|
||||
if dst != nil {
|
||||
w = io.MultiWriter(h, dst)
|
||||
}
|
||||
if _, err := io.CopyN(w, br, int64(c.length)); err != nil {
|
||||
return invalid("truncated %s chunk", c.typ[:])
|
||||
}
|
||||
var crc [4]byte
|
||||
if _, err := io.ReadFull(br, crc[:]); err != nil {
|
||||
return invalid("truncated CRC")
|
||||
}
|
||||
if binary.BigEndian.Uint32(crc[:]) != h.Sum32() {
|
||||
return invalid("CRC mismatch in %s", c.typ[:])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// idatStream отдаёт данные подряд идущих IDAT-chunk как один поток.
|
||||
type idatStream struct {
|
||||
br *bufio.Reader
|
||||
remaining uint32
|
||||
crc uint32
|
||||
next *pngChunk // первый chunk после последнего IDAT
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *idatStream) Read(p []byte) (int, error) {
|
||||
for s.remaining == 0 {
|
||||
if s.err != nil || s.next != nil {
|
||||
if s.err != nil {
|
||||
return 0, s.err
|
||||
}
|
||||
return 0, io.EOF
|
||||
}
|
||||
if err := s.finishChunk(); err != nil {
|
||||
s.err = err
|
||||
return 0, err
|
||||
}
|
||||
c, err := readChunkHeader(s.br)
|
||||
if err != nil {
|
||||
s.err = err
|
||||
return 0, err
|
||||
}
|
||||
if string(c.typ[:]) != "IDAT" {
|
||||
s.next = &c
|
||||
return 0, io.EOF
|
||||
}
|
||||
s.startChunk(c)
|
||||
}
|
||||
if uint32(len(p)) > s.remaining {
|
||||
p = p[:s.remaining]
|
||||
}
|
||||
n, err := s.br.Read(p)
|
||||
s.crc = crc32.Update(s.crc, crc32.IEEETable, p[:n])
|
||||
s.remaining -= uint32(n)
|
||||
if err != nil && err != io.EOF {
|
||||
s.err = err
|
||||
return n, err
|
||||
}
|
||||
if n == 0 && err == io.EOF {
|
||||
s.err = invalid("truncated IDAT")
|
||||
return 0, s.err
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (s *idatStream) startChunk(c pngChunk) {
|
||||
s.remaining = c.length
|
||||
s.crc = crc32.Update(0, crc32.IEEETable, c.typ[:])
|
||||
}
|
||||
|
||||
func (s *idatStream) finishChunk() error {
|
||||
var crc [4]byte
|
||||
if _, err := io.ReadFull(s.br, crc[:]); err != nil {
|
||||
return invalid("truncated CRC")
|
||||
}
|
||||
if binary.BigEndian.Uint32(crc[:]) != s.crc {
|
||||
return invalid("CRC mismatch in IDAT")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validatePNGStream проверяет распакованный поток: длину, кратность строкам
|
||||
// и байты фильтра (0..4) в начале каждой строки каждого прохода.
|
||||
func validatePNGStream(zr io.Reader, passes []pngPass, bitsPerPixel, want int64) error {
|
||||
total := int64(0)
|
||||
buf := make([]byte, 32*1024)
|
||||
for _, pass := range passes {
|
||||
rowLen := pngRowLen(pass.pw, bitsPerPixel)
|
||||
for y := int64(0); y < pass.ph; y++ {
|
||||
// читаем ровно одну строку, но чанками, чтобы не аллоцировать
|
||||
// rowLen (может быть большой для широких изображений)
|
||||
left := rowLen
|
||||
first := true
|
||||
for left > 0 {
|
||||
chunk := int64(len(buf))
|
||||
if left < chunk {
|
||||
chunk = left
|
||||
}
|
||||
n, err := io.ReadFull(zr, buf[:chunk])
|
||||
if err != nil {
|
||||
if errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, io.EOF) {
|
||||
return invalid("truncated IDAT (got %d of %d)", total, want)
|
||||
}
|
||||
return invalid("corrupt image data")
|
||||
}
|
||||
if first {
|
||||
if buf[0] > 4 {
|
||||
return invalid("bad row filter %d", buf[0])
|
||||
}
|
||||
first = false
|
||||
}
|
||||
total += int64(n)
|
||||
left -= int64(n)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Проверяем, что распакованный поток ровно want байт (ни больше, ни меньше).
|
||||
var extra [1]byte
|
||||
n, err := zr.Read(extra[:])
|
||||
if n != 0 {
|
||||
return invalid("image data longer than expected")
|
||||
}
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
return invalid("corrupt image data")
|
||||
}
|
||||
if total != want {
|
||||
return invalid("image data length %d, want %d", total, want)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validatePNG(br *bufio.Reader, maxPixels int64) (Result, error) {
|
||||
res := Result{Format: PNG}
|
||||
sig := make([]byte, 8)
|
||||
if _, err := io.ReadFull(br, sig); err != nil || !bytes.Equal(sig, pngSignature) {
|
||||
return res, invalid("not a PNG")
|
||||
}
|
||||
c, err := readChunkHeader(br)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
if string(c.typ[:]) != "IHDR" || c.length != 13 {
|
||||
return res, invalid("IHDR must be first")
|
||||
}
|
||||
var ihdr bytes.Buffer
|
||||
if err := readChunkData(br, c, &ihdr); err != nil {
|
||||
return res, err
|
||||
}
|
||||
b := ihdr.Bytes()
|
||||
w := int64(binary.BigEndian.Uint32(b[0:4]))
|
||||
h := int64(binary.BigEndian.Uint32(b[4:8]))
|
||||
depth, colorType, compression, filter, interlace := b[8], b[9], b[10], b[11], b[12]
|
||||
res.Width, res.Height = int(w), int(h)
|
||||
if w < 1 || h < 1 || w > 1<<31-1 || h > 1<<31-1 {
|
||||
return res, invalid("bad dimensions")
|
||||
}
|
||||
// Лимит пикселей — до чтения и распаковки данных изображения.
|
||||
if w*h > maxPixels {
|
||||
return res, ErrTooLarge
|
||||
}
|
||||
ch, ok := channels(colorType)
|
||||
if !ok || !validBitDepth(colorType, depth) || compression != 0 || filter != 0 || interlace > 1 {
|
||||
return res, invalid("unsupported IHDR")
|
||||
}
|
||||
bpp := int64(ch) * int64(depth)
|
||||
want := expectedRaw(w, h, bpp, interlace == 1)
|
||||
passes := pngPasses(w, h, interlace == 1)
|
||||
|
||||
sawIDAT := false
|
||||
for {
|
||||
c, err := readChunkHeader(br)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
switch string(c.typ[:]) {
|
||||
case "IDAT":
|
||||
if sawIDAT {
|
||||
return res, invalid("non-consecutive IDAT")
|
||||
}
|
||||
sawIDAT = true
|
||||
s := &idatStream{br: br}
|
||||
s.startChunk(c)
|
||||
zr, err := zlib.NewReader(s)
|
||||
if err != nil {
|
||||
return res, invalid("bad zlib header")
|
||||
}
|
||||
// Распаковка и проверка фильтров строк — без хранения пикселей.
|
||||
if err := validatePNGStream(zr, passes, bpp, want); err != nil {
|
||||
// Закрываем zlib, чтобы дочитать хвост CRC в idatStream, но
|
||||
// игнорируем ошибку закрытия: она не важна для результата.
|
||||
_ = zr.Close()
|
||||
return res, err
|
||||
}
|
||||
if err := zr.Close(); err != nil && !errors.Is(err, io.EOF) {
|
||||
return res, invalid("bad zlib trailer")
|
||||
}
|
||||
// Остаток IDAT (например, пустые chunk) дочитываем с проверкой CRC.
|
||||
if _, err := io.Copy(io.Discard, s); err != nil {
|
||||
return res, err
|
||||
}
|
||||
if s.next == nil {
|
||||
return res, invalid("missing IEND")
|
||||
}
|
||||
c = *s.next
|
||||
if string(c.typ[:]) == "IEND" {
|
||||
if err := readChunkData(br, c, nil); err != nil {
|
||||
return res, err
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
if err := readChunkData(br, c, nil); err != nil {
|
||||
return res, err
|
||||
}
|
||||
case "IEND":
|
||||
if !sawIDAT {
|
||||
return res, invalid("no image data")
|
||||
}
|
||||
if err := readChunkData(br, c, nil); err != nil {
|
||||
return res, err
|
||||
}
|
||||
return res, nil
|
||||
case "IHDR":
|
||||
return res, invalid("duplicate IHDR")
|
||||
default:
|
||||
if err := readChunkData(br, c, nil); err != nil {
|
||||
return res, err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- JPEG ---
|
||||
|
||||
func isSOF(m byte) bool {
|
||||
switch m {
|
||||
case 0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// readMarker читает 0xFF (с заполнителями) и код маркера.
|
||||
func readMarker(br *bufio.Reader) (byte, error) {
|
||||
b, err := br.ReadByte()
|
||||
if err != nil {
|
||||
return 0, invalid("truncated JPEG")
|
||||
}
|
||||
if b != 0xFF {
|
||||
return 0, invalid("expected JPEG marker")
|
||||
}
|
||||
for b == 0xFF {
|
||||
if b, err = br.ReadByte(); err != nil {
|
||||
return 0, invalid("truncated JPEG")
|
||||
}
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func segmentLength(br *bufio.Reader) (int, error) {
|
||||
var l [2]byte
|
||||
if _, err := io.ReadFull(br, l[:]); err != nil {
|
||||
return 0, invalid("truncated JPEG segment")
|
||||
}
|
||||
n := int(binary.BigEndian.Uint16(l[:]))
|
||||
if n < 2 {
|
||||
return 0, invalid("bad JPEG segment length")
|
||||
}
|
||||
return n - 2, nil
|
||||
}
|
||||
|
||||
// skipEntropy пропускает сжатые данные скана и возвращает следующий маркер.
|
||||
func skipEntropy(br *bufio.Reader) (byte, error) {
|
||||
for {
|
||||
b, err := br.ReadByte()
|
||||
if err != nil {
|
||||
return 0, invalid("truncated JPEG scan")
|
||||
}
|
||||
if b != 0xFF {
|
||||
continue
|
||||
}
|
||||
for b == 0xFF {
|
||||
if b, err = br.ReadByte(); err != nil {
|
||||
return 0, invalid("truncated JPEG scan")
|
||||
}
|
||||
}
|
||||
if b == 0x00 || (b >= 0xD0 && b <= 0xD7) {
|
||||
continue // байт-заполнитель или RSTn внутри скана
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
}
|
||||
|
||||
// readSOF читает сегмент SOF и проверяет его структуру (ITU T.81, B.2.2):
|
||||
// P(1) Y(2) X(2) Nf(1), затем Nf компонент по 3 байта. n — длина сегмента
|
||||
// без двух байт поля длины. Возвращает (width, height).
|
||||
func readSOF(br *bufio.Reader, n int) (int64, int64, error) {
|
||||
if n < 6 {
|
||||
return 0, 0, invalid("short SOF")
|
||||
}
|
||||
hdr := make([]byte, 6)
|
||||
if _, err := io.ReadFull(br, hdr); err != nil {
|
||||
return 0, 0, invalid("truncated SOF")
|
||||
}
|
||||
// hdr[0] — точность выборки (precision), не число компонент.
|
||||
h := int64(binary.BigEndian.Uint16(hdr[1:3]))
|
||||
w := int64(binary.BigEndian.Uint16(hdr[3:5]))
|
||||
nf := int(hdr[5])
|
||||
if nf == 0 {
|
||||
return 0, 0, invalid("SOF without components")
|
||||
}
|
||||
if n != 6+3*nf {
|
||||
return 0, 0, invalid("SOF length %d, want %d", n, 6+3*nf)
|
||||
}
|
||||
if _, err := br.Discard(3 * nf); err != nil {
|
||||
return 0, 0, invalid("truncated SOF")
|
||||
}
|
||||
return w, h, nil
|
||||
}
|
||||
|
||||
func validateJPEG(br *bufio.Reader, maxPixels int64) (Result, error) {
|
||||
res := Result{Format: JPEG}
|
||||
var soi [2]byte
|
||||
if _, err := io.ReadFull(br, soi[:]); err != nil || soi != [2]byte{0xFF, 0xD8} {
|
||||
return res, invalid("not a JPEG")
|
||||
}
|
||||
sawSOF, sawSOS := false, false
|
||||
marker, err := readMarker(br)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
for {
|
||||
switch {
|
||||
case marker == 0xD9: // EOI
|
||||
if !sawSOF || !sawSOS {
|
||||
return res, invalid("JPEG without frame or scan")
|
||||
}
|
||||
return res, nil
|
||||
case marker == 0xD8:
|
||||
return res, invalid("unexpected SOI")
|
||||
case marker == 0x01 || (marker >= 0xD0 && marker <= 0xD7):
|
||||
// маркеры без длины
|
||||
case isSOF(marker):
|
||||
n, err := segmentLength(br)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
if sawSOF {
|
||||
// читаем сегмент, но так и так вернём ошибку
|
||||
_, _, _ = readSOF(br, n)
|
||||
return res, invalid("multiple frames")
|
||||
}
|
||||
w, h, err := readSOF(br, n)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
res.Width, res.Height = int(w), int(h)
|
||||
if w < 1 || h < 1 {
|
||||
return res, invalid("bad JPEG dimensions")
|
||||
}
|
||||
if w*h > maxPixels {
|
||||
return res, ErrTooLarge
|
||||
}
|
||||
sawSOF = true
|
||||
case marker == 0xDA: // SOS
|
||||
if !sawSOF {
|
||||
return res, invalid("scan before frame")
|
||||
}
|
||||
n, err := segmentLength(br)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
// SOS: Ns + Ss + Se + Ah/Al + 2*Ns = 1 + 3 + 2*Ns = 4 + 2*Ns
|
||||
if n < 4 {
|
||||
return res, invalid("short SOS")
|
||||
}
|
||||
nsBuf := make([]byte, 1)
|
||||
if _, err := io.ReadFull(br, nsBuf); err != nil {
|
||||
return res, invalid("truncated SOS")
|
||||
}
|
||||
ns := int(nsBuf[0])
|
||||
if ns < 1 {
|
||||
return res, invalid("SOS without components")
|
||||
}
|
||||
if n != 4+2*ns {
|
||||
return res, invalid("SOS length %d, want %d", n, 4+2*ns)
|
||||
}
|
||||
if _, err := br.Discard(n - 1); err != nil {
|
||||
return res, invalid("truncated SOS")
|
||||
}
|
||||
sawSOS = true
|
||||
if marker, err = skipEntropy(br); err != nil {
|
||||
return res, err
|
||||
}
|
||||
continue
|
||||
default:
|
||||
n, err := segmentLength(br)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
if _, err := br.Discard(n); err != nil {
|
||||
return res, invalid("truncated JPEG segment")
|
||||
}
|
||||
}
|
||||
if marker, err = readMarker(br); err != nil {
|
||||
return res, err
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package imagecheck
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"hash/crc32"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const limit = 40_000_000
|
||||
|
||||
func testImage(w, h int) *image.RGBA {
|
||||
img := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||
for y := 0; y < h; y++ {
|
||||
for x := 0; x < w; x++ {
|
||||
img.Set(x, y, color.RGBA{uint8(x * 7), uint8(y * 3), uint8(x ^ y), 255})
|
||||
}
|
||||
}
|
||||
return img
|
||||
}
|
||||
|
||||
func encodePNG(t *testing.T, w, h int) []byte {
|
||||
var b bytes.Buffer
|
||||
if err := png.Encode(&b, testImage(w, h)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
func encodeJPEG(t *testing.T, w, h int, progressive bool) []byte {
|
||||
var b bytes.Buffer
|
||||
if err := jpeg.Encode(&b, testImage(w, h), &jpeg.Options{Quality: 80}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
func chunk(typ string, data []byte) []byte {
|
||||
var b bytes.Buffer
|
||||
binary.Write(&b, binary.BigEndian, uint32(len(data)))
|
||||
b.WriteString(typ)
|
||||
b.Write(data)
|
||||
crc := crc32.NewIEEE()
|
||||
crc.Write([]byte(typ))
|
||||
crc.Write(data)
|
||||
binary.Write(&b, binary.BigEndian, crc.Sum32())
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
// craftPNG собирает PNG вручную: так можно задать любые IHDR и поток данных.
|
||||
func craftPNG(w, h uint32, colorType, depth, interlace byte, raw []byte) []byte {
|
||||
var b bytes.Buffer
|
||||
b.Write(pngSignature)
|
||||
ihdr := make([]byte, 13)
|
||||
binary.BigEndian.PutUint32(ihdr[0:], w)
|
||||
binary.BigEndian.PutUint32(ihdr[4:], h)
|
||||
ihdr[8], ihdr[9], ihdr[12] = depth, colorType, interlace
|
||||
b.Write(chunk("IHDR", ihdr))
|
||||
var z bytes.Buffer
|
||||
zw := zlib.NewWriter(&z)
|
||||
zw.Write(raw)
|
||||
zw.Close()
|
||||
b.Write(chunk("IDAT", z.Bytes()))
|
||||
b.Write(chunk("IEND", nil))
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
func check(t *testing.T, name string, data []byte, format string, want error) {
|
||||
t.Helper()
|
||||
_, err := Validate(bytes.NewReader(data), format, limit)
|
||||
if want == nil && err != nil {
|
||||
t.Errorf("%s: unexpected error %v", name, err)
|
||||
}
|
||||
if want != nil && !errors.Is(err, want) {
|
||||
t.Errorf("%s: got %v, want %v", name, err, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidPNGAndJPEG(t *testing.T) {
|
||||
p := encodePNG(t, 320, 200)
|
||||
res, err := Validate(bytes.NewReader(p), PNG, limit)
|
||||
if err != nil || res.Width != 320 || res.Height != 200 {
|
||||
t.Fatalf("png: %+v %v", res, err)
|
||||
}
|
||||
j := encodeJPEG(t, 321, 199, false)
|
||||
res, err = Validate(bytes.NewReader(j), JPEG, limit)
|
||||
if err != nil || res.Width != 321 || res.Height != 199 {
|
||||
t.Fatalf("jpeg: %+v %v", res, err)
|
||||
}
|
||||
check(t, "png with trailing bytes", append(p, []byte("trailer")...), PNG, nil)
|
||||
}
|
||||
|
||||
func TestCourseFixture(t *testing.T) {
|
||||
data, err := os.ReadFile("../../tests/fixtures/sample.png")
|
||||
if err != nil {
|
||||
t.Skip("fixture not found")
|
||||
}
|
||||
res, err := Validate(bytes.NewReader(data), PNG, limit)
|
||||
if err != nil || res.Width != 320 || res.Height != 200 {
|
||||
t.Fatalf("fixture: %+v %v", res, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInterlacedPNG(t *testing.T) {
|
||||
// 10×7 RGB, Adam7: длина сырых данных по семи проходам.
|
||||
w, h := int64(10), int64(7)
|
||||
raw := make([]byte, expectedRaw(w, h, 24, true))
|
||||
check(t, "interlaced", craftPNG(uint32(w), uint32(h), 2, 8, 1, raw), PNG, nil)
|
||||
check(t, "interlaced short data", craftPNG(uint32(w), uint32(h), 2, 8, 1, raw[:len(raw)-1]), PNG, ErrInvalid)
|
||||
}
|
||||
|
||||
func TestBrokenImages(t *testing.T) {
|
||||
p := encodePNG(t, 64, 64)
|
||||
j := encodeJPEG(t, 64, 64, false)
|
||||
|
||||
check(t, "png truncated", p[:len(p)/2], PNG, ErrInvalid)
|
||||
check(t, "png without IEND", p[:len(p)-12], PNG, ErrInvalid)
|
||||
bad := bytes.Clone(p)
|
||||
bad[len(bad)/2] ^= 0xFF
|
||||
check(t, "png corrupted byte", bad, PNG, ErrInvalid)
|
||||
check(t, "jpeg truncated", j[:len(j)/2], JPEG, ErrInvalid)
|
||||
check(t, "jpeg without EOI", j[:len(j)-2], JPEG, ErrInvalid)
|
||||
check(t, "png declared as jpeg", p, JPEG, ErrInvalid)
|
||||
check(t, "text as png", []byte("hello, not an image at all"), PNG, ErrInvalid)
|
||||
check(t, "empty", nil, PNG, ErrInvalid)
|
||||
check(t, "png short raw data", craftPNG(8, 8, 2, 8, 0, make([]byte, 8*(1+24)-1)), PNG, ErrInvalid)
|
||||
check(t, "png bad bit depth", craftPNG(8, 8, 2, 4, 0, make([]byte, 8*(1+12))), PNG, ErrInvalid)
|
||||
}
|
||||
|
||||
func TestPixelLimitBeforeData(t *testing.T) {
|
||||
// «Бомба»: IHDR на 100000×100000, данных почти нет. Должно быть ErrTooLarge,
|
||||
// а не попытка распаковать 30 ГБ.
|
||||
bomb := craftPNG(100000, 100000, 2, 8, 0, []byte{0})
|
||||
check(t, "png bomb", bomb, PNG, ErrTooLarge)
|
||||
// Ровно на границе лимита — допустимо по пикселям (данных не хватает → invalid).
|
||||
check(t, "png at limit", craftPNG(8000, 5000, 0, 1, 0, nil), PNG, ErrInvalid)
|
||||
check(t, "png over limit", craftPNG(8000, 5001, 0, 1, 0, nil), PNG, ErrTooLarge)
|
||||
|
||||
// JPEG: подменяем размеры в SOF0 на 60000×60000.
|
||||
j := encodeJPEG(t, 16, 16, false)
|
||||
i := bytes.Index(j, []byte{0xFF, 0xC0})
|
||||
if i < 0 {
|
||||
t.Fatal("no SOF0")
|
||||
}
|
||||
big := bytes.Clone(j)
|
||||
binary.BigEndian.PutUint16(big[i+5:], 60000)
|
||||
binary.BigEndian.PutUint16(big[i+7:], 60000)
|
||||
check(t, "jpeg bomb", big, JPEG, ErrTooLarge)
|
||||
}
|
||||
|
||||
func TestJPEGSOFStructure(t *testing.T) {
|
||||
// Серый JPEG: одна компонента (Nf=1), длина SOF = 6 + 3*1.
|
||||
var g bytes.Buffer
|
||||
gray := image.NewGray(image.Rect(0, 0, 33, 17))
|
||||
if err := jpeg.Encode(&g, gray, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res, err := Validate(bytes.NewReader(g.Bytes()), JPEG, limit)
|
||||
if err != nil || res.Width != 33 || res.Height != 17 {
|
||||
t.Fatalf("grayscale jpeg: %+v %v", res, err)
|
||||
}
|
||||
// Цветной JPEG с испорченным Nf (длина сегмента больше не сходится).
|
||||
j := encodeJPEG(t, 16, 16, false)
|
||||
i := bytes.Index(j, []byte{0xFF, 0xC0})
|
||||
bad := bytes.Clone(j)
|
||||
bad[i+9] = 7 // Nf: было 3
|
||||
check(t, "jpeg SOF length mismatch", bad, JPEG, ErrInvalid)
|
||||
}
|
||||
|
||||
func TestSniff(t *testing.T) {
|
||||
if f, ok := Sniff(encodePNG(t, 2, 2)); !ok || f != PNG {
|
||||
t.Error("png sniff")
|
||||
}
|
||||
if f, ok := Sniff(encodeJPEG(t, 2, 2, false)); !ok || f != JPEG {
|
||||
t.Error("jpeg sniff")
|
||||
}
|
||||
if _, ok := Sniff([]byte("GIF89a")); ok {
|
||||
t.Error("gif must not be accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
// Package imaging строит варианты вложения по контракту lab5.
|
||||
//
|
||||
// thumbnail JPEG, вписан в 256×256 с сохранением пропорций, без увеличения,
|
||||
// EXIF orientation применён, alpha компонуется на белый,
|
||||
// размеры округляются вниз, минимум 1 px (320×200 → 256×160)
|
||||
// crop JPEG, центрированный квадрат 128×128 (маленькие увеличиваются)
|
||||
// optimized WebP, вписан в 1280×1280 без увеличения; lossy, качество WEBP_QUALITY,
|
||||
// метаданные удалены (cwebp -metadata none; пиксели и так
|
||||
// перекодированы из декодированного изображения, EXIF не переносится)
|
||||
//
|
||||
// Все кодировщики детерминированы: одинаковый вход даёт одинаковые байты, поэтому
|
||||
// повтор job перезаписывает объект тем же содержимым.
|
||||
package imaging
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
|
||||
xdraw "golang.org/x/image/draw"
|
||||
)
|
||||
|
||||
// ErrDecode — изображение не декодируется: постоянная ошибка (повтор не поможет).
|
||||
var ErrDecode = errors.New("cannot decode image")
|
||||
|
||||
// Params — параметры версии pipeline. Новая версия может менять их, не трогая
|
||||
// уже опубликованные результаты старой (ключ эффекта включает версию).
|
||||
type Params struct {
|
||||
ThumbQuality int
|
||||
CropQuality int
|
||||
WebPQuality int
|
||||
}
|
||||
|
||||
// ParamsFor — параметры по номеру версии pipeline.
|
||||
func ParamsFor(version, webpQuality int) Params {
|
||||
p := Params{ThumbQuality: 85, CropQuality: 85, WebPQuality: webpQuality}
|
||||
if version >= 2 {
|
||||
// v2 (трек 5): чуть выше качество превью — другой, но детерминированный результат.
|
||||
p.ThumbQuality, p.CropQuality = 92, 92
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// Output — закодированный вариант.
|
||||
type Output struct {
|
||||
Name string
|
||||
ContentType string
|
||||
Data []byte
|
||||
Width int
|
||||
Height int
|
||||
SHA256 string
|
||||
}
|
||||
|
||||
func newOutput(name, ctype string, data []byte, w, h int) Output {
|
||||
sum := sha256.Sum256(data)
|
||||
return Output{Name: name, ContentType: ctype, Data: data, Width: w, Height: h, SHA256: hex.EncodeToString(sum[:])}
|
||||
}
|
||||
|
||||
// Decode декодирует оригинал, применяет EXIF orientation (JPEG) и компонует
|
||||
// прозрачность на белый фон.
|
||||
func Decode(data []byte) (*image.RGBA, error) {
|
||||
src, _, err := image.Decode(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", ErrDecode, err)
|
||||
}
|
||||
b := src.Bounds()
|
||||
// Непрозрачный RGBA (типичный PNG RGB) уже готов: вторая полноразмерная копия
|
||||
// (4 байта × пиксель) не нужна — для 36 Мпикс это 137 MiB памяти worker.
|
||||
if rgba, ok := src.(*image.RGBA); ok && b.Min == (image.Point{}) && rgba.Opaque() {
|
||||
return Orient(rgba, ExifOrientation(data)), nil
|
||||
}
|
||||
out := image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
|
||||
draw.Draw(out, out.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
|
||||
draw.Draw(out, out.Bounds(), src, b.Min, draw.Over) // alpha → на белый
|
||||
return Orient(out, ExifOrientation(data)), nil
|
||||
}
|
||||
|
||||
// FitSize — вписать w×h в box×box с сохранением пропорций; без увеличения,
|
||||
// если allowUpscale=false; округление вниз, минимум 1.
|
||||
func FitSize(w, h, box int, allowUpscale bool) (int, int) {
|
||||
if !allowUpscale && w <= box && h <= box {
|
||||
return w, h
|
||||
}
|
||||
if w >= h {
|
||||
nh := h * box / w
|
||||
return box, max(1, nh)
|
||||
}
|
||||
nw := w * box / h
|
||||
return max(1, nw), box
|
||||
}
|
||||
|
||||
func resize(src image.Image, w, h int) *image.RGBA {
|
||||
dst := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||
xdraw.CatmullRom.Scale(dst, dst.Bounds(), src, src.Bounds(), xdraw.Src, nil)
|
||||
return dst
|
||||
}
|
||||
|
||||
func encodeJPEG(img image.Image, quality int) ([]byte, error) {
|
||||
var b bytes.Buffer
|
||||
if err := jpeg.Encode(&b, img, &jpeg.Options{Quality: quality}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return b.Bytes(), nil
|
||||
}
|
||||
|
||||
// Thumbnail — JPEG, вписан в 256×256 без увеличения.
|
||||
func Thumbnail(img *image.RGBA, p Params) (Output, error) {
|
||||
w, h := FitSize(img.Bounds().Dx(), img.Bounds().Dy(), 256, false)
|
||||
var src image.Image = img
|
||||
if w != img.Bounds().Dx() || h != img.Bounds().Dy() {
|
||||
src = resize(img, w, h)
|
||||
}
|
||||
data, err := encodeJPEG(src, p.ThumbQuality)
|
||||
if err != nil {
|
||||
return Output{}, err
|
||||
}
|
||||
return newOutput("thumbnail", "image/jpeg", data, w, h), nil
|
||||
}
|
||||
|
||||
// Crop — JPEG, центрированный квадрат 128×128 (маленькие исходники увеличиваются).
|
||||
func Crop(img *image.RGBA, p Params) (Output, error) {
|
||||
b := img.Bounds()
|
||||
side := min(b.Dx(), b.Dy())
|
||||
x0 := b.Min.X + (b.Dx()-side)/2
|
||||
y0 := b.Min.Y + (b.Dy()-side)/2
|
||||
sq := img.SubImage(image.Rect(x0, y0, x0+side, y0+side))
|
||||
data, err := encodeJPEG(resize(sq, 128, 128), p.CropQuality)
|
||||
if err != nil {
|
||||
return Output{}, err
|
||||
}
|
||||
return newOutput("crop", "image/jpeg", data, 128, 128), nil
|
||||
}
|
||||
|
||||
// WebPEncoder кодирует RGBA в WebP.
|
||||
type WebPEncoder func(ctx context.Context, img image.Image, quality int) ([]byte, error)
|
||||
|
||||
// CWebP — кодировщик через cwebp (libwebp-tools): lossy, -metadata none.
|
||||
// Вход — PNG во временном каталоге процесса (эфемерный, удаляется сразу).
|
||||
func CWebP(ctx context.Context, img image.Image, quality int) ([]byte, error) {
|
||||
dir, err := os.MkdirTemp("", "webp-")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer os.RemoveAll(dir)
|
||||
in, out := filepath.Join(dir, "in.png"), filepath.Join(dir, "out.webp")
|
||||
f, err := os.Create(in)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
enc := png.Encoder{CompressionLevel: png.BestSpeed}
|
||||
if err := enc.Encode(f, img); err != nil {
|
||||
f.Close()
|
||||
return nil, err
|
||||
}
|
||||
f.Close()
|
||||
cmd := exec.CommandContext(ctx, "cwebp", "-quiet", "-q", fmt.Sprint(quality), "-m", "4", "-metadata", "none", in, "-o", out)
|
||||
if msg, err := cmd.CombinedOutput(); err != nil {
|
||||
return nil, fmt.Errorf("cwebp: %v: %s", err, bytes.TrimSpace(msg))
|
||||
}
|
||||
return os.ReadFile(out)
|
||||
}
|
||||
|
||||
// Optimized — WebP, вписан в 1280×1280 без увеличения.
|
||||
func Optimized(ctx context.Context, img *image.RGBA, p Params, enc WebPEncoder) (Output, error) {
|
||||
w, h := FitSize(img.Bounds().Dx(), img.Bounds().Dy(), 1280, false)
|
||||
var src image.Image = img
|
||||
if w != img.Bounds().Dx() || h != img.Bounds().Dy() {
|
||||
src = resize(img, w, h)
|
||||
}
|
||||
data, err := enc(ctx, src, p.WebPQuality)
|
||||
if err != nil {
|
||||
return Output{}, err
|
||||
}
|
||||
if len(data) < 12 || string(data[0:4]) != "RIFF" || string(data[8:12]) != "WEBP" {
|
||||
return Output{}, errors.New("encoder produced non-WebP data")
|
||||
}
|
||||
return newOutput("optimized", "image/webp", data, w, h), nil
|
||||
}
|
||||
|
||||
// --- EXIF orientation ---
|
||||
|
||||
// ExifOrientation возвращает тег 0x0112 из APP1 Exif JPEG (1 — нет поворота).
|
||||
func ExifOrientation(data []byte) int {
|
||||
if len(data) < 4 || data[0] != 0xFF || data[1] != 0xD8 {
|
||||
return 1
|
||||
}
|
||||
i := 2
|
||||
for i+4 <= len(data) && data[i] == 0xFF {
|
||||
marker := data[i+1]
|
||||
if marker == 0xDA || marker == 0xD9 {
|
||||
break
|
||||
}
|
||||
segLen := int(binary.BigEndian.Uint16(data[i+2 : i+4]))
|
||||
if segLen < 2 || i+2+segLen > len(data) {
|
||||
break
|
||||
}
|
||||
seg := data[i+4 : i+2+segLen]
|
||||
if marker == 0xE1 && len(seg) > 14 && string(seg[:6]) == "Exif\x00\x00" {
|
||||
if o := tiffOrientation(seg[6:]); o >= 1 && o <= 8 {
|
||||
return o
|
||||
}
|
||||
}
|
||||
i += 2 + segLen
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
func tiffOrientation(t []byte) int {
|
||||
if len(t) < 8 {
|
||||
return 1
|
||||
}
|
||||
var bo binary.ByteOrder
|
||||
switch string(t[:2]) {
|
||||
case "II":
|
||||
bo = binary.LittleEndian
|
||||
case "MM":
|
||||
bo = binary.BigEndian
|
||||
default:
|
||||
return 1
|
||||
}
|
||||
off := int(bo.Uint32(t[4:8]))
|
||||
if off+2 > len(t) {
|
||||
return 1
|
||||
}
|
||||
n := int(bo.Uint16(t[off : off+2]))
|
||||
for k := 0; k < n; k++ {
|
||||
e := off + 2 + 12*k
|
||||
if e+12 > len(t) {
|
||||
return 1
|
||||
}
|
||||
if bo.Uint16(t[e:e+2]) == 0x0112 {
|
||||
return int(bo.Uint16(t[e+8 : e+10]))
|
||||
}
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
// Orient применяет EXIF orientation 1..8 (поворот/отражение).
|
||||
func Orient(src *image.RGBA, o int) *image.RGBA {
|
||||
if o <= 1 || o > 8 {
|
||||
return src
|
||||
}
|
||||
b := src.Bounds()
|
||||
w, h := b.Dx(), b.Dy()
|
||||
dw, dh := w, h
|
||||
if o >= 5 {
|
||||
dw, dh = h, w
|
||||
}
|
||||
dst := image.NewRGBA(image.Rect(0, 0, dw, dh))
|
||||
for y := 0; y < h; y++ {
|
||||
for x := 0; x < w; x++ {
|
||||
var dx, dy int
|
||||
switch o {
|
||||
case 2:
|
||||
dx, dy = w-1-x, y
|
||||
case 3:
|
||||
dx, dy = w-1-x, h-1-y
|
||||
case 4:
|
||||
dx, dy = x, h-1-y
|
||||
case 5:
|
||||
dx, dy = y, x
|
||||
case 6:
|
||||
dx, dy = h-1-y, x
|
||||
case 7:
|
||||
dx, dy = h-1-y, w-1-x
|
||||
case 8:
|
||||
dx, dy = y, w-1-x
|
||||
}
|
||||
dst.SetRGBA(dx, dy, src.RGBAAt(b.Min.X+x, b.Min.Y+y))
|
||||
}
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
||||
// SHA256Hex — lowercase hex SHA-256.
|
||||
func SHA256Hex(data []byte) string {
|
||||
sum := sha256.Sum256(data)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package imaging
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"os"
|
||||
"os/exec"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func solid(w, h int, c color.Color) *image.NRGBA {
|
||||
m := image.NewNRGBA(image.Rect(0, 0, w, h))
|
||||
for y := 0; y < h; y++ {
|
||||
for x := 0; x < w; x++ {
|
||||
m.Set(x, y, c)
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func encPNG(t *testing.T, img image.Image) []byte {
|
||||
var b bytes.Buffer
|
||||
if err := png.Encode(&b, img); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
func TestFitSize(t *testing.T) {
|
||||
cases := []struct {
|
||||
w, h, box int
|
||||
up bool
|
||||
ww, wh int
|
||||
}{
|
||||
{320, 200, 256, false, 256, 160}, // fixture курса
|
||||
{200, 320, 256, false, 160, 256},
|
||||
{100, 50, 256, false, 100, 50}, // без увеличения
|
||||
{5000, 1, 256, false, 256, 1}, // минимум 1 px
|
||||
{1, 5000, 256, false, 1, 256},
|
||||
{257, 255, 256, false, 256, 254}, // округление вниз
|
||||
{40, 30, 128, true, 128, 96},
|
||||
{3000, 2000, 1280, false, 1280, 853},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if w, h := FitSize(c.w, c.h, c.box, c.up); w != c.ww || h != c.wh {
|
||||
t.Errorf("FitSize(%d,%d,%d,%v)=%d×%d want %d×%d", c.w, c.h, c.box, c.up, w, h, c.ww, c.wh)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func jpegSize(t *testing.T, data []byte) (int, int) {
|
||||
cfg, err := jpeg.DecodeConfig(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return cfg.Width, cfg.Height
|
||||
}
|
||||
|
||||
func TestCourseFixtureThumbnail(t *testing.T) {
|
||||
data, err := os.ReadFile("../../tests/fixtures/sample.png")
|
||||
if err != nil {
|
||||
t.Skip("fixture not found")
|
||||
}
|
||||
img, err := Decode(data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
th, err := Thumbnail(img, ParamsFor(1, 80))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w, h := jpegSize(t, th.Data); w != 256 || h != 160 || th.Width != 256 || th.Height != 160 {
|
||||
t.Fatalf("thumbnail %d×%d (meta %d×%d), want 256×160", w, h, th.Width, th.Height)
|
||||
}
|
||||
again, _ := Thumbnail(img, ParamsFor(1, 80))
|
||||
if !bytes.Equal(th.Data, again.Data) {
|
||||
t.Error("thumbnail encoding is not deterministic")
|
||||
}
|
||||
cr, err := Crop(img, ParamsFor(1, 80))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w, h := jpegSize(t, cr.Data); w != 128 || h != 128 {
|
||||
t.Fatalf("crop %d×%d", w, h)
|
||||
}
|
||||
v2, _ := Thumbnail(img, ParamsFor(2, 80))
|
||||
if bytes.Equal(v2.Data, th.Data) {
|
||||
t.Error("pipeline v2 must produce a different thumbnail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSmallImageNotUpscaledButCropIs(t *testing.T) {
|
||||
img, err := Decode(encPNG(t, solid(40, 30, color.RGBA{10, 20, 30, 255})))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
th, _ := Thumbnail(img, ParamsFor(1, 80))
|
||||
if th.Width != 40 || th.Height != 30 {
|
||||
t.Errorf("small thumbnail upscaled to %d×%d", th.Width, th.Height)
|
||||
}
|
||||
cr, _ := Crop(img, ParamsFor(1, 80))
|
||||
if w, h := jpegSize(t, cr.Data); w != 128 || h != 128 {
|
||||
t.Errorf("crop of small image %d×%d", w, h)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAlphaOnWhite(t *testing.T) {
|
||||
img, err := Decode(encPNG(t, solid(10, 10, color.NRGBA{0, 0, 0, 0})))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c := img.RGBAAt(5, 5); c.R != 255 || c.G != 255 || c.B != 255 {
|
||||
t.Errorf("transparent pixel composited to %v, want white", c)
|
||||
}
|
||||
half, _ := Decode(encPNG(t, solid(4, 4, color.NRGBA{0, 0, 0, 128})))
|
||||
if c := half.RGBAAt(1, 1); c.R < 120 || c.R > 135 {
|
||||
t.Errorf("50%% black over white = %v, want ~127", c)
|
||||
}
|
||||
}
|
||||
|
||||
// withExif вставляет APP1 Exif с orientation сразу после SOI.
|
||||
func withExif(jpg []byte, orientation uint16) []byte {
|
||||
var tiff bytes.Buffer
|
||||
tiff.WriteString("MM\x00\x2a")
|
||||
binary.Write(&tiff, binary.BigEndian, uint32(8))
|
||||
binary.Write(&tiff, binary.BigEndian, uint16(1))
|
||||
binary.Write(&tiff, binary.BigEndian, uint16(0x0112))
|
||||
binary.Write(&tiff, binary.BigEndian, uint16(3))
|
||||
binary.Write(&tiff, binary.BigEndian, uint32(1))
|
||||
binary.Write(&tiff, binary.BigEndian, orientation)
|
||||
tiff.Write([]byte{0, 0})
|
||||
binary.Write(&tiff, binary.BigEndian, uint32(0))
|
||||
seg := append([]byte("Exif\x00\x00"), tiff.Bytes()...)
|
||||
var out bytes.Buffer
|
||||
out.Write(jpg[:2])
|
||||
out.Write([]byte{0xFF, 0xE1})
|
||||
binary.Write(&out, binary.BigEndian, uint16(len(seg)+2))
|
||||
out.Write(seg)
|
||||
out.Write(jpg[2:])
|
||||
return out.Bytes()
|
||||
}
|
||||
|
||||
func TestExifOrientation(t *testing.T) {
|
||||
// 300×100: слева красный, справа синий.
|
||||
src := image.NewRGBA(image.Rect(0, 0, 300, 100))
|
||||
for y := 0; y < 100; y++ {
|
||||
for x := 0; x < 300; x++ {
|
||||
c := color.RGBA{255, 0, 0, 255}
|
||||
if x >= 150 {
|
||||
c = color.RGBA{0, 0, 255, 255}
|
||||
}
|
||||
src.Set(x, y, c)
|
||||
}
|
||||
}
|
||||
var b bytes.Buffer
|
||||
jpeg.Encode(&b, src, &jpeg.Options{Quality: 95})
|
||||
data := withExif(b.Bytes(), 6) // 90° по часовой
|
||||
if o := ExifOrientation(data); o != 6 {
|
||||
t.Fatalf("orientation %d, want 6", o)
|
||||
}
|
||||
img, err := Decode(data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if img.Bounds().Dx() != 100 || img.Bounds().Dy() != 300 {
|
||||
t.Fatalf("rotated size %v, want 100×300", img.Bounds())
|
||||
}
|
||||
// После поворота на 90° по часовой левая (красная) половина оказывается сверху.
|
||||
if c := img.RGBAAt(50, 20); c.R < 200 || c.B > 60 {
|
||||
t.Errorf("top after rotation = %v, want red", c)
|
||||
}
|
||||
th, _ := Thumbnail(img, ParamsFor(1, 80))
|
||||
if th.Width != 85 || th.Height != 256 {
|
||||
t.Errorf("thumbnail of rotated %d×%d, want 85×256", th.Width, th.Height)
|
||||
}
|
||||
if ExifOrientation(b.Bytes()) != 1 {
|
||||
t.Error("no exif must mean orientation 1")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeGarbage(t *testing.T) {
|
||||
if _, err := Decode([]byte("not an image")); err == nil {
|
||||
t.Fatal("garbage decoded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOptimizedWebP(t *testing.T) {
|
||||
if _, err := exec.LookPath("cwebp"); err != nil {
|
||||
t.Skip("cwebp not installed (worker image has libwebp-tools)")
|
||||
}
|
||||
img, _ := Decode(encPNG(t, solid(2000, 1000, color.RGBA{200, 100, 50, 255})))
|
||||
out, err := Optimized(context.Background(), img, ParamsFor(1, 80), CWebP)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out.Width != 1280 || out.Height != 640 || out.ContentType != "image/webp" {
|
||||
t.Fatalf("optimized %+v", out)
|
||||
}
|
||||
again, _ := Optimized(context.Background(), img, ParamsFor(1, 80), CWebP)
|
||||
if !bytes.Equal(out.Data, again.Data) {
|
||||
t.Error("cwebp output not deterministic")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,404 @@
|
||||
// Package reconcile сверяет метаданные вложений (PostgreSQL) и объекты (S3).
|
||||
//
|
||||
// Обход — один merge-проход по двум потокам, отсортированным одинаково
|
||||
// (object_key COLLATE "C" и лексикографический листинг S3), поэтому память
|
||||
// O(1) от числа вложений, а стоимость — O(N) строк + ceil(N/1000) LIST-запросов.
|
||||
//
|
||||
// Расхождения и безопасные действия:
|
||||
//
|
||||
// stale_intent строка uploading старше grace (брошенная загрузка) → удалить объект, затем строку
|
||||
// orphan_object объект без строки, старше grace → удалить объект (после перепроверки строки)
|
||||
// missing_object строка ready без объекта → карантин: status=missing (после перепроверки Stat)
|
||||
// size_mismatch строка ready, размер объекта другой → карантин: status=missing
|
||||
// restored строка missing, объект снова есть и размер совпадает → status=ready
|
||||
// purge_missing строка missing старше grace, ни одно сообщение не ссылается → удалить строку
|
||||
// missing_variant у ready-варианта нет объекта → только отчёт (без автоисправления)
|
||||
//
|
||||
// С lab5 вложения в queued/processing/failed и их staging принадлежат pipeline
|
||||
// (lease, retry, retention): reconciler их не трогает. Объекты без строки
|
||||
// (например, частичные результаты попытки, закончившейся failed) удаляются как
|
||||
// orphan после grace — так же, как в lab4.
|
||||
//
|
||||
// Свежие объекты и намерения (моложе grace) и вложения, на которые ссылаются
|
||||
// сообщения, не удаляются никогда. Режим по умолчанию — dry-run (только отчёт).
|
||||
package reconcile
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab5/internal/storage"
|
||||
)
|
||||
|
||||
// Repo — нужные reconciler операции над метаданными.
|
||||
type Repo interface {
|
||||
StreamByKey(ctx context.Context, prefix string, fn func(*domain.Attachment) error) error
|
||||
HasKey(ctx context.Context, key string) (bool, error)
|
||||
DeleteStaleIntent(ctx context.Context, id string, cutoff time.Time) (bool, error)
|
||||
SetStatus(ctx context.Context, id, from, to string) (bool, error)
|
||||
DeleteUnreferencedMissing(ctx context.Context, id string, cutoff time.Time) (bool, error)
|
||||
IsReferenced(ctx context.Context, id string) (bool, error)
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
Prefix string
|
||||
Grace time.Duration
|
||||
Apply bool
|
||||
Now time.Time // общий «сейчас» для строк и объектов (время БД)
|
||||
// MaxItems ограничивает список примеров в отчёте на каждый вид расхождения.
|
||||
MaxItems int
|
||||
}
|
||||
|
||||
type Item struct {
|
||||
Kind string `json:"kind"`
|
||||
Key string `json:"key"`
|
||||
AttachmentID string `json:"attachment_id,omitempty"`
|
||||
Action string `json:"action"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
}
|
||||
|
||||
type Report struct {
|
||||
DryRun bool `json:"dry_run"`
|
||||
GraceSeconds float64 `json:"grace_seconds"`
|
||||
Cutoff time.Time `json:"cutoff"`
|
||||
DurationMS int64 `json:"duration_ms"`
|
||||
RowsScanned int `json:"rows_scanned"`
|
||||
ObjectsScanned int `json:"objects_scanned"`
|
||||
Consistent int `json:"consistent"`
|
||||
Found map[string]int `json:"found"`
|
||||
Fixed map[string]int `json:"fixed"`
|
||||
Skipped map[string]int `json:"skipped"`
|
||||
Calls map[string]int `json:"calls"`
|
||||
HeapAllocMB float64 `json:"heap_alloc_mb"`
|
||||
// WaitMS — сколько merge-цикл простоял в ожидании очередного элемента каждого
|
||||
// потока: показывает, кто (S3-листинг или запрос к БД) задаёт время обхода.
|
||||
WaitMS map[string]int64 `json:"wait_ms"`
|
||||
Errors []string `json:"errors"`
|
||||
Items []Item `json:"items"`
|
||||
}
|
||||
|
||||
type reconciler struct {
|
||||
repo Repo
|
||||
store storage.Store
|
||||
opt Options
|
||||
rep *Report
|
||||
items map[string]int
|
||||
}
|
||||
|
||||
func (r *reconciler) note(kind string, it Item) {
|
||||
r.rep.Found[kind]++
|
||||
if r.items[kind] < r.opt.MaxItems {
|
||||
r.items[kind]++
|
||||
r.rep.Items = append(r.rep.Items, it)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *reconciler) fail(format string, args ...any) {
|
||||
if len(r.rep.Errors) < 100 {
|
||||
r.rep.Errors = append(r.rep.Errors, fmt.Sprintf(format, args...))
|
||||
}
|
||||
}
|
||||
|
||||
// Run выполняет один проход. Ошибки отдельных действий попадают в отчёт и не
|
||||
// прерывают обход; ошибка листинга/запроса прерывает проход целиком.
|
||||
func Run(ctx context.Context, repo Repo, store storage.Store, opt Options) (*Report, error) {
|
||||
start := time.Now()
|
||||
if opt.MaxItems == 0 {
|
||||
opt.MaxItems = 50
|
||||
}
|
||||
cutoff := opt.Now.Add(-opt.Grace)
|
||||
rep := &Report{
|
||||
DryRun: !opt.Apply, GraceSeconds: opt.Grace.Seconds(), Cutoff: cutoff,
|
||||
Found: map[string]int{}, Fixed: map[string]int{}, Skipped: map[string]int{}, Calls: map[string]int{},
|
||||
Errors: []string{}, Items: []Item{}, WaitMS: map[string]int64{},
|
||||
}
|
||||
rc := &reconciler{repo: repo, store: store, opt: opt, rep: rep, items: map[string]int{}}
|
||||
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
|
||||
objs := make(chan storage.Object, 512)
|
||||
objErr := make(chan error, 1)
|
||||
go func() {
|
||||
defer close(objs)
|
||||
objErr <- store.List(ctx, opt.Prefix, func(o storage.Object) error {
|
||||
select {
|
||||
case objs <- o:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
})
|
||||
}()
|
||||
rows := make(chan *domain.Attachment, 512)
|
||||
rowErr := make(chan error, 1)
|
||||
go func() {
|
||||
defer close(rows)
|
||||
rowErr <- repo.StreamByKey(ctx, opt.Prefix, func(a *domain.Attachment) error {
|
||||
select {
|
||||
case rows <- a:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
})
|
||||
}()
|
||||
|
||||
var waitS3, waitDB time.Duration
|
||||
nextObj := func() (storage.Object, bool) {
|
||||
t := time.Now()
|
||||
o, ok := <-objs
|
||||
waitS3 += time.Since(t)
|
||||
return o, ok
|
||||
}
|
||||
nextRow := func() (*domain.Attachment, bool) {
|
||||
t := time.Now()
|
||||
a, ok := <-rows
|
||||
waitDB += time.Since(t)
|
||||
return a, ok
|
||||
}
|
||||
o, okO := nextObj()
|
||||
a, okA := nextRow()
|
||||
for okO || okA {
|
||||
switch {
|
||||
case okA && (!okO || a.ObjectKey < o.Key):
|
||||
rep.RowsScanned++
|
||||
rc.rowWithoutObject(ctx, a, cutoff)
|
||||
a, okA = nextRow()
|
||||
case okO && (!okA || o.Key < a.ObjectKey):
|
||||
rep.ObjectsScanned++
|
||||
rc.objectWithoutRow(ctx, o, cutoff)
|
||||
o, okO = nextObj()
|
||||
default:
|
||||
rep.RowsScanned++
|
||||
rep.ObjectsScanned++
|
||||
rc.both(ctx, a, o, cutoff)
|
||||
a, okA = nextRow()
|
||||
o, okO = nextObj()
|
||||
}
|
||||
}
|
||||
rep.WaitMS["s3_list"] = waitS3.Milliseconds()
|
||||
rep.WaitMS["db_stream"] = waitDB.Milliseconds()
|
||||
if err := <-objErr; err != nil {
|
||||
return rep, fmt.Errorf("list objects: %w", err)
|
||||
}
|
||||
if err := <-rowErr; err != nil {
|
||||
return rep, fmt.Errorf("stream rows: %w", err)
|
||||
}
|
||||
rep.Calls["s3_list_pages"] = (rep.ObjectsScanned + 999) / 1000
|
||||
var ms runtime.MemStats
|
||||
runtime.ReadMemStats(&ms)
|
||||
rep.HeapAllocMB = float64(ms.HeapAlloc) / (1 << 20)
|
||||
rep.DurationMS = time.Since(start).Milliseconds()
|
||||
return rep, nil
|
||||
}
|
||||
|
||||
func (r *reconciler) rowWithoutObject(ctx context.Context, a *domain.Attachment, cutoff time.Time) {
|
||||
switch a.Status {
|
||||
case "variant":
|
||||
if r.objectExists(ctx, a.ObjectKey) {
|
||||
r.rep.Skipped["recheck_object_present"]++
|
||||
return
|
||||
}
|
||||
r.note("missing_variant", Item{Kind: "missing_variant", Key: a.ObjectKey, AttachmentID: a.ID, Action: "report"})
|
||||
case "staging", domain.AttachmentQueued, domain.AttachmentProcessing, domain.AttachmentFailed:
|
||||
r.rep.Skipped["owned_by_pipeline"]++
|
||||
case domain.AttachmentUploading:
|
||||
if !a.UpdatedAt.Before(cutoff) {
|
||||
r.rep.Skipped["fresh_intent"]++ // загрузка может быть в процессе
|
||||
return
|
||||
}
|
||||
r.staleIntent(ctx, a, false)
|
||||
case domain.AttachmentReady:
|
||||
// Листинг мог начаться раньше, чем объект записан: перепроверяем точечно.
|
||||
if r.objectExists(ctx, a.ObjectKey) {
|
||||
r.rep.Skipped["recheck_object_present"]++
|
||||
return
|
||||
}
|
||||
r.quarantine(ctx, a, "missing_object", "")
|
||||
case domain.AttachmentMissing:
|
||||
r.purgeMissing(ctx, a, cutoff)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *reconciler) objectWithoutRow(ctx context.Context, o storage.Object, cutoff time.Time) {
|
||||
if !o.LastModified.Before(cutoff) {
|
||||
r.rep.Skipped["fresh_object"]++
|
||||
return
|
||||
}
|
||||
// Строка могла появиться после начала обхода — перепроверяем перед удалением.
|
||||
r.rep.Calls["db_haskey"]++
|
||||
has, err := r.repo.HasKey(ctx, o.Key)
|
||||
if err != nil {
|
||||
r.fail("haskey %s: %v", o.Key, err)
|
||||
return
|
||||
}
|
||||
if has {
|
||||
r.rep.Skipped["recheck_row_present"]++
|
||||
return
|
||||
}
|
||||
it := Item{Kind: "orphan_object", Key: o.Key, Action: "delete_object",
|
||||
Detail: fmt.Sprintf("size=%d modified=%s", o.Size, o.LastModified.UTC().Format(time.RFC3339))}
|
||||
if !r.opt.Apply {
|
||||
it.Action = "would_delete_object"
|
||||
r.note("orphan_object", it)
|
||||
return
|
||||
}
|
||||
r.rep.Calls["s3_delete"]++
|
||||
if err := r.store.Delete(ctx, o.Key); err != nil {
|
||||
r.fail("delete orphan %s: %v", o.Key, err)
|
||||
return
|
||||
}
|
||||
r.note("orphan_object", it)
|
||||
r.rep.Fixed["orphan_object"]++
|
||||
}
|
||||
|
||||
func (r *reconciler) both(ctx context.Context, a *domain.Attachment, o storage.Object, cutoff time.Time) {
|
||||
switch a.Status {
|
||||
case "variant":
|
||||
if o.Size != a.SizeBytes {
|
||||
r.note("variant_size_mismatch", Item{Kind: "variant_size_mismatch", Key: a.ObjectKey, AttachmentID: a.ID,
|
||||
Action: "report", Detail: fmt.Sprintf("db=%d s3=%d", a.SizeBytes, o.Size)})
|
||||
return
|
||||
}
|
||||
r.rep.Consistent++
|
||||
case "staging", domain.AttachmentQueued, domain.AttachmentProcessing, domain.AttachmentFailed:
|
||||
r.rep.Consistent++
|
||||
case domain.AttachmentUploading:
|
||||
if !a.UpdatedAt.Before(cutoff) {
|
||||
r.rep.Skipped["fresh_intent"]++
|
||||
return
|
||||
}
|
||||
r.staleIntent(ctx, a, true)
|
||||
case domain.AttachmentReady:
|
||||
if o.Size != a.SizeBytes {
|
||||
r.quarantine(ctx, a, "size_mismatch", fmt.Sprintf("db=%d s3=%d", a.SizeBytes, o.Size))
|
||||
return
|
||||
}
|
||||
r.rep.Consistent++
|
||||
case domain.AttachmentMissing:
|
||||
if o.Size != a.SizeBytes {
|
||||
r.purgeMissing(ctx, a, cutoff)
|
||||
return
|
||||
}
|
||||
it := Item{Kind: "restored", Key: a.ObjectKey, AttachmentID: a.ID, Action: "set_ready"}
|
||||
if !r.opt.Apply {
|
||||
it.Action = "would_set_ready"
|
||||
r.note("restored", it)
|
||||
return
|
||||
}
|
||||
r.rep.Calls["db_update"]++
|
||||
ok, err := r.repo.SetStatus(ctx, a.ID, domain.AttachmentMissing, domain.AttachmentReady)
|
||||
if err != nil {
|
||||
r.fail("restore %s: %v", a.ID, err)
|
||||
return
|
||||
}
|
||||
r.note("restored", it)
|
||||
if ok {
|
||||
r.rep.Fixed["restored"]++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *reconciler) objectExists(ctx context.Context, key string) bool {
|
||||
r.rep.Calls["s3_stat"]++
|
||||
_, err := r.store.Stat(ctx, key)
|
||||
if err == nil {
|
||||
return true
|
||||
}
|
||||
if !errors.Is(err, storage.ErrNotFound) {
|
||||
r.fail("stat %s: %v", key, err)
|
||||
return true // при ошибке хранилища ничего не трогаем
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (r *reconciler) staleIntent(ctx context.Context, a *domain.Attachment, hasObject bool) {
|
||||
it := Item{Kind: "stale_intent", Key: a.ObjectKey, AttachmentID: a.ID, Action: "delete_intent",
|
||||
Detail: "updated_at=" + a.UpdatedAt.UTC().Format(time.RFC3339)}
|
||||
if hasObject {
|
||||
it.Action = "delete_object_and_intent"
|
||||
}
|
||||
if !r.opt.Apply {
|
||||
it.Action = "would_" + it.Action
|
||||
r.note("stale_intent", it)
|
||||
return
|
||||
}
|
||||
// Сначала объект: если упадём между шагами, останется намерение без объекта,
|
||||
// и следующий проход его доберёт (обратный порядок оставил бы сироту без учёта).
|
||||
if hasObject {
|
||||
r.rep.Calls["s3_delete"]++
|
||||
if err := r.store.Delete(ctx, a.ObjectKey); err != nil {
|
||||
r.fail("delete intent object %s: %v", a.ObjectKey, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
r.rep.Calls["db_delete"]++
|
||||
ok, err := r.repo.DeleteStaleIntent(ctx, a.ID, r.opt.Now.Add(-r.opt.Grace))
|
||||
if err != nil {
|
||||
r.fail("delete intent %s: %v", a.ID, err)
|
||||
return
|
||||
}
|
||||
r.note("stale_intent", it)
|
||||
if ok {
|
||||
r.rep.Fixed["stale_intent"]++
|
||||
}
|
||||
}
|
||||
|
||||
func (r *reconciler) quarantine(ctx context.Context, a *domain.Attachment, kind, detail string) {
|
||||
it := Item{Kind: kind, Key: a.ObjectKey, AttachmentID: a.ID, Action: "quarantine", Detail: detail}
|
||||
if !r.opt.Apply {
|
||||
it.Action = "would_quarantine"
|
||||
r.note(kind, it)
|
||||
return
|
||||
}
|
||||
r.rep.Calls["db_update"]++
|
||||
ok, err := r.repo.SetStatus(ctx, a.ID, domain.AttachmentReady, domain.AttachmentMissing)
|
||||
if err != nil {
|
||||
r.fail("quarantine %s: %v", a.ID, err)
|
||||
return
|
||||
}
|
||||
r.note(kind, it)
|
||||
if ok {
|
||||
r.rep.Fixed[kind]++
|
||||
}
|
||||
}
|
||||
|
||||
// purgeMissing удаляет запись карантина, только если она старше grace и на неё
|
||||
// не ссылается ни одно сообщение. Используемые вложения остаются (их история цела).
|
||||
func (r *reconciler) purgeMissing(ctx context.Context, a *domain.Attachment, cutoff time.Time) {
|
||||
if !a.UpdatedAt.Before(cutoff) {
|
||||
r.rep.Skipped["fresh_missing"]++
|
||||
return
|
||||
}
|
||||
r.rep.Calls["db_referenced"]++
|
||||
ref, err := r.repo.IsReferenced(ctx, a.ID)
|
||||
if err != nil {
|
||||
r.fail("referenced %s: %v", a.ID, err)
|
||||
return
|
||||
}
|
||||
if ref {
|
||||
r.rep.Skipped["referenced_missing_kept"]++
|
||||
return
|
||||
}
|
||||
it := Item{Kind: "purge_missing", Key: a.ObjectKey, AttachmentID: a.ID, Action: "delete_row"}
|
||||
if !r.opt.Apply {
|
||||
it.Action = "would_delete_row"
|
||||
r.note("purge_missing", it)
|
||||
return
|
||||
}
|
||||
r.rep.Calls["db_delete"]++
|
||||
ok, err := r.repo.DeleteUnreferencedMissing(ctx, a.ID, cutoff)
|
||||
if err != nil {
|
||||
r.fail("purge %s: %v", a.ID, err)
|
||||
return
|
||||
}
|
||||
r.note("purge_missing", it)
|
||||
if ok {
|
||||
r.rep.Fixed["purge_missing"]++
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package reconcile
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"sort"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab5/internal/storage"
|
||||
)
|
||||
|
||||
type fakeStore struct{ objs map[string]storage.Object }
|
||||
|
||||
func (f *fakeStore) Put(_ context.Context, key string, r io.Reader, size int64, _ string) error {
|
||||
f.objs[key] = storage.Object{Key: key, Size: size, LastModified: time.Now()}
|
||||
return nil
|
||||
}
|
||||
func (f *fakeStore) Get(context.Context, string) (io.ReadCloser, int64, error) {
|
||||
return io.NopCloser(bytes.NewReader(nil)), 0, nil
|
||||
}
|
||||
func (f *fakeStore) Stat(_ context.Context, key string) (storage.Object, error) {
|
||||
o, ok := f.objs[key]
|
||||
if !ok {
|
||||
return o, storage.ErrNotFound
|
||||
}
|
||||
return o, nil
|
||||
}
|
||||
func (f *fakeStore) Delete(_ context.Context, key string) error { delete(f.objs, key); return nil }
|
||||
func (f *fakeStore) Copy(_ context.Context, src, dst string) error {
|
||||
o, ok := f.objs[src]
|
||||
if !ok {
|
||||
return storage.ErrNotFound
|
||||
}
|
||||
o.Key = dst
|
||||
f.objs[dst] = o
|
||||
return nil
|
||||
}
|
||||
func (f *fakeStore) List(_ context.Context, prefix string, fn func(storage.Object) error) error {
|
||||
keys := make([]string, 0, len(f.objs))
|
||||
for k := range f.objs {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, k := range keys {
|
||||
if err := fn(f.objs[k]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeRepo struct {
|
||||
rows map[string]*domain.Attachment // by id
|
||||
refs map[string]bool
|
||||
}
|
||||
|
||||
func (f *fakeRepo) StreamByKey(_ context.Context, _ string, fn func(*domain.Attachment) error) error {
|
||||
list := make([]*domain.Attachment, 0, len(f.rows))
|
||||
for _, a := range f.rows {
|
||||
c := *a
|
||||
list = append(list, &c)
|
||||
}
|
||||
sort.Slice(list, func(i, j int) bool { return list[i].ObjectKey < list[j].ObjectKey })
|
||||
for _, a := range list {
|
||||
if err := fn(a); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (f *fakeRepo) HasKey(_ context.Context, key string) (bool, error) {
|
||||
for _, a := range f.rows {
|
||||
if a.ObjectKey == key {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
func (f *fakeRepo) DeleteStaleIntent(_ context.Context, id string, cutoff time.Time) (bool, error) {
|
||||
a, ok := f.rows[id]
|
||||
if !ok || a.Status != domain.AttachmentUploading || !a.UpdatedAt.Before(cutoff) {
|
||||
return false, nil
|
||||
}
|
||||
delete(f.rows, id)
|
||||
return true, nil
|
||||
}
|
||||
func (f *fakeRepo) SetStatus(_ context.Context, id, from, to string) (bool, error) {
|
||||
a, ok := f.rows[id]
|
||||
if !ok || a.Status != from {
|
||||
return false, nil
|
||||
}
|
||||
a.Status = to
|
||||
a.UpdatedAt = now
|
||||
return true, nil
|
||||
}
|
||||
func (f *fakeRepo) DeleteUnreferencedMissing(_ context.Context, id string, cutoff time.Time) (bool, error) {
|
||||
a, ok := f.rows[id]
|
||||
if !ok || a.Status != domain.AttachmentMissing || !a.UpdatedAt.Before(cutoff) || f.refs[id] {
|
||||
return false, nil
|
||||
}
|
||||
delete(f.rows, id)
|
||||
return true, nil
|
||||
}
|
||||
func (f *fakeRepo) IsReferenced(_ context.Context, id string) (bool, error) { return f.refs[id], nil }
|
||||
|
||||
var now = time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
const grace = time.Hour
|
||||
|
||||
func old() time.Time { return now.Add(-2 * grace) }
|
||||
func fresh() time.Time { return now.Add(-time.Minute) }
|
||||
|
||||
func setup() (*fakeRepo, *fakeStore) {
|
||||
r := &fakeRepo{rows: map[string]*domain.Attachment{}, refs: map[string]bool{}}
|
||||
s := &fakeStore{objs: map[string]storage.Object{}}
|
||||
row := func(id, status string, size int64, at time.Time) {
|
||||
r.rows[id] = &domain.Attachment{ID: id, ObjectKey: "a/c/" + id, Status: status, SizeBytes: size, UpdatedAt: at}
|
||||
}
|
||||
obj := func(id string, size int64, at time.Time) {
|
||||
s.objs["a/c/"+id] = storage.Object{Key: "a/c/" + id, Size: size, LastModified: at}
|
||||
}
|
||||
// согласованное
|
||||
row("ok", domain.AttachmentReady, 10, old())
|
||||
obj("ok", 10, old())
|
||||
// брошенная загрузка с объектом и без
|
||||
row("stale1", domain.AttachmentUploading, 0, old())
|
||||
obj("stale1", 7, old())
|
||||
row("stale2", domain.AttachmentUploading, 0, old())
|
||||
// загрузка в процессе — не трогать
|
||||
row("inflight", domain.AttachmentUploading, 0, fresh())
|
||||
obj("inflight", 5, fresh())
|
||||
// сирота старая и свежая
|
||||
obj("orphan", 3, old())
|
||||
obj("orphan-fresh", 3, fresh())
|
||||
// ready без объекта: используемое и нет
|
||||
row("lost-used", domain.AttachmentReady, 9, old())
|
||||
r.refs["lost-used"] = true
|
||||
row("lost-free", domain.AttachmentReady, 9, old())
|
||||
// подменённый размер
|
||||
row("resized", domain.AttachmentReady, 10, old())
|
||||
obj("resized", 11, old())
|
||||
return r, s
|
||||
}
|
||||
|
||||
func run(t *testing.T, r *fakeRepo, s *fakeStore, apply bool, at time.Time) *Report {
|
||||
t.Helper()
|
||||
rep, err := Run(context.Background(), r, s, Options{Prefix: "a/", Grace: grace, Apply: apply, Now: at})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rep.Errors) > 0 {
|
||||
t.Fatalf("errors: %v", rep.Errors)
|
||||
}
|
||||
return rep
|
||||
}
|
||||
|
||||
func TestDryRunChangesNothing(t *testing.T) {
|
||||
r, s := setup()
|
||||
nRows, nObjs := len(r.rows), len(s.objs)
|
||||
rep := run(t, r, s, false, now)
|
||||
if len(r.rows) != nRows || len(s.objs) != nObjs || r.rows["lost-free"].Status != domain.AttachmentReady {
|
||||
t.Fatal("dry-run mutated state")
|
||||
}
|
||||
want := map[string]int{"stale_intent": 2, "orphan_object": 1, "missing_object": 2, "size_mismatch": 1}
|
||||
for k, v := range want {
|
||||
if rep.Found[k] != v {
|
||||
t.Errorf("found[%s]=%d want %d (%v)", k, rep.Found[k], v, rep.Found)
|
||||
}
|
||||
}
|
||||
if len(rep.Fixed) != 0 {
|
||||
t.Errorf("dry-run fixed %v", rep.Fixed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyFixesAndIsIdempotent(t *testing.T) {
|
||||
r, s := setup()
|
||||
run(t, r, s, true, now)
|
||||
|
||||
for _, id := range []string{"stale1", "stale2"} {
|
||||
if _, ok := r.rows[id]; ok {
|
||||
t.Errorf("stale intent %s not removed", id)
|
||||
}
|
||||
}
|
||||
if _, ok := s.objs["a/c/stale1"]; ok {
|
||||
t.Error("stale intent object not removed")
|
||||
}
|
||||
if _, ok := s.objs["a/c/orphan"]; ok {
|
||||
t.Error("old orphan not removed")
|
||||
}
|
||||
// Свежие — никогда.
|
||||
if _, ok := s.objs["a/c/orphan-fresh"]; !ok {
|
||||
t.Error("fresh orphan deleted")
|
||||
}
|
||||
if _, ok := r.rows["inflight"]; !ok {
|
||||
t.Error("in-flight intent deleted")
|
||||
}
|
||||
if _, ok := s.objs["a/c/inflight"]; !ok {
|
||||
t.Error("in-flight object deleted")
|
||||
}
|
||||
for _, id := range []string{"lost-used", "lost-free", "resized"} {
|
||||
if r.rows[id].Status != domain.AttachmentMissing {
|
||||
t.Errorf("%s not quarantined", id)
|
||||
}
|
||||
}
|
||||
if r.rows["ok"].Status != domain.AttachmentReady {
|
||||
t.Error("consistent row touched")
|
||||
}
|
||||
|
||||
// Повтор сразу: исправлять нечего, карантин ещё моложе grace.
|
||||
rep := run(t, r, s, true, now)
|
||||
if len(rep.Fixed) != 0 {
|
||||
t.Errorf("second pass fixed %v", rep.Fixed)
|
||||
}
|
||||
|
||||
// Через grace: неиспользуемая запись карантина удаляется, используемая остаётся.
|
||||
later := now.Add(2 * grace)
|
||||
run(t, r, s, true, later)
|
||||
if _, ok := r.rows["lost-free"]; ok {
|
||||
t.Error("unreferenced missing row not purged")
|
||||
}
|
||||
if _, ok := r.rows["lost-used"]; !ok {
|
||||
t.Error("referenced missing row deleted")
|
||||
}
|
||||
if _, ok := s.objs["a/c/orphan-fresh"]; ok {
|
||||
t.Error("orphan not removed after grace")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoredObjectLeavesQuarantine(t *testing.T) {
|
||||
r, s := setup()
|
||||
run(t, r, s, true, now)
|
||||
// Объект вернули (например, из бэкапа) с правильным размером.
|
||||
s.objs["a/c/lost-used"] = storage.Object{Key: "a/c/lost-used", Size: 9, LastModified: now}
|
||||
rep := run(t, r, s, true, now)
|
||||
if rep.Fixed["restored"] != 1 || r.rows["lost-used"].Status != domain.AttachmentReady {
|
||||
t.Errorf("restore failed: %v %s", rep.Fixed, r.rows["lost-used"].Status)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab5/internal/repository"
|
||||
)
|
||||
|
||||
type AttachmentRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewAttachmentRepository(pool *pgxpool.Pool) *AttachmentRepository {
|
||||
return &AttachmentRepository{pool: pool}
|
||||
}
|
||||
|
||||
const attachmentColumns = `id, chat_id, owner_id, filename, object_key, status,
|
||||
COALESCE(content_type, ''), COALESCE(size_bytes, 0), COALESCE(sha256, ''), created_at, updated_at,
|
||||
COALESCE(error_code, ''), pipeline_version, COALESCE(staging_key, '')`
|
||||
|
||||
func scanAttachment(row pgx.Row) (*domain.Attachment, error) {
|
||||
var a domain.Attachment
|
||||
err := row.Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ObjectKey, &a.Status,
|
||||
&a.ContentType, &a.SizeBytes, &a.SHA256, &a.CreatedAt, &a.UpdatedAt,
|
||||
&a.ErrorCode, &a.PipelineVersion, &a.StagingKey)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
// CreateIntent записывает намерение загрузки (status=uploading) ДО записи в S3.
|
||||
func (r *AttachmentRepository) CreateIntent(ctx context.Context, a *domain.Attachment) error {
|
||||
const q = `
|
||||
INSERT INTO attachments (id, chat_id, owner_id, filename, object_key, staging_key, status, created_at, updated_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5, $5, 'uploading', $6, $6)
|
||||
`
|
||||
if _, err := r.pool.Exec(ctx, q, a.ID, a.ChatID, a.OwnerID, a.Filename, a.ObjectKey, a.CreatedAt); err != nil {
|
||||
return fmt.Errorf("insert attachment intent: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarkQueued — точка 202. В ОДНОЙ транзакции: метаданные проверенного оригинала
|
||||
// и status=queued, логическое задание (jobs) и сообщение для broker (outbox).
|
||||
// После COMMIT работа не теряется: даже если broker недоступен или relay упал,
|
||||
// outbox будет опубликован позже. Если строки uploading уже нет — ErrNotFound.
|
||||
func (r *AttachmentRepository) MarkQueued(ctx context.Context, a *domain.Attachment, pipelineVersion, maxAttempts int) (string, error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("begin tx: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
const q = `
|
||||
UPDATE attachments
|
||||
SET status = 'queued', content_type = $2, size_bytes = $3, sha256 = $4, updated_at = $5
|
||||
WHERE id = $1::uuid AND status = 'uploading'
|
||||
`
|
||||
tag, err := tx.Exec(ctx, q, a.ID, a.ContentType, a.SizeBytes, a.SHA256, a.UpdatedAt)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("mark attachment queued: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return "", repository.ErrNotFound
|
||||
}
|
||||
jobID, err := EnqueueJobTx(ctx, tx, a.ID, pipelineVersion, maxAttempts, "upload")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return "", fmt.Errorf("commit tx: %w", err)
|
||||
}
|
||||
return jobID, nil
|
||||
}
|
||||
|
||||
// Variants — варианты указанной версии pipeline.
|
||||
func (r *AttachmentRepository) Variants(ctx context.Context, attachmentID string, version int) ([]domain.Variant, error) {
|
||||
const q = `
|
||||
SELECT name, content_type, size_bytes, width, height, sha256, object_key, pipeline_version
|
||||
FROM attachment_variants
|
||||
WHERE attachment_id = $1::uuid AND pipeline_version = $2
|
||||
ORDER BY CASE name WHEN 'thumbnail' THEN 1 WHEN 'crop' THEN 2 ELSE 3 END
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, attachmentID, version)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("select variants: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []domain.Variant{}
|
||||
for rows.Next() {
|
||||
var v domain.Variant
|
||||
if err := rows.Scan(&v.Name, &v.ContentType, &v.SizeBytes, &v.Width, &v.Height, &v.SHA256, &v.ObjectKey, &v.PipelineVersion); err != nil {
|
||||
return nil, fmt.Errorf("scan variant: %w", err)
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// DeleteIntent убирает намерение, если загрузка не удалась (компенсация).
|
||||
func (r *AttachmentRepository) DeleteIntent(ctx context.Context, id string) error {
|
||||
const q = `DELETE FROM attachments WHERE id = $1::uuid AND status = 'uploading'`
|
||||
if _, err := r.pool.Exec(ctx, q, id); err != nil {
|
||||
return fmt.Errorf("delete attachment intent: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetForMember возвращает вложение, если пользователь — участник его чата.
|
||||
// Чужое и несуществующее вложение неразличимы (ErrNotFound).
|
||||
func (r *AttachmentRepository) GetForMember(ctx context.Context, id, userID string) (*domain.Attachment, error) {
|
||||
q := `SELECT ` + attachmentColumns + `
|
||||
FROM attachments a
|
||||
WHERE a.id = $1::uuid
|
||||
AND EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = a.chat_id AND m.user_id = $2::uuid)`
|
||||
a, err := scanAttachment(r.pool.QueryRow(ctx, q, id, userID))
|
||||
if err != nil && !errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, fmt.Errorf("select attachment: %w", err)
|
||||
}
|
||||
return a, err
|
||||
}
|
||||
|
||||
// --- для reconciler ---
|
||||
|
||||
// StreamByKey отдаёт все известные БД ключи объектов в байтовом порядке (как
|
||||
// ListObjectsV2): оригинал вложения (object_key), отдельный staging-объект и
|
||||
// объекты вариантов. Для staging и вариантов Status — «staging»/«variant», чтобы
|
||||
// reconciler не путал их с оригиналом.
|
||||
func (r *AttachmentRepository) StreamByKey(ctx context.Context, prefix string, fn func(*domain.Attachment) error) error {
|
||||
const q = `
|
||||
SELECT key, id::text, status, size_bytes, updated_at FROM (
|
||||
SELECT object_key AS key, id, status, COALESCE(size_bytes, 0) AS size_bytes, updated_at FROM attachments
|
||||
UNION ALL
|
||||
SELECT staging_key, id, 'staging', COALESCE(size_bytes, 0), updated_at FROM attachments
|
||||
WHERE staging_key IS NOT NULL AND staging_key <> object_key
|
||||
UNION ALL
|
||||
SELECT object_key, attachment_id, 'variant', size_bytes, created_at FROM attachment_variants
|
||||
) k
|
||||
WHERE starts_with(key, $1)
|
||||
ORDER BY key COLLATE "C"`
|
||||
rows, err := r.pool.Query(ctx, q, prefix)
|
||||
if err != nil {
|
||||
return fmt.Errorf("stream object keys: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var a domain.Attachment
|
||||
if err := rows.Scan(&a.ObjectKey, &a.ID, &a.Status, &a.SizeBytes, &a.UpdatedAt); err != nil {
|
||||
return fmt.Errorf("scan object key: %w", err)
|
||||
}
|
||||
if err := fn(&a); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return rows.Err()
|
||||
}
|
||||
|
||||
// HasKey — есть ли строка с этим object_key (повторная проверка перед удалением объекта).
|
||||
func (r *AttachmentRepository) HasKey(ctx context.Context, key string) (bool, error) {
|
||||
var ok bool
|
||||
err := r.pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM attachments WHERE object_key = $1 OR staging_key = $1)
|
||||
OR EXISTS (SELECT 1 FROM attachment_variants WHERE object_key = $1)`, key).Scan(&ok)
|
||||
return ok, err
|
||||
}
|
||||
|
||||
// DeleteStaleIntent удаляет намерение, только если оно всё ещё uploading и старше cutoff.
|
||||
func (r *AttachmentRepository) DeleteStaleIntent(ctx context.Context, id string, cutoff time.Time) (bool, error) {
|
||||
const q = `DELETE FROM attachments WHERE id = $1::uuid AND status = 'uploading' AND updated_at < $2`
|
||||
tag, err := r.pool.Exec(ctx, q, id, cutoff)
|
||||
return tag.RowsAffected() == 1, err
|
||||
}
|
||||
|
||||
// SetStatus меняет статус ready↔missing (карантин и восстановление).
|
||||
func (r *AttachmentRepository) SetStatus(ctx context.Context, id, from, to string) (bool, error) {
|
||||
const q = `UPDATE attachments SET status = $3, updated_at = now() WHERE id = $1::uuid AND status = $2`
|
||||
tag, err := r.pool.Exec(ctx, q, id, from, to)
|
||||
return tag.RowsAffected() == 1, err
|
||||
}
|
||||
|
||||
// DeleteUnreferencedMissing удаляет запись карантина старше cutoff, если на неё
|
||||
// не ссылается ни одно сообщение. Блокировка строки (FOR UPDATE) конфликтует с
|
||||
// FOR SHARE при создании сообщения, поэтому гонки «удалили, пока прикрепляли» нет.
|
||||
func (r *AttachmentRepository) DeleteUnreferencedMissing(ctx context.Context, id string, cutoff time.Time) (bool, error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
var locked string
|
||||
err = tx.QueryRow(ctx, `SELECT id FROM attachments WHERE id = $1::uuid AND status = 'missing' AND updated_at < $2 FOR UPDATE`, id, cutoff).Scan(&locked)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
var referenced bool
|
||||
if err := tx.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM message_attachments WHERE attachment_id = $1::uuid)`, id).Scan(&referenced); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if referenced {
|
||||
return false, nil
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `DELETE FROM attachments WHERE id = $1::uuid`, id); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// IsReferenced — используется ли вложение каким-либо сообщением.
|
||||
func (r *AttachmentRepository) IsReferenced(ctx context.Context, id string) (bool, error) {
|
||||
var ok bool
|
||||
err := r.pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM message_attachments WHERE attachment_id = $1::uuid)`, id).Scan(&ok)
|
||||
return ok, err
|
||||
}
|
||||
|
||||
// TryLock — advisory lock, чтобы одновременно работал один reconciler.
|
||||
func (r *AttachmentRepository) TryLock(ctx context.Context) (func(), bool, error) {
|
||||
conn, err := r.pool.Acquire(ctx)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
var ok bool
|
||||
if err := conn.QueryRow(ctx, `SELECT pg_try_advisory_lock(4242004)`).Scan(&ok); err != nil || !ok {
|
||||
conn.Release()
|
||||
return nil, false, err
|
||||
}
|
||||
return func() {
|
||||
_, _ = conn.Exec(context.Background(), `SELECT pg_advisory_unlock(4242004)`)
|
||||
conn.Release()
|
||||
}, true, nil
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab5/internal/repository"
|
||||
)
|
||||
|
||||
type ChatRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewChatRepository(pool *pgxpool.Pool) *ChatRepository {
|
||||
return &ChatRepository{pool: pool}
|
||||
}
|
||||
|
||||
func (r *ChatRepository) Create(ctx context.Context, chat *domain.Chat) error {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin tx: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
const insertChat = `INSERT INTO chats (id, title, created_at) VALUES ($1::uuid, $2, $3)`
|
||||
if _, err := tx.Exec(ctx, insertChat, chat.ID, chat.Title, chat.CreatedAt); err != nil {
|
||||
return fmt.Errorf("insert chat: %w", err)
|
||||
}
|
||||
|
||||
const insertMember = `INSERT INTO chat_members (chat_id, user_id) VALUES ($1::uuid, $2::uuid)`
|
||||
for _, uid := range chat.MemberIDs {
|
||||
if _, err := tx.Exec(ctx, insertMember, chat.ID, uid); err != nil {
|
||||
return fmt.Errorf("insert member %s: %w", uid, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit tx: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *ChatRepository) GetByID(ctx context.Context, id string) (*domain.Chat, error) {
|
||||
const q = `SELECT id, title, created_at FROM chats WHERE id = $1::uuid`
|
||||
var c domain.Chat
|
||||
err := r.pool.QueryRow(ctx, q, id).Scan(&c.ID, &c.Title, &c.CreatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("select chat: %w", err)
|
||||
}
|
||||
|
||||
const qMembers = `SELECT user_id FROM chat_members WHERE chat_id = $1::uuid ORDER BY user_id`
|
||||
rows, err := r.pool.Query(ctx, qMembers, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("select members: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
c.MemberIDs = []string{}
|
||||
for rows.Next() {
|
||||
var uid string
|
||||
if err := rows.Scan(&uid); err != nil {
|
||||
return nil, fmt.Errorf("scan member: %w", err)
|
||||
}
|
||||
c.MemberIDs = append(c.MemberIDs, uid)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate members: %w", err)
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
func (r *ChatRepository) IsMember(ctx context.Context, chatID, userID string) (bool, error) {
|
||||
const q = `SELECT 1 FROM chat_members WHERE chat_id = $1::uuid AND user_id = $2::uuid`
|
||||
var one int
|
||||
err := r.pool.QueryRow(ctx, q, chatID, userID).Scan(&one)
|
||||
if err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, fmt.Errorf("check membership: %w", err)
|
||||
}
|
||||
const qChat = `SELECT 1 FROM chats WHERE id = $1::uuid`
|
||||
err = r.pool.QueryRow(ctx, qChat, chatID).Scan(&one)
|
||||
if err == nil {
|
||||
return false, nil
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, repository.ErrNotFound
|
||||
}
|
||||
return false, fmt.Errorf("check chat exists: %w", err)
|
||||
}
|
||||
|
||||
// MemberVersion одним запросом возвращает версию истории чата и признак членства.
|
||||
// Несуществующий чат — ErrNotFound.
|
||||
func (r *ChatRepository) MemberVersion(ctx context.Context, chatID, userID string) (int64, bool, error) {
|
||||
const q = `
|
||||
SELECT c.version,
|
||||
EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = c.id AND m.user_id = $2::uuid)
|
||||
FROM chats c
|
||||
WHERE c.id = $1::uuid
|
||||
`
|
||||
var version int64
|
||||
var member bool
|
||||
err := r.pool.QueryRow(ctx, q, chatID, userID).Scan(&version, &member)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return 0, false, repository.ErrNotFound
|
||||
}
|
||||
return 0, false, fmt.Errorf("select chat version: %w", err)
|
||||
}
|
||||
return version, member, nil
|
||||
}
|
||||
|
||||
func (r *ChatRepository) ListByMember(ctx context.Context, userID string, cursor time.Time, cursorID string, limit int) ([]*domain.Chat, error) {
|
||||
const qChats = `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE m.user_id = $1::uuid
|
||||
AND (c.created_at, c.id) > ($2::timestamptz, $3::uuid)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, qChats, userID, cursor, cursorID, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list chats: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
chats := []*domain.Chat{}
|
||||
var chatIDs []string
|
||||
for rows.Next() {
|
||||
var c domain.Chat
|
||||
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
|
||||
return nil, fmt.Errorf("scan chat: %w", err)
|
||||
}
|
||||
c.MemberIDs = []string{}
|
||||
chats = append(chats, &c)
|
||||
chatIDs = append(chatIDs, c.ID)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate chats: %w", err)
|
||||
}
|
||||
if len(chats) == 0 {
|
||||
return chats, nil
|
||||
}
|
||||
|
||||
const qMembers = `SELECT chat_id, user_id FROM chat_members WHERE chat_id = ANY($1::uuid[]) ORDER BY chat_id, user_id`
|
||||
memberRows, err := r.pool.Query(ctx, qMembers, chatIDs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list members: %w", err)
|
||||
}
|
||||
defer memberRows.Close()
|
||||
|
||||
byChat := make(map[string][]string)
|
||||
for memberRows.Next() {
|
||||
var chatID, uid string
|
||||
if err := memberRows.Scan(&chatID, &uid); err != nil {
|
||||
return nil, fmt.Errorf("scan member: %w", err)
|
||||
}
|
||||
byChat[chatID] = append(byChat[chatID], uid)
|
||||
}
|
||||
if err := memberRows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate members: %w", err)
|
||||
}
|
||||
for _, c := range chats {
|
||||
if members, ok := byChat[c.ID]; ok {
|
||||
c.MemberIDs = members
|
||||
}
|
||||
}
|
||||
return chats, nil
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab5/internal/repository"
|
||||
)
|
||||
|
||||
type MessageRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewMessageRepository(pool *pgxpool.Pool) *MessageRepository {
|
||||
return &MessageRepository{pool: pool}
|
||||
}
|
||||
|
||||
func (r *MessageRepository) Create(ctx context.Context, msg *domain.Message) error {
|
||||
const q = `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
|
||||
`
|
||||
if _, err := r.pool.Exec(ctx, q, msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt); err != nil {
|
||||
return fmt.Errorf("insert message: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateIdempotent вставляет сообщение и ключ в одной транзакции.
|
||||
// Конкурентные запросы с одним ключом сериализуются уникальным индексом
|
||||
// idempotency_keys: второй INSERT ждёт завершения первой транзакции, после
|
||||
// COMMIT получает конфликт (DO NOTHING), откатывает своё сообщение и читает
|
||||
// уже сохранённое. Если первая транзакция откатилась (транзиентная ошибка),
|
||||
// вторая просто продолжает — неуспешный результат не фиксируется.
|
||||
func (r *MessageRepository) CreateIdempotent(ctx context.Context, msg *domain.Message, key, requestHash string, ttl time.Duration) (*domain.Message, bool, error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("begin tx: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
// Ключ старше TTL больше не защищает от повтора — освобождаем его.
|
||||
const deleteExpired = `
|
||||
DELETE FROM idempotency_keys
|
||||
WHERE user_id = $1::uuid AND chat_id = $2::uuid AND key = $3
|
||||
AND created_at < now() - make_interval(secs => $4)
|
||||
`
|
||||
if _, err := tx.Exec(ctx, deleteExpired, msg.SenderID, msg.ChatID, key, ttl.Seconds()); err != nil {
|
||||
return nil, false, fmt.Errorf("delete expired key: %w", err)
|
||||
}
|
||||
|
||||
const insertMsg = `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
|
||||
`
|
||||
if _, err := tx.Exec(ctx, insertMsg, msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt); err != nil {
|
||||
return nil, false, fmt.Errorf("insert message: %w", err)
|
||||
}
|
||||
|
||||
if len(msg.AttachmentIDs) > 0 {
|
||||
if err := attachToMessage(ctx, tx, msg); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
}
|
||||
|
||||
const insertKey = `
|
||||
INSERT INTO idempotency_keys (user_id, chat_id, key, request_hash, message_id)
|
||||
VALUES ($1::uuid, $2::uuid, $3, $4, $5::uuid)
|
||||
ON CONFLICT (user_id, chat_id, key) DO NOTHING
|
||||
`
|
||||
tag, err := tx.Exec(ctx, insertKey, msg.SenderID, msg.ChatID, key, requestHash, msg.ID)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("insert idempotency key: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() == 1 {
|
||||
// Версия истории растёт атомарно с сообщением: после COMMIT любое чтение
|
||||
// увидит новую версию и не попадёт в кэш, записанный до этого сообщения.
|
||||
const bumpVersion = `UPDATE chats SET version = version + 1 WHERE id = $1::uuid`
|
||||
if _, err := tx.Exec(ctx, bumpVersion, msg.ChatID); err != nil {
|
||||
return nil, false, fmt.Errorf("bump chat version: %w", err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, false, fmt.Errorf("commit tx: %w", err)
|
||||
}
|
||||
return msg, true, nil
|
||||
}
|
||||
|
||||
// Ключ уже занят подтверждённой записью: наше сообщение не сохраняем.
|
||||
_ = tx.Rollback(ctx)
|
||||
|
||||
const selectStored = `
|
||||
SELECT k.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
` + attachmentIDsExpr + `
|
||||
FROM idempotency_keys k
|
||||
JOIN messages m ON m.id = k.message_id
|
||||
WHERE k.user_id = $1::uuid AND k.chat_id = $2::uuid AND k.key = $3
|
||||
`
|
||||
var storedHash string
|
||||
var m domain.Message
|
||||
err = r.pool.QueryRow(ctx, selectStored, msg.SenderID, msg.ChatID, key).
|
||||
Scan(&storedHash, &m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt, &m.AttachmentIDs)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("select stored message: %w", err)
|
||||
}
|
||||
if storedHash != requestHash {
|
||||
return nil, false, repository.ErrConflict
|
||||
}
|
||||
return &m, false, nil
|
||||
}
|
||||
|
||||
// DeleteExpiredKeys удаляет ключи старше TTL. Безопасно выполнять с любой реплики.
|
||||
func (r *MessageRepository) DeleteExpiredKeys(ctx context.Context, ttl time.Duration) (int64, error) {
|
||||
const q = `DELETE FROM idempotency_keys WHERE created_at < now() - make_interval(secs => $1)`
|
||||
tag, err := r.pool.Exec(ctx, q, ttl.Seconds())
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("delete expired keys: %w", err)
|
||||
}
|
||||
return tag.RowsAffected(), nil
|
||||
}
|
||||
|
||||
func (r *MessageRepository) ListByChat(ctx context.Context, chatID string, cursor time.Time, cursorID string, limit int) ([]*domain.Message, error) {
|
||||
q := `
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at, ` + attachmentIDsExpr + `
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1::uuid
|
||||
AND (m.created_at, m.id) > ($2::timestamptz, $3::uuid)
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $4
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, chatID, cursor, cursorID, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list messages: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
msgs := []*domain.Message{}
|
||||
for rows.Next() {
|
||||
var m domain.Message
|
||||
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt, &m.AttachmentIDs); err != nil {
|
||||
return nil, fmt.Errorf("scan message: %w", err)
|
||||
}
|
||||
msgs = append(msgs, &m)
|
||||
}
|
||||
return msgs, rows.Err()
|
||||
}
|
||||
|
||||
// attachmentIDsExpr — id вложений сообщения m в порядке отправки (всегда массив).
|
||||
const attachmentIDsExpr = `ARRAY(SELECT ma.attachment_id::text FROM message_attachments ma
|
||||
WHERE ma.message_id = m.id ORDER BY ma.position)`
|
||||
|
||||
// attachToMessage проверяет и привязывает вложения в транзакции сообщения.
|
||||
// FOR SHARE блокирует строки вложений до COMMIT: reconciler (FOR UPDATE) не
|
||||
// удалит вложение, которое сейчас прикрепляют. Вложение должно быть из того же
|
||||
// чата и в статусе ready; чужое, неизвестное и незавершённое — ErrNotFound.
|
||||
func attachToMessage(ctx context.Context, tx pgx.Tx, msg *domain.Message) error {
|
||||
const q = `
|
||||
SELECT id::text, status FROM attachments
|
||||
WHERE id = ANY($1::uuid[]) AND chat_id = $2::uuid
|
||||
FOR SHARE
|
||||
`
|
||||
rows, err := tx.Query(ctx, q, msg.AttachmentIDs, msg.ChatID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("select attachments: %w", err)
|
||||
}
|
||||
status := map[string]string{}
|
||||
for rows.Next() {
|
||||
var id, st string
|
||||
if err := rows.Scan(&id, &st); err != nil {
|
||||
rows.Close()
|
||||
return fmt.Errorf("scan attachment: %w", err)
|
||||
}
|
||||
status[id] = st
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return fmt.Errorf("select attachments: %w", err)
|
||||
}
|
||||
for _, id := range msg.AttachmentIDs {
|
||||
switch status[id] {
|
||||
case domain.AttachmentReady, domain.AttachmentQueued, domain.AttachmentProcessing:
|
||||
// с lab5 можно ссылаться на ещё обрабатываемое вложение
|
||||
case domain.AttachmentFailed, domain.AttachmentMissing:
|
||||
return repository.ErrConflict
|
||||
default:
|
||||
return repository.ErrNotFound // чужое, неизвестное, не принятое (uploading)
|
||||
}
|
||||
}
|
||||
batch := &pgx.Batch{}
|
||||
for i, id := range msg.AttachmentIDs {
|
||||
batch.Queue(`INSERT INTO message_attachments (message_id, attachment_id, position) VALUES ($1::uuid, $2::uuid, $3)`,
|
||||
msg.ID, id, i)
|
||||
}
|
||||
if err := tx.SendBatch(ctx, batch).Close(); err != nil {
|
||||
return fmt.Errorf("insert message attachments: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,570 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab5/internal/repository"
|
||||
)
|
||||
|
||||
// PipelineRepository — задания, outbox и фиксация результатов обработки.
|
||||
//
|
||||
// Все переходы job выполняются в транзакциях с блокировкой строки job (FOR UPDATE),
|
||||
// а фиксация результата защищена fencing-токеном (lease_owner + attempt): worker,
|
||||
// потерявший lease, не может опубликовать результат поверх новой попытки.
|
||||
type PipelineRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewPipelineRepository(pool *pgxpool.Pool) *PipelineRepository {
|
||||
return &PipelineRepository{pool: pool}
|
||||
}
|
||||
|
||||
// JobRow — состояние логической работы.
|
||||
type JobRow struct {
|
||||
JobID string
|
||||
AttachmentID string
|
||||
PipelineVersion int
|
||||
State string
|
||||
Attempt int
|
||||
MaxAttempts int
|
||||
NextAttemptAt time.Time
|
||||
LeaseUntil *time.Time
|
||||
LeaseOwner string
|
||||
LastError string
|
||||
}
|
||||
|
||||
func jobPayload(jobID, attachmentID string, version, attempt int, created time.Time) ([]byte, error) {
|
||||
return json.Marshal(domain.Job{
|
||||
SchemaVersion: 1, JobID: jobID, Type: domain.JobType, AttachmentID: attachmentID,
|
||||
PipelineVersion: version, Attempt: attempt,
|
||||
CreatedAt: created.UTC().Truncate(time.Second).Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
|
||||
func event(ctx context.Context, tx pgx.Tx, jobID, ev, detail string) error {
|
||||
_, err := tx.Exec(ctx, `INSERT INTO job_events (job_id, event, detail) VALUES ($1::uuid, $2, NULLIF($3, ''))`, jobID, ev, detail)
|
||||
return err
|
||||
}
|
||||
|
||||
func outboxTx(ctx context.Context, tx pgx.Tx, jobID, attachmentID string, version, attempt int, available time.Time) error {
|
||||
payload, err := jobPayload(jobID, attachmentID, version, attempt, time.Now())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO outbox (job_id, payload, available_at) VALUES ($1::uuid, $2, $3)`, jobID, payload, available)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert outbox: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// EnqueueJobTx создаёт логическую работу (attachment, version) и её первое
|
||||
// сообщение в outbox. Если работа этой версии уже есть — ничего не создаёт и
|
||||
// возвращает существующий job_id (ключ эффекта не дублируется).
|
||||
func EnqueueJobTx(ctx context.Context, tx pgx.Tx, attachmentID string, version, maxAttempts int, reason string) (string, error) {
|
||||
jobID := uuid.NewString()
|
||||
var got string
|
||||
err := tx.QueryRow(ctx, `
|
||||
INSERT INTO jobs (job_id, attachment_id, pipeline_version, state, max_attempts)
|
||||
VALUES ($1::uuid, $2::uuid, $3, 'queued', $4)
|
||||
ON CONFLICT (attachment_id, pipeline_version) DO NOTHING
|
||||
RETURNING job_id::text`, jobID, attachmentID, version, maxAttempts).Scan(&got)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
err = tx.QueryRow(ctx, `SELECT job_id::text FROM jobs WHERE attachment_id = $1::uuid AND pipeline_version = $2`,
|
||||
attachmentID, version).Scan(&got)
|
||||
return got, err
|
||||
}
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("insert job: %w", err)
|
||||
}
|
||||
if err := outboxTx(ctx, tx, got, attachmentID, version, 1, time.Now()); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return got, event(ctx, tx, got, "enqueued", reason)
|
||||
}
|
||||
|
||||
func lockJob(ctx context.Context, tx pgx.Tx, jobID string) (*JobRow, error) {
|
||||
var j JobRow
|
||||
var owner, lastErr *string
|
||||
err := tx.QueryRow(ctx, `
|
||||
SELECT job_id::text, attachment_id::text, pipeline_version, state, attempt, max_attempts,
|
||||
next_attempt_at, lease_until, lease_owner, last_error
|
||||
FROM jobs WHERE job_id = $1::uuid FOR UPDATE`, jobID).
|
||||
Scan(&j.JobID, &j.AttachmentID, &j.PipelineVersion, &j.State, &j.Attempt, &j.MaxAttempts,
|
||||
&j.NextAttemptAt, &j.LeaseUntil, &owner, &lastErr)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("lock job: %w", err)
|
||||
}
|
||||
if owner != nil {
|
||||
j.LeaseOwner = *owner
|
||||
}
|
||||
if lastErr != nil {
|
||||
j.LastError = *lastErr
|
||||
}
|
||||
return &j, nil
|
||||
}
|
||||
|
||||
// ClaimOutcome — решение worker по доставленному сообщению.
|
||||
type ClaimOutcome int
|
||||
|
||||
const (
|
||||
Claimed ClaimOutcome = iota // аренда получена — обрабатывать
|
||||
AlreadyDone // эффект уже опубликован — ack без работы
|
||||
Busy // валидная аренда у другого worker — ack (дубль)
|
||||
NotDue // ранняя доставка до next_attempt_at — ack, outbox доставит позже
|
||||
Terminal // failed / задания нет — ack
|
||||
ExhaustedNow // попытки исчерпаны при захвате — уже помечено failed
|
||||
)
|
||||
|
||||
// Claim захватывает работу: queued (и уже наступило next_attempt_at) или
|
||||
// processing с истёкшим lease. Номер попытки растёт при каждом захвате.
|
||||
func (r *PipelineRepository) Claim(ctx context.Context, jobID, owner string, lease time.Duration) (ClaimOutcome, *JobRow, *domain.Attachment, error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
j, err := lockJob(ctx, tx, jobID)
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return Terminal, nil, nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
var now time.Time
|
||||
if err := tx.QueryRow(ctx, `SELECT now()`).Scan(&now); err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
switch {
|
||||
case j.State == "done":
|
||||
return AlreadyDone, j, nil, nil
|
||||
case j.State == "failed":
|
||||
return Terminal, j, nil, nil
|
||||
case j.State == "processing" && j.LeaseUntil != nil && j.LeaseUntil.After(now):
|
||||
return Busy, j, nil, nil
|
||||
case j.State == "queued" && j.NextAttemptAt.After(now): // время relay и claim — одно (часы PostgreSQL)
|
||||
return NotDue, j, nil, nil
|
||||
}
|
||||
a, err := scanAttachment(tx.QueryRow(ctx, `SELECT `+attachmentColumns+` FROM attachments WHERE id = $1::uuid FOR UPDATE`, j.AttachmentID))
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return Terminal, j, nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
// Результат этой или более новой версии уже опубликован — повтор не нужен.
|
||||
if a.Status == domain.AttachmentReady && a.PipelineVersion >= j.PipelineVersion {
|
||||
if _, err := tx.Exec(ctx, `UPDATE jobs SET state = 'done', lease_until = NULL, updated_at = now() WHERE job_id = $1::uuid`, jobID); err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
if err := event(ctx, tx, jobID, "noop_already_published", fmt.Sprintf("published_version=%d", a.PipelineVersion)); err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
return AlreadyDone, j, a, tx.Commit(ctx)
|
||||
}
|
||||
takeover := j.State == "processing"
|
||||
j.Attempt++
|
||||
if j.Attempt > j.MaxAttempts {
|
||||
if err := failTx(ctx, tx, j, "retry_exhausted", "attempts exhausted at claim"); err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
return ExhaustedNow, j, a, tx.Commit(ctx)
|
||||
}
|
||||
until := now.Add(lease)
|
||||
if _, err := tx.Exec(ctx, `
|
||||
UPDATE jobs SET state = 'processing', attempt = $2, lease_until = $3, lease_owner = $4, updated_at = now()
|
||||
WHERE job_id = $1::uuid`, jobID, j.Attempt, until, owner); err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
if a.Status == domain.AttachmentQueued {
|
||||
if _, err := tx.Exec(ctx, `UPDATE attachments SET status = 'processing', updated_at = now() WHERE id = $1::uuid`, a.ID); err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
}
|
||||
ev := "claimed"
|
||||
if takeover {
|
||||
ev = "claimed_after_lease_expiry"
|
||||
}
|
||||
if err := event(ctx, tx, jobID, ev, fmt.Sprintf("attempt=%d owner=%s", j.Attempt, owner)); err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
j.State, j.LeaseUntil, j.LeaseOwner = "processing", &until, owner
|
||||
return Claimed, j, a, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// ExtendLease продлевает аренду (heartbeat), пока worker действительно работает.
|
||||
// false — аренда потеряна (её забрал другой worker после истечения).
|
||||
func (r *PipelineRepository) ExtendLease(ctx context.Context, jobID, owner string, attempt int, lease time.Duration) (bool, error) {
|
||||
tag, err := r.pool.Exec(ctx, `
|
||||
UPDATE jobs SET lease_until = now() + make_interval(secs => $4), updated_at = now()
|
||||
WHERE job_id = $1::uuid AND state = 'processing' AND lease_owner = $2 AND attempt = $3`,
|
||||
jobID, owner, attempt, lease.Seconds())
|
||||
return tag.RowsAffected() == 1, err
|
||||
}
|
||||
|
||||
// CompleteResult — что сделала фиксация.
|
||||
type CompleteResult struct {
|
||||
Applied bool // результат этой попытки зафиксирован
|
||||
Published bool // attachment переведён на эту версию
|
||||
LostLease bool // fencing: попытка уже не владеет job
|
||||
NewerPublished int // если опубликована более новая версия — её номер
|
||||
}
|
||||
|
||||
// Complete атомарно публикует результат: варианты (ON CONFLICT DO NOTHING по
|
||||
// ключу эффекта), attachment → ready на этой версии (только если опубликованная
|
||||
// версия меньше — старый результат не перезаписывает новый), job → done.
|
||||
func (r *PipelineRepository) Complete(ctx context.Context, jobID, owner string, attempt int, finalKey string, variants []domain.Variant) (CompleteResult, error) {
|
||||
var res CompleteResult
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
j, err := lockJob(ctx, tx, jobID)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
if j.State != "processing" || j.LeaseOwner != owner || j.Attempt != attempt {
|
||||
res.LostLease = true
|
||||
return res, event(ctx, tx, jobID, "result_rejected_lost_lease", fmt.Sprintf("attempt=%d owner=%s", attempt, owner))
|
||||
}
|
||||
batch := &pgx.Batch{}
|
||||
for _, v := range variants {
|
||||
batch.Queue(`
|
||||
INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type, size_bytes, width, height, sha256)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
ON CONFLICT (attachment_id, pipeline_version, name) DO NOTHING`,
|
||||
j.AttachmentID, j.PipelineVersion, v.Name, v.ObjectKey, v.ContentType, v.SizeBytes, v.Width, v.Height, v.SHA256)
|
||||
}
|
||||
if err := tx.SendBatch(ctx, batch).Close(); err != nil {
|
||||
return res, fmt.Errorf("insert variants: %w", err)
|
||||
}
|
||||
tag, err := tx.Exec(ctx, `
|
||||
UPDATE attachments
|
||||
SET status = 'ready', pipeline_version = $2, object_key = $3, error_code = NULL, updated_at = now()
|
||||
WHERE id = $1::uuid AND pipeline_version < $2 AND status <> 'missing'`,
|
||||
j.AttachmentID, j.PipelineVersion, finalKey)
|
||||
if err != nil {
|
||||
return res, fmt.Errorf("publish attachment: %w", err)
|
||||
}
|
||||
res.Published = tag.RowsAffected() == 1
|
||||
if !res.Published {
|
||||
_ = tx.QueryRow(ctx, `SELECT pipeline_version FROM attachments WHERE id = $1::uuid`, j.AttachmentID).Scan(&res.NewerPublished)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `UPDATE jobs SET state = 'done', lease_until = NULL, last_error = NULL, updated_at = now() WHERE job_id = $1::uuid`, jobID); err != nil {
|
||||
return res, err
|
||||
}
|
||||
ev, detail := "done", fmt.Sprintf("attempt=%d", attempt)
|
||||
if !res.Published {
|
||||
ev, detail = "done_not_published_newer_exists", fmt.Sprintf("attempt=%d published_version=%d", attempt, res.NewerPublished)
|
||||
}
|
||||
if err := event(ctx, tx, jobID, ev, detail); err != nil {
|
||||
return res, err
|
||||
}
|
||||
res.Applied = true
|
||||
return res, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func failTx(ctx context.Context, tx pgx.Tx, j *JobRow, code, detail string) error {
|
||||
if _, err := tx.Exec(ctx, `
|
||||
UPDATE jobs SET state = 'failed', lease_until = NULL, last_error = $2, updated_at = now()
|
||||
WHERE job_id = $1::uuid`, j.JobID, code+": "+detail); err != nil {
|
||||
return err
|
||||
}
|
||||
// Ready-вложение (переобработка новой версии) не роняется в failed: старый
|
||||
// результат остаётся опубликованным.
|
||||
if _, err := tx.Exec(ctx, `
|
||||
UPDATE attachments SET status = 'failed', error_code = $2, updated_at = now()
|
||||
WHERE id = $1::uuid AND status IN ('queued', 'processing')`, j.AttachmentID, code); err != nil {
|
||||
return err
|
||||
}
|
||||
return event(ctx, tx, j.JobID, "failed", code+": "+detail)
|
||||
}
|
||||
|
||||
// RetryOrFail: временная ошибка с оставшимися попытками → queued с backoff и
|
||||
// новым сообщением outbox (available_at в будущем); иначе → failed.
|
||||
func (r *PipelineRepository) RetryOrFail(ctx context.Context, jobID, owner string, attempt int, code, detail string, permanent bool, backoff time.Duration) (failed bool, err error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
j, err := lockJob(ctx, tx, jobID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if j.State != "processing" || j.LeaseOwner != owner || j.Attempt != attempt {
|
||||
return false, event(ctx, tx, jobID, "error_ignored_lost_lease", code)
|
||||
}
|
||||
if permanent || j.Attempt >= j.MaxAttempts {
|
||||
if !permanent {
|
||||
code = "retry_exhausted"
|
||||
}
|
||||
if err := failTx(ctx, tx, j, code, detail); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, tx.Commit(ctx)
|
||||
}
|
||||
var next time.Time
|
||||
if err := tx.QueryRow(ctx, `
|
||||
UPDATE jobs SET state = 'queued', lease_until = NULL, lease_owner = NULL, last_error = $2,
|
||||
next_attempt_at = now() + make_interval(secs => $3), updated_at = now()
|
||||
WHERE job_id = $1::uuid RETURNING next_attempt_at`, jobID, code+": "+detail, backoff.Seconds()).Scan(&next); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `UPDATE attachments SET status = 'queued', updated_at = now() WHERE id = $1::uuid AND status = 'processing'`, j.AttachmentID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := outboxTx(ctx, tx, jobID, j.AttachmentID, j.PipelineVersion, j.Attempt+1, next); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := event(ctx, tx, jobID, "retry_scheduled", fmt.Sprintf("%s; next_attempt=%d in %s", code, j.Attempt+1, backoff.Round(time.Millisecond))); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return false, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// SweepExpiredLeases возвращает в очередь работу, чей worker умер (lease истёк).
|
||||
func (r *PipelineRepository) SweepExpiredLeases(ctx context.Context) (int, error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
rows, err := tx.Query(ctx, `
|
||||
SELECT job_id::text FROM jobs
|
||||
WHERE state = 'processing' AND lease_until < now()
|
||||
ORDER BY lease_until LIMIT 100 FOR UPDATE SKIP LOCKED`)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var ids []string
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
rows.Close()
|
||||
return 0, err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
rows.Close()
|
||||
for _, id := range ids {
|
||||
j, err := lockJob(ctx, tx, id)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if j.Attempt >= j.MaxAttempts {
|
||||
if err := failTx(ctx, tx, j, "retry_exhausted", "lease expired on last attempt"); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
UPDATE jobs SET state = 'queued', lease_until = NULL, lease_owner = NULL, next_attempt_at = now(),
|
||||
last_error = 'lease_expired', updated_at = now() WHERE job_id = $1::uuid`, id); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `UPDATE attachments SET status = 'queued', updated_at = now() WHERE id = $1::uuid AND status = 'processing'`, j.AttachmentID); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if err := outboxTx(ctx, tx, id, j.AttachmentID, j.PipelineVersion, j.Attempt+1, time.Now()); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if err := event(ctx, tx, id, "lease_expired_requeued", fmt.Sprintf("owner=%s attempt=%d", j.LeaseOwner, j.Attempt)); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return len(ids), tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// OutboxMessage — неопубликованное сообщение.
|
||||
type OutboxMessage struct {
|
||||
ID int64
|
||||
JobID string
|
||||
Payload []byte
|
||||
}
|
||||
|
||||
// PublishDue публикует созревшие сообщения outbox. Строки блокируются
|
||||
// FOR UPDATE SKIP LOCKED (несколько relay не мешают друг другу); published_at
|
||||
// ставится только после publisher confirm. Падение между confirm и COMMIT даёт
|
||||
// повторную публикацию — это допустимо: consumer идемпотентен.
|
||||
func (r *PipelineRepository) PublishDue(ctx context.Context, limit int, publish func(context.Context, OutboxMessage) error, afterPublish func()) (int, error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
rows, err := tx.Query(ctx, `
|
||||
SELECT id, job_id::text, payload FROM outbox
|
||||
WHERE published_at IS NULL AND available_at <= now()
|
||||
ORDER BY id LIMIT $1 FOR UPDATE SKIP LOCKED`, limit)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var msgs []OutboxMessage
|
||||
for rows.Next() {
|
||||
var m OutboxMessage
|
||||
if err := rows.Scan(&m.ID, &m.JobID, &m.Payload); err != nil {
|
||||
rows.Close()
|
||||
return 0, err
|
||||
}
|
||||
msgs = append(msgs, m)
|
||||
}
|
||||
rows.Close()
|
||||
sent := 0
|
||||
for _, m := range msgs {
|
||||
if err := publish(ctx, m); err != nil {
|
||||
_, _ = tx.Exec(ctx, `UPDATE outbox SET publish_attempts = publish_attempts + 1 WHERE id = $1`, m.ID)
|
||||
_ = tx.Commit(ctx)
|
||||
return sent, err
|
||||
}
|
||||
if afterPublish != nil {
|
||||
afterPublish() // точка внедрения сбоя «после confirm до COMMIT»
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `UPDATE outbox SET published_at = now(), publish_attempts = publish_attempts + 1 WHERE id = $1`, m.ID); err != nil {
|
||||
return sent, err
|
||||
}
|
||||
sent++
|
||||
}
|
||||
return sent, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// Replay — явный операторский повтор failed-работы (failed → queued) с аудитом.
|
||||
// Успешную работу повторить нельзя: «повторить» не означает исполнить дубль.
|
||||
func (r *PipelineRepository) Replay(ctx context.Context, attachmentID string, version int, actor string) (string, error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
var jobID string
|
||||
if err := tx.QueryRow(ctx, `SELECT job_id::text FROM jobs WHERE attachment_id = $1::uuid AND pipeline_version = $2`,
|
||||
attachmentID, version).Scan(&jobID); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "", repository.ErrNotFound
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
j, err := lockJob(ctx, tx, jobID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if j.State != "failed" {
|
||||
_ = event(ctx, tx, jobID, "replay_refused", "state="+j.State+" actor="+actor)
|
||||
_ = tx.Commit(ctx)
|
||||
return jobID, fmt.Errorf("%w: job is %s, only failed jobs can be replayed", repository.ErrConflict, j.State)
|
||||
}
|
||||
var staging *string
|
||||
if err := tx.QueryRow(ctx, `SELECT staging_key FROM attachments WHERE id = $1::uuid FOR UPDATE`, attachmentID).Scan(&staging); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if staging == nil {
|
||||
_ = event(ctx, tx, jobID, "replay_refused", "staging removed by retention, actor="+actor)
|
||||
_ = tx.Commit(ctx)
|
||||
return jobID, fmt.Errorf("%w: source removed by staging retention", repository.ErrConflict)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
UPDATE jobs SET state = 'queued', attempt = 0, next_attempt_at = now(), last_error = NULL, updated_at = now()
|
||||
WHERE job_id = $1::uuid`, jobID); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = now() WHERE id = $1::uuid AND status = 'failed'`, attachmentID); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := outboxTx(ctx, tx, jobID, attachmentID, version, 1, time.Now()); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := event(ctx, tx, jobID, "replay", "actor="+actor); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return jobID, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// Reprocess ставит работу новой версии pipeline для уже обработанного вложения
|
||||
// (трек 2). Вложение остаётся ready со старыми вариантами до публикации новых.
|
||||
func (r *PipelineRepository) Reprocess(ctx context.Context, attachmentID string, version, maxAttempts int) (string, error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
id, err := EnqueueJobTx(ctx, tx, attachmentID, version, maxAttempts, "reprocess")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return id, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// FailedJobs — реестр failed для оператора.
|
||||
func (r *PipelineRepository) FailedJobs(ctx context.Context, limit int) ([]JobRow, error) {
|
||||
rows, err := r.pool.Query(ctx, `
|
||||
SELECT job_id::text, attachment_id::text, pipeline_version, state, attempt, max_attempts, COALESCE(last_error, '')
|
||||
FROM jobs WHERE state = 'failed' ORDER BY updated_at DESC LIMIT $1`, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []JobRow
|
||||
for rows.Next() {
|
||||
var j JobRow
|
||||
if err := rows.Scan(&j.JobID, &j.AttachmentID, &j.PipelineVersion, &j.State, &j.Attempt, &j.MaxAttempts, &j.LastError); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, j)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// StagingCandidate — staging-объект, который можно удалить.
|
||||
type StagingCandidate struct {
|
||||
AttachmentID string
|
||||
Key string
|
||||
Status string
|
||||
}
|
||||
|
||||
// StagingToClean: ready с отдельным staging-объектом (результат уже опубликован
|
||||
// не менее readyGrace назад) и failed старше retention (replay больше невозможен).
|
||||
func (r *PipelineRepository) StagingToClean(ctx context.Context, readyGrace, failedRetention time.Duration, limit int) ([]StagingCandidate, error) {
|
||||
rows, err := r.pool.Query(ctx, `
|
||||
SELECT id::text, staging_key, status FROM attachments
|
||||
WHERE staging_key IS NOT NULL AND (
|
||||
(status = 'ready' AND staging_key <> object_key AND updated_at < now() - make_interval(secs => $1))
|
||||
OR (status = 'failed' AND updated_at < now() - make_interval(secs => $2)))
|
||||
ORDER BY updated_at LIMIT $3`, readyGrace.Seconds(), failedRetention.Seconds(), limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []StagingCandidate
|
||||
for rows.Next() {
|
||||
var c StagingCandidate
|
||||
if err := rows.Scan(&c.AttachmentID, &c.Key, &c.Status); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, c)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// ClearStaging отмечает, что staging-объект удалён (только если ключ не менялся).
|
||||
func (r *PipelineRepository) ClearStaging(ctx context.Context, attachmentID, key string) error {
|
||||
_, err := r.pool.Exec(ctx, `UPDATE attachments SET staging_key = NULL WHERE id = $1::uuid AND staging_key = $2`, attachmentID, key)
|
||||
return err
|
||||
}
|
||||
|
||||
// Attachment — доверенные метаданные для worker.
|
||||
func (r *PipelineRepository) Attachment(ctx context.Context, id string) (*domain.Attachment, error) {
|
||||
return scanAttachment(r.pool.QueryRow(ctx, `SELECT `+attachmentColumns+` FROM attachments WHERE id = $1::uuid`, id))
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// NewPool создаёт пул соединений с PostgreSQL.
|
||||
// Параметры ограничены, чтобы не перегрузить БД.
|
||||
func NewPool(ctx context.Context, dsn string, maxConns int32) (*pgxpool.Pool, error) {
|
||||
cfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse dsn: %w", err)
|
||||
}
|
||||
|
||||
cfg.MaxConns = maxConns
|
||||
cfg.MinConns = min(2, maxConns)
|
||||
cfg.MaxConnIdleTime = 5 * time.Minute
|
||||
cfg.MaxConnLifetime = 30 * time.Minute
|
||||
cfg.HealthCheckPeriod = 30 * time.Second
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create pool: %w", err)
|
||||
}
|
||||
|
||||
// Проверяем, что соединение работает.
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping: %w", err)
|
||||
}
|
||||
|
||||
return pool, nil
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab5/internal/repository"
|
||||
)
|
||||
|
||||
type UserRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewUserRepository(pool *pgxpool.Pool) *UserRepository {
|
||||
return &UserRepository{pool: pool}
|
||||
}
|
||||
|
||||
func (r *UserRepository) Create(ctx context.Context, user *domain.User, passwordHash string) error {
|
||||
const q = `
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5)
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, q, user.ID, user.Username, user.DisplayName, passwordHash, user.CreatedAt)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return repository.ErrConflict
|
||||
}
|
||||
return fmt.Errorf("insert user: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetByID(ctx context.Context, id string) (*domain.User, error) {
|
||||
const q = `SELECT id, username, display_name, created_at FROM users WHERE id = $1::uuid`
|
||||
var u domain.User
|
||||
err := r.pool.QueryRow(ctx, q, id).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("select user by id: %w", err)
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetByUsername(ctx context.Context, username string) (*domain.User, error) {
|
||||
const q = `SELECT id, username, display_name, created_at FROM users WHERE username = $1`
|
||||
var u domain.User
|
||||
err := r.pool.QueryRow(ctx, q, username).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("select user by username: %w", err)
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetPasswordHash(ctx context.Context, userID string) (string, error) {
|
||||
const q = `SELECT password_hash FROM users WHERE id = $1::uuid`
|
||||
var hash string
|
||||
err := r.pool.QueryRow(ctx, q, userID).Scan(&hash)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "", repository.ErrNotFound
|
||||
}
|
||||
return "", fmt.Errorf("select password hash: %w", err)
|
||||
}
|
||||
return hash, nil
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
)
|
||||
|
||||
// Ключ кэша истории всегда содержит версию чата из PostgreSQL (chats.version),
|
||||
// которая растёт в одной транзакции с сообщением. Поэтому после подтверждённой
|
||||
// записи следующее чтение идёт по новому ключу, даже если Redis отказал в
|
||||
// любой команде: устаревшие ключи просто истекают по TTL.
|
||||
//
|
||||
// CACHE_INVALIDATION влияет только на стоимость записи (эксперимент трека 1):
|
||||
// - "version": запись не обращается к Redis;
|
||||
// - "scan": дополнительно удаляет ключи чата через SCAN, как в lab2 —
|
||||
// O(размер keyspace/100) запросов к Redis на запись. На корректность не влияет.
|
||||
const (
|
||||
InvalidationScan = "scan"
|
||||
InvalidationVersion = "version"
|
||||
)
|
||||
|
||||
type MessageCache struct {
|
||||
client *redis.Client
|
||||
scanOnSet bool
|
||||
}
|
||||
|
||||
func NewMessageCache(client *redis.Client, mode string) *MessageCache {
|
||||
return &MessageCache{client: client, scanOnSet: mode == InvalidationScan}
|
||||
}
|
||||
|
||||
type cacheEntry struct {
|
||||
Items []*domain.Message `json:"items"`
|
||||
NextCursor string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func cacheKey(chatID string, version int64, cursor string, limit int) string {
|
||||
return fmt.Sprintf("messages:%s:v%d:%s:%d", chatID, version, cursor, limit)
|
||||
}
|
||||
|
||||
func (c *MessageCache) Get(ctx context.Context, chatID string, version int64, cursor string, limit int) ([]*domain.Message, string, bool) {
|
||||
raw, err := c.client.Get(ctx, cacheKey(chatID, version, cursor, limit)).Bytes()
|
||||
if err != nil {
|
||||
return nil, "", false
|
||||
}
|
||||
var e cacheEntry
|
||||
if err := json.Unmarshal(raw, &e); err != nil {
|
||||
return nil, "", false
|
||||
}
|
||||
return e.Items, e.NextCursor, true
|
||||
}
|
||||
|
||||
func (c *MessageCache) Set(ctx context.Context, chatID string, version int64, cursor string, limit int, items []*domain.Message, next string) {
|
||||
e := cacheEntry{Items: items, NextCursor: next}
|
||||
raw, err := json.Marshal(e)
|
||||
if err != nil {
|
||||
slog.Warn("marshal cache entry failed", "err", err)
|
||||
return
|
||||
}
|
||||
if err := c.client.Set(ctx, cacheKey(chatID, version, cursor, limit), raw, 30*time.Second).Err(); err != nil {
|
||||
// Redis недоступен — не падаем, работаем без кэша.
|
||||
slog.Warn("redis set failed", "chat_id", chatID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// OnWrite вызывается после успешной записи сообщения. Свежесть чтения уже
|
||||
// обеспечена ростом chats.version в транзакции записи; в режиме scan здесь
|
||||
// только воспроизводится стоимость удаления старых ключей (lab2), и ошибка
|
||||
// Redis не может сделать историю устаревшей.
|
||||
func (c *MessageCache) OnWrite(ctx context.Context, chatID string) {
|
||||
if !c.scanOnSet {
|
||||
return
|
||||
}
|
||||
if err := c.Invalidate(ctx, chatID); err != nil {
|
||||
slog.Warn("redis scan invalidation failed", "chat_id", chatID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Invalidate удаляет все ключи messages:{chatID}:* через SCAN.
|
||||
func (c *MessageCache) Invalidate(ctx context.Context, chatID string) error {
|
||||
pattern := fmt.Sprintf("messages:%s:*", chatID)
|
||||
iter := c.client.Scan(ctx, 0, pattern, 100).Iterator()
|
||||
for iter.Next(ctx) {
|
||||
_ = c.client.Del(ctx, iter.Val()).Err()
|
||||
}
|
||||
return iter.Err()
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab5/internal/repository"
|
||||
)
|
||||
|
||||
type SessionRepository struct {
|
||||
client *redis.Client
|
||||
}
|
||||
|
||||
func NewSessionRepository(client *redis.Client) *SessionRepository {
|
||||
return &SessionRepository{client: client}
|
||||
}
|
||||
|
||||
func (r *SessionRepository) Create(ctx context.Context, s *domain.Session) error {
|
||||
key := "session:" + s.Token
|
||||
ttl := time.Until(s.ExpiresAt)
|
||||
if ttl <= 0 {
|
||||
return fmt.Errorf("session already expired")
|
||||
}
|
||||
if err := r.client.Set(ctx, key, s.UserID, ttl).Err(); err != nil {
|
||||
return fmt.Errorf("set session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *SessionRepository) GetByToken(ctx context.Context, token string) (*domain.Session, error) {
|
||||
key := "session:" + token
|
||||
userID, err := r.client.Get(ctx, key).Result()
|
||||
if err != nil {
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("get session: %w", err)
|
||||
}
|
||||
ttl, err := r.client.TTL(ctx, key).Result()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ttl: %w", err)
|
||||
}
|
||||
return &domain.Session{
|
||||
Token: token,
|
||||
UserID: userID,
|
||||
ExpiresAt: time.Now().UTC().Add(ttl),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *SessionRepository) Delete(ctx context.Context, token string) error {
|
||||
return r.client.Del(ctx, "session:"+token).Err()
|
||||
}
|
||||
|
||||
func (r *SessionRepository) DeleteExpired(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewClient(ctx context.Context, url string) (*redis.Client, error) {
|
||||
opts, err := redis.ParseURL(url)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse redis url: %w", err)
|
||||
}
|
||||
client := redis.NewClient(opts)
|
||||
if err := client.Ping(ctx).Err(); err != nil {
|
||||
return nil, fmt.Errorf("ping redis: %w", err)
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
)
|
||||
|
||||
var ErrNotFound = errNotFound{}
|
||||
|
||||
type errNotFound struct{}
|
||||
|
||||
func (errNotFound) Error() string { return "not found" }
|
||||
|
||||
var ErrConflict = errConflict{}
|
||||
|
||||
type errConflict struct{}
|
||||
|
||||
func (errConflict) Error() string { return "conflict" }
|
||||
|
||||
// UserRepository
|
||||
type UserRepository interface {
|
||||
Create(ctx context.Context, user *domain.User, passwordHash string) error
|
||||
GetByID(ctx context.Context, id string) (*domain.User, error)
|
||||
GetByUsername(ctx context.Context, username string) (*domain.User, error)
|
||||
GetPasswordHash(ctx context.Context, userID string) (string, error)
|
||||
}
|
||||
|
||||
// ChatRepository
|
||||
type ChatRepository interface {
|
||||
Create(ctx context.Context, chat *domain.Chat) error
|
||||
GetByID(ctx context.Context, id string) (*domain.Chat, error)
|
||||
IsMember(ctx context.Context, chatID, userID string) (bool, error)
|
||||
// MemberVersion — версия истории чата (растёт с каждым сообщением) и членство.
|
||||
MemberVersion(ctx context.Context, chatID, userID string) (version int64, member bool, err error)
|
||||
ListByMember(ctx context.Context, userID string, cursor time.Time, cursorID string, limit int) ([]*domain.Chat, error)
|
||||
}
|
||||
|
||||
// MessageRepository
|
||||
type MessageRepository interface {
|
||||
Create(ctx context.Context, msg *domain.Message) error
|
||||
// CreateIdempotent атомарно создаёт сообщение и запись ключа идемпотентности.
|
||||
// Если ключ уже есть с тем же requestHash — возвращает ранее созданное сообщение
|
||||
// и created=false; с другим requestHash — ErrConflict.
|
||||
CreateIdempotent(ctx context.Context, msg *domain.Message, key, requestHash string, ttl time.Duration) (stored *domain.Message, created bool, err error)
|
||||
DeleteExpiredKeys(ctx context.Context, ttl time.Duration) (int64, error)
|
||||
ListByChat(ctx context.Context, chatID string, cursor time.Time, cursorID string, limit int) ([]*domain.Message, error)
|
||||
}
|
||||
|
||||
// SessionRepository
|
||||
type SessionRepository interface {
|
||||
Create(ctx context.Context, s *domain.Session) error
|
||||
GetByToken(ctx context.Context, token string) (*domain.Session, error)
|
||||
Delete(ctx context.Context, token string) error
|
||||
DeleteExpired(ctx context.Context) error
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
_ "image/jpeg" // DecodeConfig для раннего отказа по размерам
|
||||
_ "image/png"
|
||||
"io"
|
||||
"log/slog"
|
||||
"mime"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab5/internal/imagecheck"
|
||||
"github.com/charawein/mtusi2026lab5/internal/repository"
|
||||
"github.com/charawein/mtusi2026lab5/internal/storage"
|
||||
)
|
||||
|
||||
// Раскладка bucket (все ключи назначает сервер, filename в них не попадает):
|
||||
//
|
||||
// s/{chat}/{id} — staging: проверенный оригинал до обработки
|
||||
// o/{chat}/{id} — опубликованный оригинал (worker копирует из staging)
|
||||
// v/{chat}/{id}/p{ver}/{variant} — варианты версии pipeline ver
|
||||
// a/{chat}/{id} — оригиналы lab4 (остаются на месте)
|
||||
const (
|
||||
ObjectPrefix = "a/"
|
||||
StagingPrefix = "s/"
|
||||
OriginalPrefix = "o/"
|
||||
VariantPrefix = "v/"
|
||||
)
|
||||
|
||||
type AttachmentRepository interface {
|
||||
CreateIntent(ctx context.Context, a *domain.Attachment) error
|
||||
MarkQueued(ctx context.Context, a *domain.Attachment, pipelineVersion, maxAttempts int) (string, error)
|
||||
DeleteIntent(ctx context.Context, id string) error
|
||||
GetForMember(ctx context.Context, id, userID string) (*domain.Attachment, error)
|
||||
Variants(ctx context.Context, attachmentID string, version int) ([]domain.Variant, error)
|
||||
}
|
||||
|
||||
type AttachmentService struct {
|
||||
repo AttachmentRepository
|
||||
chats repository.ChatRepository
|
||||
store storage.Store
|
||||
maxBytes int64
|
||||
maxPixels int64
|
||||
pipelineVersion int
|
||||
maxAttempts int
|
||||
}
|
||||
|
||||
func NewAttachmentService(repo AttachmentRepository, chats repository.ChatRepository, store storage.Store, maxBytes, maxPixels int64, pipelineVersion, maxAttempts int) *AttachmentService {
|
||||
return &AttachmentService{repo: repo, chats: chats, store: store, maxBytes: maxBytes, maxPixels: maxPixels,
|
||||
pipelineVersion: pipelineVersion, maxAttempts: maxAttempts}
|
||||
}
|
||||
|
||||
// validateFilename: 1–255 code points, не только пробелы, без / \ NUL и управляющих.
|
||||
func validateFilename(s string) bool {
|
||||
if !utf8.ValidString(s) || strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
if n := utf8.RuneCountInString(s); n < 1 || n > 255 {
|
||||
return false
|
||||
}
|
||||
for _, r := range s {
|
||||
if r == '/' || r == '\\' || r == 0 || unicode.IsControl(r) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// declaredType нормализует Content-Type запроса; допустимы только PNG/JPEG.
|
||||
func declaredType(h string) (string, bool) {
|
||||
mt, _, err := mime.ParseMediaType(h)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
mt = strings.ToLower(mt)
|
||||
return mt, mt == imagecheck.PNG || mt == imagecheck.JPEG
|
||||
}
|
||||
|
||||
// Upload принимает сырые байты одного изображения и возвращает снимок queued (202).
|
||||
//
|
||||
// Порядок: намерение в PostgreSQL (uploading) → потоковый PUT в S3-staging,
|
||||
// параллельно SHA-256 и структурная проверка изображения → ОДНА транзакция:
|
||||
// status=queued + задание + сообщение outbox. 202 возвращается только после
|
||||
// COMMIT: в этот момент устойчиво сохранены проверенный оригинал (staging),
|
||||
// метаданные и намерение обработки; broker для 202 не нужен (outbox опубликует).
|
||||
//
|
||||
// Ошибка до MarkQueued (проверка, PUT, обрыв клиента) компенсируется сразу:
|
||||
// удаляются объект и намерение. Ошибка самого MarkQueued — неопределённый исход
|
||||
// (COMMIT мог пройти): объект НЕ удаляется; остаток uploading+объект уберёт
|
||||
// reconciler после grace. Состояния «queued без оригинала» не бывает.
|
||||
func (s *AttachmentService) Upload(ctx context.Context, ownerID, chatID, filename, contentType string, body io.Reader, contentLength int64) (*domain.Attachment, error) {
|
||||
parsed, err := uuid.Parse(chatID)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
chatID = parsed.String()
|
||||
ok, err := s.chats.IsMember(ctx, chatID, ownerID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if !validateFilename(filename) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
declared, ok := declaredType(contentType)
|
||||
if !ok {
|
||||
return nil, ErrUnsupportedMedia
|
||||
}
|
||||
// Лимит размера — до чтения тела.
|
||||
if contentLength > s.maxBytes {
|
||||
return nil, ErrPayloadTooLarge
|
||||
}
|
||||
size := contentLength
|
||||
if size < 0 {
|
||||
// Без Content-Length (chunked): буфер не больше лимита + 1 байт.
|
||||
buf, err := io.ReadAll(io.LimitReader(body, s.maxBytes+1))
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if int64(len(buf)) > s.maxBytes {
|
||||
return nil, ErrPayloadTooLarge
|
||||
}
|
||||
body, size = bytes.NewReader(buf), int64(len(buf))
|
||||
}
|
||||
if size == 0 {
|
||||
return nil, ErrUnsupportedMedia
|
||||
}
|
||||
|
||||
// Формат — по содержимому; подмена Content-Type → 415.
|
||||
br := bufio.NewReaderSize(body, 64*1024)
|
||||
head, _ := br.Peek(int(min(size, 64*1024)))
|
||||
format, ok := imagecheck.Sniff(head)
|
||||
if !ok || format != declared {
|
||||
return nil, ErrUnsupportedMedia
|
||||
}
|
||||
// Ранний отказ по пикселям, если заголовок уместился в первые 64 KiB.
|
||||
if cfg, _, err := image.DecodeConfig(bytes.NewReader(head)); err == nil {
|
||||
if int64(cfg.Width)*int64(cfg.Height) > s.maxPixels {
|
||||
return nil, ErrPayloadTooLarge
|
||||
}
|
||||
}
|
||||
|
||||
now := nowUTC()
|
||||
id := newID()
|
||||
a := &domain.Attachment{
|
||||
ID: id, ChatID: chatID, OwnerID: ownerID, Filename: filename,
|
||||
ObjectKey: StagingPrefix + chatID + "/" + id,
|
||||
Status: domain.AttachmentUploading, CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
if err := s.repo.CreateIntent(ctx, a); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sum, putErr := s.putValidated(ctx, a.ObjectKey, br, size, format)
|
||||
if putErr != nil {
|
||||
s.compensate(ctx, a, putErr)
|
||||
return nil, putErr
|
||||
}
|
||||
|
||||
a.Status = domain.AttachmentQueued
|
||||
a.ContentType = format
|
||||
a.SizeBytes = size
|
||||
a.SHA256 = sum
|
||||
a.StagingKey = a.ObjectKey
|
||||
a.UpdatedAt = nowUTC()
|
||||
// Байты уже сохранены: доводим учёт до конца, даже если клиент отвалился.
|
||||
mctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
|
||||
defer cancel()
|
||||
if _, err := s.repo.MarkQueued(mctx, a, s.pipelineVersion, s.maxAttempts); err != nil {
|
||||
s.markReadyFailed(ctx, a, err)
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
var errClientBody = errors.New("request body read failed")
|
||||
|
||||
// trackingReader запоминает ошибку чтения, отличную от EOF.
|
||||
type trackingReader struct {
|
||||
r io.Reader
|
||||
err error
|
||||
}
|
||||
|
||||
func (t *trackingReader) Read(p []byte) (int, error) {
|
||||
n, err := t.r.Read(p)
|
||||
if err != nil && err != io.EOF {
|
||||
t.err = err
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
type bodyReader struct{ r io.Reader }
|
||||
|
||||
func (b bodyReader) Read(p []byte) (int, error) {
|
||||
n, err := b.r.Read(p)
|
||||
if err != nil && err != io.EOF {
|
||||
return n, errors.Join(errClientBody, err)
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
// putValidated пишет объект в S3 и одновременно проверяет изображение и считает
|
||||
// SHA-256. Байты проходят потоком (pipe), в памяти — только буферы чтения.
|
||||
func (s *AttachmentService) putValidated(ctx context.Context, key string, body io.Reader, size int64, format string) (string, error) {
|
||||
pr, pw := io.Pipe()
|
||||
valErr := make(chan error, 1)
|
||||
go func() {
|
||||
tr := &trackingReader{r: pr}
|
||||
_, err := imagecheck.Validate(tr, format, s.maxPixels)
|
||||
if tr.err != nil {
|
||||
// Поток оборвали снаружи (PUT в S3 упал или клиент отвалился):
|
||||
// изображение тут ни при чём, причину определит putErr.
|
||||
valErr <- nil
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
pr.CloseWithError(err) // прерывает PUT: дальше писать некуда
|
||||
}
|
||||
valErr <- err
|
||||
}()
|
||||
|
||||
h := sha256.New()
|
||||
src := io.TeeReader(io.TeeReader(bodyReader{body}, h), pw)
|
||||
putErr := s.store.Put(ctx, key, src, size, format)
|
||||
if putErr != nil {
|
||||
pw.CloseWithError(putErr)
|
||||
} else {
|
||||
pw.Close()
|
||||
}
|
||||
vErr := <-valErr
|
||||
|
||||
switch {
|
||||
case errors.Is(vErr, imagecheck.ErrTooLarge):
|
||||
return "", ErrPayloadTooLarge
|
||||
case errors.Is(vErr, imagecheck.ErrInvalid):
|
||||
return "", ErrUnsupportedMedia
|
||||
case errors.Is(putErr, errClientBody):
|
||||
return "", ErrInvalidInput
|
||||
case putErr != nil:
|
||||
slog.Warn("attachment upload to s3 failed", "err", putErr)
|
||||
return "", ErrUnavailable
|
||||
case vErr != nil:
|
||||
return "", ErrUnsupportedMedia
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// markReadyFailed: исход UPDATE неизвестен — объект оставляем. Пробуем убрать
|
||||
// намерение (DELETE ... WHERE status='uploading' безопасен при любом исходе:
|
||||
// если UPDATE уже закоммичен, он ничего не удалит). Если и это не удалось —
|
||||
// uploading+объект уберёт reconciler после grace period.
|
||||
func (s *AttachmentService) markReadyFailed(ctx context.Context, a *domain.Attachment, cause error) {
|
||||
cctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := s.repo.DeleteIntent(cctx, a.ID); err != nil {
|
||||
slog.Warn("mark ready failed, intent left for reconciler", "attachment_id", a.ID, "cause", cause.Error(), "err", err)
|
||||
return
|
||||
}
|
||||
slog.Warn("mark ready failed, object left for reconciler", "attachment_id", a.ID, "cause", cause.Error())
|
||||
}
|
||||
|
||||
// compensate убирает следы неудачной загрузки. Работает и после обрыва клиента
|
||||
// (контекст запроса отменён), поэтому использует отдельный контекст.
|
||||
func (s *AttachmentService) compensate(ctx context.Context, a *domain.Attachment, cause error) {
|
||||
cctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := s.store.Delete(cctx, a.ObjectKey); err != nil {
|
||||
slog.Warn("compensation: delete object failed, reconciler will retry", "attachment_id", a.ID, "err", err)
|
||||
}
|
||||
if err := s.repo.DeleteIntent(cctx, a.ID); err != nil {
|
||||
slog.Warn("compensation: delete intent failed, reconciler will retry", "attachment_id", a.ID, "err", err)
|
||||
}
|
||||
slog.Info("attachment upload compensated", "attachment_id", a.ID, "cause", cause.Error())
|
||||
}
|
||||
|
||||
// Get возвращает метаданные вложения участнику его чата (queued/processing/
|
||||
// ready/failed); у ready — варианты опубликованной версии pipeline.
|
||||
func (s *AttachmentService) Get(ctx context.Context, userID, id string) (*domain.Attachment, error) {
|
||||
parsed, err := uuid.Parse(id)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
a, err := s.repo.GetForMember(ctx, parsed.String(), userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
switch a.Status {
|
||||
case domain.AttachmentReady:
|
||||
if a.PipelineVersion > 0 {
|
||||
if a.Variants, err = s.repo.Variants(ctx, a.ID, a.PipelineVersion); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return a, nil
|
||||
case domain.AttachmentQueued, domain.AttachmentProcessing, domain.AttachmentFailed:
|
||||
return a, nil
|
||||
case domain.AttachmentMissing:
|
||||
// Метаданные есть, байтов нет (обнаружил reconciler): ошибка сервера, не клиента.
|
||||
return nil, ErrUnavailable
|
||||
default:
|
||||
return nil, ErrNotFound // загрузка не завершена — объекта для клиента ещё нет
|
||||
}
|
||||
}
|
||||
|
||||
// Content — что отдавать клиенту: тип, размер и ключ объекта.
|
||||
type Content struct {
|
||||
ContentType string
|
||||
Size int64
|
||||
Key string
|
||||
}
|
||||
|
||||
// Open открывает оригинал или вариант на чтение. Вызывающий закрывает ReadCloser.
|
||||
// queued/processing/failed → 409 (объект не готов), отсутствующий у ready
|
||||
// вариант → 404.
|
||||
func (s *AttachmentService) Open(ctx context.Context, userID, id, variant string) (*Content, io.ReadCloser, error) {
|
||||
a, err := s.Get(ctx, userID, id)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if a.Status != domain.AttachmentReady {
|
||||
return nil, nil, ErrConflict
|
||||
}
|
||||
c := &Content{ContentType: a.ContentType, Size: a.SizeBytes, Key: a.ObjectKey}
|
||||
if variant != "" && variant != "original" {
|
||||
c = nil
|
||||
for _, v := range a.Variants {
|
||||
if v.Name == variant {
|
||||
c = &Content{ContentType: v.ContentType, Size: v.SizeBytes, Key: v.ObjectKey}
|
||||
}
|
||||
}
|
||||
if c == nil {
|
||||
return nil, nil, ErrNotFound
|
||||
}
|
||||
}
|
||||
rc, size, err := s.store.Get(ctx, c.Key)
|
||||
if err != nil {
|
||||
if errors.Is(err, storage.ErrNotFound) {
|
||||
slog.Error("attachment object missing in s3", "attachment_id", a.ID)
|
||||
} else {
|
||||
slog.Warn("s3 get failed", "attachment_id", a.ID, "err", err)
|
||||
}
|
||||
return nil, nil, ErrUnavailable
|
||||
}
|
||||
if size != c.Size {
|
||||
rc.Close()
|
||||
slog.Error("attachment size mismatch", "attachment_id", a.ID, "variant", variant, "s3", size, "db", c.Size)
|
||||
return nil, nil, ErrUnavailable
|
||||
}
|
||||
return c, rc, nil
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/storage"
|
||||
)
|
||||
|
||||
// failingStore читает failAfter байт и падает — как PUT в недоступный S3.
|
||||
type failingStore struct {
|
||||
storage.Store
|
||||
failAfter int64
|
||||
got []byte
|
||||
}
|
||||
|
||||
func (f *failingStore) Put(_ context.Context, _ string, r io.Reader, size int64, _ string) error {
|
||||
if f.failAfter < 0 {
|
||||
b, err := io.ReadAll(r)
|
||||
f.got = b
|
||||
return err
|
||||
}
|
||||
b, err := io.ReadAll(io.LimitReader(r, f.failAfter))
|
||||
f.got = b
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return errors.New("s3 put: connection refused")
|
||||
}
|
||||
|
||||
type errReader struct{ data []byte }
|
||||
|
||||
func (e *errReader) Read(p []byte) (int, error) {
|
||||
if len(e.data) == 0 {
|
||||
return 0, errors.New("connection reset by peer")
|
||||
}
|
||||
n := copy(p, e.data)
|
||||
e.data = e.data[n:]
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func samplePNG(t *testing.T) []byte {
|
||||
img := image.NewRGBA(image.Rect(0, 0, 200, 150))
|
||||
for y := 0; y < 150; y++ {
|
||||
for x := 0; x < 200; x++ {
|
||||
img.Set(x, y, color.RGBA{uint8(x), uint8(y), uint8(x ^ y), 255})
|
||||
}
|
||||
}
|
||||
var b bytes.Buffer
|
||||
if err := png.Encode(&b, img); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
func TestPutValidatedClassifiesCause(t *testing.T) {
|
||||
data := samplePNG(t)
|
||||
size := int64(len(data))
|
||||
svc := &AttachmentService{maxBytes: 10 << 20, maxPixels: 40_000_000}
|
||||
|
||||
// S3 падает посреди потока: это 503, а не «битое изображение».
|
||||
svc.store = &failingStore{failAfter: size / 3}
|
||||
if _, err := svc.putValidated(context.Background(), "k", bytes.NewReader(data), size, "image/png"); !errors.Is(err, ErrUnavailable) {
|
||||
t.Errorf("s3 failure mid-stream: got %v, want ErrUnavailable", err)
|
||||
}
|
||||
// S3 падает сразу.
|
||||
svc.store = &failingStore{failAfter: 0}
|
||||
if _, err := svc.putValidated(context.Background(), "k", bytes.NewReader(data), size, "image/png"); !errors.Is(err, ErrUnavailable) {
|
||||
t.Errorf("s3 failure at start: got %v, want ErrUnavailable", err)
|
||||
}
|
||||
// Клиент оборвал тело: 400, не 415 и не 503.
|
||||
svc.store = &failingStore{failAfter: -1}
|
||||
if _, err := svc.putValidated(context.Background(), "k", &errReader{data: data[:len(data)/2]}, size, "image/png"); !errors.Is(err, ErrInvalidInput) {
|
||||
t.Errorf("client body error: got %v, want ErrInvalidInput", err)
|
||||
}
|
||||
// Битое изображение при исправном S3: 415.
|
||||
bad := bytes.Clone(data)
|
||||
bad[len(bad)/2] ^= 0xFF
|
||||
svc.store = &failingStore{failAfter: -1}
|
||||
if _, err := svc.putValidated(context.Background(), "k", bytes.NewReader(bad), size, "image/png"); !errors.Is(err, ErrUnsupportedMedia) {
|
||||
t.Errorf("corrupt image: got %v, want ErrUnsupportedMedia", err)
|
||||
}
|
||||
// Всё хорошо: SHA-256 и байты целиком дошли до S3.
|
||||
ok := &failingStore{failAfter: -1}
|
||||
svc.store = ok
|
||||
sum, err := svc.putValidated(context.Background(), "k", bytes.NewReader(data), size, "image/png")
|
||||
if err != nil || len(sum) != 64 || !bytes.Equal(ok.got, data) {
|
||||
t.Errorf("valid upload: sum=%q err=%v bytes_equal=%v", sum, err, bytes.Equal(ok.got, data))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab5/internal/repository"
|
||||
)
|
||||
|
||||
type AuthService struct {
|
||||
users repository.UserRepository
|
||||
sessions repository.SessionRepository
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
func NewAuthService(users repository.UserRepository, sessions repository.SessionRepository, ttl time.Duration) *AuthService {
|
||||
return &AuthService{users: users, sessions: sessions, ttl: ttl}
|
||||
}
|
||||
|
||||
func (s *AuthService) Login(ctx context.Context, username, password string) (*domain.Session, *domain.User, error) {
|
||||
u, err := s.users.GetByUsername(ctx, username)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
_, _ = hashPassword("dummy-password-for-timing")
|
||||
return nil, nil, ErrUnauthorized
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
hash, err := s.users.GetPasswordHash(ctx, u.ID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
if err := verifyPassword(password, hash); err != nil {
|
||||
if errors.Is(err, ErrPasswordMismatch) {
|
||||
return nil, nil, ErrUnauthorized
|
||||
}
|
||||
return nil, nil, fmt.Errorf("verify password: %w", err)
|
||||
}
|
||||
|
||||
token, err := generateToken()
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("generate token: %w", err)
|
||||
}
|
||||
|
||||
now := nowUTC()
|
||||
sess := &domain.Session{
|
||||
Token: token,
|
||||
UserID: u.ID,
|
||||
ExpiresAt: now.Add(s.ttl),
|
||||
CreatedAt: now,
|
||||
}
|
||||
if err := s.sessions.Create(ctx, sess); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return sess, u, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) ValidateSession(ctx context.Context, token string) (*domain.User, error) {
|
||||
sess, err := s.sessions.GetByToken(ctx, token)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
// Redis недоступен — возвращаем 401, чтобы клиент перелогинился,
|
||||
// либо 503, если хотим явно показать проблему зависимости.
|
||||
return nil, ErrUnauthorized // ← было: return nil, err
|
||||
}
|
||||
if nowUTC().After(sess.ExpiresAt) {
|
||||
_ = s.sessions.Delete(ctx, token)
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
u, err := s.users.GetByID(ctx, sess.UserID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) Logout(ctx context.Context, token string) error {
|
||||
return s.sessions.Delete(ctx, token)
|
||||
}
|
||||
|
||||
func generateToken() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab5/internal/repository"
|
||||
)
|
||||
|
||||
type ChatService struct {
|
||||
chats repository.ChatRepository
|
||||
users repository.UserRepository
|
||||
}
|
||||
|
||||
func NewChatService(chats repository.ChatRepository, users repository.UserRepository) *ChatService {
|
||||
return &ChatService{chats: chats, users: users}
|
||||
}
|
||||
|
||||
func (s *ChatService) Create(ctx context.Context, callerID, title string, memberIDs []string) (*domain.Chat, error) {
|
||||
if !validateTitle(title) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if len(memberIDs) == 0 || len(memberIDs) > 100 {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
// Нормализация UUID: убираем разницу регистра.
|
||||
normalized := make([]string, 0, len(memberIDs))
|
||||
seen := make(map[string]struct{}, len(memberIDs))
|
||||
callerFound := false
|
||||
callerParsed, err := uuid.Parse(callerID)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
callerID = callerParsed.String()
|
||||
|
||||
for _, id := range memberIDs {
|
||||
parsed, err := uuid.Parse(id)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
id = parsed.String()
|
||||
if _, dup := seen[id]; dup {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
normalized = append(normalized, id)
|
||||
if id == callerID {
|
||||
callerFound = true
|
||||
}
|
||||
}
|
||||
if !callerFound {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
for id := range seen {
|
||||
if _, err := s.users.GetByID(ctx, id); err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
c := &domain.Chat{
|
||||
ID: newID(),
|
||||
Title: title,
|
||||
MemberIDs: normalized,
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
if err := s.chats.Create(ctx, c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *ChatService) Get(ctx context.Context, callerID, chatID string) (*domain.Chat, error) {
|
||||
parsed, err := uuid.Parse(chatID)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
chatID = parsed.String()
|
||||
|
||||
ok, err := s.chats.IsMember(ctx, chatID, callerID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
c, err := s.chats.GetByID(ctx, chatID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *ChatService) List(ctx context.Context, callerID, cursor string, limit int) ([]*domain.Chat, string, error) {
|
||||
if limit < 1 || limit > 100 {
|
||||
return nil, "", ErrInvalidInput
|
||||
}
|
||||
|
||||
cursorTime := time.Unix(0, 0).UTC()
|
||||
cursorID := "00000000-0000-0000-0000-000000000000"
|
||||
if cursor != "" {
|
||||
t, id, err := decodeCursor(cursor, callerID)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
cursorTime, cursorID = t, id
|
||||
}
|
||||
|
||||
items, err := s.chats.ListByMember(ctx, callerID, cursorTime, cursorID, limit+1)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if items == nil {
|
||||
items = []*domain.Chat{}
|
||||
}
|
||||
|
||||
var next string
|
||||
if len(items) > limit {
|
||||
items = items[:limit]
|
||||
last := items[limit-1]
|
||||
next = encodeCursor(callerID, last.CreatedAt, last.ID)
|
||||
}
|
||||
return items, next, nil
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func encodeCursor(scope string, createdAt time.Time, id string) string {
|
||||
raw := scope + "|" + createdAt.UTC().Format(time.RFC3339Nano) + "|" + id
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
func decodeCursor(cursor, expectedScope string) (time.Time, string, error) {
|
||||
raw, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return time.Time{}, "", ErrInvalidInput
|
||||
}
|
||||
parts := strings.SplitN(string(raw), "|", 3)
|
||||
if len(parts) != 3 {
|
||||
return time.Time{}, "", ErrInvalidInput
|
||||
}
|
||||
if _, err := uuid.Parse(parts[0]); err != nil {
|
||||
return time.Time{}, "", ErrInvalidInput
|
||||
}
|
||||
if parts[0] != expectedScope {
|
||||
return time.Time{}, "", ErrInvalidInput
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil {
|
||||
return time.Time{}, "", ErrInvalidInput
|
||||
}
|
||||
if _, err := uuid.Parse(parts[2]); err != nil {
|
||||
return time.Time{}, "", ErrInvalidInput
|
||||
}
|
||||
return t, parts[2], nil
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package service
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrInvalidInput = errors.New("invalid input")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrUnavailable = errors.New("unavailable")
|
||||
ErrPasswordMismatch = errors.New("password mismatch")
|
||||
ErrPayloadTooLarge = errors.New("payload too large")
|
||||
ErrUnsupportedMedia = errors.New("unsupported media type")
|
||||
)
|
||||
@@ -0,0 +1,23 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func newID() string {
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
panic(fmt.Sprintf("crypto/rand failed: %v", err))
|
||||
}
|
||||
b[6] = (b[6] & 0x0f) | 0x40
|
||||
b[8] = (b[8] & 0x3f) | 0x80
|
||||
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
|
||||
}
|
||||
|
||||
// nowUTC возвращает время UTC с точностью до секунд.
|
||||
// PostgreSQL и Python-клиент тестов ожидают формат без наносекунд.
|
||||
func nowUTC() time.Time {
|
||||
return time.Now().UTC().Truncate(time.Second)
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab5/internal/repository"
|
||||
redisrepo "github.com/charawein/mtusi2026lab5/internal/repository/redis"
|
||||
)
|
||||
|
||||
type MessageService struct {
|
||||
messages repository.MessageRepository
|
||||
chats repository.ChatRepository
|
||||
cache *redisrepo.MessageCache
|
||||
idempotencyTTL time.Duration
|
||||
}
|
||||
|
||||
func NewMessageService(messages repository.MessageRepository, chats repository.ChatRepository, cache *redisrepo.MessageCache, idempotencyTTL time.Duration) *MessageService {
|
||||
return &MessageService{messages: messages, chats: chats, cache: cache, idempotencyTTL: idempotencyTTL}
|
||||
}
|
||||
|
||||
var idempotencyKeyRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
// requestHash — отпечаток семантики тела запроса. Хешируем уже разобранные поля,
|
||||
// а не сырые байты: порядок ключей JSON не важен, отсутствующий attachment_ids
|
||||
// равен [], порядок самих вложений значим.
|
||||
func requestHash(text string, attachmentIDs []string) string {
|
||||
if attachmentIDs == nil {
|
||||
attachmentIDs = []string{}
|
||||
}
|
||||
raw, _ := json.Marshal(struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}{Text: text, AttachmentIDs: attachmentIDs})
|
||||
sum := sha256.Sum256(raw)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// Send создаёт сообщение с обязательным Idempotency-Key. Повтор с тем же ключом
|
||||
// и телом возвращает исходное сообщение, с другим телом — ErrConflict.
|
||||
// Доступ к чату проверяется при каждом повторе.
|
||||
func (s *MessageService) Send(ctx context.Context, senderID, chatID, text string, attachmentIDs []string, idempotencyKey string) (*domain.Message, error) {
|
||||
if !idempotencyKeyRe.MatchString(idempotencyKey) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
parsed, err := uuid.Parse(chatID)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
chatID = parsed.String()
|
||||
|
||||
ids, ok := normalizeAttachmentIDs(attachmentIDs)
|
||||
if !ok {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
// С вложениями допустим пустой text; иначе — обычные правила текста.
|
||||
if !(len(ids) > 0 && text == "") && !validateText(text) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
ok, err = s.chats.IsMember(ctx, chatID, senderID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
|
||||
m := &domain.Message{
|
||||
ID: newID(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: nowUTC(),
|
||||
|
||||
AttachmentIDs: ids,
|
||||
}
|
||||
stored, created, err := s.messages.CreateIdempotent(ctx, m, idempotencyKey, requestHash(text, ids), s.idempotencyTTL)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, repository.ErrConflict):
|
||||
return nil, ErrConflict
|
||||
case errors.Is(err, repository.ErrNotFound):
|
||||
return nil, ErrNotFound // чужое/неизвестное/незавершённое вложение
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if !created {
|
||||
return stored, nil
|
||||
}
|
||||
|
||||
// Версия чата уже увеличена в транзакции записи; здесь только режим scan.
|
||||
if s.cache != nil {
|
||||
s.cache.OnWrite(ctx, chatID)
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (s *MessageService) List(ctx context.Context, callerID, chatID, cursor string, limit int) ([]*domain.Message, string, error) {
|
||||
parsed, err := uuid.Parse(chatID)
|
||||
if err != nil {
|
||||
return nil, "", ErrInvalidInput
|
||||
}
|
||||
chatID = parsed.String()
|
||||
|
||||
if limit < 1 || limit > 100 {
|
||||
return nil, "", ErrInvalidInput
|
||||
}
|
||||
|
||||
// Членство и версия истории — одним запросом к PostgreSQL. Версия читается
|
||||
// до истории, поэтому под ключом версии v лежат данные не старее v.
|
||||
version, ok, err := s.chats.MemberVersion(ctx, chatID, callerID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, "", ErrNotFound
|
||||
}
|
||||
return nil, "", err
|
||||
}
|
||||
if !ok {
|
||||
return nil, "", ErrNotFound
|
||||
}
|
||||
|
||||
if s.cache != nil {
|
||||
if items, next, hit := s.cache.Get(ctx, chatID, version, cursor, limit); hit {
|
||||
return items, next, nil
|
||||
}
|
||||
}
|
||||
|
||||
cursorTime := time.Unix(0, 0).UTC()
|
||||
cursorID := "00000000-0000-0000-0000-000000000000"
|
||||
if cursor != "" {
|
||||
t, id, err := decodeCursor(cursor, chatID)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
cursorTime, cursorID = t, id
|
||||
}
|
||||
|
||||
items, err := s.messages.ListByChat(ctx, chatID, cursorTime, cursorID, limit+1)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if items == nil {
|
||||
items = []*domain.Message{}
|
||||
}
|
||||
|
||||
var next string
|
||||
if len(items) > limit {
|
||||
items = items[:limit]
|
||||
last := items[limit-1]
|
||||
next = encodeCursor(chatID, last.CreatedAt, last.ID)
|
||||
}
|
||||
|
||||
if s.cache != nil {
|
||||
s.cache.Set(ctx, chatID, version, cursor, limit, items, next)
|
||||
}
|
||||
return items, next, nil
|
||||
}
|
||||
|
||||
// normalizeAttachmentIDs: 0–10 уникальных UUID; приводит к каноническому виду.
|
||||
func normalizeAttachmentIDs(in []string) ([]string, bool) {
|
||||
if len(in) > 10 {
|
||||
return nil, false
|
||||
}
|
||||
out := make([]string, 0, len(in))
|
||||
seen := make(map[string]bool, len(in))
|
||||
for _, raw := range in {
|
||||
u, err := uuid.Parse(raw)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
id := u.String()
|
||||
if seen[id] {
|
||||
return nil, false
|
||||
}
|
||||
seen[id] = true
|
||||
out = append(out, id)
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
argonTime = 1
|
||||
argonMemory = 64 * 1024
|
||||
argonThreads = 4
|
||||
argonKeyLen = 32
|
||||
argonSaltLen = 16
|
||||
)
|
||||
|
||||
func hashPassword(password string) (string, error) {
|
||||
salt := make([]byte, argonSaltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("generate salt: %w", err)
|
||||
}
|
||||
hash := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
||||
return fmt.Sprintf(
|
||||
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version, argonMemory, argonTime, argonThreads,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(hash),
|
||||
), nil
|
||||
}
|
||||
|
||||
func verifyPassword(password, encoded string) error {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return fmt.Errorf("invalid hash format")
|
||||
}
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
|
||||
return fmt.Errorf("parse version: %w", err)
|
||||
}
|
||||
if version != argon2.Version {
|
||||
return fmt.Errorf("incompatible version: %d", version)
|
||||
}
|
||||
var mem uint32
|
||||
var iters uint32
|
||||
var threads uint8
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &mem, &iters, &threads); err != nil {
|
||||
return fmt.Errorf("parse params: %w", err)
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode salt: %w", err)
|
||||
}
|
||||
want, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode hash: %w", err)
|
||||
}
|
||||
got := argon2.IDKey([]byte(password), salt, iters, mem, threads, uint32(len(want)))
|
||||
if subtle.ConstantTimeCompare(got, want) != 1 {
|
||||
return ErrPasswordMismatch
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab5/internal/repository"
|
||||
)
|
||||
|
||||
type UserService struct {
|
||||
users repository.UserRepository
|
||||
}
|
||||
|
||||
func NewUserService(users repository.UserRepository) *UserService {
|
||||
return &UserService{users: users}
|
||||
}
|
||||
|
||||
// Register создаёт нового пользователя. Возвращает ErrInvalidInput при невалидных
|
||||
// данных и ErrConflict, если username занят.
|
||||
func (s *UserService) Register(ctx context.Context, username, displayName, password string) (*domain.User, error) {
|
||||
if !validateUsername(username) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if !validateDisplayName(displayName) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if !validatePassword(password) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
hash, err := hashPassword(password)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("hash password: %w", err)
|
||||
}
|
||||
|
||||
u := &domain.User{
|
||||
ID: newID(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
if err := s.users.Create(ctx, u, hash); err != nil {
|
||||
if errors.Is(err, repository.ErrConflict) {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// GetByID возвращает пользователя. Возвращает ErrNotFound, если такого нет.
|
||||
// Используется middleware аутентификации для проверки X-User-Id.
|
||||
func (s *UserService) GetByID(ctx context.Context, id string) (*domain.User, error) {
|
||||
u, err := s.users.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
// validatePassword: 12–128 code points и не только пробельные символы
|
||||
// (обязательная строка по контракту не может состоять из одних пробелов).
|
||||
func validatePassword(s string) bool {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 12 && n <= 128
|
||||
}
|
||||
|
||||
// validateUsername проверяет формат username по README: строго [a-z0-9_]{3,32}.
|
||||
func validateUsername(s string) bool {
|
||||
return usernameRe.MatchString(s)
|
||||
}
|
||||
|
||||
// validateDisplayName проверяет display_name: 1–100 Unicode code points,
|
||||
// не состоит только из пробельных символов.
|
||||
func validateDisplayName(s string) bool {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 1 && n <= 100
|
||||
}
|
||||
|
||||
// validateTitle проверяет title чата: 1–100 code points, не только пробелы.
|
||||
func validateTitle(s string) bool {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 1 && n <= 100
|
||||
}
|
||||
|
||||
// validateText проверяет text сообщения: 1–4000 code points, не только пробелы.
|
||||
// В lab4 появится возможность отправить пустой text, если есть attachment_ids.
|
||||
func validateText(s string) bool {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 1 && n <= 4000
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidatePassword(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
in string
|
||||
want bool
|
||||
}{
|
||||
{"обычный", "correct-horse-12", true},
|
||||
{"ровно 12", strings.Repeat("a", 12), true},
|
||||
{"128 code points", strings.Repeat("я", 128), true},
|
||||
{"двоеточие допустимо", "pass:word:1234", true},
|
||||
{"пробелы внутри допустимы", " pass word ", true},
|
||||
{"короче 12", strings.Repeat("a", 11), false},
|
||||
{"длиннее 128", strings.Repeat("a", 129), false},
|
||||
{"12 пробелов", strings.Repeat(" ", 12), false},
|
||||
{"пробельные символы разных видов", strings.Repeat(" \t\n ", 4), false},
|
||||
{"пусто", "", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := validatePassword(c.in); got != c.want {
|
||||
t.Errorf("%s: validatePassword(%q) = %v, want %v", c.name, c.in, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateText(t *testing.T) {
|
||||
if validateText(strings.Repeat(" ", 5)) {
|
||||
t.Error("whitespace-only text must be rejected")
|
||||
}
|
||||
if !validateText("привет") {
|
||||
t.Error("normal text must be accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
// Package storage — приватное S3-хранилище байтов вложений (MinIO).
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
// ErrNotFound — объекта нет в bucket.
|
||||
var ErrNotFound = errors.New("object not found")
|
||||
|
||||
// Object — элемент листинга.
|
||||
type Object struct {
|
||||
Key string
|
||||
Size int64
|
||||
LastModified time.Time
|
||||
}
|
||||
|
||||
// Store — то, что нужно приложению и reconciler от объектного хранилища.
|
||||
type Store interface {
|
||||
Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error
|
||||
Get(ctx context.Context, key string) (io.ReadCloser, int64, error)
|
||||
Stat(ctx context.Context, key string) (Object, error)
|
||||
Delete(ctx context.Context, key string) error
|
||||
// List отдаёт объекты с префиксом в лексикографическом (байтовом) порядке ключей.
|
||||
List(ctx context.Context, prefix string, fn func(Object) error) error
|
||||
// Copy — серверное копирование объекта (байты не проходят через приложение).
|
||||
Copy(ctx context.Context, src, dst string) error
|
||||
}
|
||||
|
||||
type S3 struct {
|
||||
client *minio.Client
|
||||
bucket string
|
||||
}
|
||||
|
||||
func NewS3(endpoint, region, bucket, accessKey, secretKey string) (*S3, error) {
|
||||
u, err := url.Parse(endpoint)
|
||||
if err != nil || u.Host == "" {
|
||||
return nil, fmt.Errorf("bad S3 endpoint %q", endpoint)
|
||||
}
|
||||
c, err := minio.New(u.Host, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(accessKey, secretKey, ""),
|
||||
Secure: u.Scheme == "https",
|
||||
Region: region,
|
||||
// По умолчанию minio-go повторяет до 10 раз; при недоступном S3 клиент
|
||||
// должен быстро получить 503, а не ждать таймаута LB.
|
||||
MaxRetries: 2,
|
||||
BucketLookup: minio.BucketLookupPath,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("s3 client: %w", err)
|
||||
}
|
||||
return &S3{client: c, bucket: bucket}, nil
|
||||
}
|
||||
|
||||
func isNotFound(err error) bool {
|
||||
code := minio.ToErrorResponse(err).Code
|
||||
return code == "NoSuchKey" || code == "NotFound"
|
||||
}
|
||||
|
||||
// Put пишет объект одним PUT, читая r потоково (size известен заранее).
|
||||
func (s *S3) Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error {
|
||||
_, err := s.client.PutObject(ctx, s.bucket, key, r, size, minio.PutObjectOptions{
|
||||
ContentType: contentType,
|
||||
DisableMultipart: true,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("s3 put: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *S3) Get(ctx context.Context, key string) (io.ReadCloser, int64, error) {
|
||||
obj, err := s.client.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("s3 get: %w", err)
|
||||
}
|
||||
// GetObject ленивый: ошибки (нет объекта, S3 недоступен) видны на Stat.
|
||||
st, err := obj.Stat()
|
||||
if err != nil {
|
||||
obj.Close()
|
||||
if isNotFound(err) {
|
||||
return nil, 0, ErrNotFound
|
||||
}
|
||||
return nil, 0, fmt.Errorf("s3 stat: %w", err)
|
||||
}
|
||||
return obj, st.Size, nil
|
||||
}
|
||||
|
||||
func (s *S3) Stat(ctx context.Context, key string) (Object, error) {
|
||||
st, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{})
|
||||
if err != nil {
|
||||
if isNotFound(err) {
|
||||
return Object{}, ErrNotFound
|
||||
}
|
||||
return Object{}, fmt.Errorf("s3 stat: %w", err)
|
||||
}
|
||||
return Object{Key: st.Key, Size: st.Size, LastModified: st.LastModified}, nil
|
||||
}
|
||||
|
||||
// Delete идемпотентен: удаление отсутствующего объекта не ошибка.
|
||||
func (s *S3) Delete(ctx context.Context, key string) error {
|
||||
if err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}); err != nil && !isNotFound(err) {
|
||||
return fmt.Errorf("s3 delete: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *S3) List(ctx context.Context, prefix string, fn func(Object) error) error {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
for o := range s.client.ListObjects(ctx, s.bucket, minio.ListObjectsOptions{Prefix: prefix, Recursive: true}) {
|
||||
if o.Err != nil {
|
||||
return fmt.Errorf("s3 list: %w", o.Err)
|
||||
}
|
||||
if strings.HasSuffix(o.Key, "/") {
|
||||
continue
|
||||
}
|
||||
if err := fn(Object{Key: o.Key, Size: o.Size, LastModified: o.LastModified}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *S3) Copy(ctx context.Context, src, dst string) error {
|
||||
_, err := s.client.CopyObject(ctx,
|
||||
minio.CopyDestOptions{Bucket: s.bucket, Object: dst},
|
||||
minio.CopySrcOptions{Bucket: s.bucket, Object: src})
|
||||
if err != nil {
|
||||
if isNotFound(err) {
|
||||
return ErrNotFound
|
||||
}
|
||||
return fmt.Errorf("s3 copy: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/service"
|
||||
"github.com/charawein/mtusi2026lab5/internal/transport/httputil"
|
||||
)
|
||||
|
||||
type AttachmentHandler struct {
|
||||
attachments *service.AttachmentService
|
||||
}
|
||||
|
||||
func NewAttachmentHandler(attachments *service.AttachmentService) *AttachmentHandler {
|
||||
return &AttachmentHandler{attachments: attachments}
|
||||
}
|
||||
|
||||
// Upload: POST /api/v1/chats/{chat_id}/attachments?filename=... с сырыми байтами PNG/JPEG.
|
||||
func (h *AttachmentHandler) Upload(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
if uid == "" {
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
if len(q["filename"]) != 1 {
|
||||
httputil.WriteError(w, r, service.ErrInvalidInput)
|
||||
return
|
||||
}
|
||||
// MaxBytesReader — второй рубеж: не дать прочитать больше лимита + 1 байт,
|
||||
// даже если Content-Length солгал.
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 10*1024*1024+1)
|
||||
a, err := h.attachments.Upload(r.Context(), uid, r.PathValue("chat_id"), q.Get("filename"),
|
||||
r.Header.Get("Content-Type"), r.Body, r.ContentLength)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
// 202: оригинал устойчиво принят, обработка асинхронна; готовность — по GET.
|
||||
httputil.WriteJSON(w, r, http.StatusAccepted, a)
|
||||
}
|
||||
|
||||
// Get: GET /api/v1/attachments/{attachment_id} — метаданные.
|
||||
func (h *AttachmentHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
a, err := h.attachments.Get(r.Context(), uid, r.PathValue("attachment_id"))
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusOK, a)
|
||||
}
|
||||
|
||||
// Content: GET /api/v1/attachments/{attachment_id}/content[?variant=original] — байты
|
||||
// через авторизованный API, без redirect на S3.
|
||||
func (h *AttachmentHandler) Content(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
variant := r.URL.Query().Get("variant")
|
||||
switch variant {
|
||||
case "", "original", "thumbnail", "crop", "optimized":
|
||||
default:
|
||||
httputil.WriteError(w, r, service.ErrInvalidInput)
|
||||
return
|
||||
}
|
||||
c, rc, err := h.attachments.Open(r.Context(), uid, r.PathValue("attachment_id"), variant)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
defer rc.Close()
|
||||
w.Header().Set("Content-Type", c.ContentType)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(c.Size, 10))
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if n, err := io.Copy(w, rc); err != nil {
|
||||
// Заголовок уже отправлен: клиент увидит обрыв по Content-Length.
|
||||
slog.Warn("attachment download interrupted", "attachment_id", r.PathValue("attachment_id"), "sent", n, "err", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab5/internal/service"
|
||||
"github.com/charawein/mtusi2026lab5/internal/transport/httputil"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
auth *service.AuthService
|
||||
}
|
||||
|
||||
func NewAuthHandler(auth *service.AuthService) *AuthHandler {
|
||||
return &AuthHandler{auth: auth}
|
||||
}
|
||||
|
||||
type sessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
User *domain.User `json:"user"`
|
||||
}
|
||||
|
||||
func (h *AuthHandler) CreateSession(w http.ResponseWriter, r *http.Request) {
|
||||
username, password, ok := parseBasicAuth(r.Header.Get("Authorization"))
|
||||
if !ok {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
sess, u, err := h.auth.Login(r.Context(), username, password)
|
||||
if err != nil {
|
||||
if err == service.ErrUnauthorized {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
}
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
// Формат RFC3339 без микросекунд: "2026-10-09T19:00:36Z".
|
||||
// Python-клиент тестов ожидает 'Z' в конце строки.
|
||||
httputil.WriteJSON(w, r, http.StatusCreated, sessionResponse{
|
||||
Token: sess.Token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: sess.ExpiresAt.UTC().Truncate(time.Second).Format(time.RFC3339),
|
||||
User: u,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *AuthHandler) RevokeSession(w http.ResponseWriter, r *http.Request) {
|
||||
token := bearerToken(r)
|
||||
if token == "" {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
if err := h.auth.Logout(r.Context(), token); err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func parseBasicAuth(h string) (string, string, bool) {
|
||||
const prefix = "Basic "
|
||||
if !strings.HasPrefix(h, prefix) {
|
||||
return "", "", false
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(h[len(prefix):])
|
||||
if err != nil {
|
||||
return "", "", false
|
||||
}
|
||||
parts := strings.SplitN(string(raw), ":", 2)
|
||||
if len(parts) != 2 {
|
||||
return "", "", false
|
||||
}
|
||||
return parts[0], parts[1], true
|
||||
}
|
||||
|
||||
func bearerToken(r *http.Request) string {
|
||||
h := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(h, "Bearer ") {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimPrefix(h, "Bearer ")
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/service"
|
||||
"github.com/charawein/mtusi2026lab5/internal/transport/httputil"
|
||||
)
|
||||
|
||||
type ChatHandler struct {
|
||||
chats *service.ChatService
|
||||
}
|
||||
|
||||
func NewChatHandler(chats *service.ChatService) *ChatHandler {
|
||||
return &ChatHandler{chats: chats}
|
||||
}
|
||||
|
||||
func (h *ChatHandler) CreateChat(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
if uid == "" {
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
if err := httputil.DecodeJSON(r, &body); err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
c, err := h.chats.Create(r.Context(), uid, body.Title, body.MemberIDs)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusCreated, c)
|
||||
}
|
||||
|
||||
func (h *ChatHandler) ListChats(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
if uid == "" {
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
limit, err := httputil.ParseLimit(r)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
cursor := r.URL.Query().Get("cursor")
|
||||
|
||||
items, next, err := h.chats.List(r.Context(), uid, cursor, limit)
|
||||
if err != nil {
|
||||
// ВРЕМЕННО: логируем точную ошибку
|
||||
slog.Error("ListChats failed", "err", err, "uid", uid, "cursor", cursor, "limit", limit)
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusOK, httputil.PageResponse{Items: items, NextCursor: httputil.NextOrNull(next)})
|
||||
}
|
||||
|
||||
func (h *ChatHandler) GetChat(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
if uid == "" {
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
if chatID == "" {
|
||||
httputil.WriteError(w, r, service.ErrInvalidInput)
|
||||
return
|
||||
}
|
||||
|
||||
c, err := h.chats.Get(r.Context(), uid, chatID)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusOK, c)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/service"
|
||||
"github.com/charawein/mtusi2026lab5/internal/transport/httputil"
|
||||
)
|
||||
|
||||
type HealthHandler struct {
|
||||
pool *pgxpool.Pool
|
||||
redis *redis.Client
|
||||
draining *atomic.Bool
|
||||
}
|
||||
|
||||
func NewHealthHandler(pool *pgxpool.Pool, redisClient *redis.Client, draining *atomic.Bool) *HealthHandler {
|
||||
return &HealthHandler{pool: pool, redis: redisClient, draining: draining}
|
||||
}
|
||||
|
||||
// Live проверяет только жизнь процесса.
|
||||
func (h *HealthHandler) Live(w http.ResponseWriter, r *http.Request) {
|
||||
httputil.WriteJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
|
||||
}
|
||||
|
||||
// Ready проверяет доступность PostgreSQL и Redis.
|
||||
// После SIGTERM возвращает 503, чтобы LB исключил реплику до закрытия listener.
|
||||
func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) {
|
||||
if h.draining.Load() {
|
||||
httputil.WriteError(w, r, service.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := h.pool.Ping(ctx); err != nil {
|
||||
httputil.WriteError(w, r, service.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
if err := h.redis.Ping(ctx).Err(); err != nil {
|
||||
httputil.WriteError(w, r, service.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
|
||||
}
|
||||
|
||||
type healthResponse struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user