forked from mtusi2026/mtusi2026lab4
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ad36ab8a92 | ||
|
|
110236d01f | ||
|
|
b3d5d76302 | ||
|
|
ec0e6707b8 | ||
|
|
7e60f099d3 |
@@ -0,0 +1,93 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches: [main]
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ci-${{ github.repository }}-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
verify:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 45
|
||||||
|
env:
|
||||||
|
COMPOSE_PROJECT_NAME: mtusi2026lab4-${{ github.run_id }}
|
||||||
|
API_BIND_ADDRESS: 127.0.0.1:0
|
||||||
|
SWAGGER_BIND_ADDRESS: 127.0.0.1:0
|
||||||
|
PROMETHEUS_BIND_ADDRESS: 127.0.0.1:0
|
||||||
|
GRAFANA_BIND_ADDRESS: 127.0.0.1:0
|
||||||
|
steps:
|
||||||
|
- name: Checkout exact commit
|
||||||
|
run: |
|
||||||
|
git init .
|
||||||
|
git remote add origin https://gitea.privcloud.tech/${{ github.repository }}.git
|
||||||
|
git fetch --depth=1 origin ${{ github.sha }}
|
||||||
|
git checkout --detach FETCH_HEAD
|
||||||
|
|
||||||
|
- uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version-file: go.mod
|
||||||
|
cache: false
|
||||||
|
|
||||||
|
- name: Check contract
|
||||||
|
run: make check
|
||||||
|
|
||||||
|
- name: Validate OpenAPI
|
||||||
|
run: |
|
||||||
|
python3 -m venv .venv
|
||||||
|
.venv/bin/python -m pip install -r requirements-dev.txt
|
||||||
|
make validate PYTHON=.venv/bin/python
|
||||||
|
|
||||||
|
- name: Check formatting and shell scripts
|
||||||
|
run: |
|
||||||
|
test -z "$(gofmt -l cmd internal migrations)"
|
||||||
|
sh -n infra/minio/bootstrap.sh scripts/restart.sh scripts/rolling-update.sh scripts/stop-one.sh
|
||||||
|
|
||||||
|
- name: Lint
|
||||||
|
uses: golangci/golangci-lint-action@v7
|
||||||
|
with:
|
||||||
|
version: v2.13.2
|
||||||
|
args: --timeout=5m
|
||||||
|
skip-cache: true
|
||||||
|
|
||||||
|
- name: Unit tests and build
|
||||||
|
run: |
|
||||||
|
go test -race ./...
|
||||||
|
go build ./cmd/...
|
||||||
|
|
||||||
|
- name: Prepare local stack
|
||||||
|
run: |
|
||||||
|
cp lab4.env.example .env
|
||||||
|
docker compose config --quiet
|
||||||
|
docker compose up -d --build --scale api=2 --wait --wait-timeout 150
|
||||||
|
network=$(docker inspect --format '{{range $name, $_ := .NetworkSettings.Networks}}{{$name}}{{end}}' "$(docker compose ps -q nginx)")
|
||||||
|
docker network connect "$network" "$HOSTNAME"
|
||||||
|
printf '%s\n' "$network" > .ci-network
|
||||||
|
|
||||||
|
- name: Integration checks
|
||||||
|
run: |
|
||||||
|
set -a
|
||||||
|
. ./.env
|
||||||
|
set +a
|
||||||
|
test "$(curl --noproxy '*' -s -o /dev/null -w '%{http_code}' "http://s3:9000/$S3_BUCKET")" = "403"
|
||||||
|
make test BASE_URL=http://nginx:8080
|
||||||
|
docker compose --profile tests run --rm --build tests
|
||||||
|
go run ./cmd/dependencycheck -base-url=http://nginx:8080
|
||||||
|
make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL=http://nginx:8080
|
||||||
|
make test-failover ACTION_SCRIPT=scripts/stop-one.sh BASE_URL=http://nginx:8080
|
||||||
|
docker compose up -d --scale api=2 --wait --wait-timeout 90
|
||||||
|
|
||||||
|
- name: Container logs
|
||||||
|
if: failure()
|
||||||
|
run: if [ -f .env ]; then docker compose logs --no-color --tail=200; fi
|
||||||
|
|
||||||
|
- name: Stop local stack
|
||||||
|
if: always()
|
||||||
|
run: |
|
||||||
|
if [ -f .ci-network ]; then docker network disconnect "$(cat .ci-network)" "$HOSTNAME"; fi
|
||||||
|
if [ -f .env ]; then docker compose --profile tests down -v --remove-orphans; fi
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
name: Deploy production
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: production
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
verify:
|
||||||
|
name: Verify selected commit
|
||||||
|
if: github.ref == 'refs/heads/main'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 45
|
||||||
|
env:
|
||||||
|
COMPOSE_PROJECT_NAME: mtusi2026lab4-deploy-${{ github.run_id }}
|
||||||
|
API_BIND_ADDRESS: 127.0.0.1:0
|
||||||
|
SWAGGER_BIND_ADDRESS: 127.0.0.1:0
|
||||||
|
PROMETHEUS_BIND_ADDRESS: 127.0.0.1:0
|
||||||
|
GRAFANA_BIND_ADDRESS: 127.0.0.1:0
|
||||||
|
steps:
|
||||||
|
- name: Checkout exact commit
|
||||||
|
run: |
|
||||||
|
git init .
|
||||||
|
git remote add origin https://gitea.privcloud.tech/${{ github.repository }}.git
|
||||||
|
git fetch --depth=1 origin ${{ github.sha }}
|
||||||
|
git checkout --detach FETCH_HEAD
|
||||||
|
|
||||||
|
- uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version-file: go.mod
|
||||||
|
cache: false
|
||||||
|
|
||||||
|
- name: Check contract
|
||||||
|
run: make check
|
||||||
|
|
||||||
|
- name: Validate OpenAPI
|
||||||
|
run: |
|
||||||
|
python3 -m venv .venv
|
||||||
|
.venv/bin/python -m pip install -r requirements-dev.txt
|
||||||
|
make validate PYTHON=.venv/bin/python
|
||||||
|
|
||||||
|
- name: Check formatting and shell scripts
|
||||||
|
run: |
|
||||||
|
test -z "$(gofmt -l cmd internal migrations)"
|
||||||
|
sh -n infra/minio/bootstrap.sh scripts/restart.sh scripts/rolling-update.sh scripts/stop-one.sh
|
||||||
|
|
||||||
|
- name: Lint
|
||||||
|
uses: golangci/golangci-lint-action@v7
|
||||||
|
with:
|
||||||
|
version: v2.13.2
|
||||||
|
args: --timeout=5m
|
||||||
|
skip-cache: true
|
||||||
|
|
||||||
|
- name: Unit tests and build
|
||||||
|
run: |
|
||||||
|
go test -race ./...
|
||||||
|
go build ./cmd/...
|
||||||
|
|
||||||
|
- name: Prepare local stack
|
||||||
|
run: |
|
||||||
|
cp lab4.env.example .env
|
||||||
|
docker compose config --quiet
|
||||||
|
docker compose up -d --build --scale api=2 --wait --wait-timeout 150
|
||||||
|
network=$(docker inspect --format '{{range $name, $_ := .NetworkSettings.Networks}}{{$name}}{{end}}' "$(docker compose ps -q nginx)")
|
||||||
|
docker network connect "$network" "$HOSTNAME"
|
||||||
|
printf '%s\n' "$network" > .ci-network
|
||||||
|
|
||||||
|
- name: Integration checks
|
||||||
|
run: |
|
||||||
|
set -a
|
||||||
|
. ./.env
|
||||||
|
set +a
|
||||||
|
test "$(curl --noproxy '*' -s -o /dev/null -w '%{http_code}' "http://s3:9000/$S3_BUCKET")" = "403"
|
||||||
|
make test BASE_URL=http://nginx:8080
|
||||||
|
docker compose --profile tests run --rm --build tests
|
||||||
|
go run ./cmd/dependencycheck -base-url=http://nginx:8080
|
||||||
|
make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL=http://nginx:8080
|
||||||
|
make test-failover ACTION_SCRIPT=scripts/stop-one.sh BASE_URL=http://nginx:8080
|
||||||
|
|
||||||
|
- name: Container logs
|
||||||
|
if: failure()
|
||||||
|
run: if [ -f .env ]; then docker compose logs --no-color --tail=200; fi
|
||||||
|
|
||||||
|
- name: Stop local stack
|
||||||
|
if: always()
|
||||||
|
run: |
|
||||||
|
if [ -f .ci-network ]; then docker network disconnect "$(cat .ci-network)" "$HOSTNAME"; fi
|
||||||
|
if [ -f .env ]; then docker compose --profile tests down -v --remove-orphans; fi
|
||||||
|
|
||||||
|
deploy:
|
||||||
|
name: Deploy selected commit
|
||||||
|
needs: verify
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
environment: production
|
||||||
|
env:
|
||||||
|
DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
|
||||||
|
DEPLOY_USER: ${{ secrets.DEPLOY_USER }}
|
||||||
|
DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
|
||||||
|
DEPLOY_KNOWN_HOSTS: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
|
||||||
|
DEPLOY_SHA: ${{ github.sha }}
|
||||||
|
steps:
|
||||||
|
- name: Configure SSH
|
||||||
|
run: |
|
||||||
|
umask 077
|
||||||
|
mkdir -p ~/.ssh
|
||||||
|
printf '%s\n' "$DEPLOY_SSH_KEY" > ~/.ssh/id_ed25519
|
||||||
|
printf '%s\n' "$DEPLOY_KNOWN_HOSTS" > ~/.ssh/known_hosts
|
||||||
|
|
||||||
|
- name: Deploy and verify
|
||||||
|
run: |
|
||||||
|
ssh "$DEPLOY_USER@$DEPLOY_HOST" "
|
||||||
|
set -eu
|
||||||
|
cd ~/mtusi2026lab4
|
||||||
|
git fetch origin main
|
||||||
|
git cat-file -e '$DEPLOY_SHA^{commit}'
|
||||||
|
git reset --hard '$DEPLOY_SHA'
|
||||||
|
git clean -fd
|
||||||
|
scripts/rolling-update.sh
|
||||||
|
test \"\$(git rev-parse HEAD)\" = '$DEPLOY_SHA'
|
||||||
|
docker compose ps
|
||||||
|
"
|
||||||
+6
-1
@@ -1,8 +1,12 @@
|
|||||||
FROM golang:1.26.5-alpine3.24 AS build
|
FROM golang:1.26.5-alpine3.24 AS build
|
||||||
|
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
|
ENV GOMAXPROCS=2 GOMEMLIMIT=1GiB
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN go build -o /out/messenger ./cmd/messenger
|
RUN go build -p=1 -o /out/messenger ./cmd/messenger
|
||||||
|
RUN go build -p=1 -o /out/lab4experiment ./cmd/lab4experiment
|
||||||
|
|
||||||
FROM build AS test
|
FROM build AS test
|
||||||
|
|
||||||
@@ -30,6 +34,7 @@ FROM alpine:3.24.2
|
|||||||
|
|
||||||
RUN addgroup -S app && adduser -S -G app -u 10001 app
|
RUN addgroup -S app && adduser -S -G app -u 10001 app
|
||||||
COPY --from=build --chown=app:app /out/messenger /app/messenger
|
COPY --from=build --chown=app:app /out/messenger /app/messenger
|
||||||
|
COPY --from=build --chown=app:app /out/lab4experiment /app/lab4experiment
|
||||||
|
|
||||||
USER app
|
USER app
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|||||||
@@ -1,37 +1,174 @@
|
|||||||
# Отчёт — лабораторная 4
|
# Отчёт — лабораторная работа № 4
|
||||||
|
|
||||||
- Автор, группа: TODO
|
- Автор: Пластинин Денис, БВТ2303.
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
- Целевая оценка: 5.
|
||||||
- Commit/PR: TODO после публикации
|
- Выбранный трек: 2, согласованность PostgreSQL и S3.
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
- Ветка: `solution/bvt2303-plastinin`.
|
||||||
|
- Источники и инструменты: документация Go, PostgreSQL и MinIO; Codex использован при реализации.
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Запуск из чистого clone
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
Требуются Docker Engine с Compose V2, Git и свободные локальные порты 8080, 8081, 9090 и 3000. Для запуска Go-проверок вне контейнера нужен Go 1.26. Образы приложения и MinIO собираются из исходников внутри Docker. Версии Go, PostgreSQL, Valkey, Nginx, MinIO и остальных компонентов закреплены в Dockerfile и `compose.yaml`.
|
||||||
|
|
||||||
## Архитектура и решения
|
```sh
|
||||||
|
cp lab4.env.example .env
|
||||||
|
docker compose --env-file .env config --quiet
|
||||||
|
docker compose --env-file .env up -d --build --scale api=2 --wait --wait-timeout 180
|
||||||
|
```
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab3, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
После запуска доступны:
|
||||||
|
|
||||||
|
- API через Nginx: `http://localhost:8080`;
|
||||||
|
- Swagger UI: `http://localhost:8081`;
|
||||||
|
- Prometheus: `http://localhost:9090`;
|
||||||
|
- Grafana: `http://localhost:3000`, пользователь `admin`, пароль из `GRAFANA_ADMIN_PASSWORD`.
|
||||||
|
|
||||||
|
Публичные и внутренние проверки:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
make check
|
||||||
|
make test BASE_URL=http://localhost:8080
|
||||||
|
docker compose --profile tests run --rm --build tests
|
||||||
|
go test -race ./...
|
||||||
|
go vet ./...
|
||||||
|
```
|
||||||
|
|
||||||
|
Сверка PostgreSQL и S3 выполняется внутри запущенной API-реплики. Без `--apply` команда ничего не удаляет:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose exec -T api /app/messenger reconcile-attachments --grace-period=1h
|
||||||
|
docker compose exec -T api /app/messenger reconcile-attachments --apply --grace-period=1h
|
||||||
|
```
|
||||||
|
|
||||||
|
Эксперименты запускаются на чистом стенде:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose exec -T api /app/lab4experiment memory
|
||||||
|
docker compose exec -T api /app/lab4experiment consistency
|
||||||
|
```
|
||||||
|
|
||||||
|
Безопасная остановка сохраняет данные в Docker volumes:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose down
|
||||||
|
```
|
||||||
|
|
||||||
|
Полное удаление учебных данных выполняется только явно:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose down -v
|
||||||
|
```
|
||||||
|
|
||||||
|
## Архитектура
|
||||||
|
|
||||||
|
```text
|
||||||
|
клиент
|
||||||
|
|
|
||||||
|
v
|
||||||
|
Nginx :8080
|
||||||
|
|
|
||||||
|
+---- API replica 1 ----+
|
||||||
|
| |
|
||||||
|
+---- API replica 2 ----+---- PostgreSQL: пользователи, чаты,
|
||||||
|
| сообщения, metadata
|
||||||
|
+---- Valkey: сессии
|
||||||
|
+---- MinIO: приватные байты изображений
|
||||||
|
|
||||||
|
Prometheus <---- API /metrics, MinIO, Nginx, PostgreSQL, Valkey
|
||||||
|
|
|
||||||
|
+---- Grafana
|
||||||
|
```
|
||||||
|
|
||||||
|
Из лабораторной № 3 сохранены две и более API-реплики, Nginx, общие PostgreSQL и Valkey, Bearer-сессии, keyset pagination, идемпотентность сообщений, graceful shutdown, failover, метрики и управляемое развёртывание. В лабораторной № 4 добавлены приватное объектное хранилище, модель вложения, бинарная загрузка и скачивание, привязка вложений к сообщениям и сверка двух хранилищ.
|
||||||
|
|
||||||
|
PostgreSQL остаётся источником истины для прав доступа и метаданных. Таблица `attachments` хранит владельца, чат, отображаемое имя, MIME, размер, SHA-256 и внутренний object key. Таблица `message_attachments` задаёт упорядоченную связь многие ко многим с сообщениями. Object key генерируется сервером и не зависит от имени файла.
|
||||||
|
|
||||||
|
MinIO хранит только байты оригиналов. Bucket закрыт для анонимного доступа. Bootstrap повторяемо создаёт bucket, policy и отдельного пользователя приложения. API получает только действия list/get/put/delete в одном bucket. Root credentials используются bootstrap-контейнером и не передаются API. Web-консоль MinIO отключена и её порт не опубликован.
|
||||||
|
|
||||||
|
## Загрузка и чтение вложения
|
||||||
|
|
||||||
|
Клиент передаёт сырые байты PNG или JPEG. Сервер ограничивает HTTP body до 10 MiB до полного чтения, проверяет заявленный и фактический MIME, декодирует конфигурацию изображения, ограничивает число пикселей 40 миллионами и проверяет полную декодируемость. Filename содержит от 1 до 255 Unicode-символов и не может содержать разделители пути, NUL, управляющие символы или состоять только из пробелов.
|
||||||
|
|
||||||
|
При успешной загрузке сервер генерирует UUID для вложения и отдельный случайный object key, считает SHA-256, записывает объект в MinIO и затем metadata в PostgreSQL. Ответ `201 ready` возвращается только после обеих операций. Если результат записи PostgreSQL неоднозначен, сервер повторно ищет строку по attachment ID и object key. Найденная строка означает успешный commit и приводит к `201`; подтверждённое отсутствие строки разрешает компенсирующее удаление object; ошибка повторной проверки оставляет object для последующей безопасной сверки reconciler.
|
||||||
|
|
||||||
|
Метаданные и содержимое читаются только после проверки Bearer-сессии и членства пользователя в чате. Посторонний пользователь и неизвестный идентификатор дают одинаковый `404`. API отдаёт байты самостоятельно без redirect и возвращает сохранённый `Content-Type` и точный `Content-Length`.
|
||||||
|
|
||||||
|
Сообщение принимает до десяти уникальных `attachment_ids`. В одной транзакции PostgreSQL проверяются членство отправителя и принадлежность каждого вложения нужному чату, создаются сообщение, связи и запись идемпотентности. Отсутствующее поле `attachment_ids` и пустой массив дают одинаковый семантический hash. Пустой текст допустим только при наличии вложения.
|
||||||
|
|
||||||
|
## Согласованность PostgreSQL и S3
|
||||||
|
|
||||||
|
Операции PostgreSQL и S3 не входят в общую распределённую транзакцию. Возможны два вида расхождений:
|
||||||
|
|
||||||
|
1. object существует в S3, но metadata отсутствует;
|
||||||
|
2. metadata существует, но object отсутствует.
|
||||||
|
|
||||||
|
Команда `reconcile-attachments` проходит оба набора в порядке object key постранично, поэтому объём памяти ограничен размером двух страниц. По умолчанию включён dry-run. Grace period защищает свежие объекты и строки, которые могут относиться к ещё выполняющейся операции.
|
||||||
|
|
||||||
|
В режиме `--apply` старый orphan в S3 удаляется. Старая строка с отсутствующим объектом удаляется только при отсутствии ссылки из `message_attachments`; проверка возраста и отсутствия ссылки повторяется атомарным `DELETE`. Используемая строка сохраняется и попадает в отчёт для ручного восстановления объекта. Повторный запуск после исправления не выполняет дополнительных удалений.
|
||||||
|
|
||||||
|
## Ограничение памяти
|
||||||
|
|
||||||
|
Размер тела ограничен `http.MaxBytesReader`, поэтому неизвестный `Content-Length` не позволяет читать бесконечный поток. Исходные байты и декодированное изображение находятся в памяти только во время синхронной загрузки. Перед полной декодировкой weighted semaphore резервирует для запроса сумму размера исходных байтов и восьми байт на пиксель. Общий бюджет одной реплики равен 384 MiB, а лимит её контейнера — 512 MiB. Максимально допустимое изображение требует не более 330 485 760 байт расчётного бюджета. Если свободного бюджета нет, API отвечает `429` с `Retry-After: 1`.
|
||||||
|
|
||||||
|
Go-инструмент `cmd/lab4experiment` создаёт случайное JPEG-изображение и выполняет четыре волны по 12 одновременных загрузок. Передача каждой копии ограничена по скорости, чтобы нагрузка длилась дольше интервала scrape. Наблюдаемый пик heap и resident memory двух API-процессов читается из Prometheus с интервалом одна секунда. Это измерение локального стенда, а не универсальная оценка производительности S3.
|
||||||
|
|
||||||
|
В эксперименте успешно завершились все 48 загрузок файла размером 3 759 914 байт. Четыре волны заняли 12,629 секунды. После трёх секунд стабилизации суммарный heap двух реплик вырос с 181 133 200 до наблюдаемого пика 202 374 848 байт, то есть на 21 241 648 байт. Суммарный RSS вырос с 241 922 048 до 381 063 168 байт, то есть на 139 141 120 байт. Наблюдаемый пик остался ниже общего контейнерного лимита двух реплик 1 GiB.
|
||||||
|
|
||||||
|
## Наблюдаемость
|
||||||
|
|
||||||
|
API экспортирует общие HTTP-метрики и отдельные показатели загрузок:
|
||||||
|
|
||||||
|
- `messenger_attachment_uploads_total{result}`;
|
||||||
|
- `messenger_attachment_upload_duration_seconds`;
|
||||||
|
- `messenger_attachment_upload_bytes_total`.
|
||||||
|
|
||||||
|
Prometheus обнаруживает все API-реплики через Docker DNS и отдельно собирает MinIO, Nginx, PostgreSQL и Valkey. Grafana показывает частоту и p95 загрузок, объём принятых байтов, число и ёмкость объектов MinIO, ошибки S3, доступность компонентов, RPS, классы HTTP-ответов и память Go.
|
||||||
|
|
||||||
|
`/health/live` проверяет только процесс. `/health/ready` требует доступных PostgreSQL, Valkey и приватного bucket S3. Недоступность Grafana или Prometheus не останавливает API.
|
||||||
|
|
||||||
## Доказательства критериев
|
## Доказательства критериев
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
| Критерий | Команда или сценарий | Результат | Доказательство |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
| Контракт и OpenAPI | `make check`, `make validate` | offline check PASS; validate входит в CI | `evidence/lab4-verification.txt` |
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
| Unit и integration | `go test ./...`, race/tests profile в CI | unit PASS | `evidence/lab4-verification.txt` |
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
| Upload/download и ACL | `make test` | PASS | `evidence/lab4-verification.txt` |
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
| Межрепличный failover и restart | public resilience hooks | проверяются CI точного commit | `.gitea/workflows/ci.yml` |
|
||||||
|
| Приватный bucket и повторный bootstrap | anonymous HTTP check, два запуска bootstrap | PASS | `evidence/lab4-verification.txt` |
|
||||||
|
| 12 конкурентных загрузок и память | `lab4experiment memory` | 48/48 PASS, observed RSS peak 381 063 168 B | `evidence/lab4-memory.json` |
|
||||||
|
| Трек 2: dry-run/apply/repeat | `lab4experiment consistency` | PASS, повторный apply: 0 удалений | `evidence/lab4-consistency.json` |
|
||||||
|
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
## Эксперимент согласованности
|
||||||
|
|
||||||
## Эксперименты и отказы
|
Гипотеза: постраничная сверка с grace period может автоматически удалить старые безопасные расхождения, не удаляя свежие данные и metadata используемого вложения; второй apply будет идемпотентным.
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
Методика на чистом стенде:
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
1. создать согласованное вложение;
|
||||||
| --- | --- | --- | --- |
|
2. удалить S3 object у непривязанного вложения;
|
||||||
| TODO | TODO | TODO | TODO |
|
3. привязать другое вложение к сообщению и удалить его S3 object;
|
||||||
|
4. создать object без metadata;
|
||||||
|
5. выполнить apply с grace period один час и проверить сохранность свежих аномалий;
|
||||||
|
6. выполнить dry-run с нулевым grace period;
|
||||||
|
7. выполнить apply и проверить удаление orphan и непривязанной строки;
|
||||||
|
8. повторить apply и проверить отсутствие новых действий.
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
Фактическая стоимость обхода записывается как число просмотренных объектов и строк, размер страницы и wall time. Алгоритм выполняет линейный merge двух отсортированных потоков; дополнительные запросы проверки ссылок нужны только для metadata с отсутствующим объектом.
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
При размере страницы 10 фактический запуск пересёк границу страницы и просмотрел 206 строк metadata и 205 objects. Apply с часовым grace period занял 58 миллисекунд и сохранил один свежий orphan и две свежие строки с отсутствующим object. При нулевом grace period dry-run за 65 миллисекунд обнаружил старый orphan, старую непривязанную строку и одну используемую строку. Apply за 77 миллисекунд удалил только orphan и непривязанную строку. Повторный apply занял 38 миллисекунд, выполнил ноль удалений, а используемая строка осталась в PostgreSQL.
|
||||||
|
|
||||||
|
## Ограничения
|
||||||
|
|
||||||
|
- Между S3 PUT и PostgreSQL INSERT нет общей транзакции; компенсация и reconciler обеспечивают eventual consistency.
|
||||||
|
- Удалённый object используемого вложения автоматически не восстанавливается: строка сохраняется и требует восстановления байтов из резервной копии либо решения оператора.
|
||||||
|
- Grace period основан на времени PostgreSQL и S3; для удалённого стенда требуется синхронизация часов.
|
||||||
|
- Admission control действует отдельно в каждой API-реплике; при изменении контейнерного лимита его бюджет нужно настраивать вместе с `ATTACHMENT_DECODE_MEMORY_BYTES`.
|
||||||
|
- MinIO собирается из официального закреплённого source tag, поскольку готовые community images больше не публикуются. Это увеличивает время первого CI build.
|
||||||
|
- Локальный HTTP допустим только для учебного стенда с синтетическими данными; удалённое развёртывание требует TLS.
|
||||||
|
|
||||||
|
## Источники
|
||||||
|
|
||||||
|
- [MinIO releases](https://github.com/minio/minio/releases)
|
||||||
|
- [MinIO Go SDK](https://github.com/minio/minio-go)
|
||||||
|
- [PostgreSQL constraints](https://www.postgresql.org/docs/current/ddl-constraints.html)
|
||||||
|
- [Go image package](https://pkg.go.dev/image)
|
||||||
|
|||||||
@@ -0,0 +1,654 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"image/jpeg"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/config"
|
||||||
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/database"
|
||||||
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/objectstore"
|
||||||
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/postgres"
|
||||||
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/reconcile"
|
||||||
|
)
|
||||||
|
|
||||||
|
const experimentPassword = "Lab4-experiment-password"
|
||||||
|
|
||||||
|
type apiClient struct {
|
||||||
|
baseURL string
|
||||||
|
client *http.Client
|
||||||
|
token string
|
||||||
|
}
|
||||||
|
|
||||||
|
type attachment struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type setup struct {
|
||||||
|
client *apiClient
|
||||||
|
chatID string
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
if err := run(os.Args[1:], os.Stdout); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func run(arguments []string, output io.Writer) error {
|
||||||
|
if len(arguments) == 0 {
|
||||||
|
return errors.New("usage: lab4experiment memory|consistency [flags]")
|
||||||
|
}
|
||||||
|
switch arguments[0] {
|
||||||
|
case "memory":
|
||||||
|
return runMemory(arguments[1:], output)
|
||||||
|
case "consistency":
|
||||||
|
return runConsistency(arguments[1:], output)
|
||||||
|
default:
|
||||||
|
return errors.New("usage: lab4experiment memory|consistency [flags]")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type memoryResult struct {
|
||||||
|
Replicas int `json:"replicas"`
|
||||||
|
Concurrency int `json:"concurrency"`
|
||||||
|
Rounds int `json:"rounds"`
|
||||||
|
SettleTimeMillis int64 `json:"settle_time_ms"`
|
||||||
|
ImageBytes int `json:"image_bytes"`
|
||||||
|
UploadRateBytes int64 `json:"upload_rate_bytes_per_second"`
|
||||||
|
SuccessfulUploads int64 `json:"successful_uploads"`
|
||||||
|
FailedUploads int64 `json:"failed_uploads"`
|
||||||
|
DurationMillis int64 `json:"duration_ms"`
|
||||||
|
HeapBaselineBytes int64 `json:"heap_baseline_bytes"`
|
||||||
|
HeapPeakBytes int64 `json:"heap_peak_bytes"`
|
||||||
|
HeapDeltaBytes int64 `json:"heap_delta_bytes"`
|
||||||
|
RSSBaselineBytes int64 `json:"rss_baseline_bytes"`
|
||||||
|
RSSPeakBytes int64 `json:"rss_peak_bytes"`
|
||||||
|
RSSDeltaBytes int64 `json:"rss_delta_bytes"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func runMemory(arguments []string, output io.Writer) error {
|
||||||
|
flags := flag.NewFlagSet("memory", flag.ContinueOnError)
|
||||||
|
flags.SetOutput(io.Discard)
|
||||||
|
baseURL := flags.String("base-url", "http://nginx:8080", "messenger base URL")
|
||||||
|
prometheusURL := flags.String("prometheus-url", "http://prometheus:9090", "Prometheus base URL")
|
||||||
|
replicas := flags.Int("replicas", 2, "expected API replicas")
|
||||||
|
concurrency := flags.Int("concurrency", 12, "number of concurrent uploads")
|
||||||
|
rounds := flags.Int("rounds", 4, "number of upload waves")
|
||||||
|
width := flags.Int("width", 2048, "image width")
|
||||||
|
height := flags.Int("height", 2048, "image height")
|
||||||
|
uploadRate := flags.Int64("upload-rate", 1536*1024, "bytes per second for each upload")
|
||||||
|
settleTime := flags.Duration("settle-time", 3*time.Second, "delay before the baseline sample")
|
||||||
|
if err := flags.Parse(arguments); err != nil || flags.NArg() != 0 {
|
||||||
|
return errors.New("invalid memory experiment flags")
|
||||||
|
}
|
||||||
|
if *replicas < 1 || *concurrency < 10 || *rounds < 1 || *width < 1 || *height < 1 || *uploadRate < 1 || *settleTime < 0 {
|
||||||
|
return errors.New("concurrency must be at least 10 and rounds/dimensions/rate must be positive")
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
|
||||||
|
defer cancel()
|
||||||
|
fixture, err := jpegFixture(*width, *height)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := waitForReplicas(ctx, *prometheusURL, *replicas); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
settle := time.NewTimer(*settleTime)
|
||||||
|
defer settle.Stop()
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
case <-settle.C:
|
||||||
|
}
|
||||||
|
heapBaseline, err := prometheusValue(ctx, *prometheusURL, freshMetricQuery("go_memstats_heap_alloc_bytes"))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
rssBaseline, err := prometheusValue(ctx, *prometheusURL, freshMetricQuery("process_resident_memory_bytes"))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
environment, err := prepare(ctx, *baseURL)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var successful atomic.Int64
|
||||||
|
var failed atomic.Int64
|
||||||
|
var firstError struct {
|
||||||
|
sync.Mutex
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
heapPeak := heapBaseline
|
||||||
|
rssPeak := rssBaseline
|
||||||
|
loadDone := make(chan struct{})
|
||||||
|
sampleDone := make(chan error, 1)
|
||||||
|
go sampleMemory(ctx, *prometheusURL, *replicas, loadDone, &heapPeak, &rssPeak, sampleDone)
|
||||||
|
started := time.Now()
|
||||||
|
for round := range *rounds {
|
||||||
|
var workers sync.WaitGroup
|
||||||
|
workers.Add(*concurrency)
|
||||||
|
for index := range *concurrency {
|
||||||
|
go func(round, index int) {
|
||||||
|
defer workers.Done()
|
||||||
|
reader := newRateReader(fixture, *uploadRate)
|
||||||
|
filename := fmt.Sprintf("memory-%02d-%02d.jpg", round, index)
|
||||||
|
if _, err := environment.client.upload(ctx, environment.chatID, filename, reader, int64(len(fixture))); err != nil {
|
||||||
|
failed.Add(1)
|
||||||
|
firstError.Lock()
|
||||||
|
if firstError.err == nil {
|
||||||
|
firstError.err = err
|
||||||
|
}
|
||||||
|
firstError.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
successful.Add(1)
|
||||||
|
}(round, index)
|
||||||
|
}
|
||||||
|
workers.Wait()
|
||||||
|
}
|
||||||
|
close(loadDone)
|
||||||
|
if err := <-sampleDone; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
result := memoryResult{
|
||||||
|
Replicas: *replicas, Concurrency: *concurrency, Rounds: *rounds, SettleTimeMillis: settleTime.Milliseconds(),
|
||||||
|
ImageBytes: len(fixture), UploadRateBytes: *uploadRate,
|
||||||
|
SuccessfulUploads: successful.Load(), FailedUploads: failed.Load(), DurationMillis: time.Since(started).Milliseconds(),
|
||||||
|
HeapBaselineBytes: heapBaseline, HeapPeakBytes: heapPeak, HeapDeltaBytes: heapPeak - heapBaseline,
|
||||||
|
RSSBaselineBytes: rssBaseline, RSSPeakBytes: rssPeak, RSSDeltaBytes: rssPeak - rssBaseline,
|
||||||
|
}
|
||||||
|
if result.FailedUploads > 0 {
|
||||||
|
return fmt.Errorf("%d uploads failed: %w", result.FailedUploads, firstError.err)
|
||||||
|
}
|
||||||
|
return writeJSON(output, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
func sampleMemory(
|
||||||
|
ctx context.Context,
|
||||||
|
prometheusURL string,
|
||||||
|
expectedReplicas int,
|
||||||
|
done <-chan struct{},
|
||||||
|
heapPeak *int64,
|
||||||
|
rssPeak *int64,
|
||||||
|
result chan<- error,
|
||||||
|
) {
|
||||||
|
ticker := time.NewTicker(500 * time.Millisecond)
|
||||||
|
defer ticker.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
result <- ctx.Err()
|
||||||
|
return
|
||||||
|
case <-done:
|
||||||
|
result <- nil
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
replicas, err := prometheusValue(ctx, prometheusURL, activeReplicasQuery())
|
||||||
|
if err != nil {
|
||||||
|
result <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if replicas != int64(expectedReplicas) {
|
||||||
|
result <- fmt.Errorf("active API replicas = %d, expected %d", replicas, expectedReplicas)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
heap, err := prometheusValue(ctx, prometheusURL, freshMetricQuery("go_memstats_heap_alloc_bytes"))
|
||||||
|
if err != nil {
|
||||||
|
result <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rss, err := prometheusValue(ctx, prometheusURL, freshMetricQuery("process_resident_memory_bytes"))
|
||||||
|
if err != nil {
|
||||||
|
result <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
*heapPeak = max(*heapPeak, heap)
|
||||||
|
*rssPeak = max(*rssPeak, rss)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type consistencyResult struct {
|
||||||
|
PageSize int `json:"page_size"`
|
||||||
|
SeededConsistent int `json:"seeded_consistent"`
|
||||||
|
FreshApply reconciliationRun `json:"fresh_apply"`
|
||||||
|
DryRun reconciliationRun `json:"dry_run"`
|
||||||
|
Apply reconciliationRun `json:"apply"`
|
||||||
|
RepeatedApply reconciliationRun `json:"repeated_apply"`
|
||||||
|
FreshPreserved bool `json:"fresh_preserved"`
|
||||||
|
OrphanDeleted bool `json:"orphan_deleted"`
|
||||||
|
UnusedDeleted bool `json:"unused_metadata_deleted"`
|
||||||
|
InUsePreserved bool `json:"in_use_metadata_preserved"`
|
||||||
|
TotalDurationMillis int64 `json:"total_duration_ms"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type reconciliationRun struct {
|
||||||
|
DurationMillis int64 `json:"duration_ms"`
|
||||||
|
Report reconcile.Report `json:"report"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func runConsistency(arguments []string, output io.Writer) error {
|
||||||
|
flags := flag.NewFlagSet("consistency", flag.ContinueOnError)
|
||||||
|
flags.SetOutput(io.Discard)
|
||||||
|
baseURL := flags.String("base-url", "http://nginx:8080", "messenger base URL")
|
||||||
|
pageSize := flags.Int("page-size", 10, "reconciliation page size")
|
||||||
|
if err := flags.Parse(arguments); err != nil || flags.NArg() != 0 {
|
||||||
|
return errors.New("invalid consistency experiment flags")
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||||
|
defer cancel()
|
||||||
|
settings, err := config.Load()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
pool, err := database.Open(ctx, database.Config{
|
||||||
|
URL: settings.DatabaseURL, MinConnections: settings.DBMinConns, MaxConnections: settings.DBMaxConns,
|
||||||
|
MaxConnectionAge: settings.DBMaxConnectionAge, MaxConnectionIdle: settings.DBMaxConnectionIdle,
|
||||||
|
HealthCheckPeriod: settings.DBHealthCheckPeriod, ConnectTimeout: settings.DependencyTimeout,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer pool.Close()
|
||||||
|
objects, err := objectstore.New(objectstore.Config{
|
||||||
|
Endpoint: settings.S3Endpoint, Region: settings.S3Region, Bucket: settings.S3Bucket,
|
||||||
|
AccessKey: settings.S3AccessKey, SecretKey: settings.S3SecretKey,
|
||||||
|
UseTLS: settings.S3UseTLS, Timeout: settings.S3Timeout,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
metadata := postgres.New(pool)
|
||||||
|
clean, err := reconcile.New(metadata, objects, reconcile.Config{Prefix: "attachments/", PageSize: *pageSize, GraceTime: 0})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
initial, err := clean.Run(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if hasAnomalies(initial) {
|
||||||
|
return errors.New("consistency experiment requires a stack without existing attachment anomalies")
|
||||||
|
}
|
||||||
|
|
||||||
|
started := time.Now()
|
||||||
|
environment, err := prepare(ctx, *baseURL)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fixture, err := jpegFixture(320, 200)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
seededConsistent := *pageSize + 1
|
||||||
|
for index := range seededConsistent {
|
||||||
|
filename := fmt.Sprintf("consistent-%03d.jpg", index)
|
||||||
|
if _, err := environment.client.upload(ctx, environment.chatID, filename, bytes.NewReader(fixture), int64(len(fixture))); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
unused, err := environment.client.upload(ctx, environment.chatID, "unused-missing.jpg", bytes.NewReader(fixture), int64(len(fixture)))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
inUse, err := environment.client.upload(ctx, environment.chatID, "in-use-missing.jpg", bytes.NewReader(fixture), int64(len(fixture)))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := environment.client.createMessage(ctx, environment.chatID, inUse.ID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
keys, err := attachmentKeys(ctx, pool, []string{unused.ID, inUse.ID})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := objects.Delete(ctx, keys[unused.ID]); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := objects.Delete(ctx, keys[inUse.ID]); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
orphanKey := "attachments/experiment-" + uuid.NewString() + "/original"
|
||||||
|
if err := objects.Put(ctx, orphanKey, "image/jpeg", fixture); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
fresh, err := reconcile.New(metadata, objects, reconcile.Config{
|
||||||
|
Prefix: "attachments/", PageSize: *pageSize, GraceTime: time.Hour, Apply: true,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
freshRun, err := measuredReconciliation(ctx, fresh)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
freshPreserved := objectExists(ctx, objects, orphanKey) &&
|
||||||
|
attachmentExists(ctx, pool, unused.ID) && attachmentExists(ctx, pool, inUse.ID)
|
||||||
|
|
||||||
|
dryRun, err := reconcile.New(metadata, objects, reconcile.Config{Prefix: "attachments/", PageSize: *pageSize})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
dryRunResult, err := measuredReconciliation(ctx, dryRun)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
apply, err := reconcile.New(metadata, objects, reconcile.Config{
|
||||||
|
Prefix: "attachments/", PageSize: *pageSize, Apply: true,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
applyResult, err := measuredReconciliation(ctx, apply)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
repeatedResult, err := measuredReconciliation(ctx, apply)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
result := consistencyResult{
|
||||||
|
PageSize: *pageSize, SeededConsistent: seededConsistent,
|
||||||
|
FreshApply: freshRun, DryRun: dryRunResult, Apply: applyResult, RepeatedApply: repeatedResult,
|
||||||
|
FreshPreserved: freshPreserved, OrphanDeleted: !objectExists(ctx, objects, orphanKey),
|
||||||
|
UnusedDeleted: !attachmentExists(ctx, pool, unused.ID), InUsePreserved: attachmentExists(ctx, pool, inUse.ID),
|
||||||
|
TotalDurationMillis: time.Since(started).Milliseconds(),
|
||||||
|
}
|
||||||
|
if !result.FreshPreserved || !result.OrphanDeleted || !result.UnusedDeleted || !result.InUsePreserved ||
|
||||||
|
repeatedResult.Report.DeletedOrphanObjects != 0 || repeatedResult.Report.DeletedUnreferencedRows != 0 {
|
||||||
|
return fmt.Errorf("unexpected reconciliation result: %+v", result)
|
||||||
|
}
|
||||||
|
return writeJSON(output, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
func measuredReconciliation(ctx context.Context, reconciler *reconcile.Reconciler) (reconciliationRun, error) {
|
||||||
|
started := time.Now()
|
||||||
|
report, err := reconciler.Run(ctx)
|
||||||
|
return reconciliationRun{DurationMillis: time.Since(started).Milliseconds(), Report: report}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func hasAnomalies(report reconcile.Report) bool {
|
||||||
|
return report.FreshOrphanObjects != 0 || report.OldOrphanObjects != 0 ||
|
||||||
|
report.FreshMissingObjects != 0 || report.ReferencedMissingObjects != 0 ||
|
||||||
|
report.OldUnreferencedMetadata != 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func attachmentKeys(ctx context.Context, pool *pgxpool.Pool, ids []string) (map[string]string, error) {
|
||||||
|
rows, err := pool.Query(ctx, `SELECT id::text, object_key FROM attachments WHERE id::text = ANY($1)`, ids)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("query attachment keys: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
keys := make(map[string]string, len(ids))
|
||||||
|
for rows.Next() {
|
||||||
|
var id string
|
||||||
|
var key string
|
||||||
|
if err := rows.Scan(&id, &key); err != nil {
|
||||||
|
return nil, fmt.Errorf("scan attachment key: %w", err)
|
||||||
|
}
|
||||||
|
keys[id] = key
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, fmt.Errorf("iterate attachment keys: %w", err)
|
||||||
|
}
|
||||||
|
if len(keys) != len(ids) {
|
||||||
|
return nil, errors.New("not all attachment keys were found")
|
||||||
|
}
|
||||||
|
return keys, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func attachmentExists(ctx context.Context, pool *pgxpool.Pool, id string) bool {
|
||||||
|
var exists bool
|
||||||
|
return pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM attachments WHERE id = $1)`, id).Scan(&exists) == nil && exists
|
||||||
|
}
|
||||||
|
|
||||||
|
func objectExists(ctx context.Context, objects *objectstore.Store, key string) bool {
|
||||||
|
_, err := objects.Stat(ctx, key)
|
||||||
|
return err == nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func prepare(ctx context.Context, baseURL string) (setup, error) {
|
||||||
|
client := &apiClient{baseURL: strings.TrimRight(baseURL, "/"), client: &http.Client{Timeout: 90 * time.Second}}
|
||||||
|
username := "lab4_" + strings.ReplaceAll(uuid.NewString()[:18], "-", "")
|
||||||
|
var user struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
if err := client.jsonRequest(ctx, http.MethodPost, "/api/v1/users", map[string]string{
|
||||||
|
"username": username, "display_name": "Lab 4 experiment", "password": experimentPassword,
|
||||||
|
}, &user, ""); err != nil {
|
||||||
|
return setup{}, err
|
||||||
|
}
|
||||||
|
credentials := base64.StdEncoding.EncodeToString([]byte(username + ":" + experimentPassword))
|
||||||
|
var session struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
}
|
||||||
|
if err := client.jsonRequest(ctx, http.MethodPost, "/api/v1/auth/sessions", nil, &session, "Basic "+credentials); err != nil {
|
||||||
|
return setup{}, err
|
||||||
|
}
|
||||||
|
client.token = session.Token
|
||||||
|
var chat struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
if err := client.jsonRequest(ctx, http.MethodPost, "/api/v1/chats", map[string]any{
|
||||||
|
"title": "Lab 4 experiment", "member_ids": []string{user.ID},
|
||||||
|
}, &chat, "Bearer "+client.token); err != nil {
|
||||||
|
return setup{}, err
|
||||||
|
}
|
||||||
|
return setup{client: client, chatID: chat.ID}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *apiClient) upload(
|
||||||
|
ctx context.Context,
|
||||||
|
chatID string,
|
||||||
|
filename string,
|
||||||
|
body io.Reader,
|
||||||
|
contentLength int64,
|
||||||
|
) (attachment, error) {
|
||||||
|
path := "/api/v1/chats/" + chatID + "/attachments?filename=" + filename
|
||||||
|
request, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+path, body)
|
||||||
|
if err != nil {
|
||||||
|
return attachment{}, err
|
||||||
|
}
|
||||||
|
request.ContentLength = contentLength
|
||||||
|
request.Header.Set("Authorization", "Bearer "+c.token)
|
||||||
|
request.Header.Set("Content-Type", "image/jpeg")
|
||||||
|
response, err := c.client.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return attachment{}, err
|
||||||
|
}
|
||||||
|
defer func() { _ = response.Body.Close() }()
|
||||||
|
if response.StatusCode != http.StatusCreated {
|
||||||
|
message, _ := io.ReadAll(io.LimitReader(response.Body, 4096))
|
||||||
|
return attachment{}, fmt.Errorf("upload status %d: %s", response.StatusCode, message)
|
||||||
|
}
|
||||||
|
var result attachment
|
||||||
|
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
|
||||||
|
return attachment{}, err
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *apiClient) createMessage(ctx context.Context, chatID, attachmentID string) error {
|
||||||
|
return c.jsonRequest(ctx, http.MethodPost, "/api/v1/chats/"+chatID+"/messages", map[string]any{
|
||||||
|
"text": "", "attachment_ids": []string{attachmentID},
|
||||||
|
}, nil, "Bearer "+c.token, "Idempotency-Key", uuid.NewString())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *apiClient) jsonRequest(
|
||||||
|
ctx context.Context,
|
||||||
|
method string,
|
||||||
|
path string,
|
||||||
|
payload any,
|
||||||
|
result any,
|
||||||
|
authorization string,
|
||||||
|
extraHeader ...string,
|
||||||
|
) error {
|
||||||
|
var body io.Reader
|
||||||
|
if payload != nil {
|
||||||
|
encoded, err := json.Marshal(payload)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
body = bytes.NewReader(encoded)
|
||||||
|
}
|
||||||
|
request, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, body)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if payload != nil {
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
}
|
||||||
|
if authorization != "" {
|
||||||
|
request.Header.Set("Authorization", authorization)
|
||||||
|
}
|
||||||
|
for index := 0; index+1 < len(extraHeader); index += 2 {
|
||||||
|
request.Header.Set(extraHeader[index], extraHeader[index+1])
|
||||||
|
}
|
||||||
|
response, err := c.client.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer func() { _ = response.Body.Close() }()
|
||||||
|
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||||
|
message, _ := io.ReadAll(io.LimitReader(response.Body, 4096))
|
||||||
|
return fmt.Errorf("%s %s status %d: %s", method, path, response.StatusCode, message)
|
||||||
|
}
|
||||||
|
if result == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return json.NewDecoder(response.Body).Decode(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitForReplicas(ctx context.Context, prometheusURL string, expected int) error {
|
||||||
|
ticker := time.NewTicker(time.Second)
|
||||||
|
defer ticker.Stop()
|
||||||
|
for {
|
||||||
|
count, err := prometheusValue(ctx, prometheusURL, activeReplicasQuery())
|
||||||
|
if err == nil && count == int64(expected) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return fmt.Errorf("wait for %d Prometheus API targets: %w", expected, ctx.Err())
|
||||||
|
case <-ticker.C:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func activeReplicasQuery() string {
|
||||||
|
return `count(timestamp(process_resident_memory_bytes{job="messenger"}) > time() - 10)`
|
||||||
|
}
|
||||||
|
|
||||||
|
func freshMetricQuery(metric string) string {
|
||||||
|
return fmt.Sprintf(`sum(%[1]s{job="messenger"} and on(instance) (timestamp(%[1]s{job="messenger"}) > time() - 10))`, metric)
|
||||||
|
}
|
||||||
|
|
||||||
|
func prometheusValue(ctx context.Context, baseURL, query string) (int64, error) {
|
||||||
|
request, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(baseURL, "/")+"/api/v1/query", nil)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
values := request.URL.Query()
|
||||||
|
values.Set("query", query)
|
||||||
|
request.URL.RawQuery = values.Encode()
|
||||||
|
response, err := http.DefaultClient.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
defer func() { _ = response.Body.Close() }()
|
||||||
|
if response.StatusCode != http.StatusOK {
|
||||||
|
return 0, fmt.Errorf("prometheus status %d", response.StatusCode)
|
||||||
|
}
|
||||||
|
var payload struct {
|
||||||
|
Status string `json:"status"`
|
||||||
|
Data struct {
|
||||||
|
Result []struct {
|
||||||
|
Value []json.RawMessage `json:"value"`
|
||||||
|
} `json:"result"`
|
||||||
|
} `json:"data"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(response.Body).Decode(&payload); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if payload.Status != "success" || len(payload.Data.Result) != 1 || len(payload.Data.Result[0].Value) != 2 {
|
||||||
|
return 0, errors.New("prometheus query returned no scalar value")
|
||||||
|
}
|
||||||
|
var raw string
|
||||||
|
if err := json.Unmarshal(payload.Data.Result[0].Value[1], &raw); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
value, err := strconv.ParseFloat(raw, 64)
|
||||||
|
return int64(value), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func jpegFixture(width, height int) ([]byte, error) {
|
||||||
|
pixels := image.NewRGBA(image.Rect(0, 0, width, height))
|
||||||
|
state := uint64(0x9e3779b97f4a7c15)
|
||||||
|
for index := range pixels.Pix {
|
||||||
|
state ^= state << 13
|
||||||
|
state ^= state >> 7
|
||||||
|
state ^= state << 17
|
||||||
|
pixels.Pix[index] = byte(state >> 24)
|
||||||
|
}
|
||||||
|
var encoded bytes.Buffer
|
||||||
|
if err := jpeg.Encode(&encoded, pixels, &jpeg.Options{Quality: 90}); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return encoded.Bytes(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type rateReader struct {
|
||||||
|
reader *bytes.Reader
|
||||||
|
rate int64
|
||||||
|
started time.Time
|
||||||
|
read int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func newRateReader(data []byte, rate int64) *rateReader {
|
||||||
|
return &rateReader{reader: bytes.NewReader(data), rate: rate, started: time.Now()}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *rateReader) Read(buffer []byte) (int, error) {
|
||||||
|
for {
|
||||||
|
allowed := time.Since(r.started).Nanoseconds()*r.rate/int64(time.Second) - r.read
|
||||||
|
if allowed > 0 {
|
||||||
|
if int64(len(buffer)) > allowed {
|
||||||
|
buffer = buffer[:allowed]
|
||||||
|
}
|
||||||
|
count, err := r.reader.Read(buffer)
|
||||||
|
r.read += int64(count)
|
||||||
|
return count, err
|
||||||
|
}
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeJSON(output io.Writer, value any) error {
|
||||||
|
encoder := json.NewEncoder(output)
|
||||||
|
encoder.SetIndent("", " ")
|
||||||
|
return encoder.Encode(value)
|
||||||
|
}
|
||||||
+84
-1
@@ -2,20 +2,26 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/config"
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/config"
|
||||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/database"
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/database"
|
||||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/logger"
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/logger"
|
||||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/messenger"
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/messenger"
|
||||||
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/objectstore"
|
||||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/password"
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/password"
|
||||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/postgres"
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/postgres"
|
||||||
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/reconcile"
|
||||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/session"
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/session"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -34,7 +40,10 @@ func run(logger *slog.Logger, arguments []string) error {
|
|||||||
if len(arguments) == 1 && arguments[0] == "migrate" {
|
if len(arguments) == 1 && arguments[0] == "migrate" {
|
||||||
return runMigrations()
|
return runMigrations()
|
||||||
}
|
}
|
||||||
return fmt.Errorf("usage: messenger [migrate]")
|
if len(arguments) > 0 && arguments[0] == "reconcile-attachments" {
|
||||||
|
return runAttachmentReconciliation(arguments[1:], os.Stdout)
|
||||||
|
}
|
||||||
|
return fmt.Errorf("usage: messenger [migrate|reconcile-attachments]")
|
||||||
}
|
}
|
||||||
|
|
||||||
func runServer(logger *slog.Logger) error {
|
func runServer(logger *slog.Logger) error {
|
||||||
@@ -68,16 +77,28 @@ func runServer(logger *slog.Logger) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
objects, err := objectstore.New(objectstore.Config{
|
||||||
|
Endpoint: settings.S3Endpoint, Region: settings.S3Region, Bucket: settings.S3Bucket,
|
||||||
|
AccessKey: settings.S3AccessKey, SecretKey: settings.S3SecretKey,
|
||||||
|
UseTLS: settings.S3UseTLS, Timeout: settings.S3Timeout,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
app := messenger.NewServer(
|
app := messenger.NewServer(
|
||||||
logger,
|
logger,
|
||||||
postgres.New(pool),
|
postgres.New(pool),
|
||||||
sessions,
|
sessions,
|
||||||
passwords,
|
passwords,
|
||||||
|
objects,
|
||||||
settings.SessionTTL,
|
settings.SessionTTL,
|
||||||
settings.IdempotencyTTL,
|
settings.IdempotencyTTL,
|
||||||
settings.RequestTimeout,
|
settings.RequestTimeout,
|
||||||
instanceID,
|
instanceID,
|
||||||
settings.SwaggerPort,
|
settings.SwaggerPort,
|
||||||
|
settings.AttachmentMaxBytes,
|
||||||
|
settings.AttachmentMaxPixels,
|
||||||
|
settings.AttachmentDecodeMemory,
|
||||||
)
|
)
|
||||||
server := &http.Server{
|
server := &http.Server{
|
||||||
Addr: settings.Address,
|
Addr: settings.Address,
|
||||||
@@ -130,3 +151,65 @@ func runMigrations() error {
|
|||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
return database.Migrate(context.Background(), pool, settings.MigrationTimeout)
|
return database.Migrate(context.Background(), pool, settings.MigrationTimeout)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type reconciliationOutput struct {
|
||||||
|
Mode string `json:"mode"`
|
||||||
|
GracePeriod string `json:"grace_period"`
|
||||||
|
PageSize int `json:"page_size"`
|
||||||
|
DurationMillis int64 `json:"duration_ms"`
|
||||||
|
Report reconcile.Report `json:"report"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func runAttachmentReconciliation(arguments []string, output io.Writer) error {
|
||||||
|
flags := flag.NewFlagSet("reconcile-attachments", flag.ContinueOnError)
|
||||||
|
flags.SetOutput(io.Discard)
|
||||||
|
apply := flags.Bool("apply", false, "apply safe repairs")
|
||||||
|
gracePeriod := flags.Duration("grace-period", time.Hour, "minimum anomaly age")
|
||||||
|
pageSize := flags.Int("page-size", 500, "S3 and PostgreSQL page size")
|
||||||
|
if err := flags.Parse(arguments); err != nil || flags.NArg() != 0 {
|
||||||
|
return fmt.Errorf("usage: messenger reconcile-attachments [--apply] [--grace-period=1h] [--page-size=500]")
|
||||||
|
}
|
||||||
|
|
||||||
|
settings, err := config.Load()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||||
|
defer stop()
|
||||||
|
pool, err := database.Open(ctx, database.Config{
|
||||||
|
URL: settings.DatabaseURL, MinConnections: settings.DBMinConns, MaxConnections: settings.DBMaxConns,
|
||||||
|
MaxConnectionAge: settings.DBMaxConnectionAge, MaxConnectionIdle: settings.DBMaxConnectionIdle,
|
||||||
|
HealthCheckPeriod: settings.DBHealthCheckPeriod, ConnectTimeout: settings.DependencyTimeout,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer pool.Close()
|
||||||
|
objects, err := objectstore.New(objectstore.Config{
|
||||||
|
Endpoint: settings.S3Endpoint, Region: settings.S3Region, Bucket: settings.S3Bucket,
|
||||||
|
AccessKey: settings.S3AccessKey, SecretKey: settings.S3SecretKey,
|
||||||
|
UseTLS: settings.S3UseTLS, Timeout: settings.S3Timeout,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
reconciler, err := reconcile.New(postgres.New(pool), objects, reconcile.Config{
|
||||||
|
Prefix: "attachments/", PageSize: *pageSize, GraceTime: *gracePeriod, Apply: *apply,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
started := time.Now()
|
||||||
|
report, err := reconciler.Run(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
mode := "dry-run"
|
||||||
|
if *apply {
|
||||||
|
mode = "apply"
|
||||||
|
}
|
||||||
|
return json.NewEncoder(output).Encode(reconciliationOutput{
|
||||||
|
Mode: mode, GracePeriod: gracePeriod.String(), PageSize: *pageSize,
|
||||||
|
DurationMillis: time.Since(started).Milliseconds(), Report: report,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
@@ -32,6 +32,55 @@ services:
|
|||||||
mem_limit: ${VALKEY_MEMORY}
|
mem_limit: ${VALKEY_MEMORY}
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
|
s3:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: infra/minio/server.Dockerfile
|
||||||
|
args:
|
||||||
|
MINIO_VERSION: RELEASE.2025-10-15T17-29-55Z
|
||||||
|
image: mtusi-minio:RELEASE.2025-10-15T17-29-55Z
|
||||||
|
command: ["server", "/data", "--address", ":9000"]
|
||||||
|
environment:
|
||||||
|
MINIO_ROOT_USER: ${MINIO_ROOT_USER}
|
||||||
|
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD}
|
||||||
|
MINIO_BROWSER: "off"
|
||||||
|
MINIO_PROMETHEUS_AUTH_TYPE: public
|
||||||
|
volumes:
|
||||||
|
- s3_data:/data
|
||||||
|
expose:
|
||||||
|
- "9000"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:9000/minio/health/ready"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 20
|
||||||
|
cpus: ${S3_CPUS}
|
||||||
|
mem_limit: ${S3_MEMORY}
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
s3-bootstrap:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: infra/minio/client.Dockerfile
|
||||||
|
args:
|
||||||
|
MC_VERSION: RELEASE.2025-08-13T08-35-41Z
|
||||||
|
image: mtusi-mc:RELEASE.2025-08-13T08-35-41Z
|
||||||
|
entrypoint: ["/bin/sh", "/usr/local/bin/bootstrap.sh"]
|
||||||
|
environment:
|
||||||
|
MINIO_ROOT_USER: ${MINIO_ROOT_USER}
|
||||||
|
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD}
|
||||||
|
S3_BUCKET: ${S3_BUCKET}
|
||||||
|
S3_ACCESS_KEY: ${S3_ACCESS_KEY}
|
||||||
|
S3_SECRET_KEY: ${S3_SECRET_KEY}
|
||||||
|
depends_on:
|
||||||
|
s3:
|
||||||
|
condition: service_healthy
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
cpus: ${S3_BOOTSTRAP_CPUS}
|
||||||
|
mem_limit: ${S3_BOOTSTRAP_MEMORY}
|
||||||
|
restart: "no"
|
||||||
|
|
||||||
migrate:
|
migrate:
|
||||||
image: ${API_IMAGE:-mtusi-messenger:lab4}
|
image: ${API_IMAGE:-mtusi-messenger:lab4}
|
||||||
command: ["/app/messenger", "migrate"]
|
command: ["/app/messenger", "migrate"]
|
||||||
@@ -82,6 +131,16 @@ services:
|
|||||||
PASSWORD_SALT_LENGTH: ${PASSWORD_SALT_LENGTH}
|
PASSWORD_SALT_LENGTH: ${PASSWORD_SALT_LENGTH}
|
||||||
PASSWORD_KEY_LENGTH: ${PASSWORD_KEY_LENGTH}
|
PASSWORD_KEY_LENGTH: ${PASSWORD_KEY_LENGTH}
|
||||||
SWAGGER_PORT: ${SWAGGER_PORT}
|
SWAGGER_PORT: ${SWAGGER_PORT}
|
||||||
|
S3_ENDPOINT: ${S3_ENDPOINT}
|
||||||
|
S3_REGION: ${S3_REGION}
|
||||||
|
S3_BUCKET: ${S3_BUCKET}
|
||||||
|
S3_ACCESS_KEY: ${S3_ACCESS_KEY}
|
||||||
|
S3_SECRET_KEY: ${S3_SECRET_KEY}
|
||||||
|
S3_USE_TLS: ${S3_USE_TLS}
|
||||||
|
S3_TIMEOUT_SECONDS: ${S3_TIMEOUT_SECONDS}
|
||||||
|
ATTACHMENT_MAX_BYTES: ${ATTACHMENT_MAX_BYTES}
|
||||||
|
ATTACHMENT_MAX_PIXELS: ${ATTACHMENT_MAX_PIXELS}
|
||||||
|
ATTACHMENT_DECODE_MEMORY_BYTES: ${ATTACHMENT_DECODE_MEMORY_BYTES}
|
||||||
expose:
|
expose:
|
||||||
- "8080"
|
- "8080"
|
||||||
depends_on:
|
depends_on:
|
||||||
@@ -89,6 +148,8 @@ services:
|
|||||||
condition: service_completed_successfully
|
condition: service_completed_successfully
|
||||||
valkey:
|
valkey:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
|
s3-bootstrap:
|
||||||
|
condition: service_completed_successfully
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:${APP_PORT}/health/ready || exit 1"]
|
test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:${APP_PORT}/health/ready || exit 1"]
|
||||||
interval: 2s
|
interval: 2s
|
||||||
@@ -211,6 +272,7 @@ services:
|
|||||||
- nginx-exporter
|
- nginx-exporter
|
||||||
- postgres-exporter
|
- postgres-exporter
|
||||||
- valkey-exporter
|
- valkey-exporter
|
||||||
|
- s3
|
||||||
cpus: ${PROMETHEUS_CPUS}
|
cpus: ${PROMETHEUS_CPUS}
|
||||||
mem_limit: ${PROMETHEUS_MEMORY}
|
mem_limit: ${PROMETHEUS_MEMORY}
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
@@ -239,3 +301,4 @@ volumes:
|
|||||||
valkey_data:
|
valkey_data:
|
||||||
prometheus_data:
|
prometheus_data:
|
||||||
grafana_data:
|
grafana_data:
|
||||||
|
s3_data:
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
{
|
||||||
|
"page_size": 10,
|
||||||
|
"seeded_consistent": 11,
|
||||||
|
"fresh_apply": {
|
||||||
|
"duration_ms": 58,
|
||||||
|
"report": {
|
||||||
|
"metadata_scanned": 206,
|
||||||
|
"objects_scanned": 205,
|
||||||
|
"consistent": 204,
|
||||||
|
"fresh_orphan_objects": 1,
|
||||||
|
"old_orphan_objects": 0,
|
||||||
|
"deleted_orphan_objects": 0,
|
||||||
|
"fresh_missing_objects": 2,
|
||||||
|
"referenced_missing_objects": 0,
|
||||||
|
"old_unreferenced_metadata": 0,
|
||||||
|
"deleted_unreferenced_rows": 0
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"dry_run": {
|
||||||
|
"duration_ms": 65,
|
||||||
|
"report": {
|
||||||
|
"metadata_scanned": 206,
|
||||||
|
"objects_scanned": 205,
|
||||||
|
"consistent": 204,
|
||||||
|
"fresh_orphan_objects": 0,
|
||||||
|
"old_orphan_objects": 1,
|
||||||
|
"deleted_orphan_objects": 0,
|
||||||
|
"fresh_missing_objects": 0,
|
||||||
|
"referenced_missing_objects": 1,
|
||||||
|
"old_unreferenced_metadata": 1,
|
||||||
|
"deleted_unreferenced_rows": 0
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"apply": {
|
||||||
|
"duration_ms": 77,
|
||||||
|
"report": {
|
||||||
|
"metadata_scanned": 206,
|
||||||
|
"objects_scanned": 205,
|
||||||
|
"consistent": 204,
|
||||||
|
"fresh_orphan_objects": 0,
|
||||||
|
"old_orphan_objects": 1,
|
||||||
|
"deleted_orphan_objects": 1,
|
||||||
|
"fresh_missing_objects": 0,
|
||||||
|
"referenced_missing_objects": 1,
|
||||||
|
"old_unreferenced_metadata": 1,
|
||||||
|
"deleted_unreferenced_rows": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"repeated_apply": {
|
||||||
|
"duration_ms": 38,
|
||||||
|
"report": {
|
||||||
|
"metadata_scanned": 205,
|
||||||
|
"objects_scanned": 204,
|
||||||
|
"consistent": 204,
|
||||||
|
"fresh_orphan_objects": 0,
|
||||||
|
"old_orphan_objects": 0,
|
||||||
|
"deleted_orphan_objects": 0,
|
||||||
|
"fresh_missing_objects": 0,
|
||||||
|
"referenced_missing_objects": 1,
|
||||||
|
"old_unreferenced_metadata": 0,
|
||||||
|
"deleted_unreferenced_rows": 0
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"fresh_preserved": true,
|
||||||
|
"orphan_deleted": true,
|
||||||
|
"unused_metadata_deleted": true,
|
||||||
|
"in_use_metadata_preserved": true,
|
||||||
|
"total_duration_ms": 515
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"replicas": 2,
|
||||||
|
"concurrency": 12,
|
||||||
|
"rounds": 4,
|
||||||
|
"settle_time_ms": 3000,
|
||||||
|
"image_bytes": 3759914,
|
||||||
|
"upload_rate_bytes_per_second": 1572864,
|
||||||
|
"successful_uploads": 48,
|
||||||
|
"failed_uploads": 0,
|
||||||
|
"duration_ms": 12629,
|
||||||
|
"heap_baseline_bytes": 181133200,
|
||||||
|
"heap_peak_bytes": 202374848,
|
||||||
|
"heap_delta_bytes": 21241648,
|
||||||
|
"rss_baseline_bytes": 241922048,
|
||||||
|
"rss_peak_bytes": 381063168,
|
||||||
|
"rss_delta_bytes": 139141120
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
Date: 2026-10-02
|
||||||
|
Environment: linux/arm64 containers, Docker Compose, 2 API replicas
|
||||||
|
|
||||||
|
PASS gofmt for changed Go files
|
||||||
|
PASS go test ./...
|
||||||
|
PASS go build ./cmd/...
|
||||||
|
PASS make check
|
||||||
|
PASS make test BASE_URL=http://localhost:8080
|
||||||
|
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
|
||||||
|
PASS MinIO server RELEASE.2025-10-15T17-29-55Z built from the official source tag
|
||||||
|
PASS mc RELEASE.2025-08-13T08-35-41Z built from the official source tag
|
||||||
|
PASS bucket bootstrap executed twice without an error
|
||||||
|
PASS anonymous bucket request returned HTTP 403
|
||||||
|
PASS application credentials can list only the configured bucket and cannot create another bucket
|
||||||
|
PASS 48 of 48 uploads succeeded in 4 waves with concurrency 12
|
||||||
|
PASS reconciler preserved fresh and referenced anomalies, removed safe old anomalies, and repeated apply made no changes
|
||||||
|
|
||||||
|
The pull request CI runs OpenAPI validation, race tests, lint, integration tests,
|
||||||
|
persistence and API-replica failover on the exact pushed commit.
|
||||||
@@ -5,37 +5,49 @@ go 1.26.0
|
|||||||
require (
|
require (
|
||||||
github.com/google/uuid v1.6.0
|
github.com/google/uuid v1.6.0
|
||||||
github.com/jackc/pgx/v5 v5.11.0
|
github.com/jackc/pgx/v5 v5.11.0
|
||||||
|
github.com/minio/minio-go/v7 v7.0.99
|
||||||
github.com/prometheus/client_golang v1.23.2
|
github.com/prometheus/client_golang v1.23.2
|
||||||
github.com/spf13/viper v1.21.0
|
github.com/spf13/viper v1.21.0
|
||||||
github.com/stretchr/testify v1.11.1
|
github.com/stretchr/testify v1.11.1
|
||||||
github.com/valkey-io/valkey-go v1.0.78
|
github.com/valkey-io/valkey-go v1.0.78
|
||||||
golang.org/x/crypto v0.57.0
|
golang.org/x/crypto v0.57.0
|
||||||
|
golang.org/x/sync v0.23.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/beorn7/perks v1.0.1 // indirect
|
github.com/beorn7/perks v1.0.1 // indirect
|
||||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||||
|
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||||
|
github.com/go-ini/ini v1.67.0 // indirect
|
||||||
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
|
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
|
||||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||||
|
github.com/klauspost/compress v1.18.2 // indirect
|
||||||
|
github.com/klauspost/cpuid/v2 v2.2.11 // 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/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||||
|
github.com/philhofer/fwd v1.2.0 // indirect
|
||||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||||
github.com/prometheus/client_model v0.6.2 // indirect
|
github.com/prometheus/client_model v0.6.2 // indirect
|
||||||
github.com/prometheus/common v0.66.1 // indirect
|
github.com/prometheus/common v0.66.1 // indirect
|
||||||
github.com/prometheus/procfs v0.16.1 // indirect
|
github.com/prometheus/procfs v0.16.1 // indirect
|
||||||
|
github.com/rs/xid v1.6.0 // indirect
|
||||||
github.com/sagikazarmark/locafero v0.11.0 // indirect
|
github.com/sagikazarmark/locafero v0.11.0 // indirect
|
||||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
|
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
|
||||||
github.com/spf13/afero v1.15.0 // indirect
|
github.com/spf13/afero v1.15.0 // indirect
|
||||||
github.com/spf13/cast v1.10.0 // indirect
|
github.com/spf13/cast v1.10.0 // indirect
|
||||||
github.com/spf13/pflag v1.0.10 // indirect
|
github.com/spf13/pflag v1.0.10 // indirect
|
||||||
github.com/subosito/gotenv v1.6.0 // indirect
|
github.com/subosito/gotenv v1.6.0 // indirect
|
||||||
|
github.com/tinylib/msgp v1.6.1 // indirect
|
||||||
go.yaml.in/yaml/v2 v2.4.2 // indirect
|
go.yaml.in/yaml/v2 v2.4.2 // indirect
|
||||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||||
golang.org/x/sync v0.23.0 // indirect
|
golang.org/x/net v0.58.0 // indirect
|
||||||
golang.org/x/sys v0.48.0 // indirect
|
golang.org/x/sys v0.48.0 // indirect
|
||||||
golang.org/x/text v0.42.0 // indirect
|
golang.org/x/text v0.42.0 // indirect
|
||||||
google.golang.org/protobuf v1.36.8 // indirect
|
google.golang.org/protobuf v1.36.8 // indirect
|
||||||
|
|||||||
@@ -5,10 +5,14 @@ github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XL
|
|||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/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/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||||
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||||
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
||||||
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||||
|
github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=
|
||||||
|
github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
|
||||||
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
|
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
|
||||||
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||||
@@ -23,20 +27,33 @@ 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/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 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||||
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
|
github.com/klauspost/compress v1.18.2 h1:iiPHWW0YrcFgpBYhsA6D1+fqHssJscY/Tm/y2Uqnapk=
|
||||||
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
|
github.com/klauspost/compress v1.18.2/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
|
||||||
|
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||||
|
github.com/klauspost/cpuid/v2 v2.2.11 h1:0OwqZRYI2rFrjS4kvkDnqJkKHdHaRnCm68/DY4OxRzU=
|
||||||
|
github.com/klauspost/cpuid/v2 v2.2.11/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||||
|
github.com/klauspost/crc32 v1.3.0 h1:sSmTt3gUt81RP655XGZPElI0PelVTZ6YwCRnPSupoFM=
|
||||||
|
github.com/klauspost/crc32 v1.3.0/go.mod h1:D7kQaZhnkX/Y0tstFGf8VUzv2UofNGqCjnC3zdHB0Hw=
|
||||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||||
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
||||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||||
|
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.0.99 h1:2vH/byrwUkIpFQFOilvTfaUpvAX3fEFhEzO+DR3DlCE=
|
||||||
|
github.com/minio/minio-go/v7 v7.0.99/go.mod h1:EtGNKtlX20iL2yaYnxEigaIvj0G0GwSDnifnG8ClIdw=
|
||||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||||
github.com/onsi/gomega v1.42.1 h1:iN1rCUX+44NZ1Dc97MPoeFYbFR0vh8zxoxMFwKdyZ6I=
|
github.com/onsi/gomega v1.42.1 h1:iN1rCUX+44NZ1Dc97MPoeFYbFR0vh8zxoxMFwKdyZ6I=
|
||||||
github.com/onsi/gomega v1.42.1/go.mod h1:REff/hsDsodHoKlWsP2mAPhu1+5/6hVYNf9rIEBpeSg=
|
github.com/onsi/gomega v1.42.1/go.mod h1:REff/hsDsodHoKlWsP2mAPhu1+5/6hVYNf9rIEBpeSg=
|
||||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||||
|
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 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
|
github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
|
||||||
@@ -49,6 +66,8 @@ github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzM
|
|||||||
github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=
|
github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=
|
||||||
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
|
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
|
||||||
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
|
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
|
||||||
|
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
|
||||||
|
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
|
||||||
github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc=
|
github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc=
|
||||||
github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik=
|
github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik=
|
||||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw=
|
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw=
|
||||||
@@ -68,6 +87,8 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu
|
|||||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
|
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
|
||||||
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
||||||
|
github.com/tinylib/msgp v1.6.1 h1:ESRv8eL3u+DNHUoSAAQRE50Hm162zqAnBoGv9PzScPY=
|
||||||
|
github.com/tinylib/msgp v1.6.1/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA=
|
||||||
github.com/valkey-io/valkey-go v1.0.78 h1:1Ce8hRaaNXpKfqmqZQRhnbVh1eW8MGR873pdXVvE4y8=
|
github.com/valkey-io/valkey-go v1.0.78 h1:1Ce8hRaaNXpKfqmqZQRhnbVh1eW8MGR873pdXVvE4y8=
|
||||||
github.com/valkey-io/valkey-go v1.0.78/go.mod h1:gvC/r2m3eW4Hbj0YnjogTzNtFdPSM/D+NCqen+5OABM=
|
github.com/valkey-io/valkey-go v1.0.78/go.mod h1:gvC/r2m3eW4Hbj0YnjogTzNtFdPSM/D+NCqen+5OABM=
|
||||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
alias_name=bootstrap
|
||||||
|
policy_name=messenger-attachments
|
||||||
|
policy_file=/tmp/messenger-attachments-policy.json
|
||||||
|
|
||||||
|
mc alias set "$alias_name" http://s3:9000 "$MINIO_ROOT_USER" "$MINIO_ROOT_PASSWORD"
|
||||||
|
mc mb --ignore-existing "$alias_name/$S3_BUCKET"
|
||||||
|
mc anonymous set none "$alias_name/$S3_BUCKET"
|
||||||
|
|
||||||
|
cat >"$policy_file" <<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 "$alias_name" "$policy_name" "$policy_file"
|
||||||
|
mc admin user add "$alias_name" "$S3_ACCESS_KEY" "$S3_SECRET_KEY"
|
||||||
|
mc admin policy attach "$alias_name" "$policy_name" --user "$S3_ACCESS_KEY"
|
||||||
|
|
||||||
|
mc alias set application http://s3:9000 "$S3_ACCESS_KEY" "$S3_SECRET_KEY"
|
||||||
|
mc ls "application/$S3_BUCKET" >/dev/null
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
FROM golang:1.24.8-alpine3.22 AS build
|
||||||
|
|
||||||
|
ARG MC_VERSION
|
||||||
|
RUN apk add --no-cache git
|
||||||
|
RUN git clone --depth 1 --branch "${MC_VERSION}" https://github.com/minio/mc.git /src/mc
|
||||||
|
WORKDIR /src/mc
|
||||||
|
RUN go mod download
|
||||||
|
RUN LDFLAGS="$(MC_RELEASE=RELEASE go run buildscripts/gen-ldflags.go)" && \
|
||||||
|
GOMAXPROCS=2 GOMEMLIMIT=1GiB CGO_ENABLED=0 go build -p=1 -tags kqueue -trimpath -ldflags "$LDFLAGS" -o /out/mc .
|
||||||
|
|
||||||
|
FROM alpine:3.22.2
|
||||||
|
|
||||||
|
COPY --from=build /out/mc /usr/local/bin/mc
|
||||||
|
COPY infra/minio/bootstrap.sh /usr/local/bin/bootstrap.sh
|
||||||
|
|
||||||
|
ENTRYPOINT ["mc"]
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
FROM golang:1.24.8-alpine3.22 AS build
|
||||||
|
|
||||||
|
ARG MINIO_VERSION
|
||||||
|
RUN apk add --no-cache git
|
||||||
|
RUN git clone --depth 1 --branch "${MINIO_VERSION}" https://github.com/minio/minio.git /src/minio
|
||||||
|
WORKDIR /src/minio
|
||||||
|
RUN go mod download
|
||||||
|
RUN LDFLAGS="$(MINIO_RELEASE=RELEASE go run buildscripts/gen-ldflags.go)" && \
|
||||||
|
GOMAXPROCS=2 GOMEMLIMIT=1GiB CGO_ENABLED=0 go build -p=1 -tags kqueue -trimpath -ldflags "$LDFLAGS" -o /out/minio .
|
||||||
|
|
||||||
|
FROM alpine:3.22.2
|
||||||
|
|
||||||
|
RUN addgroup -S minio && adduser -S -G minio minio && mkdir /data && chown minio:minio /data
|
||||||
|
COPY --from=build /out/minio /usr/local/bin/minio
|
||||||
|
|
||||||
|
USER minio
|
||||||
|
VOLUME ["/data"]
|
||||||
|
ENTRYPOINT ["minio"]
|
||||||
+93
-24
@@ -12,29 +12,39 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
Address string
|
Address string
|
||||||
DatabaseURL string
|
DatabaseURL string
|
||||||
CacheURL string
|
CacheURL string
|
||||||
SessionTTL time.Duration
|
SessionTTL time.Duration
|
||||||
IdempotencyTTL time.Duration
|
IdempotencyTTL time.Duration
|
||||||
DBMaxConns int32
|
DBMaxConns int32
|
||||||
DBMinConns int32
|
DBMinConns int32
|
||||||
DBMaxConnectionAge time.Duration
|
DBMaxConnectionAge time.Duration
|
||||||
DBMaxConnectionIdle time.Duration
|
DBMaxConnectionIdle time.Duration
|
||||||
DBHealthCheckPeriod time.Duration
|
DBHealthCheckPeriod time.Duration
|
||||||
DependencyTimeout time.Duration
|
DependencyTimeout time.Duration
|
||||||
RequestTimeout time.Duration
|
RequestTimeout time.Duration
|
||||||
HTTPReadHeaderTimeout time.Duration
|
HTTPReadHeaderTimeout time.Duration
|
||||||
HTTPReadTimeout time.Duration
|
HTTPReadTimeout time.Duration
|
||||||
HTTPWriteTimeout time.Duration
|
HTTPWriteTimeout time.Duration
|
||||||
HTTPIdleTimeout time.Duration
|
HTTPIdleTimeout time.Duration
|
||||||
HTTPShutdownTimeout time.Duration
|
HTTPShutdownTimeout time.Duration
|
||||||
PasswordMemoryKiB uint32
|
PasswordMemoryKiB uint32
|
||||||
PasswordIterations uint32
|
PasswordIterations uint32
|
||||||
PasswordParallelism uint8
|
PasswordParallelism uint8
|
||||||
PasswordSaltLength uint32
|
PasswordSaltLength uint32
|
||||||
PasswordKeyLength uint32
|
PasswordKeyLength uint32
|
||||||
SwaggerPort string
|
SwaggerPort string
|
||||||
|
S3Endpoint string
|
||||||
|
S3Region string
|
||||||
|
S3Bucket string
|
||||||
|
S3AccessKey string
|
||||||
|
S3SecretKey string
|
||||||
|
S3UseTLS bool
|
||||||
|
S3Timeout time.Duration
|
||||||
|
AttachmentMaxBytes int64
|
||||||
|
AttachmentMaxPixels int64
|
||||||
|
AttachmentDecodeMemory int64
|
||||||
}
|
}
|
||||||
|
|
||||||
type MigrationConfig struct {
|
type MigrationConfig struct {
|
||||||
@@ -142,6 +152,50 @@ func Load() (Config, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return Config{}, err
|
return Config{}, err
|
||||||
}
|
}
|
||||||
|
s3Endpoint, err := requiredString(values, "S3_ENDPOINT")
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
s3Region, err := requiredString(values, "S3_REGION")
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
s3Bucket, err := requiredString(values, "S3_BUCKET")
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
s3AccessKey, err := requiredString(values, "S3_ACCESS_KEY")
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
s3SecretKey, err := requiredString(values, "S3_SECRET_KEY")
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
s3UseTLS, err := boolean(values, "S3_USE_TLS")
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
s3Timeout, err := seconds(values, "S3_TIMEOUT_SECONDS", 1, 300)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
attachmentMaxBytes, err := integer(values, "ATTACHMENT_MAX_BYTES", 1, 10*1024*1024)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
attachmentMaxPixels, err := integer(values, "ATTACHMENT_MAX_PIXELS", 1, 40_000_000)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
attachmentDecodeMemory, err := integer(values, "ATTACHMENT_DECODE_MEMORY_BYTES", 1, 1024*1024*1024)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
minimumDecodeMemory := int64(attachmentMaxBytes) + int64(attachmentMaxPixels)*8
|
||||||
|
if int64(attachmentDecodeMemory) < minimumDecodeMemory {
|
||||||
|
return Config{}, fmt.Errorf("ATTACHMENT_DECODE_MEMORY_BYTES: must be at least %d", minimumDecodeMemory)
|
||||||
|
}
|
||||||
|
|
||||||
return Config{
|
return Config{
|
||||||
Address: net.JoinHostPort(host, port), DatabaseURL: database.url, CacheURL: cacheURL,
|
Address: net.JoinHostPort(host, port), DatabaseURL: database.url, CacheURL: cacheURL,
|
||||||
@@ -155,7 +209,10 @@ func Load() (Config, error) {
|
|||||||
HTTPShutdownTimeout: shutdownTimeout, PasswordMemoryKiB: uint32(passwordMemory),
|
HTTPShutdownTimeout: shutdownTimeout, PasswordMemoryKiB: uint32(passwordMemory),
|
||||||
PasswordIterations: uint32(passwordIterations), PasswordParallelism: uint8(passwordParallelism),
|
PasswordIterations: uint32(passwordIterations), PasswordParallelism: uint8(passwordParallelism),
|
||||||
PasswordSaltLength: uint32(passwordSaltLength), PasswordKeyLength: uint32(passwordKeyLength),
|
PasswordSaltLength: uint32(passwordSaltLength), PasswordKeyLength: uint32(passwordKeyLength),
|
||||||
SwaggerPort: swaggerPort,
|
SwaggerPort: swaggerPort, S3Endpoint: s3Endpoint, S3Region: s3Region, S3Bucket: s3Bucket,
|
||||||
|
S3AccessKey: s3AccessKey, S3SecretKey: s3SecretKey, S3UseTLS: s3UseTLS, S3Timeout: s3Timeout,
|
||||||
|
AttachmentMaxBytes: int64(attachmentMaxBytes), AttachmentMaxPixels: int64(attachmentMaxPixels),
|
||||||
|
AttachmentDecodeMemory: int64(attachmentDecodeMemory),
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -260,3 +317,15 @@ func integerValue(value string, minimum, maximum int) (int, error) {
|
|||||||
}
|
}
|
||||||
return parsed, nil
|
return parsed, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func boolean(values *viper.Viper, name string) (bool, error) {
|
||||||
|
value, err := requiredString(values, name)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
parsed, err := strconv.ParseBool(value)
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("%s: must be true or false", name)
|
||||||
|
}
|
||||||
|
return parsed, nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,260 @@
|
|||||||
|
package messenger
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"image"
|
||||||
|
_ "image/jpeg"
|
||||||
|
_ "image/png"
|
||||||
|
"io"
|
||||||
|
"mime"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"golang.org/x/sync/semaphore"
|
||||||
|
|
||||||
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
|
||||||
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/objectstore"
|
||||||
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/postgres"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request) *apiError {
|
||||||
|
started := time.Now()
|
||||||
|
result := "client_error"
|
||||||
|
defer func() {
|
||||||
|
s.metrics.attachmentUploads.WithLabelValues(result).Inc()
|
||||||
|
s.metrics.attachmentDuration.Observe(time.Since(started).Seconds())
|
||||||
|
}()
|
||||||
|
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
return methodNotAllowed(w, http.MethodPost)
|
||||||
|
}
|
||||||
|
user, _, authErr := s.authenticate(r)
|
||||||
|
if authErr != nil {
|
||||||
|
return authErr
|
||||||
|
}
|
||||||
|
chatID, valid := canonicalID(strings.Split(r.URL.Path, "/")[4])
|
||||||
|
if !valid {
|
||||||
|
return invalidRequest()
|
||||||
|
}
|
||||||
|
filename, valid := attachmentFilename(r.URL.Query())
|
||||||
|
if !valid {
|
||||||
|
return invalidRequest()
|
||||||
|
}
|
||||||
|
if _, err := s.messengerStore.ChatForUser(r.Context(), chatID, user.ID); errors.Is(err, postgres.ErrNotFound) {
|
||||||
|
return notFound()
|
||||||
|
} else if err != nil {
|
||||||
|
result = "dependency_error"
|
||||||
|
return unavailable()
|
||||||
|
}
|
||||||
|
data, contentType, readErr := readImage(w, r, s.maxUploadBytes, s.maxImagePixels, s.decodeMemory)
|
||||||
|
if readErr != nil {
|
||||||
|
return readErr
|
||||||
|
}
|
||||||
|
|
||||||
|
attachmentID, err := newID()
|
||||||
|
if err != nil {
|
||||||
|
result = "dependency_error"
|
||||||
|
return internalError()
|
||||||
|
}
|
||||||
|
objectID, err := newID()
|
||||||
|
if err != nil {
|
||||||
|
result = "dependency_error"
|
||||||
|
return internalError()
|
||||||
|
}
|
||||||
|
objectKey := "attachments/" + objectID + "/original"
|
||||||
|
if err := s.objects.Put(r.Context(), objectKey, contentType, data); err != nil {
|
||||||
|
result = "dependency_error"
|
||||||
|
return unavailable()
|
||||||
|
}
|
||||||
|
digest := sha256.Sum256(data)
|
||||||
|
attachment, err := s.messengerStore.CreateAttachment(r.Context(), model.Attachment{
|
||||||
|
ID: attachmentID, ChatID: chatID, OwnerID: user.ID, Filename: filename,
|
||||||
|
ContentType: contentType, SizeBytes: int64(len(data)), SHA256: hex.EncodeToString(digest[:]), ObjectKey: objectKey,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
result = "dependency_error"
|
||||||
|
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), s.requestTTL)
|
||||||
|
defer cancel()
|
||||||
|
stored, lookupErr := s.messengerStore.AttachmentByStorage(cleanupCtx, attachmentID, objectKey)
|
||||||
|
if lookupErr == nil {
|
||||||
|
result = "success"
|
||||||
|
s.metrics.attachmentBytes.Add(float64(len(data)))
|
||||||
|
writeJSON(w, http.StatusCreated, stored)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if !errors.Is(lookupErr, postgres.ErrNotFound) {
|
||||||
|
s.logger.Error("attachment outcome is unknown", "attachment_id", attachmentID, "error", lookupErr)
|
||||||
|
return unavailable()
|
||||||
|
}
|
||||||
|
if cleanupErr := s.objects.Delete(cleanupCtx, objectKey); cleanupErr != nil {
|
||||||
|
s.logger.Error("attachment compensation failed", "object_key", objectKey, "error", cleanupErr)
|
||||||
|
}
|
||||||
|
if errors.Is(err, postgres.ErrNotFound) {
|
||||||
|
return notFound()
|
||||||
|
}
|
||||||
|
return unavailable()
|
||||||
|
}
|
||||||
|
result = "success"
|
||||||
|
s.metrics.attachmentBytes.Add(float64(len(data)))
|
||||||
|
writeJSON(w, http.StatusCreated, attachment)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func attachmentFilename(query url.Values) (string, bool) {
|
||||||
|
if len(query) != 1 || len(query["filename"]) != 1 {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
filename := query["filename"][0]
|
||||||
|
length := utf8.RuneCountInString(filename)
|
||||||
|
if !utf8.ValidString(filename) || strings.TrimSpace(filename) == "" || length < 1 || length > 255 {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
for _, char := range filename {
|
||||||
|
if char == '/' || char == '\\' || char == 0 || unicode.IsControl(char) {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return filename, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func readImage(
|
||||||
|
w http.ResponseWriter,
|
||||||
|
r *http.Request,
|
||||||
|
maxBytes int64,
|
||||||
|
maxPixels int64,
|
||||||
|
decodeMemory *semaphore.Weighted,
|
||||||
|
) ([]byte, string, *apiError) {
|
||||||
|
mediaType, parameters, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||||
|
if err != nil || len(parameters) != 0 || mediaType != "image/png" && mediaType != "image/jpeg" {
|
||||||
|
return nil, "", &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "unsupported image type"}
|
||||||
|
}
|
||||||
|
if r.ContentLength > maxBytes {
|
||||||
|
return nil, "", &apiError{http.StatusRequestEntityTooLarge, errorCodePayloadTooLarge, "image is too large"}
|
||||||
|
}
|
||||||
|
r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
|
||||||
|
data, err := io.ReadAll(r.Body)
|
||||||
|
if err != nil {
|
||||||
|
var tooLarge *http.MaxBytesError
|
||||||
|
if errors.As(err, &tooLarge) {
|
||||||
|
return nil, "", &apiError{http.StatusRequestEntityTooLarge, errorCodePayloadTooLarge, "image is too large"}
|
||||||
|
}
|
||||||
|
return nil, "", invalidRequest()
|
||||||
|
}
|
||||||
|
if len(data) == 0 {
|
||||||
|
return nil, "", &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "invalid image"}
|
||||||
|
}
|
||||||
|
detected := http.DetectContentType(data)
|
||||||
|
if detected != mediaType {
|
||||||
|
return nil, "", &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "content type does not match image"}
|
||||||
|
}
|
||||||
|
imageConfig, format, err := image.DecodeConfig(bytes.NewReader(data))
|
||||||
|
if err != nil || imageContentType(format) != mediaType {
|
||||||
|
return nil, "", &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "invalid image"}
|
||||||
|
}
|
||||||
|
pixels := int64(imageConfig.Width) * int64(imageConfig.Height)
|
||||||
|
if imageConfig.Width < 1 || imageConfig.Height < 1 || pixels > maxPixels {
|
||||||
|
return nil, "", &apiError{http.StatusRequestEntityTooLarge, errorCodePayloadTooLarge, "image dimensions are too large"}
|
||||||
|
}
|
||||||
|
decodeBytes := pixels*8 + int64(len(data))
|
||||||
|
if !decodeMemory.TryAcquire(decodeBytes) {
|
||||||
|
w.Header().Set("Retry-After", "1")
|
||||||
|
return nil, "", &apiError{http.StatusTooManyRequests, errorCodeRateLimited, "image capacity is temporarily exhausted"}
|
||||||
|
}
|
||||||
|
defer decodeMemory.Release(decodeBytes)
|
||||||
|
if _, format, err := image.Decode(bytes.NewReader(data)); err != nil || imageContentType(format) != mediaType {
|
||||||
|
return nil, "", &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "invalid image"}
|
||||||
|
}
|
||||||
|
return data, mediaType, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func imageContentType(format string) string {
|
||||||
|
switch format {
|
||||||
|
case "png":
|
||||||
|
return "image/png"
|
||||||
|
case "jpeg":
|
||||||
|
return "image/jpeg"
|
||||||
|
default:
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) attachmentMetadata(w http.ResponseWriter, r *http.Request) *apiError {
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
return methodNotAllowed(w, http.MethodGet)
|
||||||
|
}
|
||||||
|
user, _, authErr := s.authenticate(r)
|
||||||
|
if authErr != nil {
|
||||||
|
return authErr
|
||||||
|
}
|
||||||
|
attachment, apiErr := s.attachmentForUser(r, user.ID)
|
||||||
|
if apiErr != nil {
|
||||||
|
return apiErr
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, attachment)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) attachmentContent(w http.ResponseWriter, r *http.Request) *apiError {
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
return methodNotAllowed(w, http.MethodGet)
|
||||||
|
}
|
||||||
|
user, _, authErr := s.authenticate(r)
|
||||||
|
if authErr != nil {
|
||||||
|
return authErr
|
||||||
|
}
|
||||||
|
if !originalVariant(r.URL.Query()) {
|
||||||
|
return invalidRequest()
|
||||||
|
}
|
||||||
|
attachment, apiErr := s.attachmentForUser(r, user.ID)
|
||||||
|
if apiErr != nil {
|
||||||
|
return apiErr
|
||||||
|
}
|
||||||
|
content, err := s.objects.Get(r.Context(), attachment.ObjectKey)
|
||||||
|
if errors.Is(err, objectstore.ErrNotFound) {
|
||||||
|
return unavailable()
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return unavailable()
|
||||||
|
}
|
||||||
|
defer func() { _ = content.Close() }()
|
||||||
|
w.Header().Set("Content-Type", attachment.ContentType)
|
||||||
|
w.Header().Set("Content-Length", strconv.FormatInt(attachment.SizeBytes, 10))
|
||||||
|
w.Header().Set("Content-Disposition", mime.FormatMediaType("inline", map[string]string{"filename": attachment.Filename}))
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
if _, err := io.Copy(w, content); err != nil {
|
||||||
|
s.logger.Warn("attachment download interrupted", "attachment_id", attachment.ID, "error", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func originalVariant(query url.Values) bool {
|
||||||
|
if len(query) == 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return len(query) == 1 && len(query["variant"]) == 1 && query["variant"][0] == "original"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) attachmentForUser(r *http.Request, userID string) (Attachment, *apiError) {
|
||||||
|
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
|
||||||
|
attachmentID, valid := canonicalID(parts[3])
|
||||||
|
if !valid {
|
||||||
|
return Attachment{}, invalidRequest()
|
||||||
|
}
|
||||||
|
attachment, err := s.messengerStore.AttachmentForUser(r.Context(), attachmentID, userID)
|
||||||
|
if errors.Is(err, postgres.ErrNotFound) {
|
||||||
|
return Attachment{}, notFound()
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return Attachment{}, unavailable()
|
||||||
|
}
|
||||||
|
return attachment, nil
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ const (
|
|||||||
errorCodePayloadTooLarge = "payload_too_large"
|
errorCodePayloadTooLarge = "payload_too_large"
|
||||||
errorCodeUnavailable = "unavailable"
|
errorCodeUnavailable = "unavailable"
|
||||||
errorCodeConflict = "conflict"
|
errorCodeConflict = "conflict"
|
||||||
|
errorCodeRateLimited = "rate_limited"
|
||||||
)
|
)
|
||||||
|
|
||||||
type apiError struct {
|
type apiError struct {
|
||||||
|
|||||||
@@ -38,6 +38,9 @@ func (s *Server) readiness(w http.ResponseWriter, r *http.Request) *apiError {
|
|||||||
if err := s.sessions.Ping(ctx); err != nil {
|
if err := s.sessions.Ping(ctx); err != nil {
|
||||||
return unavailable()
|
return unavailable()
|
||||||
}
|
}
|
||||||
|
if err := s.objects.Ping(ctx); err != nil {
|
||||||
|
return unavailable()
|
||||||
|
}
|
||||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -207,16 +210,17 @@ func (s *Server) messages(w http.ResponseWriter, r *http.Request) *apiError {
|
|||||||
return invalidRequest()
|
return invalidRequest()
|
||||||
}
|
}
|
||||||
var input struct {
|
var input struct {
|
||||||
Text string `json:"text"`
|
Text string `json:"text"`
|
||||||
|
AttachmentIDs []string `json:"attachment_ids"`
|
||||||
}
|
}
|
||||||
if err := readJSON(w, r, &input); err != nil {
|
if err := readJSON(w, r, &input); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if !validText(input.Text, 4000) {
|
if !validMessage(input.Text, input.AttachmentIDs) || !canonicalAttachmentIDs(input.AttachmentIDs) {
|
||||||
return invalidRequest()
|
return invalidRequest()
|
||||||
}
|
}
|
||||||
message, replay, err := s.messengerStore.CreateMessage(
|
message, replay, err := s.messengerStore.CreateMessage(
|
||||||
r.Context(), chatID, user.ID, input.Text, key, s.idempotencyTTL,
|
r.Context(), chatID, user.ID, input.Text, input.AttachmentIDs, key, s.idempotencyTTL,
|
||||||
)
|
)
|
||||||
if errors.Is(err, postgres.ErrNotFound) {
|
if errors.Is(err, postgres.ErrNotFound) {
|
||||||
return notFound()
|
return notFound()
|
||||||
@@ -234,6 +238,32 @@ func (s *Server) messages(w http.ResponseWriter, r *http.Request) *apiError {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func validMessage(text string, attachmentIDs []string) bool {
|
||||||
|
if !utf8.ValidString(text) || utf8.RuneCountInString(text) > 4000 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return len(attachmentIDs) > 0 || strings.TrimSpace(text) != ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func canonicalAttachmentIDs(attachmentIDs []string) bool {
|
||||||
|
if len(attachmentIDs) > 10 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
seen := make(map[string]struct{}, len(attachmentIDs))
|
||||||
|
for index, attachmentID := range attachmentIDs {
|
||||||
|
canonical, valid := canonicalID(attachmentID)
|
||||||
|
if !valid {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if _, duplicate := seen[canonical]; duplicate {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
seen[canonical] = struct{}{}
|
||||||
|
attachmentIDs[index] = canonical
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
func (s *Server) listMessages(w http.ResponseWriter, r *http.Request, user User, chatID string) *apiError {
|
func (s *Server) listMessages(w http.ResponseWriter, r *http.Request, user User, chatID string) *apiError {
|
||||||
limit, cursor, err := pageParams(r, "message", chatID)
|
limit, cursor, err := pageParams(r, "message", chatID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package messenger
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"io"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
|
||||||
@@ -15,8 +16,18 @@ type MessengerStore interface {
|
|||||||
CreateChat(context.Context, string, []string, string) (model.Chat, error)
|
CreateChat(context.Context, string, []string, string) (model.Chat, error)
|
||||||
ChatForUser(context.Context, string, string) (model.Chat, error)
|
ChatForUser(context.Context, string, string) (model.Chat, error)
|
||||||
ListChats(context.Context, string, *model.Position, int) ([]model.Chat, bool, error)
|
ListChats(context.Context, string, *model.Position, int) ([]model.Chat, bool, error)
|
||||||
CreateMessage(context.Context, string, string, string, string, time.Duration) (model.Message, bool, error)
|
CreateMessage(context.Context, string, string, string, []string, string, time.Duration) (model.Message, bool, error)
|
||||||
ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error)
|
ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error)
|
||||||
|
CreateAttachment(context.Context, model.Attachment) (model.Attachment, error)
|
||||||
|
AttachmentByStorage(context.Context, string, string) (model.Attachment, error)
|
||||||
|
AttachmentForUser(context.Context, string, string) (model.Attachment, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type ObjectStore interface {
|
||||||
|
Ping(context.Context) error
|
||||||
|
Put(context.Context, string, string, []byte) error
|
||||||
|
Get(context.Context, string) (io.ReadCloser, error)
|
||||||
|
Delete(context.Context, string) error
|
||||||
}
|
}
|
||||||
|
|
||||||
type SessionStore interface {
|
type SessionStore interface {
|
||||||
|
|||||||
@@ -12,11 +12,14 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type metrics struct {
|
type metrics struct {
|
||||||
requests *prometheus.CounterVec
|
requests *prometheus.CounterVec
|
||||||
duration *prometheus.HistogramVec
|
duration *prometheus.HistogramVec
|
||||||
inFlight prometheus.Gauge
|
inFlight prometheus.Gauge
|
||||||
replays prometheus.Counter
|
replays prometheus.Counter
|
||||||
handler http.Handler
|
attachmentUploads *prometheus.CounterVec
|
||||||
|
attachmentDuration prometheus.Histogram
|
||||||
|
attachmentBytes prometheus.Counter
|
||||||
|
handler http.Handler
|
||||||
}
|
}
|
||||||
|
|
||||||
func newMetrics() *metrics {
|
func newMetrics() *metrics {
|
||||||
@@ -47,12 +50,31 @@ func newMetrics() *metrics {
|
|||||||
Name: "idempotency_replays_total",
|
Name: "idempotency_replays_total",
|
||||||
Help: "Message requests served from an idempotency record.",
|
Help: "Message requests served from an idempotency record.",
|
||||||
}),
|
}),
|
||||||
|
attachmentUploads: prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||||
|
Namespace: "messenger",
|
||||||
|
Name: "attachment_uploads_total",
|
||||||
|
Help: "Completed attachment uploads by result.",
|
||||||
|
}, []string{"result"}),
|
||||||
|
attachmentDuration: prometheus.NewHistogram(prometheus.HistogramOpts{
|
||||||
|
Namespace: "messenger",
|
||||||
|
Name: "attachment_upload_duration_seconds",
|
||||||
|
Help: "Attachment upload duration in seconds.",
|
||||||
|
Buckets: prometheus.DefBuckets,
|
||||||
|
}),
|
||||||
|
attachmentBytes: prometheus.NewCounter(prometheus.CounterOpts{
|
||||||
|
Namespace: "messenger",
|
||||||
|
Name: "attachment_upload_bytes_total",
|
||||||
|
Help: "Bytes accepted by successful attachment uploads.",
|
||||||
|
}),
|
||||||
}
|
}
|
||||||
registry.MustRegister(
|
registry.MustRegister(
|
||||||
result.requests,
|
result.requests,
|
||||||
result.duration,
|
result.duration,
|
||||||
result.inFlight,
|
result.inFlight,
|
||||||
result.replays,
|
result.replays,
|
||||||
|
result.attachmentUploads,
|
||||||
|
result.attachmentDuration,
|
||||||
|
result.attachmentBytes,
|
||||||
collectors.NewGoCollector(),
|
collectors.NewGoCollector(),
|
||||||
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
|
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
|
||||||
)
|
)
|
||||||
@@ -79,5 +101,14 @@ func routeTemplate(path string) string {
|
|||||||
if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "messages" {
|
if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "messages" {
|
||||||
return "/api/v1/chats/{chat_id}/messages"
|
return "/api/v1/chats/{chat_id}/messages"
|
||||||
}
|
}
|
||||||
|
if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "attachments" {
|
||||||
|
return "/api/v1/chats/{chat_id}/attachments"
|
||||||
|
}
|
||||||
|
if len(parts) == 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" {
|
||||||
|
return "/api/v1/attachments/{attachment_id}"
|
||||||
|
}
|
||||||
|
if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" && parts[4] == "content" {
|
||||||
|
return "/api/v1/attachments/{attachment_id}/content"
|
||||||
|
}
|
||||||
return "unknown"
|
return "unknown"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
type User = model.User
|
type User = model.User
|
||||||
type Chat = model.Chat
|
type Chat = model.Chat
|
||||||
type Message = model.Message
|
type Message = model.Message
|
||||||
|
type Attachment = model.Attachment
|
||||||
|
|
||||||
func newID() (string, error) {
|
func newID() (string, error) {
|
||||||
id, err := uuid.NewRandom()
|
id, err := uuid.NewRandom()
|
||||||
|
|||||||
@@ -33,6 +33,12 @@ func (s *Server) route(w http.ResponseWriter, r *http.Request) *apiError {
|
|||||||
handler = s.chat
|
handler = s.chat
|
||||||
} else if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "messages" {
|
} else if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "messages" {
|
||||||
handler = s.messages
|
handler = s.messages
|
||||||
|
} else if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "attachments" {
|
||||||
|
handler = s.uploadAttachment
|
||||||
|
} else if len(parts) == 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" {
|
||||||
|
handler = s.attachmentMetadata
|
||||||
|
} else if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" && parts[4] == "content" {
|
||||||
|
handler = s.attachmentContent
|
||||||
} else {
|
} else {
|
||||||
return notFound()
|
return notFound()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,18 +6,24 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"golang.org/x/sync/semaphore"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Server struct {
|
type Server struct {
|
||||||
messengerStore MessengerStore
|
messengerStore MessengerStore
|
||||||
sessions SessionStore
|
sessions SessionStore
|
||||||
passwords PasswordService
|
passwords PasswordService
|
||||||
|
objects ObjectStore
|
||||||
sessionTTL time.Duration
|
sessionTTL time.Duration
|
||||||
idempotencyTTL time.Duration
|
idempotencyTTL time.Duration
|
||||||
requestTTL time.Duration
|
requestTTL time.Duration
|
||||||
instanceID string
|
instanceID string
|
||||||
logger *slog.Logger
|
logger *slog.Logger
|
||||||
swaggerPort string
|
swaggerPort string
|
||||||
|
maxUploadBytes int64
|
||||||
|
maxImagePixels int64
|
||||||
|
decodeMemory *semaphore.Weighted
|
||||||
metrics *metrics
|
metrics *metrics
|
||||||
ready atomic.Bool
|
ready atomic.Bool
|
||||||
}
|
}
|
||||||
@@ -37,16 +43,22 @@ func NewServer(
|
|||||||
messages MessengerStore,
|
messages MessengerStore,
|
||||||
sessions SessionStore,
|
sessions SessionStore,
|
||||||
passwords PasswordService,
|
passwords PasswordService,
|
||||||
|
objects ObjectStore,
|
||||||
sessionTTL time.Duration,
|
sessionTTL time.Duration,
|
||||||
idempotencyTTL time.Duration,
|
idempotencyTTL time.Duration,
|
||||||
requestTTL time.Duration,
|
requestTTL time.Duration,
|
||||||
instanceID string,
|
instanceID string,
|
||||||
swaggerPort string,
|
swaggerPort string,
|
||||||
|
maxUploadBytes int64,
|
||||||
|
maxImagePixels int64,
|
||||||
|
decodeMemoryBytes int64,
|
||||||
) *Server {
|
) *Server {
|
||||||
s := &Server{
|
s := &Server{
|
||||||
messengerStore: messages, sessions: sessions, passwords: passwords,
|
messengerStore: messages, sessions: sessions, passwords: passwords, objects: objects,
|
||||||
sessionTTL: sessionTTL, idempotencyTTL: idempotencyTTL, requestTTL: requestTTL,
|
sessionTTL: sessionTTL, idempotencyTTL: idempotencyTTL, requestTTL: requestTTL,
|
||||||
instanceID: instanceID, logger: logger, swaggerPort: swaggerPort, metrics: newMetrics(),
|
instanceID: instanceID, logger: logger, swaggerPort: swaggerPort,
|
||||||
|
maxUploadBytes: maxUploadBytes, maxImagePixels: maxImagePixels,
|
||||||
|
decodeMemory: semaphore.NewWeighted(decodeMemoryBytes), metrics: newMetrics(),
|
||||||
}
|
}
|
||||||
s.ready.Store(true)
|
s.ready.Store(true)
|
||||||
return s
|
return s
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
package messenger
|
package messenger
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
"image/png"
|
||||||
"io"
|
"io"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -13,6 +17,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/stretchr/testify/suite"
|
"github.com/stretchr/testify/suite"
|
||||||
|
"golang.org/x/sync/semaphore"
|
||||||
|
|
||||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
|
||||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/postgres"
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/postgres"
|
||||||
@@ -34,14 +39,19 @@ func (s *MessengerSuite) SetupTest() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type messengerStoreStub struct {
|
type messengerStoreStub struct {
|
||||||
pingErr error
|
pingErr error
|
||||||
userByID model.User
|
userByID model.User
|
||||||
userByIDErr error
|
userByIDErr error
|
||||||
credentials model.UserCredentials
|
credentials model.UserCredentials
|
||||||
credentialsErr error
|
credentialsErr error
|
||||||
message model.Message
|
message model.Message
|
||||||
messageReplay bool
|
messageReplay bool
|
||||||
messageErr error
|
messageErr error
|
||||||
|
attachment model.Attachment
|
||||||
|
attachmentErr error
|
||||||
|
storedAttachment model.Attachment
|
||||||
|
storedAttachmentExists bool
|
||||||
|
storedAttachmentErr error
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s messengerStoreStub) Ping(context.Context) error { return s.pingErr }
|
func (s messengerStoreStub) Ping(context.Context) error { return s.pingErr }
|
||||||
@@ -63,12 +73,57 @@ func (messengerStoreStub) ChatForUser(context.Context, string, string) (model.Ch
|
|||||||
func (messengerStoreStub) ListChats(context.Context, string, *model.Position, int) ([]model.Chat, bool, error) {
|
func (messengerStoreStub) ListChats(context.Context, string, *model.Position, int) ([]model.Chat, bool, error) {
|
||||||
return nil, false, nil
|
return nil, false, nil
|
||||||
}
|
}
|
||||||
func (s messengerStoreStub) CreateMessage(context.Context, string, string, string, string, time.Duration) (model.Message, bool, error) {
|
func (s messengerStoreStub) CreateMessage(context.Context, string, string, string, []string, string, time.Duration) (model.Message, bool, error) {
|
||||||
return s.message, s.messageReplay, s.messageErr
|
return s.message, s.messageReplay, s.messageErr
|
||||||
}
|
}
|
||||||
func (messengerStoreStub) ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error) {
|
func (messengerStoreStub) ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error) {
|
||||||
return nil, false, nil
|
return nil, false, nil
|
||||||
}
|
}
|
||||||
|
func (s messengerStoreStub) CreateAttachment(context.Context, model.Attachment) (model.Attachment, error) {
|
||||||
|
return s.attachment, s.attachmentErr
|
||||||
|
}
|
||||||
|
func (s messengerStoreStub) AttachmentByStorage(context.Context, string, string) (model.Attachment, error) {
|
||||||
|
if s.storedAttachmentErr != nil {
|
||||||
|
return model.Attachment{}, s.storedAttachmentErr
|
||||||
|
}
|
||||||
|
if !s.storedAttachmentExists {
|
||||||
|
return model.Attachment{}, postgres.ErrNotFound
|
||||||
|
}
|
||||||
|
return s.storedAttachment, nil
|
||||||
|
}
|
||||||
|
func (s messengerStoreStub) AttachmentForUser(context.Context, string, string) (model.Attachment, error) {
|
||||||
|
return s.attachment, s.attachmentErr
|
||||||
|
}
|
||||||
|
|
||||||
|
type objectStoreStub struct {
|
||||||
|
pingErr error
|
||||||
|
putErr error
|
||||||
|
getData []byte
|
||||||
|
getErr error
|
||||||
|
deleteErr error
|
||||||
|
putKey *string
|
||||||
|
deletedKey *string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s objectStoreStub) Ping(context.Context) error { return s.pingErr }
|
||||||
|
func (s objectStoreStub) Put(_ context.Context, key string, _ string, _ []byte) error {
|
||||||
|
if s.putKey != nil {
|
||||||
|
*s.putKey = key
|
||||||
|
}
|
||||||
|
return s.putErr
|
||||||
|
}
|
||||||
|
func (s objectStoreStub) Get(context.Context, string) (io.ReadCloser, error) {
|
||||||
|
if s.getErr != nil {
|
||||||
|
return nil, s.getErr
|
||||||
|
}
|
||||||
|
return io.NopCloser(bytes.NewReader(s.getData)), nil
|
||||||
|
}
|
||||||
|
func (s objectStoreStub) Delete(_ context.Context, key string) error {
|
||||||
|
if s.deletedKey != nil {
|
||||||
|
*s.deletedKey = key
|
||||||
|
}
|
||||||
|
return s.deleteErr
|
||||||
|
}
|
||||||
|
|
||||||
type sessionStub struct {
|
type sessionStub struct {
|
||||||
pingErr error
|
pingErr error
|
||||||
@@ -100,14 +155,19 @@ func (s *MessengerSuite) TestReadinessReturnsUnavailableForDependencyFailure() {
|
|||||||
name string
|
name string
|
||||||
store messengerStoreStub
|
store messengerStoreStub
|
||||||
sessions sessionStub
|
sessions sessionStub
|
||||||
|
objects objectStoreStub
|
||||||
}{
|
}{
|
||||||
{name: "postgres", store: messengerStoreStub{pingErr: errDependency}},
|
{name: "postgres", store: messengerStoreStub{pingErr: errDependency}},
|
||||||
{name: "valkey", sessions: sessionStub{pingErr: errDependency}},
|
{name: "valkey", sessions: sessionStub{pingErr: errDependency}},
|
||||||
|
{name: "s3", objects: objectStoreStub{pingErr: errDependency}},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
server := s.newTestServer(tt.store, tt.sessions, passwordsStub{})
|
server := NewServer(
|
||||||
|
s.logger, tt.store, tt.sessions, passwordsStub{}, tt.objects, time.Hour, 24*time.Hour,
|
||||||
|
time.Second, "test-instance", "8081", 10*1024*1024, 40_000_000, 384*1024*1024,
|
||||||
|
)
|
||||||
response := serveRequest(server, http.MethodGet, "/health/ready", "")
|
response := serveRequest(server, http.MethodGet, "/health/ready", "")
|
||||||
if response.Code != http.StatusServiceUnavailable {
|
if response.Code != http.StatusServiceUnavailable {
|
||||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable)
|
t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable)
|
||||||
@@ -160,6 +220,18 @@ func (s *MessengerSuite) TestAuthenticationChallenges() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *MessengerSuite) TestAttachmentContentAuthenticatesBeforeVariantValidation() {
|
||||||
|
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
|
||||||
|
response := serveRequest(
|
||||||
|
server,
|
||||||
|
http.MethodGet,
|
||||||
|
"/api/v1/attachments/00000000-0000-0000-0000-000000000001/content?variant=invalid",
|
||||||
|
"",
|
||||||
|
)
|
||||||
|
s.Equal(http.StatusUnauthorized, response.Code)
|
||||||
|
s.Equal(`Bearer realm="messenger"`, response.Header().Get("WWW-Authenticate"))
|
||||||
|
}
|
||||||
|
|
||||||
func (s *MessengerSuite) TestSessionCreationRejectsChunkedBody() {
|
func (s *MessengerSuite) TestSessionCreationRejectsChunkedBody() {
|
||||||
t := s.T()
|
t := s.T()
|
||||||
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
|
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
|
||||||
@@ -242,8 +314,135 @@ func (s *MessengerSuite) TestMessageCreationReturnsConflictForReusedKeyWithDiffe
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *MessengerSuite) TestImageValidation() {
|
||||||
|
data := testPNG(s.T(), 2, 2)
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
contentType string
|
||||||
|
data []byte
|
||||||
|
maxBytes int64
|
||||||
|
maxPixels int64
|
||||||
|
wantStatus int
|
||||||
|
}{
|
||||||
|
{name: "valid", contentType: "image/png", data: data, maxBytes: 1024, maxPixels: 4},
|
||||||
|
{name: "spoofed MIME", contentType: "image/jpeg", data: data, maxBytes: 1024, maxPixels: 4, wantStatus: http.StatusUnsupportedMediaType},
|
||||||
|
{name: "too many pixels", contentType: "image/png", data: data, maxBytes: 1024, maxPixels: 3, wantStatus: http.StatusRequestEntityTooLarge},
|
||||||
|
{name: "too many bytes", contentType: "image/png", data: data, maxBytes: int64(len(data) - 1), maxPixels: 4, wantStatus: http.StatusRequestEntityTooLarge},
|
||||||
|
{name: "damaged", contentType: "image/png", data: data[:16], maxBytes: 1024, maxPixels: 4, wantStatus: http.StatusUnsupportedMediaType},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
s.Run(tt.name, func() {
|
||||||
|
request := httptest.NewRequest(http.MethodPost, "/upload", bytes.NewReader(tt.data))
|
||||||
|
request.Header.Set("Content-Type", tt.contentType)
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
actual, _, apiErr := readImage(
|
||||||
|
response, request, tt.maxBytes, tt.maxPixels, semaphore.NewWeighted(384*1024*1024),
|
||||||
|
)
|
||||||
|
if tt.wantStatus == 0 {
|
||||||
|
s.Require().Nil(apiErr)
|
||||||
|
s.Equal(tt.data, actual)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.Require().NotNil(apiErr)
|
||||||
|
s.Equal(tt.wantStatus, apiErr.status)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *MessengerSuite) TestImageValidationLimitsConcurrentDecodeMemory() {
|
||||||
|
data := testPNG(s.T(), 2, 2)
|
||||||
|
request := httptest.NewRequest(http.MethodPost, "/upload", bytes.NewReader(data))
|
||||||
|
request.Header.Set("Content-Type", "image/png")
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
_, _, apiErr := readImage(response, request, 1024, 4, semaphore.NewWeighted(1))
|
||||||
|
s.Require().NotNil(apiErr)
|
||||||
|
s.Equal(http.StatusTooManyRequests, apiErr.status)
|
||||||
|
s.Equal("1", response.Header().Get("Retry-After"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *MessengerSuite) TestAttachmentFilenameValidation() {
|
||||||
|
for _, filename := range []string{"", " ", "../photo.png", "dir\\photo.png", "photo\x00.png", "photo\n.png"} {
|
||||||
|
_, valid := attachmentFilename(map[string][]string{"filename": {filename}})
|
||||||
|
s.False(valid, filename)
|
||||||
|
}
|
||||||
|
filename, valid := attachmentFilename(map[string][]string{"filename": {"фото.png"}})
|
||||||
|
s.True(valid)
|
||||||
|
s.Equal("фото.png", filename)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *MessengerSuite) TestUploadCompensatesObjectWhenMetadataWriteFails() {
|
||||||
|
var putKey, deletedKey string
|
||||||
|
store := messengerStoreStub{
|
||||||
|
userByID: model.User{ID: "00000000-0000-0000-0000-000000000001"},
|
||||||
|
attachmentErr: errDependency,
|
||||||
|
}
|
||||||
|
objects := objectStoreStub{putKey: &putKey, deletedKey: &deletedKey}
|
||||||
|
server := NewServer(
|
||||||
|
s.logger, store, sessionStub{userID: store.userByID.ID}, passwordsStub{}, objects,
|
||||||
|
time.Hour, 24*time.Hour, time.Second, "test-instance", "8081", 10*1024*1024, 40_000_000, 384*1024*1024,
|
||||||
|
)
|
||||||
|
data := testPNG(s.T(), 2, 2)
|
||||||
|
request := httptest.NewRequest(
|
||||||
|
http.MethodPost,
|
||||||
|
"/api/v1/chats/00000000-0000-0000-0000-000000000002/attachments?filename=photo.png",
|
||||||
|
bytes.NewReader(data),
|
||||||
|
)
|
||||||
|
request.Header.Set("Authorization", "Bearer valid-token")
|
||||||
|
request.Header.Set("Content-Type", "image/png")
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
server.Handler().ServeHTTP(response, request)
|
||||||
|
s.Equal(http.StatusServiceUnavailable, response.Code)
|
||||||
|
s.NotEmpty(putKey)
|
||||||
|
s.Equal(putKey, deletedKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *MessengerSuite) TestUploadKeepsObjectWhenMetadataCommitSucceeded() {
|
||||||
|
var deletedKey string
|
||||||
|
stored := model.Attachment{
|
||||||
|
ID: "00000000-0000-0000-0000-000000000003",
|
||||||
|
ChatID: "00000000-0000-0000-0000-000000000002",
|
||||||
|
OwnerID: "00000000-0000-0000-0000-000000000001",
|
||||||
|
Filename: "photo.png", ContentType: "image/png", SizeBytes: 1, SHA256: strings.Repeat("0", 64),
|
||||||
|
Status: "ready", Variants: []model.Variant{}, CreatedAt: time.Now(), UpdatedAt: time.Now(),
|
||||||
|
}
|
||||||
|
store := messengerStoreStub{
|
||||||
|
userByID: model.User{ID: stored.OwnerID}, attachmentErr: errDependency,
|
||||||
|
storedAttachment: stored, storedAttachmentExists: true,
|
||||||
|
}
|
||||||
|
server := NewServer(
|
||||||
|
s.logger, store, sessionStub{userID: stored.OwnerID}, passwordsStub{}, objectStoreStub{deletedKey: &deletedKey},
|
||||||
|
time.Hour, 24*time.Hour, time.Second, "test-instance", "8081", 10*1024*1024, 40_000_000, 384*1024*1024,
|
||||||
|
)
|
||||||
|
data := testPNG(s.T(), 2, 2)
|
||||||
|
request := httptest.NewRequest(
|
||||||
|
http.MethodPost,
|
||||||
|
"/api/v1/chats/00000000-0000-0000-0000-000000000002/attachments?filename=photo.png",
|
||||||
|
bytes.NewReader(data),
|
||||||
|
)
|
||||||
|
request.Header.Set("Authorization", "Bearer valid-token")
|
||||||
|
request.Header.Set("Content-Type", "image/png")
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
server.Handler().ServeHTTP(response, request)
|
||||||
|
s.Equal(http.StatusCreated, response.Code)
|
||||||
|
s.Empty(deletedKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testPNG(t *testing.T, width, height int) []byte {
|
||||||
|
t.Helper()
|
||||||
|
var data bytes.Buffer
|
||||||
|
imageData := image.NewRGBA(image.Rect(0, 0, width, height))
|
||||||
|
imageData.Set(0, 0, color.White)
|
||||||
|
if err := png.Encode(&data, imageData); err != nil {
|
||||||
|
t.Fatalf("encode PNG: %v", err)
|
||||||
|
}
|
||||||
|
return data.Bytes()
|
||||||
|
}
|
||||||
|
|
||||||
func (s *MessengerSuite) newTestServer(messages MessengerStore, sessions SessionStore, passwords PasswordService) *Server {
|
func (s *MessengerSuite) newTestServer(messages MessengerStore, sessions SessionStore, passwords PasswordService) *Server {
|
||||||
return NewServer(s.logger, messages, sessions, passwords, time.Hour, 24*time.Hour, time.Second, "test-instance", "8081")
|
return NewServer(
|
||||||
|
s.logger, messages, sessions, passwords, objectStoreStub{}, time.Hour, 24*time.Hour,
|
||||||
|
time.Second, "test-instance", "8081", 10*1024*1024, 40_000_000, 384*1024*1024,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
func serveRequest(server *Server, method, path, body string) *httptest.ResponseRecorder {
|
func serveRequest(server *Server, method, path, body string) *httptest.ResponseRecorder {
|
||||||
|
|||||||
+68
-11
@@ -27,11 +27,37 @@ type Chat struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Message struct {
|
type Message struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
ChatID string `json:"chat_id"`
|
ChatID string `json:"chat_id"`
|
||||||
SenderID string `json:"sender_id"`
|
SenderID string `json:"sender_id"`
|
||||||
Text string `json:"text"`
|
Text string `json:"text"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
AttachmentIDs []string `json:"attachment_ids"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Attachment struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
ChatID string `json:"chat_id"`
|
||||||
|
OwnerID string `json:"owner_id"`
|
||||||
|
Filename string `json:"filename"`
|
||||||
|
ContentType string `json:"content_type"`
|
||||||
|
SizeBytes int64 `json:"size_bytes"`
|
||||||
|
SHA256 string `json:"sha256"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Variants []Variant `json:"variants"`
|
||||||
|
ErrorCode *string `json:"error_code"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
ObjectKey string `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Variant struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
ContentType string `json:"content_type"`
|
||||||
|
SizeBytes int64 `json:"size_bytes"`
|
||||||
|
SHA256 string `json:"sha256"`
|
||||||
|
Width int `json:"width"`
|
||||||
|
Height int `json:"height"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type Position struct {
|
type Position struct {
|
||||||
@@ -54,11 +80,27 @@ type chatJSON struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type messageJSON struct {
|
type messageJSON struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
ChatID string `json:"chat_id"`
|
ChatID string `json:"chat_id"`
|
||||||
SenderID string `json:"sender_id"`
|
SenderID string `json:"sender_id"`
|
||||||
Text string `json:"text"`
|
Text string `json:"text"`
|
||||||
CreatedAt string `json:"created_at"`
|
CreatedAt string `json:"created_at"`
|
||||||
|
AttachmentIDs []string `json:"attachment_ids"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type attachmentJSON 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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u User) MarshalJSON() ([]byte, error) {
|
func (u User) MarshalJSON() ([]byte, error) {
|
||||||
@@ -70,7 +112,22 @@ func (c Chat) MarshalJSON() ([]byte, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (m Message) MarshalJSON() ([]byte, error) {
|
func (m Message) MarshalJSON() ([]byte, error) {
|
||||||
return json.Marshal(messageJSON{m.ID, m.ChatID, m.SenderID, m.Text, formatTime(m.CreatedAt)})
|
attachments := m.AttachmentIDs
|
||||||
|
if attachments == nil {
|
||||||
|
attachments = []string{}
|
||||||
|
}
|
||||||
|
return json.Marshal(messageJSON{m.ID, m.ChatID, m.SenderID, m.Text, formatTime(m.CreatedAt), attachments})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a Attachment) MarshalJSON() ([]byte, error) {
|
||||||
|
variants := a.Variants
|
||||||
|
if variants == nil {
|
||||||
|
variants = []Variant{}
|
||||||
|
}
|
||||||
|
return json.Marshal(attachmentJSON{
|
||||||
|
a.ID, a.ChatID, a.OwnerID, a.Filename, a.ContentType, a.SizeBytes, a.SHA256,
|
||||||
|
a.Status, variants, a.ErrorCode, formatTime(a.CreatedAt), formatTime(a.UpdatedAt),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func FormatTime(value time.Time) string {
|
func FormatTime(value time.Time) string {
|
||||||
|
|||||||
@@ -0,0 +1,180 @@
|
|||||||
|
package objectstore
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/minio/minio-go/v7"
|
||||||
|
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||||
|
)
|
||||||
|
|
||||||
|
var ErrNotFound = errors.New("object not found")
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
Endpoint string
|
||||||
|
Region string
|
||||||
|
Bucket string
|
||||||
|
AccessKey string
|
||||||
|
SecretKey string
|
||||||
|
UseTLS bool
|
||||||
|
Timeout time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
type Object struct {
|
||||||
|
Key string
|
||||||
|
Size int64
|
||||||
|
LastModified time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
type Store struct {
|
||||||
|
client *minio.Client
|
||||||
|
bucket string
|
||||||
|
timeout time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(config Config) (*Store, error) {
|
||||||
|
endpoint, err := endpointHost(config.Endpoint, config.UseTLS)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(config.Bucket) == "" || config.Timeout <= 0 {
|
||||||
|
return nil, errors.New("invalid object store configuration")
|
||||||
|
}
|
||||||
|
client, err := minio.New(endpoint, &minio.Options{
|
||||||
|
Creds: credentials.NewStaticV4(config.AccessKey, config.SecretKey, ""),
|
||||||
|
Secure: config.UseTLS,
|
||||||
|
Region: config.Region,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("create S3 client: %w", err)
|
||||||
|
}
|
||||||
|
return &Store{client: client, bucket: config.Bucket, timeout: config.Timeout}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func endpointHost(value string, useTLS bool) (string, error) {
|
||||||
|
value = strings.TrimSpace(value)
|
||||||
|
if !strings.Contains(value, "://") {
|
||||||
|
if value == "" {
|
||||||
|
return "", errors.New("S3 endpoint is required")
|
||||||
|
}
|
||||||
|
return value, nil
|
||||||
|
}
|
||||||
|
parsed, err := url.Parse(value)
|
||||||
|
if err != nil || parsed.Host == "" || parsed.Path != "" && parsed.Path != "/" {
|
||||||
|
return "", errors.New("invalid S3 endpoint")
|
||||||
|
}
|
||||||
|
if (parsed.Scheme == "https") != useTLS || parsed.Scheme != "http" && parsed.Scheme != "https" {
|
||||||
|
return "", errors.New("S3 endpoint scheme conflicts with S3_USE_TLS")
|
||||||
|
}
|
||||||
|
return parsed.Host, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) Ping(ctx context.Context) error {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||||
|
defer cancel()
|
||||||
|
exists, err := s.client.BucketExists(ctx, s.bucket)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("check S3 bucket: %w", err)
|
||||||
|
}
|
||||||
|
if !exists {
|
||||||
|
return errors.New("S3 bucket does not exist")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) Put(ctx context.Context, key, contentType string, data []byte) error {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||||
|
defer cancel()
|
||||||
|
_, err := s.client.PutObject(
|
||||||
|
ctx, s.bucket, key, bytes.NewReader(data), int64(len(data)), minio.PutObjectOptions{ContentType: contentType},
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("put S3 object: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||||
|
object, err := s.client.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
|
||||||
|
if err != nil {
|
||||||
|
cancel()
|
||||||
|
return nil, objectError("get S3 object", err)
|
||||||
|
}
|
||||||
|
if _, err := object.Stat(); err != nil {
|
||||||
|
cancel()
|
||||||
|
_ = object.Close()
|
||||||
|
return nil, objectError("stat S3 object", err)
|
||||||
|
}
|
||||||
|
return &timeoutReader{ReadCloser: object, cancel: cancel}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) Stat(ctx context.Context, key string) (Object, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||||
|
defer cancel()
|
||||||
|
info, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{})
|
||||||
|
if err != nil {
|
||||||
|
return Object{}, objectError("stat S3 object", err)
|
||||||
|
}
|
||||||
|
return Object{Key: info.Key, Size: info.Size, LastModified: info.LastModified}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) Delete(ctx context.Context, key string) error {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||||
|
defer cancel()
|
||||||
|
if err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}); err != nil {
|
||||||
|
return objectError("delete S3 object", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) List(ctx context.Context, prefix, after string, limit int) ([]Object, string, error) {
|
||||||
|
if limit < 1 || limit > 1000 {
|
||||||
|
return nil, "", errors.New("object list limit must be between 1 and 1000")
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||||
|
defer cancel()
|
||||||
|
objects := make([]Object, 0, limit+1)
|
||||||
|
options := minio.ListObjectsOptions{Prefix: prefix, Recursive: true, StartAfter: after, MaxKeys: limit + 1}
|
||||||
|
for info := range s.client.ListObjects(ctx, s.bucket, options) {
|
||||||
|
if info.Err != nil {
|
||||||
|
return nil, "", fmt.Errorf("list S3 objects: %w", info.Err)
|
||||||
|
}
|
||||||
|
objects = append(objects, Object{Key: info.Key, Size: info.Size, LastModified: info.LastModified})
|
||||||
|
if len(objects) == limit+1 {
|
||||||
|
cancel()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var next string
|
||||||
|
if len(objects) > limit {
|
||||||
|
objects = objects[:limit]
|
||||||
|
next = objects[len(objects)-1].Key
|
||||||
|
}
|
||||||
|
return objects, next, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type timeoutReader struct {
|
||||||
|
io.ReadCloser
|
||||||
|
cancel context.CancelFunc
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *timeoutReader) Close() error {
|
||||||
|
err := r.ReadCloser.Close()
|
||||||
|
r.cancel()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func objectError(action string, err error) error {
|
||||||
|
response := minio.ToErrorResponse(err)
|
||||||
|
if response.Code == "NoSuchKey" || response.Code == "NoSuchObject" {
|
||||||
|
return ErrNotFound
|
||||||
|
}
|
||||||
|
return fmt.Errorf("%s: %w", action, err)
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
package postgres
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
|
||||||
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (s *Store) CreateAttachment(ctx context.Context, attachment model.Attachment) (model.Attachment, error) {
|
||||||
|
const query = `
|
||||||
|
INSERT INTO attachments (
|
||||||
|
id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key
|
||||||
|
)
|
||||||
|
SELECT $1, $2, $3, $4, $5, $6, $7, $8
|
||||||
|
WHERE EXISTS (
|
||||||
|
SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $3
|
||||||
|
)
|
||||||
|
RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||||
|
object_key, created_at, updated_at`
|
||||||
|
|
||||||
|
err := s.pool.QueryRow(
|
||||||
|
ctx, query, attachment.ID, attachment.ChatID, attachment.OwnerID, attachment.Filename,
|
||||||
|
attachment.ContentType, attachment.SizeBytes, attachment.SHA256, attachment.ObjectKey,
|
||||||
|
).Scan(
|
||||||
|
&attachment.ID, &attachment.ChatID, &attachment.OwnerID, &attachment.Filename,
|
||||||
|
&attachment.ContentType, &attachment.SizeBytes, &attachment.SHA256, &attachment.ObjectKey,
|
||||||
|
&attachment.CreatedAt, &attachment.UpdatedAt,
|
||||||
|
)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return model.Attachment{}, ErrNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return model.Attachment{}, fmt.Errorf("create attachment: %w", err)
|
||||||
|
}
|
||||||
|
return readyAttachment(attachment), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) AttachmentForUser(ctx context.Context, attachmentID, userID string) (model.Attachment, error) {
|
||||||
|
const query = `
|
||||||
|
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes,
|
||||||
|
a.sha256, a.object_key, a.created_at, a.updated_at
|
||||||
|
FROM attachments a
|
||||||
|
JOIN chat_members member ON member.chat_id = a.chat_id AND member.user_id = $2
|
||||||
|
WHERE a.id = $1`
|
||||||
|
|
||||||
|
var attachment model.Attachment
|
||||||
|
err := s.pool.QueryRow(ctx, query, attachmentID, userID).Scan(
|
||||||
|
&attachment.ID, &attachment.ChatID, &attachment.OwnerID, &attachment.Filename,
|
||||||
|
&attachment.ContentType, &attachment.SizeBytes, &attachment.SHA256, &attachment.ObjectKey,
|
||||||
|
&attachment.CreatedAt, &attachment.UpdatedAt,
|
||||||
|
)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return model.Attachment{}, ErrNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return model.Attachment{}, fmt.Errorf("get attachment for user: %w", err)
|
||||||
|
}
|
||||||
|
return readyAttachment(attachment), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) AttachmentByStorage(ctx context.Context, attachmentID, objectKey string) (model.Attachment, error) {
|
||||||
|
const query = `
|
||||||
|
SELECT id, chat_id, owner_id, filename, content_type, size_bytes,
|
||||||
|
sha256, object_key, created_at, updated_at
|
||||||
|
FROM attachments
|
||||||
|
WHERE id = $1 AND object_key = $2`
|
||||||
|
|
||||||
|
var attachment model.Attachment
|
||||||
|
err := s.pool.QueryRow(ctx, query, attachmentID, objectKey).Scan(
|
||||||
|
&attachment.ID, &attachment.ChatID, &attachment.OwnerID, &attachment.Filename,
|
||||||
|
&attachment.ContentType, &attachment.SizeBytes, &attachment.SHA256, &attachment.ObjectKey,
|
||||||
|
&attachment.CreatedAt, &attachment.UpdatedAt,
|
||||||
|
)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return model.Attachment{}, ErrNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return model.Attachment{}, fmt.Errorf("get attachment by storage: %w", err)
|
||||||
|
}
|
||||||
|
return readyAttachment(attachment), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) ListAttachments(ctx context.Context, afterObjectKey string, limit int) ([]model.Attachment, string, error) {
|
||||||
|
if limit < 1 || limit > 1000 {
|
||||||
|
return nil, "", fmt.Errorf("attachment list limit must be between 1 and 1000")
|
||||||
|
}
|
||||||
|
const query = `
|
||||||
|
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||||
|
object_key, created_at, updated_at
|
||||||
|
FROM attachments
|
||||||
|
WHERE object_key > $1
|
||||||
|
ORDER BY object_key
|
||||||
|
LIMIT $2`
|
||||||
|
rows, err := s.pool.Query(ctx, query, afterObjectKey, limit+1)
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", fmt.Errorf("list attachments: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
attachments, err := pgx.CollectRows(rows, pgx.RowToFunc[model.Attachment](func(row pgx.CollectableRow) (model.Attachment, error) {
|
||||||
|
var attachment model.Attachment
|
||||||
|
err := row.Scan(
|
||||||
|
&attachment.ID, &attachment.ChatID, &attachment.OwnerID, &attachment.Filename,
|
||||||
|
&attachment.ContentType, &attachment.SizeBytes, &attachment.SHA256, &attachment.ObjectKey,
|
||||||
|
&attachment.CreatedAt, &attachment.UpdatedAt,
|
||||||
|
)
|
||||||
|
return readyAttachment(attachment), err
|
||||||
|
}))
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", fmt.Errorf("scan attachments: %w", err)
|
||||||
|
}
|
||||||
|
var next string
|
||||||
|
if len(attachments) > limit {
|
||||||
|
attachments = attachments[:limit]
|
||||||
|
next = attachments[len(attachments)-1].ObjectKey
|
||||||
|
}
|
||||||
|
return attachments, next, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) AttachmentReferenced(ctx context.Context, attachmentID string) (bool, error) {
|
||||||
|
const query = `SELECT EXISTS (SELECT 1 FROM message_attachments WHERE attachment_id = $1)`
|
||||||
|
var referenced bool
|
||||||
|
if err := s.pool.QueryRow(ctx, query, attachmentID).Scan(&referenced); err != nil {
|
||||||
|
return false, fmt.Errorf("check attachment references: %w", err)
|
||||||
|
}
|
||||||
|
return referenced, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) DeleteAttachmentIfUnreferencedBefore(
|
||||||
|
ctx context.Context,
|
||||||
|
attachmentID string,
|
||||||
|
createdBefore time.Time,
|
||||||
|
) (bool, error) {
|
||||||
|
const query = `
|
||||||
|
DELETE FROM attachments a
|
||||||
|
WHERE a.id = $1
|
||||||
|
AND a.created_at <= $2
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id)`
|
||||||
|
result, err := s.pool.Exec(ctx, query, attachmentID, createdBefore)
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("delete old unreferenced attachment: %w", err)
|
||||||
|
}
|
||||||
|
return result.RowsAffected() == 1, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func readyAttachment(attachment model.Attachment) model.Attachment {
|
||||||
|
attachment.Status = "ready"
|
||||||
|
attachment.Variants = []model.Variant{}
|
||||||
|
return attachment
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"time"
|
"time"
|
||||||
@@ -21,9 +22,13 @@ func (s *Store) CreateMessage(
|
|||||||
chatID string,
|
chatID string,
|
||||||
senderID string,
|
senderID string,
|
||||||
text string,
|
text string,
|
||||||
|
attachmentIDs []string,
|
||||||
idempotencyKey string,
|
idempotencyKey string,
|
||||||
idempotencyTTL time.Duration,
|
idempotencyTTL time.Duration,
|
||||||
) (model.Message, bool, error) {
|
) (model.Message, bool, error) {
|
||||||
|
if attachmentIDs == nil {
|
||||||
|
attachmentIDs = []string{}
|
||||||
|
}
|
||||||
var (
|
var (
|
||||||
tx pgx.Tx
|
tx pgx.Tx
|
||||||
err error
|
err error
|
||||||
@@ -46,13 +51,23 @@ func (s *Store) CreateMessage(
|
|||||||
if !visible {
|
if !visible {
|
||||||
return model.Message{}, false, ErrNotFound
|
return model.Message{}, false, ErrNotFound
|
||||||
}
|
}
|
||||||
|
validAttachments, err := attachmentsBelongToChat(ctx, tx, chatID, attachmentIDs)
|
||||||
|
if err != nil {
|
||||||
|
return model.Message{}, false, err
|
||||||
|
}
|
||||||
|
if !validAttachments {
|
||||||
|
return model.Message{}, false, ErrNotFound
|
||||||
|
}
|
||||||
if err = deleteExpiredIdempotencyRecords(ctx, tx, expiredIdempotencyCleanupBatch); err != nil {
|
if err = deleteExpiredIdempotencyRecords(ctx, tx, expiredIdempotencyCleanupBatch); err != nil {
|
||||||
return model.Message{}, false, err
|
return model.Message{}, false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
requestHash = sha256.Sum256([]byte(text))
|
requestHash, err = messageRequestHash(text, attachmentIDs)
|
||||||
|
if err != nil {
|
||||||
|
return model.Message{}, false, err
|
||||||
|
}
|
||||||
message, replay, err = createIdempotentMessage(
|
message, replay, err = createIdempotentMessage(
|
||||||
ctx, tx, chatID, senderID, text, idempotencyKey, requestHash[:], idempotencyTTL,
|
ctx, tx, chatID, senderID, text, attachmentIDs, idempotencyKey, requestHash[:], idempotencyTTL,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return model.Message{}, false, err
|
return model.Message{}, false, err
|
||||||
@@ -63,6 +78,35 @@ func (s *Store) CreateMessage(
|
|||||||
return message, replay, nil
|
return message, replay, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func messageRequestHash(text string, attachmentIDs []string) ([sha256.Size]byte, error) {
|
||||||
|
if attachmentIDs == nil {
|
||||||
|
attachmentIDs = []string{}
|
||||||
|
}
|
||||||
|
payload, err := json.Marshal(struct {
|
||||||
|
Text string `json:"text"`
|
||||||
|
AttachmentIDs []string `json:"attachment_ids"`
|
||||||
|
}{text, attachmentIDs})
|
||||||
|
if err != nil {
|
||||||
|
return [sha256.Size]byte{}, fmt.Errorf("marshal message request: %w", err)
|
||||||
|
}
|
||||||
|
return sha256.Sum256(payload), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func attachmentsBelongToChat(ctx context.Context, tx pgx.Tx, chatID string, attachmentIDs []string) (bool, error) {
|
||||||
|
if len(attachmentIDs) == 0 {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
const query = `
|
||||||
|
SELECT count(*)
|
||||||
|
FROM attachments
|
||||||
|
WHERE chat_id = $1 AND id::text = ANY($2)`
|
||||||
|
var count int
|
||||||
|
if err := tx.QueryRow(ctx, query, chatID, attachmentIDs).Scan(&count); err != nil {
|
||||||
|
return false, fmt.Errorf("validate message attachments: %w", err)
|
||||||
|
}
|
||||||
|
return count == len(attachmentIDs), nil
|
||||||
|
}
|
||||||
|
|
||||||
func chatVisibleInTransaction(ctx context.Context, tx pgx.Tx, chatID, userID string) (bool, error) {
|
func chatVisibleInTransaction(ctx context.Context, tx pgx.Tx, chatID, userID string) (bool, error) {
|
||||||
const query = `
|
const query = `
|
||||||
SELECT EXISTS (
|
SELECT EXISTS (
|
||||||
@@ -84,6 +128,7 @@ func createIdempotentMessage(
|
|||||||
chatID string,
|
chatID string,
|
||||||
senderID string,
|
senderID string,
|
||||||
text string,
|
text string,
|
||||||
|
attachmentIDs []string,
|
||||||
idempotencyKey string,
|
idempotencyKey string,
|
||||||
requestHash []byte,
|
requestHash []byte,
|
||||||
idempotencyTTL time.Duration,
|
idempotencyTTL time.Duration,
|
||||||
@@ -126,7 +171,7 @@ func createIdempotentMessage(
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
message, err = insertMessage(ctx, tx, messageID, chatID, senderID, text)
|
message, err = insertMessage(ctx, tx, messageID, chatID, senderID, text, attachmentIDs)
|
||||||
return message, false, err
|
return message, false, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -235,6 +280,7 @@ func insertMessage(
|
|||||||
chatID string,
|
chatID string,
|
||||||
senderID string,
|
senderID string,
|
||||||
text string,
|
text string,
|
||||||
|
attachmentIDs []string,
|
||||||
) (model.Message, error) {
|
) (model.Message, error) {
|
||||||
const query = `
|
const query = `
|
||||||
INSERT INTO messages (id, chat_id, sender_id, text)
|
INSERT INTO messages (id, chat_id, sender_id, text)
|
||||||
@@ -255,14 +301,37 @@ func insertMessage(
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return model.Message{}, fmt.Errorf("insert message: %w", err)
|
return model.Message{}, fmt.Errorf("insert message: %w", err)
|
||||||
}
|
}
|
||||||
|
if err := insertMessageAttachments(ctx, tx, messageID, chatID, attachmentIDs); err != nil {
|
||||||
|
return model.Message{}, err
|
||||||
|
}
|
||||||
|
message.AttachmentIDs = make([]string, len(attachmentIDs))
|
||||||
|
copy(message.AttachmentIDs, attachmentIDs)
|
||||||
return message, nil
|
return message, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func insertMessageAttachments(ctx context.Context, tx pgx.Tx, messageID, chatID string, attachmentIDs []string) error {
|
||||||
|
const query = `
|
||||||
|
INSERT INTO message_attachments (message_id, chat_id, attachment_id, position)
|
||||||
|
VALUES ($1, $2, $3, $4)`
|
||||||
|
for position, attachmentID := range attachmentIDs {
|
||||||
|
if _, err := tx.Exec(ctx, query, messageID, chatID, attachmentID, position); err != nil {
|
||||||
|
return fmt.Errorf("insert message attachment: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func messageByID(ctx context.Context, tx pgx.Tx, messageID string) (model.Message, error) {
|
func messageByID(ctx context.Context, tx pgx.Tx, messageID string) (model.Message, error) {
|
||||||
const query = `
|
const query = `
|
||||||
SELECT id, chat_id, sender_id, text, created_at
|
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||||
FROM messages
|
ARRAY(
|
||||||
WHERE id = $1`
|
SELECT ma.attachment_id::text
|
||||||
|
FROM message_attachments ma
|
||||||
|
WHERE ma.message_id = m.id
|
||||||
|
ORDER BY ma.position
|
||||||
|
)
|
||||||
|
FROM messages m
|
||||||
|
WHERE m.id = $1`
|
||||||
|
|
||||||
var (
|
var (
|
||||||
message model.Message
|
message model.Message
|
||||||
@@ -274,6 +343,7 @@ func messageByID(ctx context.Context, tx pgx.Tx, messageID string) (model.Messag
|
|||||||
&message.SenderID,
|
&message.SenderID,
|
||||||
&message.Text,
|
&message.Text,
|
||||||
&message.CreatedAt,
|
&message.CreatedAt,
|
||||||
|
&message.AttachmentIDs,
|
||||||
)
|
)
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
return model.Message{}, fmt.Errorf("idempotency result message not found")
|
return model.Message{}, fmt.Errorf("idempotency result message not found")
|
||||||
|
|||||||
@@ -344,11 +344,17 @@ func (s *Store) ListMessages(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const query = `
|
const query = `
|
||||||
SELECT id, chat_id, sender_id, text, created_at
|
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||||
FROM messages
|
ARRAY(
|
||||||
WHERE chat_id = $1
|
SELECT ma.attachment_id::text
|
||||||
AND ($2::timestamptz IS NULL OR (created_at, id) > ($2, $3::uuid))
|
FROM message_attachments ma
|
||||||
ORDER BY created_at, id
|
WHERE ma.message_id = m.id
|
||||||
|
ORDER BY ma.position
|
||||||
|
)
|
||||||
|
FROM messages m
|
||||||
|
WHERE m.chat_id = $1
|
||||||
|
AND ($2::timestamptz IS NULL OR (m.created_at, m.id) > ($2, $3::uuid))
|
||||||
|
ORDER BY m.created_at, m.id
|
||||||
LIMIT $4`
|
LIMIT $4`
|
||||||
|
|
||||||
var afterTime any
|
var afterTime any
|
||||||
@@ -372,6 +378,7 @@ func (s *Store) ListMessages(
|
|||||||
&message.SenderID,
|
&message.SenderID,
|
||||||
&message.Text,
|
&message.Text,
|
||||||
&message.CreatedAt,
|
&message.CreatedAt,
|
||||||
|
&message.AttachmentIDs,
|
||||||
)
|
)
|
||||||
return message, err
|
return message, err
|
||||||
}))
|
}))
|
||||||
|
|||||||
@@ -100,18 +100,16 @@ func (s *PostgresSuite) TestMessageIdempotencyReplayAndConflict() {
|
|||||||
owner, chatID := createOwnerAndChat(t, store)
|
owner, chatID := createOwnerAndChat(t, store)
|
||||||
key := uuid.NewString()
|
key := uuid.NewString()
|
||||||
|
|
||||||
first, replay, err := store.CreateMessage(context.Background(), chatID, owner.ID, "same body", key, 24*time.Hour)
|
first, replay, err := store.CreateMessage(context.Background(), chatID, owner.ID, "same body", nil, key, 24*time.Hour)
|
||||||
if err != nil || replay {
|
if err != nil || replay {
|
||||||
t.Fatalf("first CreateMessage() = (%v, %t, %v)", first, replay, err)
|
t.Fatalf("first CreateMessage() = (%v, %t, %v)", first, replay, err)
|
||||||
}
|
}
|
||||||
second, replay, err := store.CreateMessage(context.Background(), chatID, owner.ID, "same body", key, 24*time.Hour)
|
second, replay, err := store.CreateMessage(context.Background(), chatID, owner.ID, "same body", []string{}, key, 24*time.Hour)
|
||||||
if err != nil || !replay {
|
if err != nil || !replay {
|
||||||
t.Fatalf("replay CreateMessage() = (%v, %t, %v)", second, replay, err)
|
t.Fatalf("replay CreateMessage() = (%v, %t, %v)", second, replay, err)
|
||||||
}
|
}
|
||||||
if first != second {
|
s.Equal(first, second)
|
||||||
t.Fatalf("replay message = %v, want %v", second, first)
|
if _, _, err := store.CreateMessage(context.Background(), chatID, owner.ID, "different body", nil, key, 24*time.Hour); !errors.Is(err, postgres.ErrIdempotencyConflict) {
|
||||||
}
|
|
||||||
if _, _, err := store.CreateMessage(context.Background(), chatID, owner.ID, "different body", key, 24*time.Hour); !errors.Is(err, postgres.ErrIdempotencyConflict) {
|
|
||||||
t.Fatalf("conflicting CreateMessage() error = %v, want ErrIdempotencyConflict", err)
|
t.Fatalf("conflicting CreateMessage() error = %v, want ErrIdempotencyConflict", err)
|
||||||
}
|
}
|
||||||
if count := messageCount(t, pool, chatID); count != 1 {
|
if count := messageCount(t, pool, chatID); count != 1 {
|
||||||
@@ -119,6 +117,62 @@ func (s *PostgresSuite) TestMessageIdempotencyReplayAndConflict() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *PostgresSuite) TestAttachmentAccessAndMessageLinking() {
|
||||||
|
owner, chatID := createOwnerAndChat(s.T(), s.store)
|
||||||
|
outsider, err := s.store.CreateUser(context.Background(), uniqueUsername(), "Outsider", "password-hash")
|
||||||
|
s.Require().NoError(err)
|
||||||
|
attachment := model.Attachment{
|
||||||
|
ID: uuid.NewString(), ChatID: chatID, OwnerID: owner.ID, Filename: "photo.png",
|
||||||
|
ContentType: "image/png", SizeBytes: 128, SHA256: strings.Repeat("a", 64),
|
||||||
|
ObjectKey: "attachments/" + uuid.NewString() + "/original",
|
||||||
|
}
|
||||||
|
created, err := s.store.CreateAttachment(context.Background(), attachment)
|
||||||
|
s.Require().NoError(err)
|
||||||
|
s.Equal("ready", created.Status)
|
||||||
|
s.Empty(created.Variants)
|
||||||
|
s.Nil(created.ErrorCode)
|
||||||
|
|
||||||
|
visible, err := s.store.AttachmentForUser(context.Background(), created.ID, owner.ID)
|
||||||
|
s.Require().NoError(err)
|
||||||
|
s.Equal(created, visible)
|
||||||
|
_, err = s.store.AttachmentForUser(context.Background(), created.ID, outsider.ID)
|
||||||
|
s.ErrorIs(err, postgres.ErrNotFound)
|
||||||
|
|
||||||
|
message, replay, err := s.store.CreateMessage(
|
||||||
|
context.Background(), chatID, owner.ID, "", []string{created.ID}, uuid.NewString(), 24*time.Hour,
|
||||||
|
)
|
||||||
|
s.Require().NoError(err)
|
||||||
|
s.False(replay)
|
||||||
|
s.Equal([]string{created.ID}, message.AttachmentIDs)
|
||||||
|
|
||||||
|
messages, _, err := s.store.ListMessages(context.Background(), chatID, owner.ID, nil, 10)
|
||||||
|
s.Require().NoError(err)
|
||||||
|
s.Len(messages, 1)
|
||||||
|
s.Equal([]string{created.ID}, messages[0].AttachmentIDs)
|
||||||
|
referenced, err := s.store.AttachmentReferenced(context.Background(), created.ID)
|
||||||
|
s.Require().NoError(err)
|
||||||
|
s.True(referenced)
|
||||||
|
deleted, err := s.store.DeleteAttachmentIfUnreferencedBefore(context.Background(), created.ID, time.Now().Add(time.Hour))
|
||||||
|
s.Require().NoError(err)
|
||||||
|
s.False(deleted)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PostgresSuite) TestMessageRejectsAttachmentFromAnotherChat() {
|
||||||
|
owner, firstChatID := createOwnerAndChat(s.T(), s.store)
|
||||||
|
secondChat, err := s.store.CreateChat(context.Background(), "Second", []string{owner.ID}, owner.ID)
|
||||||
|
s.Require().NoError(err)
|
||||||
|
attachment, err := s.store.CreateAttachment(context.Background(), model.Attachment{
|
||||||
|
ID: uuid.NewString(), ChatID: firstChatID, OwnerID: owner.ID, Filename: "photo.png",
|
||||||
|
ContentType: "image/png", SizeBytes: 128, SHA256: strings.Repeat("b", 64),
|
||||||
|
ObjectKey: "attachments/" + uuid.NewString() + "/original",
|
||||||
|
})
|
||||||
|
s.Require().NoError(err)
|
||||||
|
_, _, err = s.store.CreateMessage(
|
||||||
|
context.Background(), secondChat.ID, owner.ID, "wrong chat", []string{attachment.ID}, uuid.NewString(), 24*time.Hour,
|
||||||
|
)
|
||||||
|
s.ErrorIs(err, postgres.ErrNotFound)
|
||||||
|
}
|
||||||
|
|
||||||
func (s *PostgresSuite) TestConcurrentMessageIdempotency() {
|
func (s *PostgresSuite) TestConcurrentMessageIdempotency() {
|
||||||
t := s.T()
|
t := s.T()
|
||||||
pool := s.pool
|
pool := s.pool
|
||||||
@@ -139,7 +193,7 @@ func (s *PostgresSuite) TestConcurrentMessageIdempotency() {
|
|||||||
go func() {
|
go func() {
|
||||||
defer group.Done()
|
defer group.Done()
|
||||||
message, replay, err := stores[worker%len(stores)].CreateMessage(
|
message, replay, err := stores[worker%len(stores)].CreateMessage(
|
||||||
context.Background(), chatID, owner.ID, "concurrent body", key, 24*time.Hour,
|
context.Background(), chatID, owner.ID, "concurrent body", nil, key, 24*time.Hour,
|
||||||
)
|
)
|
||||||
results <- result{message: message, replay: replay, err: err}
|
results <- result{message: message, replay: replay, err: err}
|
||||||
}()
|
}()
|
||||||
@@ -186,13 +240,13 @@ func (s *PostgresSuite) TestMessageIdempotencyScopeAndExpiry() {
|
|||||||
}
|
}
|
||||||
key := uuid.NewString()
|
key := uuid.NewString()
|
||||||
|
|
||||||
if _, _, err := store.CreateMessage(context.Background(), chat.ID, owner.ID, "owner", key, 24*time.Hour); err != nil {
|
if _, _, err := store.CreateMessage(context.Background(), chat.ID, owner.ID, "owner", nil, key, 24*time.Hour); err != nil {
|
||||||
t.Fatalf("owner CreateMessage() error = %v", err)
|
t.Fatalf("owner CreateMessage() error = %v", err)
|
||||||
}
|
}
|
||||||
if _, _, err := store.CreateMessage(context.Background(), chat.ID, second.ID, "second", key, 24*time.Hour); err != nil {
|
if _, _, err := store.CreateMessage(context.Background(), chat.ID, second.ID, "second", nil, key, 24*time.Hour); err != nil {
|
||||||
t.Fatalf("second user CreateMessage() error = %v", err)
|
t.Fatalf("second user CreateMessage() error = %v", err)
|
||||||
}
|
}
|
||||||
if _, _, err := store.CreateMessage(context.Background(), chatID, owner.ID, "other chat", key, 24*time.Hour); err != nil {
|
if _, _, err := store.CreateMessage(context.Background(), chatID, owner.ID, "other chat", nil, key, 24*time.Hour); err != nil {
|
||||||
t.Fatalf("other chat CreateMessage() error = %v", err)
|
t.Fatalf("other chat CreateMessage() error = %v", err)
|
||||||
}
|
}
|
||||||
if _, err := pool.Exec(context.Background(), `
|
if _, err := pool.Exec(context.Background(), `
|
||||||
@@ -202,7 +256,7 @@ func (s *PostgresSuite) TestMessageIdempotencyScopeAndExpiry() {
|
|||||||
WHERE user_id = $1 AND chat_id = $2 AND key = $3`, owner.ID, chat.ID, key); err != nil {
|
WHERE user_id = $1 AND chat_id = $2 AND key = $3`, owner.ID, chat.ID, key); err != nil {
|
||||||
t.Fatalf("expire idempotency key: %v", err)
|
t.Fatalf("expire idempotency key: %v", err)
|
||||||
}
|
}
|
||||||
message, replay, err := store.CreateMessage(context.Background(), chat.ID, owner.ID, "after expiry", key, 24*time.Hour)
|
message, replay, err := store.CreateMessage(context.Background(), chat.ID, owner.ID, "after expiry", nil, key, 24*time.Hour)
|
||||||
if err != nil || replay || message.Text != "after expiry" {
|
if err != nil || replay || message.Text != "after expiry" {
|
||||||
t.Fatalf("expired CreateMessage() = (%v, %t, %v)", message, replay, err)
|
t.Fatalf("expired CreateMessage() = (%v, %t, %v)", message, replay, err)
|
||||||
}
|
}
|
||||||
@@ -212,7 +266,7 @@ func (s *PostgresSuite) TestExpiredIdempotencyRecordsAreCleanedOnNewMessages() {
|
|||||||
t := s.T()
|
t := s.T()
|
||||||
owner, chatID := createOwnerAndChat(t, s.store)
|
owner, chatID := createOwnerAndChat(t, s.store)
|
||||||
expiredKey := uuid.NewString()
|
expiredKey := uuid.NewString()
|
||||||
if _, _, err := s.store.CreateMessage(context.Background(), chatID, owner.ID, "expired", expiredKey, 24*time.Hour); err != nil {
|
if _, _, err := s.store.CreateMessage(context.Background(), chatID, owner.ID, "expired", nil, expiredKey, 24*time.Hour); err != nil {
|
||||||
t.Fatalf("create expired message: %v", err)
|
t.Fatalf("create expired message: %v", err)
|
||||||
}
|
}
|
||||||
if _, err := s.pool.Exec(context.Background(), `
|
if _, err := s.pool.Exec(context.Background(), `
|
||||||
@@ -223,7 +277,7 @@ func (s *PostgresSuite) TestExpiredIdempotencyRecordsAreCleanedOnNewMessages() {
|
|||||||
t.Fatalf("expire idempotency key: %v", err)
|
t.Fatalf("expire idempotency key: %v", err)
|
||||||
}
|
}
|
||||||
if _, _, err := s.store.CreateMessage(
|
if _, _, err := s.store.CreateMessage(
|
||||||
context.Background(), chatID, owner.ID, "new message", uuid.NewString(), 24*time.Hour,
|
context.Background(), chatID, owner.ID, "new message", nil, uuid.NewString(), 24*time.Hour,
|
||||||
); err != nil {
|
); err != nil {
|
||||||
t.Fatalf("create new message: %v", err)
|
t.Fatalf("create new message: %v", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,236 @@
|
|||||||
|
package reconcile
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
|
||||||
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/objectstore"
|
||||||
|
)
|
||||||
|
|
||||||
|
type MetadataStore interface {
|
||||||
|
ListAttachments(context.Context, string, int) ([]model.Attachment, string, error)
|
||||||
|
AttachmentReferenced(context.Context, string) (bool, error)
|
||||||
|
DeleteAttachmentIfUnreferencedBefore(context.Context, string, time.Time) (bool, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type ObjectStore interface {
|
||||||
|
List(context.Context, string, string, int) ([]objectstore.Object, string, error)
|
||||||
|
Delete(context.Context, string) error
|
||||||
|
}
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
Prefix string
|
||||||
|
PageSize int
|
||||||
|
GraceTime time.Duration
|
||||||
|
Apply bool
|
||||||
|
Now func() time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
type Report struct {
|
||||||
|
MetadataScanned int `json:"metadata_scanned"`
|
||||||
|
ObjectsScanned int `json:"objects_scanned"`
|
||||||
|
Consistent int `json:"consistent"`
|
||||||
|
FreshOrphanObjects int `json:"fresh_orphan_objects"`
|
||||||
|
OldOrphanObjects int `json:"old_orphan_objects"`
|
||||||
|
DeletedOrphanObjects int `json:"deleted_orphan_objects"`
|
||||||
|
FreshMissingObjects int `json:"fresh_missing_objects"`
|
||||||
|
ReferencedMissingObjects int `json:"referenced_missing_objects"`
|
||||||
|
OldUnreferencedMetadata int `json:"old_unreferenced_metadata"`
|
||||||
|
DeletedUnreferencedRows int `json:"deleted_unreferenced_rows"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Reconciler struct {
|
||||||
|
metadata MetadataStore
|
||||||
|
objects ObjectStore
|
||||||
|
config Config
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(metadata MetadataStore, objects ObjectStore, config Config) (*Reconciler, error) {
|
||||||
|
if config.PageSize < 1 || config.PageSize > 1000 {
|
||||||
|
return nil, fmt.Errorf("page size must be between 1 and 1000")
|
||||||
|
}
|
||||||
|
if config.GraceTime < 0 {
|
||||||
|
return nil, fmt.Errorf("grace time must not be negative")
|
||||||
|
}
|
||||||
|
if config.Now == nil {
|
||||||
|
config.Now = time.Now
|
||||||
|
}
|
||||||
|
return &Reconciler{metadata: metadata, objects: objects, config: config}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Reconciler) Run(ctx context.Context) (Report, error) {
|
||||||
|
metadata, err := newMetadataIterator(ctx, r.metadata, r.config.PageSize)
|
||||||
|
if err != nil {
|
||||||
|
return Report{}, err
|
||||||
|
}
|
||||||
|
objects, err := newObjectIterator(ctx, r.objects, r.config.Prefix, r.config.PageSize)
|
||||||
|
if err != nil {
|
||||||
|
return Report{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
cutoff := r.config.Now().Add(-r.config.GraceTime)
|
||||||
|
var report Report
|
||||||
|
for metadata.current != nil || objects.current != nil {
|
||||||
|
switch {
|
||||||
|
case metadata.current == nil || objects.current != nil && objects.current.Key < metadata.current.ObjectKey:
|
||||||
|
if err := r.handleOrphanObject(ctx, *objects.current, cutoff, &report); err != nil {
|
||||||
|
return report, err
|
||||||
|
}
|
||||||
|
if err := objects.advance(ctx); err != nil {
|
||||||
|
return report, err
|
||||||
|
}
|
||||||
|
case objects.current == nil || metadata.current.ObjectKey < objects.current.Key:
|
||||||
|
if err := r.handleMissingObject(ctx, *metadata.current, cutoff, &report); err != nil {
|
||||||
|
return report, err
|
||||||
|
}
|
||||||
|
if err := metadata.advance(ctx); err != nil {
|
||||||
|
return report, err
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
report.MetadataScanned++
|
||||||
|
report.ObjectsScanned++
|
||||||
|
report.Consistent++
|
||||||
|
if err := metadata.advance(ctx); err != nil {
|
||||||
|
return report, err
|
||||||
|
}
|
||||||
|
if err := objects.advance(ctx); err != nil {
|
||||||
|
return report, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return report, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Reconciler) handleOrphanObject(ctx context.Context, object objectstore.Object, cutoff time.Time, report *Report) error {
|
||||||
|
report.ObjectsScanned++
|
||||||
|
if object.LastModified.After(cutoff) {
|
||||||
|
report.FreshOrphanObjects++
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
report.OldOrphanObjects++
|
||||||
|
if !r.config.Apply {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err := r.objects.Delete(ctx, object.Key); err != nil {
|
||||||
|
return fmt.Errorf("delete orphan object %q: %w", object.Key, err)
|
||||||
|
}
|
||||||
|
report.DeletedOrphanObjects++
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Reconciler) handleMissingObject(ctx context.Context, metadata model.Attachment, cutoff time.Time, report *Report) error {
|
||||||
|
report.MetadataScanned++
|
||||||
|
if metadata.CreatedAt.After(cutoff) {
|
||||||
|
report.FreshMissingObjects++
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
referenced, err := r.metadata.AttachmentReferenced(ctx, metadata.ID)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("check attachment metadata %q: %w", metadata.ID, err)
|
||||||
|
}
|
||||||
|
if referenced {
|
||||||
|
report.ReferencedMissingObjects++
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
report.OldUnreferencedMetadata++
|
||||||
|
if !r.config.Apply {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
deleted, err := r.metadata.DeleteAttachmentIfUnreferencedBefore(ctx, metadata.ID, cutoff)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("delete attachment metadata %q: %w", metadata.ID, err)
|
||||||
|
}
|
||||||
|
if deleted {
|
||||||
|
report.DeletedUnreferencedRows++
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type metadataIterator struct {
|
||||||
|
store MetadataStore
|
||||||
|
pageSize int
|
||||||
|
after string
|
||||||
|
page []model.Attachment
|
||||||
|
index int
|
||||||
|
current *model.Attachment
|
||||||
|
done bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func newMetadataIterator(ctx context.Context, store MetadataStore, pageSize int) (*metadataIterator, error) {
|
||||||
|
iterator := &metadataIterator{store: store, pageSize: pageSize}
|
||||||
|
if err := iterator.advance(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return iterator, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *metadataIterator) advance(ctx context.Context) error {
|
||||||
|
for {
|
||||||
|
if i.index < len(i.page) {
|
||||||
|
i.current = &i.page[i.index]
|
||||||
|
i.index++
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if i.done {
|
||||||
|
i.current = nil
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
page, next, err := i.store.ListAttachments(ctx, i.after, i.pageSize)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("list attachment metadata: %w", err)
|
||||||
|
}
|
||||||
|
i.page = page
|
||||||
|
i.index = 0
|
||||||
|
i.after = next
|
||||||
|
i.done = next == ""
|
||||||
|
if len(page) == 0 && !i.done {
|
||||||
|
return fmt.Errorf("metadata page is empty but has continuation")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type objectIterator struct {
|
||||||
|
store ObjectStore
|
||||||
|
prefix string
|
||||||
|
pageSize int
|
||||||
|
after string
|
||||||
|
page []objectstore.Object
|
||||||
|
index int
|
||||||
|
current *objectstore.Object
|
||||||
|
done bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func newObjectIterator(ctx context.Context, store ObjectStore, prefix string, pageSize int) (*objectIterator, error) {
|
||||||
|
iterator := &objectIterator{store: store, prefix: prefix, pageSize: pageSize}
|
||||||
|
if err := iterator.advance(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return iterator, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *objectIterator) advance(ctx context.Context) error {
|
||||||
|
for {
|
||||||
|
if i.index < len(i.page) {
|
||||||
|
i.current = &i.page[i.index]
|
||||||
|
i.index++
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if i.done {
|
||||||
|
i.current = nil
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
page, next, err := i.store.List(ctx, i.prefix, i.after, i.pageSize)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("list objects: %w", err)
|
||||||
|
}
|
||||||
|
i.page = page
|
||||||
|
i.index = 0
|
||||||
|
i.after = next
|
||||||
|
i.done = next == ""
|
||||||
|
if len(page) == 0 && !i.done {
|
||||||
|
return fmt.Errorf("object page is empty but has continuation")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
package reconcile
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"sort"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
|
||||||
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
|
||||||
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/objectstore"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestReconcilerDryRunAndApply(t *testing.T) {
|
||||||
|
now := time.Date(2026, 10, 2, 12, 0, 0, 0, time.UTC)
|
||||||
|
metadata := &metadataStub{items: []model.Attachment{
|
||||||
|
{ID: "consistent", ObjectKey: "attachments/consistent", CreatedAt: now.Add(-time.Hour)},
|
||||||
|
{ID: "fresh-missing", ObjectKey: "attachments/fresh-missing", CreatedAt: now.Add(-time.Minute)},
|
||||||
|
{ID: "old-missing", ObjectKey: "attachments/old-missing", CreatedAt: now.Add(-time.Hour)},
|
||||||
|
{ID: "referenced-missing", ObjectKey: "attachments/referenced-missing", CreatedAt: now.Add(-time.Hour)},
|
||||||
|
}, referenced: map[string]bool{"referenced-missing": true}}
|
||||||
|
objects := &objectStub{items: []objectstore.Object{
|
||||||
|
{Key: "attachments/consistent", LastModified: now.Add(-time.Hour)},
|
||||||
|
{Key: "attachments/fresh-orphan", LastModified: now.Add(-time.Minute)},
|
||||||
|
{Key: "attachments/old-orphan", LastModified: now.Add(-time.Hour)},
|
||||||
|
}}
|
||||||
|
|
||||||
|
dryRun, err := New(metadata, objects, Config{
|
||||||
|
Prefix: "attachments/", PageSize: 2, GraceTime: 10 * time.Minute, Now: func() time.Time { return now },
|
||||||
|
})
|
||||||
|
require.NoError(t, err)
|
||||||
|
report, err := dryRun.Run(context.Background())
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, Report{
|
||||||
|
MetadataScanned: 4, ObjectsScanned: 3, Consistent: 1,
|
||||||
|
FreshOrphanObjects: 1, OldOrphanObjects: 1, FreshMissingObjects: 1,
|
||||||
|
ReferencedMissingObjects: 1, OldUnreferencedMetadata: 1,
|
||||||
|
}, report)
|
||||||
|
require.Empty(t, metadata.deleted)
|
||||||
|
require.Empty(t, objects.deleted)
|
||||||
|
|
||||||
|
apply, err := New(metadata, objects, Config{
|
||||||
|
Prefix: "attachments/", PageSize: 2, GraceTime: 10 * time.Minute, Apply: true,
|
||||||
|
Now: func() time.Time { return now },
|
||||||
|
})
|
||||||
|
require.NoError(t, err)
|
||||||
|
report, err = apply.Run(context.Background())
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, 1, report.DeletedOrphanObjects)
|
||||||
|
require.Equal(t, 1, report.DeletedUnreferencedRows)
|
||||||
|
require.Equal(t, []string{"old-missing"}, metadata.deleted)
|
||||||
|
require.Equal(t, []string{"attachments/old-orphan"}, objects.deleted)
|
||||||
|
|
||||||
|
report, err = apply.Run(context.Background())
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Zero(t, report.DeletedOrphanObjects)
|
||||||
|
require.Zero(t, report.DeletedUnreferencedRows)
|
||||||
|
require.Equal(t, 1, report.FreshOrphanObjects)
|
||||||
|
require.Equal(t, 1, report.FreshMissingObjects)
|
||||||
|
require.Equal(t, 1, report.ReferencedMissingObjects)
|
||||||
|
}
|
||||||
|
|
||||||
|
type metadataStub struct {
|
||||||
|
items []model.Attachment
|
||||||
|
referenced map[string]bool
|
||||||
|
deleted []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *metadataStub) ListAttachments(_ context.Context, after string, limit int) ([]model.Attachment, string, error) {
|
||||||
|
items := append([]model.Attachment(nil), s.items...)
|
||||||
|
sort.Slice(items, func(i, j int) bool { return items[i].ObjectKey < items[j].ObjectKey })
|
||||||
|
start := 0
|
||||||
|
for start < len(items) && items[start].ObjectKey <= after {
|
||||||
|
start++
|
||||||
|
}
|
||||||
|
end := min(start+limit, len(items))
|
||||||
|
var next string
|
||||||
|
if end < len(items) {
|
||||||
|
next = items[end-1].ObjectKey
|
||||||
|
}
|
||||||
|
return items[start:end], next, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *metadataStub) AttachmentReferenced(_ context.Context, id string) (bool, error) {
|
||||||
|
return s.referenced[id], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *metadataStub) DeleteAttachmentIfUnreferencedBefore(_ context.Context, id string, _ time.Time) (bool, error) {
|
||||||
|
for index, item := range s.items {
|
||||||
|
if item.ID == id && !s.referenced[id] {
|
||||||
|
s.items = append(s.items[:index], s.items[index+1:]...)
|
||||||
|
s.deleted = append(s.deleted, id)
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type objectStub struct {
|
||||||
|
items []objectstore.Object
|
||||||
|
deleted []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *objectStub) List(_ context.Context, _ string, after string, limit int) ([]objectstore.Object, string, error) {
|
||||||
|
items := append([]objectstore.Object(nil), s.items...)
|
||||||
|
sort.Slice(items, func(i, j int) bool { return items[i].Key < items[j].Key })
|
||||||
|
start := 0
|
||||||
|
for start < len(items) && items[start].Key <= after {
|
||||||
|
start++
|
||||||
|
}
|
||||||
|
end := min(start+limit, len(items))
|
||||||
|
var next string
|
||||||
|
if end < len(items) {
|
||||||
|
next = items[end-1].Key
|
||||||
|
}
|
||||||
|
return items[start:end], next, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *objectStub) Delete(_ context.Context, key string) error {
|
||||||
|
for index, item := range s.items {
|
||||||
|
if item.Key == key {
|
||||||
|
s.items = append(s.items[:index], s.items[index+1:]...)
|
||||||
|
s.deleted = append(s.deleted, key)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
+21
-1
@@ -26,6 +26,22 @@ DATABASE_URL=postgres://messenger:local-postgres-password@postgres:5432/messenge
|
|||||||
VALKEY_PASSWORD=local-valkey-password
|
VALKEY_PASSWORD=local-valkey-password
|
||||||
CACHE_URL=redis://default:local-valkey-password@valkey:6379/0
|
CACHE_URL=redis://default:local-valkey-password@valkey:6379/0
|
||||||
|
|
||||||
|
# Административные данные MinIO используются только при bootstrap.
|
||||||
|
MINIO_ROOT_USER=local-minio-admin
|
||||||
|
MINIO_ROOT_PASSWORD=local-minio-admin-password
|
||||||
|
|
||||||
|
# API использует отдельного пользователя с доступом только к bucket вложений.
|
||||||
|
S3_ENDPOINT=s3:9000
|
||||||
|
S3_REGION=us-east-1
|
||||||
|
S3_BUCKET=messenger-attachments
|
||||||
|
S3_ACCESS_KEY=messenger-app
|
||||||
|
S3_SECRET_KEY=local-messenger-s3-password
|
||||||
|
S3_USE_TLS=false
|
||||||
|
S3_TIMEOUT_SECONDS=5
|
||||||
|
ATTACHMENT_MAX_BYTES=10485760
|
||||||
|
ATTACHMENT_MAX_PIXELS=40000000
|
||||||
|
ATTACHMENT_DECODE_MEMORY_BYTES=402653184
|
||||||
|
|
||||||
# Размер пула и обслуживание соединений PostgreSQL.
|
# Размер пула и обслуживание соединений PostgreSQL.
|
||||||
DB_MIN_CONNS=1
|
DB_MIN_CONNS=1
|
||||||
DB_MAX_CONNS=10
|
DB_MAX_CONNS=10
|
||||||
@@ -55,7 +71,7 @@ SWAGGER_PORT=8081
|
|||||||
|
|
||||||
# Ограничения ресурсов контейнеров.
|
# Ограничения ресурсов контейнеров.
|
||||||
API_CPUS=1
|
API_CPUS=1
|
||||||
API_MEMORY=256m
|
API_MEMORY=512m
|
||||||
MIGRATE_CPUS=0.5
|
MIGRATE_CPUS=0.5
|
||||||
MIGRATE_MEMORY=128m
|
MIGRATE_MEMORY=128m
|
||||||
NGINX_CPUS=0.5
|
NGINX_CPUS=0.5
|
||||||
@@ -74,6 +90,10 @@ POSTGRES_CPUS=2
|
|||||||
POSTGRES_MEMORY=1g
|
POSTGRES_MEMORY=1g
|
||||||
VALKEY_CPUS=1
|
VALKEY_CPUS=1
|
||||||
VALKEY_MEMORY=256m
|
VALKEY_MEMORY=256m
|
||||||
|
S3_CPUS=1
|
||||||
|
S3_MEMORY=512m
|
||||||
|
S3_BOOTSTRAP_CPUS=0.25
|
||||||
|
S3_BOOTSTRAP_MEMORY=256m
|
||||||
|
|
||||||
# Пароль локального администратора Grafana.
|
# Пароль локального администратора Grafana.
|
||||||
GRAFANA_ADMIN_PASSWORD=local-grafana-password
|
GRAFANA_ADMIN_PASSWORD=local-grafana-password
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
ALTER TABLE messages
|
||||||
|
DROP CONSTRAINT messages_text_length,
|
||||||
|
DROP CONSTRAINT messages_text_not_blank;
|
||||||
|
|
||||||
|
ALTER TABLE messages
|
||||||
|
ADD CONSTRAINT messages_text_length CHECK (char_length(text) BETWEEN 0 AND 4000),
|
||||||
|
ADD CONSTRAINT messages_id_chat_unique UNIQUE (id, chat_id);
|
||||||
|
|
||||||
|
CREATE TABLE attachments (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
chat_id UUID NOT NULL,
|
||||||
|
owner_id UUID NOT NULL,
|
||||||
|
filename TEXT NOT NULL,
|
||||||
|
content_type TEXT NOT NULL,
|
||||||
|
size_bytes BIGINT NOT NULL,
|
||||||
|
sha256 TEXT NOT NULL,
|
||||||
|
object_key TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
CONSTRAINT attachments_id_chat_unique UNIQUE (id, chat_id),
|
||||||
|
CONSTRAINT attachments_object_key_unique UNIQUE (object_key),
|
||||||
|
CONSTRAINT attachments_owner_membership_fk FOREIGN KEY (chat_id, owner_id)
|
||||||
|
REFERENCES chat_members (chat_id, user_id) ON DELETE CASCADE,
|
||||||
|
CONSTRAINT attachments_filename_length CHECK (char_length(filename) BETWEEN 1 AND 255),
|
||||||
|
CONSTRAINT attachments_content_type CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||||||
|
CONSTRAINT attachments_size CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||||
|
CONSTRAINT attachments_sha256 CHECK (sha256 ~ '^[a-f0-9]{64}$'),
|
||||||
|
CONSTRAINT attachments_object_key_length CHECK (char_length(object_key) BETWEEN 1 AND 1024)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX attachments_chat_id_created_at_id_idx ON attachments (chat_id, created_at, id);
|
||||||
|
|
||||||
|
CREATE TABLE message_attachments (
|
||||||
|
message_id UUID NOT NULL,
|
||||||
|
chat_id UUID NOT NULL,
|
||||||
|
attachment_id UUID NOT NULL,
|
||||||
|
position SMALLINT NOT NULL,
|
||||||
|
CONSTRAINT message_attachments_pk PRIMARY KEY (message_id, attachment_id),
|
||||||
|
CONSTRAINT message_attachments_position_unique UNIQUE (message_id, position),
|
||||||
|
CONSTRAINT message_attachments_position_range CHECK (position BETWEEN 0 AND 9),
|
||||||
|
CONSTRAINT message_attachments_message_chat_fk FOREIGN KEY (message_id, chat_id)
|
||||||
|
REFERENCES messages (id, chat_id) ON DELETE CASCADE,
|
||||||
|
CONSTRAINT message_attachments_attachment_fk FOREIGN KEY (attachment_id, chat_id)
|
||||||
|
REFERENCES attachments (id, chat_id) ON DELETE RESTRICT
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX message_attachments_attachment_id_idx ON message_attachments (attachment_id);
|
||||||
@@ -85,6 +85,50 @@
|
|||||||
{"expr": "sum(redis_db_keys)", "legendFormat": "keys", "refId": "A"},
|
{"expr": "sum(redis_db_keys)", "legendFormat": "keys", "refId": "A"},
|
||||||
{"expr": "rate(redis_commands_processed_total[1m])", "legendFormat": "commands/s", "refId": "B"}
|
{"expr": "rate(redis_commands_processed_total[1m])", "legendFormat": "commands/s", "refId": "B"}
|
||||||
]
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "timeseries", "title": "Attachment uploads by result", "id": 15,
|
||||||
|
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 56},
|
||||||
|
"targets": [{"expr": "sum by (result) (rate(messenger_attachment_uploads_total[1m]))", "legendFormat": "{{result}}", "refId": "A"}]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "timeseries", "title": "Attachment upload latency p95", "id": 16,
|
||||||
|
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 56},
|
||||||
|
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
|
||||||
|
"targets": [{"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_upload_duration_seconds_bucket[5m])))", "legendFormat": "p95", "refId": "A"}]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "timeseries", "title": "Attachment upload traffic", "id": 17,
|
||||||
|
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 64},
|
||||||
|
"fieldConfig": {"defaults": {"unit": "Bps"}, "overrides": []},
|
||||||
|
"targets": [{"expr": "sum(rate(messenger_attachment_upload_bytes_total[1m]))", "legendFormat": "bytes/s", "refId": "A"}]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "timeseries", "title": "MinIO objects", "id": 18,
|
||||||
|
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 64},
|
||||||
|
"targets": [{"expr": "sum(minio_cluster_usage_object_total)", "legendFormat": "objects", "refId": "A"}]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "timeseries", "title": "MinIO requests and errors", "id": 19,
|
||||||
|
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 64},
|
||||||
|
"targets": [
|
||||||
|
{"expr": "sum(rate(minio_s3_requests_total[1m]))", "legendFormat": "requests/s", "refId": "A"},
|
||||||
|
{"expr": "sum(rate(minio_s3_requests_errors_total[1m]))", "legendFormat": "errors/s", "refId": "B"}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "timeseries", "title": "MinIO availability", "id": 20,
|
||||||
|
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 72},
|
||||||
|
"targets": [{"expr": "up{job=\"minio\"}", "legendFormat": "up", "refId": "A"}]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "timeseries", "title": "MinIO storage", "id": 21,
|
||||||
|
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 72},
|
||||||
|
"fieldConfig": {"defaults": {"unit": "bytes"}, "overrides": []},
|
||||||
|
"targets": [
|
||||||
|
{"expr": "sum(minio_cluster_usage_total_bytes)", "legendFormat": "used", "refId": "A"},
|
||||||
|
{"expr": "sum(minio_cluster_capacity_usable_free_bytes)", "legendFormat": "free", "refId": "B"}
|
||||||
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"refresh": "5s",
|
"refresh": "5s",
|
||||||
@@ -93,7 +137,7 @@
|
|||||||
"templating": {"list": []},
|
"templating": {"list": []},
|
||||||
"time": {"from": "now-15m", "to": "now"},
|
"time": {"from": "now-15m", "to": "now"},
|
||||||
"timezone": "browser",
|
"timezone": "browser",
|
||||||
"title": "Messenger lab3 overview",
|
"title": "Messenger lab4 overview",
|
||||||
"uid": "messenger-overview",
|
"uid": "messenger-overview",
|
||||||
"version": 2
|
"version": 3
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
global:
|
global:
|
||||||
scrape_interval: 5s
|
scrape_interval: 1s
|
||||||
evaluation_interval: 5s
|
evaluation_interval: 1s
|
||||||
|
|
||||||
scrape_configs:
|
scrape_configs:
|
||||||
- job_name: messenger
|
- job_name: messenger
|
||||||
@@ -21,3 +21,8 @@ scrape_configs:
|
|||||||
- job_name: valkey
|
- job_name: valkey
|
||||||
static_configs:
|
static_configs:
|
||||||
- targets: ["valkey-exporter:9121"]
|
- targets: ["valkey-exporter:9121"]
|
||||||
|
|
||||||
|
- job_name: minio
|
||||||
|
metrics_path: /minio/v2/metrics/cluster
|
||||||
|
static_configs:
|
||||||
|
- targets: ["s3:9000"]
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ http {
|
|||||||
|
|
||||||
server {
|
server {
|
||||||
listen 8080;
|
listen 8080;
|
||||||
|
client_max_body_size 11m;
|
||||||
|
|
||||||
location / {
|
location / {
|
||||||
proxy_pass http://messenger;
|
proxy_pass http://messenger;
|
||||||
@@ -34,6 +35,7 @@ http {
|
|||||||
proxy_set_header Host $host;
|
proxy_set_header Host $host;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_request_buffering off;
|
||||||
|
|
||||||
proxy_connect_timeout 1s;
|
proxy_connect_timeout 1s;
|
||||||
proxy_send_timeout 10s;
|
proxy_send_timeout 10s;
|
||||||
|
|||||||
+3
-2
@@ -2,7 +2,8 @@
|
|||||||
|
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
docker compose stop nginx api valkey postgres
|
docker compose stop nginx api valkey postgres s3
|
||||||
docker compose start postgres valkey
|
docker compose start postgres valkey s3
|
||||||
|
docker compose run --rm s3-bootstrap
|
||||||
docker compose run --rm migrate
|
docker compose run --rm migrate
|
||||||
docker compose up -d --wait --wait-timeout 90
|
docker compose up -d --wait --wait-timeout 90
|
||||||
|
|||||||
@@ -34,7 +34,8 @@ for container in $old_containers; do
|
|||||||
done
|
done
|
||||||
|
|
||||||
docker compose build
|
docker compose build
|
||||||
docker compose up -d postgres valkey
|
docker compose up -d postgres valkey s3
|
||||||
|
docker compose run --rm s3-bootstrap
|
||||||
docker compose run --rm migrate
|
docker compose run --rm migrate
|
||||||
|
|
||||||
if [ "$old_count" -lt 2 ]; then
|
if [ "$old_count" -lt 2 ]; then
|
||||||
|
|||||||
Reference in New Issue
Block a user