forked from mtusi2026/mtusi2026lab4
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4fc1f40099 |
@@ -18,3 +18,6 @@ __pycache__
|
||||
node_modules
|
||||
evidence
|
||||
.DS_Store
|
||||
.stress
|
||||
student-tests
|
||||
.local/
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
## Лабораторная 4
|
||||
|
||||
Автор / группа: TODO
|
||||
Целевая оценка (3/4/5): TODO
|
||||
Трек 5, если заявлен: TODO
|
||||
Автор / группа: Медведев Андрей Михайлович, БПИ2303
|
||||
Целевая оценка (3/4/5): 5
|
||||
Трек 5: 2 «Согласованность двух хранилищ»
|
||||
|
||||
Что реализовано и что перенесено: TODO
|
||||
Команды запуска из чистого clone: TODO
|
||||
Результаты проверок и ссылка на REPORT.md: TODO
|
||||
Ограничения / известные ошибки: TODO
|
||||
Источники и использование ИИ: TODO
|
||||
Что реализовано и что перенесено: Приватный RustFS на k3s + Pingap, PNG/JPEG upload/download и согласованные metadata; reconciler и native исследование частичных отказов. Проверены десять upload и экстремальные PNG/Adam7 с измерением памяти. Собственный Go core перенесён из предыдущей лабы с объявленными изменениями API.
|
||||
Команды запуска из чистого clone: RUN.md, начиная с bun --no-env-file scripts/k3s.ts up.
|
||||
Результаты проверок и ссылка на REPORT.md: REPORT.md; фактический вывод в evidence/, хеши проверенных исходников в evidence/SOURCE.sha256.
|
||||
Ограничения / известные ошибки: один host и общие зависимости; ограничения измерений и сценариев перечислены в REPORT.md.
|
||||
Источники и использование ИИ: оригинальный skeleton и собственная предыдущая работа; Codex использован для кода, тестов и отчёта. Независимый review native runtime сохранён в evidence/k3s/REVIEW.md; прежний backend review — в evidence/REVIEW.md.
|
||||
|
||||
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
||||
- [ ] Контракт и публичные тесты не ослаблены.
|
||||
- [ ] make check и make test выполнены; приложен реальный вывод.
|
||||
- [ ] Сценарии отказов/безопасности своего уровня воспроизведены.
|
||||
- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
|
||||
- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
|
||||
- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами; native эксперименты и ограничения описаны в REPORT.md.
|
||||
- [x] Контракт и публичные тесты не ослаблены.
|
||||
- [x] make check и make test выполнены; приложен реальный вывод.
|
||||
- [x] Сценарии отказов/безопасности своего уровня воспроизведены.
|
||||
- [x] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
|
||||
- [x] README задания сохранён, REPORT.md и RUN.md описывают моё решение.
|
||||
|
||||
@@ -30,3 +30,7 @@ coverage/
|
||||
.vscode/
|
||||
# Keep small, sanitized evidence summaries in evidence/ under version control.
|
||||
# Inspect git diff --cached: ignore rules are not a secret scanner.
|
||||
.stress
|
||||
.trash-1792138598/
|
||||
|
||||
.local/
|
||||
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
# Сборка: тег и digest закреплены, модули строго по go.sum (-mod=readonly).
|
||||
# Вместо слоя `go mod download` — cache mount: go.mod объявляет ещё и dev-
|
||||
# инструменты (oapi-codegen, golangci-lint), а `go mod download` тянул бы их
|
||||
# в образ сборки; `go build` скачивает только то, что нужно бинарнику.
|
||||
FROM golang:1.27.2-alpine@sha256:f92b6ef800e499660581efdabdf25d9d817a9d124eaf900924f0504e7e27e12d AS build
|
||||
WORKDIR /src
|
||||
ENV CGO_ENABLED=0 GOFLAGS=-mod=readonly
|
||||
COPY backend/ ./
|
||||
RUN --mount=type=cache,target=/go/pkg/mod \
|
||||
--mount=type=cache,target=/root/.cache/go-build \
|
||||
go build -trimpath -ldflags='-s -w' -o /out/messenger ./cmd/app && \
|
||||
go build -trimpath -ldflags='-s -w' -o /out/fixture-cleanup ./cmd/fixture-cleanup && \
|
||||
go test -c -o /out/integration.test ./integration && \
|
||||
go test -c -o /out/image-memory.test ./internal/adapter/imagefile
|
||||
|
||||
# Runtime: только статический бинарник, без shell и пакетного менеджера,
|
||||
# пользователь nonroot (uid 65532).
|
||||
FROM gcr.io/distroless/static-debian13:nonroot@sha256:e2e927ec666bae08560abb3c55d0659eceabb657f56b6782ab500a9fc7f555e3
|
||||
COPY --from=build /out/messenger /messenger
|
||||
COPY --from=build /out/fixture-cleanup /fixture-cleanup
|
||||
COPY --from=build /out/integration.test /integration.test
|
||||
COPY --from=build /out/image-memory.test /image-memory.test
|
||||
USER 65532:65532
|
||||
# GOMEMLIMIT рассчитан на запуск с --memory=256m (REPORT.md): GC начинает
|
||||
# работать активнее до того, как ядро убьёт процесс по OOM.
|
||||
ENV APP_HOST=0.0.0.0 APP_PORT=8080 GOMEMLIMIT=200MiB
|
||||
EXPOSE 8080
|
||||
# curl в образе нет: healthcheck — тот же бинарник с флагом.
|
||||
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
|
||||
CMD ["/messenger", "-healthcheck"]
|
||||
STOPSIGNAL SIGTERM
|
||||
# Exec-форма: сервер — PID 1 и сам получает SIGTERM.
|
||||
ENTRYPOINT ["/messenger"]
|
||||
@@ -1,37 +1,58 @@
|
||||
# Отчёт — лабораторная 4
|
||||
# Лабораторная 4. Приватный S3 и вложения на k3s + Pingap
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
Автор: Медведев Андрей Михайлович, БПИ2303. Целевая оценка — 5, трек 2 «Согласованность двух хранилищ». Основной стенд использует k3s + Pingap, две взаимозаменяемые API, общий PostgreSQL, Valkey и приватный RustFS. Оригинальное задание и контракты сохранены; k3s выбран автором как альтернатива предложенным Compose/Swarm. Принятие этой альтернативы преподавателем не заявляется.
|
||||
|
||||
## Запуск из чистого clone
|
||||
Код, тесты и отчёт подготовлены с помощью Codex. Команды — [RUN.md](RUN.md). Предыдущий Compose/HAProxy вариант и его показатели находятся в [архивном отчёте](docs/archive/compose-report.md), а новые доказательства — в evidence/k3s/.
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
## Архитектура и безопасность доступа
|
||||
|
||||
## Архитектура и решения
|
||||
Клиент обращается к localhost:28204 через LoadBalancer Service и Pingap 0.16.0. API обнаруживаются по DNS headless Service; Traefik выключен. Kubernetes Secrets создаются из локальных случайных credentials через stdin; приватный kubeconfig закреплён за собственным кластером. Глобальный kubeconfig не меняется. Runtime проверяет server container ID и Namespace UID; partial cleanup разрешён только для собственного exclusive claim с совпадающим nonce.
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab3, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
PostgreSQL, Valkey и RustFS используют разные PVC. Миграции и bucket bootstrap выполняются отдельными Jobs. Bootstrap получает root и application keys одним projected volume; обычные API получают только application S3 credentials, database URL и cache URL. Root-secret и административная консоль не публикуются наружу. Application identity имеет права на свой bucket и prefix, а создание постороннего bucket запрещено.
|
||||
|
||||
## Доказательства критериев
|
||||
Регистрация, persisted sessions, ACL чатов, keyset pagination и транзакционная идемпотентность перенесены из предыдущей лабы. Все защищённые запросы проверяют действующую сессию в PostgreSQL; Valkey — только неавторитетный кэш профиля. Привязка чужого или другого чата attachment отклоняется.
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
## Upload, download и согласованность
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
Upload проверяет членство, filename, максимальные 10 МиБ и содержимое PNG/JPEG. Временный файл ограничен 10 МиБ + 1 байт, одновременно считается SHA-256. DecodeConfig ограничивает изображение 40 млн пикселей до полноценного decode. MIME spoofing, повреждение, опасное имя и превышение лимитов возвращают пользовательскую ошибку, а не 500.
|
||||
|
||||
## Эксперименты и отказы
|
||||
До PUT создаётся устойчивое намерение uploading. Только после записи оригинала в S3 и финализации metadata возвращается 201 ready. Неопределённый ответ PUT или отказ SQL сохраняют намерение; опасного компенсирующего удаления подтверждённого оригинала нет. S3-вызовы не выполняются внутри SQL-транзакции.
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
Оригиналы имеют уникальный серверный ключ originals/UUID и не перезаписываются. Download проверяет ACL и размер, отдаёт bytes через API без redirect и контролирует полноту потока. Missing/uploading/abandoned — внутренние состояния; API не возвращает ложный ready. Сообщение допускает пустой text при наличии вложения; не более десяти уникальных attachment ID. Отсутствующий attachment_ids и [] имеют одинаковую семантику для Idempotency-Key, а обязательный text не может быть null.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
HTTP/SQL бюджеты, DNS/health-check Pingap и drain API согласованы с предыдущей лабой. Одна API декодирует не более одного изображения одновременно; hard limit API — 2 ГиБ, GOMEMLIMIT=1536MiB. Runtime отвергает уменьшение этого бюджета, потому что 40 млн сильно сжатых пикселей могут потребовать существенно больше памяти, чем 10 МиБ исходного файла.
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
## Подтверждённые проверки k3s-варианта
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
- Публичный upload → message → download smoke прошёл. Успешный оригинал сравнивается побайтно, чужой пользователь получает 404. Вывод — evidence/k3s/smoke.txt.
|
||||
- HTTP acceptance проверил malformed/MIME/filename/size, чужой attachment, другой чат, JSON null, общий токен и идемпотентность. Анонимный прямой S3 GET запрещён. Отключение S3 вернуло HTTP 503 за 8448 мс при upload context 20 секунд и клиентском timeout 25 секунд; после восстановления подтверждённый оригинал сохранился. Вывод — evidence/k3s/acceptance.txt.
|
||||
- Два failover-сценария сохранили metadata, сессию и bytes через другую API. Остановка подтверждается реальным container ID и нативным CRI состоянием, а не только исчезновением Pod из API. Вывод — evidence/k3s/failover-1.txt, failover-2.txt и stopped-*-after.json.
|
||||
- Полный restart API, PostgreSQL, Valkey, RustFS и Pingap сохранил прежний токен, сообщения и файл. Проверяется замена всех исходных workload UID с одинаковым run_id before/after. Повторный up с миграциями и идемпотентным bucket bootstrap тоже сохранил данные. Файлы — evidence/k3s/persistence.txt, restart-postcondition.txt и redeploy.txt.
|
||||
- Scoped wrapper проверен настоящим SELECT через stdin. Unit-тесты и независимое ревью покрывают ownership, secret mounts, image identities, game guard, остановку конкретного процесса и ошибки cleanup.
|
||||
- Offline skeleton/OpenAPI проверки прошли. Go-код, нормативный контракт и публичные tests при переносе не менялись.
|
||||
|
||||
## Исследование согласованности двух хранилищ
|
||||
|
||||
Новый эксперимент выполнен в отдельном случайном k3s-кластере с пустыми БД и bucket. Runner запускает native integration Job и удаляет весь свой кластер до PASS. Source scope и итог — evidence/k3s/reconciliation/run-FVKocZ/.
|
||||
|
||||
Реальный PostgreSQL trigger вызвал ошибку финализации после успешного PUT. Также потерян ответ выполненного PUT, удалён оригинал используемого вложения, оставлено прерванное намерение и создан старый orphan. Новый объект создан перед сверкой для проверки grace period. Это фактические ошибки на границе PostgreSQL/S3; обработка SQL cleanup дополнительно проверена на чате с посторонним участником.
|
||||
|
||||
Reconciler обрабатывает не более 100 metadata и 100 объектов за batch. Default — dry-run, apply задаётся явно. Grace по умолчанию 10 минут, минимально 60 секунд при upload deadline 20 секунд. Свежие и будущие timestamps не разрешают удаление. Inventory и HEAD нормализуются к UTC-секундам; перед orphan delete сравниваются ETag, размер, возраст и отсутствие актуальных metadata. Любой учтённый объект защищён от orphan cleanup. При ошибке continuation очищается, чтобы повторить неуспешную страницу.
|
||||
|
||||
Dry-run увидел 5 metadata, 5 объектов, один orphan, два missing и две восстановимые загрузки; изменений не внёс. Apply удалил один старый orphan и изменил четыре metadata, восстановив две загрузки. Используемый оригинал и свежий объект сохранились. Повтор дал ноль изменений и удалений. После восстановления корректных bytes missing-вложение снова стало ready; сообщения и metadata не удалялись.
|
||||
|
||||
Для apply считались запросы именно S3-клиента reconciler: 12 HTTP-запросов и 2227 прочитанных bytes на этом наборе. Фоновые readiness-запросы API не включаются в этот клиентский счётчик. Реальные выводы трёх integration tests сохранены в tests.txt; все три прошли.
|
||||
|
||||
## Измерения памяти на k3s
|
||||
|
||||
На omarchy без игры выполнены два новых эксперимента. Проверка game-running вернула ровно 1 до и после каждого измерения; ошибка определения состояния также останавливает runner. Host — Ryzen 7 5700X, Linux x86_64; лимит каждой API — 1 CPU/2 ГиБ, GOMEMLIMIT=1536MiB, одновременно декодируется одно изображение на API. Это измерения нового стенда, отдельно от исторических Compose результатов.
|
||||
|
||||
В evidence/k3s/concurrent-images/run-Y14n1Y/ сохранены десять одновременных upload PNG размером 3 148 214 байт, передаваемых порциями 64 КиБ с паузой 30 мс. Восемь запросов получили 201, два — ограниченный 503. Каждый успешный оригинал скачан и побайтно сравнён с fixture. Нативный cgroup memory.peak двух API равен 68 116 480 и 68 026 368 байт, примерно 64,96 и 64,88 МиБ. UID обеих API не изменились, readiness после эксперимента сохранилась. Итог записывается только после успешного cleanup своего набора данных; samples и summary.json приложены.
|
||||
|
||||
Отдельный Kubernetes Job проверил настоящий PNG RGBA64 размером 40 000 000×1 пикселей в обычном и Adam7 вариантах, по две последовательные проверки каждого, одновременно с тремя Argon2 worker. TestWorstCaseImagesWithinBudget прошёл за 5,34 с; Linux VmHWM показал 1 555 800 КиБ, примерно 1519,34 МиБ, при hard limit 2 097 152 КиБ. Job использовал 2 CPU/2 ГиБ и GOMEMLIMIT=1536MiB. Вывод и hash image.go находятся в evidence/k3s/image-memory-6l7yZ5/. VmHWM здесь измеряет RSS тестового процесса; cgroup peak API в предыдущем эксперименте включает память контейнера, поэтому это разные метрики.
|
||||
|
||||
Оба эксперимента короткие и относятся к указанным fixtures и ограничениям. Они подтверждают проверенные границы, но не являются доказательством отсутствия OOM для произвольной смеси запросов. Публичный API по-прежнему принимает не более 10 МиБ и 40 млн пикселей, а перегрузка может завершаться 503.
|
||||
|
||||
## Ограничения
|
||||
|
||||
Один host, один k3s server, единственные PostgreSQL, Pingap и S3 остаются точками отказа. PVC сохраняют данные при проверенном restart, но не обеспечивают HA при потере host. Прерванная загрузка может оставлять намерение до сверки. POST upload не обещает идемпотентность; повтор может создать другое вложение. Reconciler не заменяет полный checksum scrub всех ready-объектов. HTTP стенд привязан к loopback; публичный production rollout не выполнялся.
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
# Запуск лабораторной 4 на k3s + Pingap
|
||||
|
||||
Автор: Медведев Андрей Михайлович, БПИ2303. Все команды выполняются из корня этой лабы. Исходное задание сохранено в README.md, контракт — в contracts/; описание реализации и результаты находятся в REPORT.md.
|
||||
|
||||
Проверенный host — Linux x86_64 с Docker 29.9.2, k3d 5.9.0, kubectl 1.37.1 и Bun 1.4.4. В кластере используется закреплённый k3s 1.37.1 и Pingap 0.16.0. Для публичных проверок нужен Python 3.9+; для проверок Go и генератора PNG — Go 1.27.2. Большие сборки и эксперименты выполняются на тестовом host, не на Mac.
|
||||
|
||||
## Запуск с нуля
|
||||
|
||||
```sh
|
||||
bun --no-env-file scripts/k3s.ts up
|
||||
```
|
||||
|
||||
Команда создаёт отдельный одноузловой кластер vp-lab4-medvedev, собирает API, проверяет и импортирует образы, создаёт Secrets и PVC, ждёт реального SQL-запроса, выполняет миграции отдельным Job и проверяет HTTP через Pingap. На первом запуске отсутствующие публичные образы скачиваются по закреплённым digest; имеющийся кеш используется повторно. При импорте выбирается linux/amd64, чтобы не переносить отсутствующие части многоплатформенного image index.
|
||||
|
||||
API доступен по http://127.0.0.1:28204. Кластер не меняет глобальный kubeconfig. Его приватный kubeconfig и синтетические credentials находятся в .local/, исключённом из git и Docker context. Повторный запуск сохраняет PVC и данные. В обычных API-подах нет root-credentials S3.
|
||||
|
||||
## Проверки
|
||||
|
||||
```sh
|
||||
python3 -m venv .venv
|
||||
.venv/bin/pip install -r requirements-dev.txt
|
||||
make check PYTHON=.venv/bin/python
|
||||
make validate PYTHON=.venv/bin/python
|
||||
make test BASE_URL=http://127.0.0.1:28204
|
||||
BASE_URL=http://127.0.0.1:28204 bun --no-env-file student-tests/acceptance.ts
|
||||
bun --no-env-file student-tests/kube-stdin.ts
|
||||
bun test student-tests/k3s-model.test.ts
|
||||
```
|
||||
|
||||
HTTP acceptance удаляет только собственный случайный набор; публичные проверки сохраняют свои синтетические записи для демонстрации. Проверка stdin действительно выполняет SELECT в PostgreSQL, а не ограничивается exit status процесса psql.
|
||||
|
||||
Остановка обслужившей реплики и её восстановление:
|
||||
|
||||
```sh
|
||||
make test-failover BASE_URL=http://127.0.0.1:28204 ACTION_SCRIPT=scripts/stop-one.sh
|
||||
bun --no-env-file scripts/k3s.ts configure
|
||||
```
|
||||
|
||||
Повторите обе команды для следующей реплики. TARGET_INSTANCE_ID задаёт публичный тест. Hook проверяет Pod UID, масштабирует API до одной реплики и аварийно останавливает процесс выбранного пода; нативный CRI inventory подтверждает отсутствие работающего процесса с его UID. Свидетельства сохраняются в evidence/k3s/stop-one-before.json и stop-one-after.json. Для штатной замены используется обычный rollout с readiness и preStop, без аварийного kill.
|
||||
|
||||
Полный рестарт компонентов с прежним токеном и данными:
|
||||
|
||||
```sh
|
||||
make test-persistence BASE_URL=http://127.0.0.1:28204 ACTION_SCRIPT=scripts/restart.sh
|
||||
```
|
||||
|
||||
Hook записывает реальные Pod UID до и после рестарта и дожидается API через Pingap. PostgreSQL, Valkey, S3 и Pingap входят в сценарий. Проверки backend выполняются отдельно:
|
||||
|
||||
```sh
|
||||
cd backend
|
||||
go test -race ./...
|
||||
go tool golangci-lint run
|
||||
go generate ./...
|
||||
```
|
||||
|
||||
После них вернитесь в корень лабы. Контракты и публичные тесты сохранены, версия OpenAPI не менялась при переносе.
|
||||
|
||||
## S3, согласованность и память
|
||||
|
||||
Отказ S3 с восстановлением и проверкой сохранённого оригинала:
|
||||
|
||||
```sh
|
||||
FAIL_S3=1 BASE_URL=http://127.0.0.1:28204 bun --no-env-file student-tests/acceptance.ts
|
||||
```
|
||||
|
||||
Частичные отказы, dry-run, apply и повтор проверяются в отдельном случайном кластере с пустой БД и bucket на localhost:28404:
|
||||
|
||||
```sh
|
||||
bun --no-env-file student-tests/reconciliation.ts
|
||||
```
|
||||
|
||||
Runner удаляет свой кластер после завершения. Прямой запуск destructive integration в основном кластере отвергается. Результаты находятся в evidence/k3s/reconciliation/run-*.
|
||||
|
||||
Обычная сверка основного стенда по 100 metadata и 100 объектов за batch:
|
||||
|
||||
```sh
|
||||
bun --no-env-file scripts/k3s.ts task reconcile
|
||||
bun --no-env-file scripts/k3s.ts task reconcile -apply
|
||||
```
|
||||
|
||||
Первая команда — dry-run. Для продолжения передайте NextMetadata и NextObject через -after и -object-after. Default grace равен 10 минутам; минимально 60 секунд. При ошибке повторяется прежняя страница.
|
||||
|
||||
Память измеряется только без игры на тестовом host. Сначала создайте fixture из корня лабы:
|
||||
|
||||
```sh
|
||||
go run ./student-tests/image-fixtures/main.go
|
||||
BASE_URL=http://127.0.0.1:28204 bun --no-env-file student-tests/concurrent-images.ts
|
||||
./student-tests/image-memory.sh
|
||||
```
|
||||
|
||||
Первый эксперимент начинает десять upload, проверяет bytes каждого успешного оригинала и снимает настоящий cgroup memory.peak API. Второй выполняет экстремальный PNG-тест отдельным Job с hard limit 2 ГиБ. Native CLI тоже проверяет game-running до и после memory Job, поэтому обход shell-скрипта не разрешает измерение во время игры.
|
||||
|
||||
## Остановка и удаление своего стенда
|
||||
|
||||
Остановка сохраняет кластер и PVC:
|
||||
|
||||
```sh
|
||||
bun --no-env-file scripts/k3s.ts stop
|
||||
```
|
||||
|
||||
Повторный up возвращает сохранённые данные. Полное удаление кластера вместе с его учебными данными выполняется явно из работающего стенда:
|
||||
|
||||
```sh
|
||||
bun --no-env-file scripts/k3s.ts destroy
|
||||
```
|
||||
|
||||
Если кластер был остановлен, сначала выполните up. Runtime проверяет собственный claim, immutable ID server-контейнера и Namespace UID; чужой кластер или заменённый namespace автоматически не принимаются. Оригинальное задание предлагает Compose/Swarm; k3s выбран автором как альтернативный стенд, и принятие этого варианта преподавателем не заявляется.
|
||||
@@ -0,0 +1,36 @@
|
||||
version: "2"
|
||||
run:
|
||||
allow-parallel-runners: true
|
||||
linters:
|
||||
default: standard
|
||||
enable: [depguard]
|
||||
settings:
|
||||
errcheck:
|
||||
# Close тела ответа и файла, открытого на чтение: ошибке некуда деться.
|
||||
exclude-functions:
|
||||
- (io.ReadCloser).Close
|
||||
- (*os.File).Close
|
||||
depguard:
|
||||
rules:
|
||||
# Гексагон: ядро и use-case'ы зависят от портов, а не от адаптеров и транспорта.
|
||||
inner-pure:
|
||||
files: ["**/internal/domain/**", "**/internal/application/**"]
|
||||
deny:
|
||||
- pkg: backend/internal/adapter
|
||||
desc: домен и приложение зависят от портов, не от адаптеров
|
||||
- pkg: backend/internal/config
|
||||
desc: конфиг читает только cmd
|
||||
- pkg: net/http
|
||||
desc: HTTP только в adapter/handler
|
||||
- pkg: github.com/go-chi
|
||||
desc: роутер только в adapter/handler
|
||||
- pkg: github.com/rs/zerolog
|
||||
desc: логирование на границе, в адаптерах
|
||||
domain-core:
|
||||
files: ["**/internal/domain/**"]
|
||||
deny:
|
||||
- pkg: backend/internal/application
|
||||
desc: домен не знает о use-case'ах
|
||||
exclusions:
|
||||
paths:
|
||||
- ".*\\.gen\\.go$"
|
||||
@@ -0,0 +1,191 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"backend/db"
|
||||
"backend/internal/adapter/handler"
|
||||
"backend/internal/adapter/password"
|
||||
"backend/internal/adapter/repository/postgres"
|
||||
"backend/internal/adapter/storage"
|
||||
"backend/internal/application/usecase"
|
||||
"backend/internal/config"
|
||||
"backend/pkg/logger"
|
||||
"backend/pkg/server"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func main() {
|
||||
healthcheck := flag.Bool("healthcheck", false, "проверить /health/ready и выйти (для Docker HEALTHCHECK)")
|
||||
migrate := flag.Bool("migrate", false, "apply migrations and exit")
|
||||
bootstrapS3 := flag.Bool("bootstrap-s3", false, "initialize private bucket and application IAM credentials")
|
||||
reconcile := flag.Bool("reconcile", false, "reconcile at most 100 metadata rows and 100 objects; dry-run by default")
|
||||
apply := flag.Bool("apply", false, "apply safe reconciliation changes")
|
||||
grace := flag.Duration("grace", 10*time.Minute, "minimum safe object age, at least 60 seconds")
|
||||
after := flag.String("after", "", "metadata UUID cursor")
|
||||
objectAfter := flag.String("object-after", "", "object key cursor")
|
||||
flag.Parse()
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "config:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if *healthcheck {
|
||||
os.Exit(probe(cfg.Port))
|
||||
}
|
||||
|
||||
log := logger.New(cfg.LogLevel)
|
||||
dsn, err := config.ReadSecret(cfg.DatabaseURLFile)
|
||||
if err != nil {
|
||||
log.Fatal().Msg("database secret unavailable")
|
||||
}
|
||||
if *migrate {
|
||||
if err = db.Migrate(context.Background(), dsn); err != nil {
|
||||
log.Fatal().Err(err).Msg("migration failed")
|
||||
}
|
||||
return
|
||||
}
|
||||
s3config, err := storage.ReadConfig("/run/secrets/s3_credentials")
|
||||
if err != nil {
|
||||
log.Fatal().Msg("S3 application credentials unavailable")
|
||||
}
|
||||
objects, err := storage.FromConfig(s3config)
|
||||
if err != nil {
|
||||
log.Fatal().Msg("invalid S3 endpoint")
|
||||
}
|
||||
if *bootstrapS3 {
|
||||
root, e := storage.ReadConfig("/run/secrets/s3_root")
|
||||
if e != nil {
|
||||
log.Fatal().Msg("S3 bootstrap credentials unavailable")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
if e = storage.Bootstrap(ctx, root, s3config); e != nil {
|
||||
log.Fatal().Err(e).Msg("S3 bootstrap failed")
|
||||
}
|
||||
return
|
||||
}
|
||||
pc, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
log.Fatal().Msg("invalid database configuration")
|
||||
}
|
||||
pc.MaxConns = cfg.MaxConns
|
||||
pc.MinConns = 0
|
||||
pc.ConnConfig.ConnectTimeout = time.Second
|
||||
pc.ConnConfig.RuntimeParams["statement_timeout"] = "2000"
|
||||
pc.ConnConfig.RuntimeParams["lock_timeout"] = "1000"
|
||||
pool, err := pgxpool.NewWithConfig(context.Background(), pc)
|
||||
if err != nil {
|
||||
log.Fatal().Msg("database initialization failed")
|
||||
}
|
||||
defer pool.Close()
|
||||
var cache *redis.Client
|
||||
if url, e := config.ReadSecret(cfg.CacheURLFile); e == nil {
|
||||
opts, e := redis.ParseURL(url)
|
||||
if e != nil {
|
||||
log.Fatal().Msg("invalid cache configuration")
|
||||
}
|
||||
opts.MaxRetries = 0
|
||||
opts.DialTimeout = 80 * time.Millisecond
|
||||
opts.ReadTimeout = 80 * time.Millisecond
|
||||
opts.WriteTimeout = 80 * time.Millisecond
|
||||
cache = redis.NewClient(opts)
|
||||
defer func() { _ = cache.Close() }()
|
||||
}
|
||||
store := postgres.New(pool, cache)
|
||||
if *reconcile {
|
||||
cursor := uuid.Nil
|
||||
if *after != "" {
|
||||
cursor, err = uuid.Parse(*after)
|
||||
if err != nil {
|
||||
log.Fatal().Msg("invalid metadata cursor")
|
||||
}
|
||||
}
|
||||
if len(*objectAfter) > 64 {
|
||||
log.Fatal().Msg("object cursor too long")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
report, e := usecase.NewReconciler(store, objects, time.Now).Run(ctx, cursor, *objectAfter, *grace, *apply)
|
||||
if err = json.NewEncoder(os.Stdout).Encode(report); err != nil {
|
||||
log.Fatal().Msg("reconciliation report write failed")
|
||||
}
|
||||
if e != nil {
|
||||
log.Fatal().Err(e).Msg("reconciliation incomplete")
|
||||
}
|
||||
return
|
||||
}
|
||||
app := usecase.NewMessenger(store)
|
||||
auth := usecase.NewAuth(store, password.New(), app, time.Duration(cfg.SessionTTLSeconds)*time.Second, time.Now)
|
||||
attachments := usecase.NewAttachments(store, app, objects)
|
||||
probeDependencies := func(ctx context.Context) error {
|
||||
if e := pool.Ping(ctx); e != nil {
|
||||
return e
|
||||
}
|
||||
return objects.Ready(ctx)
|
||||
}
|
||||
h := handler.New(app, auth, attachments, probeDependencies, handler.Limits{
|
||||
MaxBodyBytes: cfg.MaxBodyBytes,
|
||||
MaxInflight: cfg.MaxInflight,
|
||||
MaxQueue: cfg.MaxQueue,
|
||||
QueueTimeout: cfg.QueueTimeout,
|
||||
}, func() any {
|
||||
return map[string]any{"pool_total": pool.Stat().TotalConns(), "pool_acquired": pool.Stat().AcquiredConns(), "pool_max": pool.Stat().MaxConns()}
|
||||
}, &log)
|
||||
srv := server.New(cfg.Addr(), h.Router())
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||||
defer stop()
|
||||
|
||||
serveErr := make(chan error, 1)
|
||||
go func() { serveErr <- srv.ListenAndServe() }()
|
||||
log.Info().Str("addr", cfg.Addr()).Str("env", cfg.Env).
|
||||
Int("max_inflight", cfg.MaxInflight).
|
||||
Int("max_queue", cfg.MaxQueue).Msg("server started")
|
||||
|
||||
select {
|
||||
case err := <-serveErr:
|
||||
log.Fatal().Err(err).Msg("server failed")
|
||||
case <-ctx.Done():
|
||||
}
|
||||
|
||||
started := time.Now()
|
||||
log.Info().Dur("timeout", cfg.ShutdownTimeout).Msg("shutdown signal received, draining")
|
||||
h.Drain()
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||
log.Error().Err(err).Msg("shutdown timed out, open requests aborted")
|
||||
}
|
||||
if err := <-serveErr; err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
log.Error().Err(err).Msg("server error")
|
||||
}
|
||||
log.Info().Dur("took", time.Since(started)).Msg("shutdown complete")
|
||||
}
|
||||
|
||||
// probe — healthcheck без curl в образе distroless: сам бинарник ходит в
|
||||
// /health/ready и возвращает код выхода для Docker.
|
||||
func probe(port int) int {
|
||||
client := http.Client{Timeout: 2 * time.Second}
|
||||
resp, err := client.Get(fmt.Sprintf("http://127.0.0.1:%d/health/ready", port))
|
||||
if err != nil {
|
||||
return 1
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
// An explicit test-only tool, never called by the HTTP server.
|
||||
package main
|
||||
|
||||
import (
|
||||
"backend/internal/adapter/storage"
|
||||
"backend/internal/config"
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"os"
|
||||
"regexp"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if e := run(); e != nil {
|
||||
fmt.Fprintln(os.Stderr, "fixture cleanup failed")
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
func run() error {
|
||||
if len(os.Args) != 2 || !regexp.MustCompile(`^st_[a-f0-9]{16}$`).MatchString(os.Args[1]) {
|
||||
return fmt.Errorf("explicit synthetic fixture prefix required")
|
||||
}
|
||||
prefix := os.Args[1]
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
dsn, e := config.ReadSecret("/run/secrets/database_url")
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
pool, e := pgxpool.New(ctx, dsn)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
defer pool.Close()
|
||||
credentials, e := storage.ReadConfig("/run/secrets/s3_credentials")
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
objects, e := storage.FromConfig(credentials)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
rows, e := pool.Query(ctx, `SELECT a.id FROM attachments a JOIN users u ON u.id=a.owner_id WHERE left(u.username,19)=$1 LIMIT 1001`, prefix)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
ids := []uuid.UUID{}
|
||||
for rows.Next() {
|
||||
var id uuid.UUID
|
||||
if e = rows.Scan(&id); e != nil {
|
||||
rows.Close()
|
||||
return e
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
rows.Close()
|
||||
if e = rows.Err(); e != nil {
|
||||
return e
|
||||
}
|
||||
if len(ids) > 1000 {
|
||||
return fmt.Errorf("cleanup bound exceeded")
|
||||
}
|
||||
tx, e := pool.Begin(ctx)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
_, e = tx.Exec(ctx, `CREATE TEMP TABLE own_users ON COMMIT DROP AS SELECT id FROM users WHERE left(username,19)=$1`, prefix)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
statements := []string{
|
||||
`DO $$ BEGIN IF EXISTS(SELECT 1 FROM chat_members mine JOIN chat_members other ON other.chat_id=mine.chat_id WHERE mine.user_id IN(SELECT id FROM own_users) AND other.user_id NOT IN(SELECT id FROM own_users)) THEN RAISE EXCEPTION 'fixture has foreign memberships';END IF;END $$`,
|
||||
`CREATE TEMP TABLE own_chats ON COMMIT DROP AS SELECT DISTINCT mine.chat_id AS id FROM chat_members mine WHERE mine.user_id IN (SELECT id FROM own_users) AND NOT EXISTS(SELECT 1 FROM chat_members other WHERE other.chat_id=mine.chat_id AND other.user_id NOT IN(SELECT id FROM own_users))`,
|
||||
`DELETE FROM message_attachments WHERE message_id IN (SELECT id FROM messages WHERE sender_id IN (SELECT id FROM own_users))`,
|
||||
`DELETE FROM idempotency WHERE user_id IN (SELECT id FROM own_users)`,
|
||||
`DELETE FROM messages WHERE sender_id IN (SELECT id FROM own_users)`,
|
||||
`DELETE FROM sessions WHERE user_id IN (SELECT id FROM own_users)`,
|
||||
`DELETE FROM attachments WHERE owner_id IN (SELECT id FROM own_users)`,
|
||||
`DELETE FROM chat_members WHERE chat_id IN (SELECT id FROM own_chats)`,
|
||||
`DELETE FROM chats WHERE id IN (SELECT id FROM own_chats)`,
|
||||
`DELETE FROM users WHERE id IN (SELECT id FROM own_users)`,
|
||||
}
|
||||
for _, statement := range statements {
|
||||
if _, e = tx.Exec(ctx, statement); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
if e = tx.Commit(ctx); e != nil {
|
||||
return e
|
||||
}
|
||||
// Delete bytes only after confirmed metadata deletion. Failed/uncertain SQL leaves originals intact;
|
||||
// a failed S3 delete leaves an inaccessible orphan for the grace-protected reconciler.
|
||||
for _, id := range ids {
|
||||
if e = objects.Remove(ctx, "originals/"+id.String()); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package: handler
|
||||
generate:
|
||||
models: true
|
||||
chi-server: true
|
||||
strict-server: true
|
||||
output: api.gen.go
|
||||
output-options:
|
||||
overlay:
|
||||
path: ../../../generator-overlay.yaml
|
||||
# date-time -> handler.Timestamp: ровно 6 цифр дробной части (см. timestamp.go)
|
||||
type-mapping:
|
||||
string:
|
||||
formats:
|
||||
date-time:
|
||||
type: Timestamp
|
||||
@@ -0,0 +1,25 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"embed"
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/pressly/goose/v3"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrations embed.FS
|
||||
|
||||
func Migrate(ctx context.Context, dsn string) error {
|
||||
conn, err := sql.Open("pgx", dsn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = conn.Close() }()
|
||||
goose.SetBaseFS(migrations)
|
||||
if err = goose.SetDialect("postgres"); err != nil {
|
||||
return err
|
||||
}
|
||||
return goose.UpContext(ctx, conn, "migrations")
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||
password_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
chat_count integer NOT NULL DEFAULT 0 CHECK (chat_count BETWEEN 0 AND 1000),
|
||||
message_count integer NOT NULL DEFAULT 0 CHECK (message_count BETWEEN 0 AND 1000000),
|
||||
attachment_count integer NOT NULL DEFAULT 0 CHECK (attachment_count BETWEEN 0 AND 10000)
|
||||
);
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
CREATE INDEX member_chats ON chat_members(user_id,chat_id);
|
||||
CREATE INDEX chats_order ON chats(created_at,id);
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
sender_id uuid NOT NULL REFERENCES users(id),
|
||||
text text NOT NULL CHECK (char_length(text) BETWEEN 0 AND 4000),
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
FOREIGN KEY (chat_id,sender_id) REFERENCES chat_members(chat_id,user_id)
|
||||
);
|
||||
CREATE INDEX messages_history ON messages(chat_id,created_at,id);
|
||||
CREATE TABLE sessions (
|
||||
token_hash text PRIMARY KEY CHECK (length(token_hash)=64),
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
expires_at timestamptz NOT NULL
|
||||
);
|
||||
CREATE INDEX sessions_user ON sessions(user_id,expires_at);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE sessions;
|
||||
DROP TABLE messages;
|
||||
DROP TABLE chat_members;
|
||||
DROP TABLE chats;
|
||||
DROP TABLE users;
|
||||
@@ -0,0 +1,12 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE idempotency (
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
key text NOT NULL CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'),
|
||||
payload_hash text NOT NULL CHECK (length(payload_hash)=64),
|
||||
message_id uuid NOT NULL REFERENCES messages(id) DEFERRABLE INITIALLY DEFERRED,
|
||||
expires_at timestamptz NOT NULL,
|
||||
PRIMARY KEY(user_id,chat_id,key)
|
||||
);
|
||||
-- +goose Down
|
||||
DROP TABLE idempotency;
|
||||
@@ -0,0 +1,26 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE attachments (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
owner_id uuid NOT NULL REFERENCES users(id),
|
||||
filename text NOT NULL CHECK(char_length(filename) BETWEEN 1 AND 255),
|
||||
content_type text NOT NULL CHECK(content_type IN ('image/png','image/jpeg')),
|
||||
size_bytes bigint NOT NULL CHECK(size_bytes BETWEEN 1 AND 10485760),
|
||||
sha256 text NOT NULL CHECK(sha256 ~ '^[a-f0-9]{64}$'),
|
||||
status text NOT NULL CHECK(status IN ('uploading','ready','missing','abandoned')),
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
FOREIGN KEY(chat_id,owner_id) REFERENCES chat_members(chat_id,user_id)
|
||||
);
|
||||
CREATE INDEX attachments_owner ON attachments(owner_id,id);
|
||||
CREATE TABLE message_attachments (
|
||||
message_id uuid NOT NULL REFERENCES messages(id),
|
||||
attachment_id uuid NOT NULL REFERENCES attachments(id),
|
||||
ordinal integer NOT NULL CHECK(ordinal BETWEEN 0 AND 9),
|
||||
PRIMARY KEY(message_id,ordinal),
|
||||
UNIQUE(message_id,attachment_id)
|
||||
);
|
||||
CREATE INDEX attachment_references ON message_attachments(attachment_id);
|
||||
-- +goose Down
|
||||
DROP TABLE message_attachments;
|
||||
DROP TABLE attachments;
|
||||
@@ -0,0 +1,15 @@
|
||||
-- name: ChargeAttachment :one
|
||||
UPDATE users SET attachment_count=attachment_count+1 WHERE id=$1 AND attachment_count<10000 RETURNING id;
|
||||
-- name: InsertAttachment :one
|
||||
INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,status)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,'uploading') RETURNING *;
|
||||
-- name: GetAttachment :one
|
||||
SELECT * FROM attachments WHERE id=$1 FOR SHARE;
|
||||
-- name: SetAttachmentStatus :execrows
|
||||
UPDATE attachments SET status=$2,updated_at=clock_timestamp() WHERE id=$1 AND status=$3;
|
||||
-- name: InsertMessageAttachment :exec
|
||||
INSERT INTO message_attachments(message_id,attachment_id,ordinal) VALUES($1,$2,$3);
|
||||
-- name: MessageAttachments :many
|
||||
SELECT attachment_id FROM message_attachments WHERE message_id=$1 ORDER BY ordinal LIMIT 10;
|
||||
-- name: ReconcileAttachments :many
|
||||
SELECT * FROM attachments WHERE id>$1 ORDER BY id LIMIT 101;
|
||||
@@ -0,0 +1,42 @@
|
||||
-- name: CreateUser :one
|
||||
INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4)
|
||||
RETURNING id,username,display_name,created_at;
|
||||
-- name: GetUser :one
|
||||
SELECT id,username,display_name,created_at FROM users WHERE id=$1;
|
||||
-- name: Credentials :one
|
||||
SELECT id,password_hash FROM users WHERE username=$1;
|
||||
-- name: ChargeChat :one
|
||||
UPDATE users SET chat_count=chat_count+1 WHERE id=$1 AND chat_count<1000 RETURNING id;
|
||||
-- name: ChargeMessage :one
|
||||
UPDATE users SET message_count=message_count+1 WHERE id=$1 AND message_count<1000000 RETURNING id;
|
||||
-- name: InsertChat :one
|
||||
INSERT INTO chats(id,title) VALUES($1,$2) RETURNING id,title,created_at;
|
||||
-- name: InsertMembers :exec
|
||||
INSERT INTO chat_members(chat_id,user_id) SELECT $1,unnest($2::uuid[]);
|
||||
-- name: GetChat :one
|
||||
SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id)::uuid[] AS members
|
||||
FROM chats c WHERE c.id=$1;
|
||||
-- name: ListChats :many
|
||||
SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id)::uuid[] AS members
|
||||
FROM chats c JOIN chat_members m ON m.chat_id=c.id
|
||||
WHERE m.user_id=sqlc.arg(member_id) AND (c.created_at,c.id)>(sqlc.arg(after_time)::timestamptz,sqlc.arg(after_id)::uuid)
|
||||
ORDER BY c.created_at,c.id LIMIT sqlc.arg(page_limit);
|
||||
-- name: InsertMessage :one
|
||||
INSERT INTO messages(id,chat_id,sender_id,text) VALUES($1,$2,$3,$4) RETURNING id,chat_id,sender_id,text,created_at;
|
||||
-- name: ListMessages :many
|
||||
SELECT m.id,m.chat_id,m.sender_id,m.text,m.created_at,
|
||||
ARRAY(SELECT attachment_id FROM message_attachments WHERE message_id=m.id ORDER BY ordinal LIMIT 10)::uuid[] AS attachment_ids
|
||||
FROM messages m WHERE m.chat_id=$1 AND (m.created_at,m.id)>(sqlc.arg(after_time)::timestamptz,sqlc.arg(after_id)::uuid)
|
||||
ORDER BY m.created_at,m.id LIMIT sqlc.arg(page_limit);
|
||||
-- name: LockSessionOwner :one
|
||||
SELECT id FROM users WHERE id=$1 FOR UPDATE;
|
||||
-- name: DeleteExpiredSessions :exec
|
||||
DELETE FROM sessions WHERE user_id=$1 AND expires_at<=clock_timestamp();
|
||||
-- name: InsertSession :one
|
||||
INSERT INTO sessions(token_hash,user_id,expires_at)
|
||||
SELECT $1,$2,$3 WHERE (SELECT count(*) FROM sessions WHERE user_id=$2)<100
|
||||
RETURNING user_id;
|
||||
-- name: AuthenticateSession :one
|
||||
SELECT user_id FROM sessions WHERE token_hash=$1 AND expires_at>clock_timestamp();
|
||||
-- name: RevokeSession :exec
|
||||
DELETE FROM sessions WHERE token_hash=$1;
|
||||
@@ -0,0 +1,12 @@
|
||||
-- name: ReserveKey :one
|
||||
INSERT INTO idempotency(user_id,chat_id,key,payload_hash,message_id,expires_at)
|
||||
VALUES($1,$2,$3,$4,$5,clock_timestamp()+interval '24 hours')
|
||||
ON CONFLICT(user_id,chat_id,key) DO UPDATE SET payload_hash=excluded.payload_hash,
|
||||
message_id=excluded.message_id,expires_at=excluded.expires_at
|
||||
WHERE idempotency.expires_at<=clock_timestamp()
|
||||
RETURNING message_id;
|
||||
-- name: ReplayMessage :one
|
||||
SELECT m.id,m.chat_id,m.sender_id,m.text,m.created_at,i.payload_hash,
|
||||
ARRAY(SELECT attachment_id FROM message_attachments WHERE message_id=m.id ORDER BY ordinal LIMIT 10)::uuid[] AS attachment_ids
|
||||
FROM idempotency i JOIN messages m ON m.id=i.message_id
|
||||
WHERE i.user_id=$1 AND i.chat_id=$2 AND i.key=$3;
|
||||
@@ -0,0 +1,16 @@
|
||||
version: '2'
|
||||
sql:
|
||||
- schema: ../migrations
|
||||
queries: queries
|
||||
engine: postgresql
|
||||
gen:
|
||||
go:
|
||||
package: queries
|
||||
out: ../../internal/adapter/repository/postgres/queries
|
||||
sql_package: pgx/v5
|
||||
emit_empty_slices: true
|
||||
overrides:
|
||||
- db_type: uuid
|
||||
go_type: github.com/google/uuid.UUID
|
||||
- db_type: timestamptz
|
||||
go_type: time.Time
|
||||
@@ -0,0 +1,15 @@
|
||||
overlay: 1.0.0
|
||||
info:
|
||||
title: Go DTO generation view; normative contract remains unchanged
|
||||
version: 1.0.0
|
||||
actions:
|
||||
# oapi-codegen 2.8 emits duplicate Body fields for two binary MIME types.
|
||||
# The adapter reads the original bounded request stream and validates both types.
|
||||
- target: $.paths['/api/v1/chats/{chat_id}/attachments'].post.requestBody.content['image/jpeg']
|
||||
remove: true
|
||||
# anyOf expresses runtime requirements, not different Go representations.
|
||||
# The domain enforces text-or-attachments; the adapter keeps strict JSON decoding.
|
||||
- target: $.components.schemas.CreateMessage.anyOf
|
||||
remove: true
|
||||
- target: $.components.schemas.Message.anyOf
|
||||
remove: true
|
||||
+331
@@ -0,0 +1,331 @@
|
||||
module backend
|
||||
|
||||
go 1.27.2
|
||||
|
||||
tool (
|
||||
github.com/golangci/golangci-lint/v2/cmd/golangci-lint
|
||||
github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen
|
||||
github.com/pressly/goose/v3/cmd/goose
|
||||
github.com/sqlc-dev/sqlc/cmd/sqlc
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/go-chi/chi/v5 v5.5.0
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/oapi-codegen/runtime v1.7.0
|
||||
github.com/rs/zerolog v1.35.1
|
||||
github.com/spf13/viper v1.21.0
|
||||
)
|
||||
|
||||
require (
|
||||
4d63.com/gocheckcompilerdirectives v1.4.0 // indirect
|
||||
4d63.com/gochecknoglobals v0.2.2 // indirect
|
||||
cel.dev/expr v0.25.3 // indirect
|
||||
charm.land/lipgloss/v2 v2.0.6 // indirect
|
||||
codeberg.org/chavacava/garif v0.2.1 // indirect
|
||||
codeberg.org/polyfloyd/go-errorlint v1.9.0 // indirect
|
||||
dev.gaijin.team/go/exhaustruct/v4 v4.0.0 // indirect
|
||||
dev.gaijin.team/go/exhaustruct/v5 v5.2.0 // indirect
|
||||
dev.gaijin.team/go/golib v0.8.1 // indirect
|
||||
filippo.io/edwards25519 v1.2.0 // indirect
|
||||
github.com/4meepo/tagalign v1.4.4 // indirect
|
||||
github.com/Abirdcfly/dupword v0.1.8 // indirect
|
||||
github.com/AdminBenni/iota-mixing v1.0.0 // indirect
|
||||
github.com/AlwxSin/noinlineerr v1.0.6 // indirect
|
||||
github.com/Antonboom/errname v1.1.2 // indirect
|
||||
github.com/Antonboom/nilnil v1.1.2 // indirect
|
||||
github.com/Antonboom/testifylint v1.6.4 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.24.0 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.15.0 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.13.0 // indirect
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.10.1 // indirect
|
||||
github.com/BurntSushi/toml v1.6.0 // indirect
|
||||
github.com/ClickHouse/ch-go v0.75.0 // indirect
|
||||
github.com/ClickHouse/clickhouse-go-linter v1.2.1 // indirect
|
||||
github.com/ClickHouse/clickhouse-go/v2 v2.51.0 // indirect
|
||||
github.com/Djarvur/go-err113 v0.1.1 // indirect
|
||||
github.com/Masterminds/semver/v3 v3.5.0 // indirect
|
||||
github.com/MirrexOne/unqueryvet v1.5.4 // indirect
|
||||
github.com/OpenPeeDeeP/depguard/v2 v2.2.1 // indirect
|
||||
github.com/alecthomas/chroma/v2 v2.27.0 // indirect
|
||||
github.com/alecthomas/go-check-sumtype v0.5.1-0.20260828200218-ae6904d28606 // indirect
|
||||
github.com/alexkohler/nakedret/v2 v2.0.6 // indirect
|
||||
github.com/alexkohler/prealloc v1.1.0 // indirect
|
||||
github.com/alfatraining/structtag v1.0.0 // indirect
|
||||
github.com/alingse/asasalint v0.0.11 // indirect
|
||||
github.com/alingse/nilnesserr v0.2.0 // indirect
|
||||
github.com/andybalholm/brotli v1.3.0 // indirect
|
||||
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
|
||||
github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect
|
||||
github.com/ashanbrown/forbidigo/v2 v2.3.1 // indirect
|
||||
github.com/ashanbrown/makezero/v2 v2.2.1 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/bkielbasa/cyclop v1.2.3 // indirect
|
||||
github.com/blizzy78/varnamelen v0.8.0 // indirect
|
||||
github.com/bombsimon/wsl/v4 v4.7.0 // indirect
|
||||
github.com/bombsimon/wsl/v5 v5.9.0 // indirect
|
||||
github.com/breml/bidichk v0.3.3 // indirect
|
||||
github.com/breml/errchkjson v0.4.1 // indirect
|
||||
github.com/butuzov/ireturn v0.4.1 // indirect
|
||||
github.com/butuzov/mirror v1.3.3 // indirect
|
||||
github.com/catenacyber/perfsprint v0.10.1 // indirect
|
||||
github.com/ccojocar/zxcvbn-go v1.0.4 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/charithe/durationcheck v0.0.11 // indirect
|
||||
github.com/charmbracelet/colorprofile v0.4.3 // indirect
|
||||
github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 // indirect
|
||||
github.com/charmbracelet/x/ansi v0.11.8 // indirect
|
||||
github.com/charmbracelet/x/term v0.2.2 // indirect
|
||||
github.com/charmbracelet/x/termios v0.1.1 // indirect
|
||||
github.com/charmbracelet/x/windows v0.2.2 // indirect
|
||||
github.com/ckaznocha/intrange v0.3.1 // indirect
|
||||
github.com/clipperhouse/displaywidth v0.11.0 // indirect
|
||||
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
|
||||
github.com/coder/websocket v1.8.15 // indirect
|
||||
github.com/coreos/go-semver v0.3.1 // indirect
|
||||
github.com/cubicdaiya/gonp v1.0.4 // indirect
|
||||
github.com/curioswitch/go-reassign v0.3.0 // indirect
|
||||
github.com/daixiang0/gci v0.13.7 // indirect
|
||||
github.com/dave/dst v0.27.3 // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/denis-tingaikin/go-header v0.5.0 // indirect
|
||||
github.com/dlclark/regexp2/v2 v2.2.1 // indirect
|
||||
github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936 // indirect
|
||||
github.com/dustin/go-humanize v1.1.0 // indirect
|
||||
github.com/elastic/go-sysinfo v1.15.5 // indirect
|
||||
github.com/elastic/go-windows v1.0.2 // indirect
|
||||
github.com/ettle/strcase v0.2.0 // indirect
|
||||
github.com/fatih/color v1.19.0 // indirect
|
||||
github.com/fatih/structtag v1.2.0 // indirect
|
||||
github.com/firefart/nonamedreturns v1.0.8 // indirect
|
||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||
github.com/fzipp/gocyclo v0.6.0 // indirect
|
||||
github.com/getkin/kin-openapi v0.142.0 // indirect
|
||||
github.com/ghostiam/protogetter v1.0.1 // indirect
|
||||
github.com/go-critic/go-critic v0.15.0 // indirect
|
||||
github.com/go-faster/city v1.0.1 // indirect
|
||||
github.com/go-faster/errors v0.8.0 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.23.1 // indirect
|
||||
github.com/go-openapi/swag/jsonname v0.26.0 // indirect
|
||||
github.com/go-sql-driver/mysql v1.10.1 // indirect
|
||||
github.com/go-toolsmith/astcast v1.1.0 // indirect
|
||||
github.com/go-toolsmith/astcopy v1.1.0 // indirect
|
||||
github.com/go-toolsmith/astequal v1.2.0 // indirect
|
||||
github.com/go-toolsmith/astfmt v1.1.0 // indirect
|
||||
github.com/go-toolsmith/astp v1.1.0 // indirect
|
||||
github.com/go-toolsmith/strparse v1.1.0 // indirect
|
||||
github.com/go-toolsmith/typep v1.1.0 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
|
||||
github.com/go-xmlfmt/xmlfmt v1.1.3 // indirect
|
||||
github.com/gobwas/glob v0.2.3 // indirect
|
||||
github.com/godoc-lint/godoc-lint v0.11.4 // indirect
|
||||
github.com/gofrs/flock v0.13.1 // indirect
|
||||
github.com/golang-jwt/jwt/v4 v4.5.2 // indirect
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
|
||||
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // indirect
|
||||
github.com/golang-sql/sqlexp v0.1.0 // indirect
|
||||
github.com/golang/protobuf v1.5.4 // indirect
|
||||
github.com/golangci/asciicheck v0.5.0 // indirect
|
||||
github.com/golangci/canonicalheader v0.0.0-20260827115959-a25c71c521f6 // indirect
|
||||
github.com/golangci/dupl v0.0.0-20260401084720-c99c5cf5c202 // indirect
|
||||
github.com/golangci/go-printf-func-name v0.1.1 // indirect
|
||||
github.com/golangci/gofmt v0.0.0-20260820135601-e84e05053792 // indirect
|
||||
github.com/golangci/golangci-lint/v2 v2.14.0 // indirect
|
||||
github.com/golangci/golines v0.15.0 // indirect
|
||||
github.com/golangci/misspell v0.8.0 // indirect
|
||||
github.com/golangci/plugin-module-register v0.1.2 // indirect
|
||||
github.com/golangci/revgrep v0.8.0 // indirect
|
||||
github.com/golangci/rowserrcheck v0.0.0-20260419091836-c5f79b8a11ba // indirect
|
||||
github.com/golangci/swaggoswag v0.0.0-20250504205917-77f2aca3143e // indirect
|
||||
github.com/golangci/unconvert v0.0.0-20250410112200-a129a6e6413e // indirect
|
||||
github.com/google/cel-go v0.28.0 // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/gordonklaus/ineffassign v0.2.0 // indirect
|
||||
github.com/gostaticanalysis/analysisutil v0.7.1 // indirect
|
||||
github.com/gostaticanalysis/comment v1.5.0 // indirect
|
||||
github.com/gostaticanalysis/forcetypeassert v0.2.0 // indirect
|
||||
github.com/gostaticanalysis/nilerr v0.1.2 // indirect
|
||||
github.com/hashicorp/go-immutable-radix/v2 v2.1.0 // indirect
|
||||
github.com/hashicorp/go-version v1.9.0 // indirect
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
|
||||
github.com/hexops/gotextdiff v1.0.3 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/pgx/v5 v5.13.0 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.3 // indirect
|
||||
github.com/jgautheron/goconst v1.11.0 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jjti/go-spancheck v0.6.5 // indirect
|
||||
github.com/joho/godotenv v1.5.1 // indirect
|
||||
github.com/jonboulle/clockwork v0.5.0 // indirect
|
||||
github.com/julz/importas v0.2.0 // indirect
|
||||
github.com/karamaru-alpha/copyloopvar v1.2.2 // indirect
|
||||
github.com/kisielk/errcheck v1.20.0 // indirect
|
||||
github.com/kkHAIKE/contextcheck v1.1.6 // indirect
|
||||
github.com/klauspost/compress v1.20.4 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 // indirect
|
||||
github.com/klauspost/crc32 v1.3.0 // indirect
|
||||
github.com/kulti/thelper v0.7.1 // indirect
|
||||
github.com/kunwardeep/paralleltest v1.0.15 // indirect
|
||||
github.com/kylelemons/godebug v1.1.0 // indirect
|
||||
github.com/ldez/exptostd v0.4.5 // indirect
|
||||
github.com/ldez/gomoddirectives v0.10.0 // indirect
|
||||
github.com/ldez/grignotin v0.10.1 // indirect
|
||||
github.com/ldez/structtags v0.6.1 // indirect
|
||||
github.com/ldez/tagliatelle v0.8.0 // indirect
|
||||
github.com/ldez/usetesting v0.5.0 // indirect
|
||||
github.com/leonklingele/grouper v1.1.2 // indirect
|
||||
github.com/lucasb-eyer/go-colorful v1.4.1 // indirect
|
||||
github.com/macabu/inamedparam v0.2.0 // indirect
|
||||
github.com/manuelarte/embeddedstructfieldcheck v0.4.0 // indirect
|
||||
github.com/manuelarte/funcorder v0.6.0 // indirect
|
||||
github.com/maratori/testableexamples v1.0.1 // indirect
|
||||
github.com/maratori/testpackage v1.1.2 // indirect
|
||||
github.com/matoous/godox v1.1.0 // indirect
|
||||
github.com/mattn/go-colorable v0.1.15 // indirect
|
||||
github.com/mattn/go-isatty v0.0.24 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.24 // indirect
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
|
||||
github.com/mfridman/interpolate v0.0.2 // indirect
|
||||
github.com/mfridman/xflag v0.1.0 // indirect
|
||||
github.com/mgechev/revive v1.17.0 // indirect
|
||||
github.com/microsoft/go-mssqldb v1.11.2 // indirect
|
||||
github.com/minio/crc64nvme v1.1.1 // indirect
|
||||
github.com/minio/md5-simd v1.1.2 // indirect
|
||||
github.com/minio/minio-go/v7 v7.4.1 // indirect
|
||||
github.com/mitchellh/go-homedir v1.1.0 // indirect
|
||||
github.com/moricho/tparallel v0.3.2 // indirect
|
||||
github.com/muesli/cancelreader v0.2.2 // indirect
|
||||
github.com/nakabonne/nestif v0.3.1 // indirect
|
||||
github.com/ncruces/go-sqlite3 v0.32.0 // indirect
|
||||
github.com/ncruces/go-strftime v1.1.0 // indirect
|
||||
github.com/ncruces/julianday v1.0.0 // indirect
|
||||
github.com/nishanths/exhaustive v0.13.0 // indirect
|
||||
github.com/nishanths/predeclared v0.2.2 // indirect
|
||||
github.com/nunnatsa/ginkgolinter v0.24.0 // indirect
|
||||
github.com/oapi-codegen/oapi-codegen/v2 v2.8.0 // indirect
|
||||
github.com/oasdiff/yaml v0.1.1 // indirect
|
||||
github.com/oasdiff/yaml3 v0.0.14 // indirect
|
||||
github.com/paulmach/orb v0.14.0 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.4.3 // indirect
|
||||
github.com/pganalyze/pg_query_go/v6 v6.2.2 // indirect
|
||||
github.com/philhofer/fwd v1.2.0 // indirect
|
||||
github.com/pierrec/lz4/v4 v4.1.33 // indirect
|
||||
github.com/pingcap/errors v0.11.5-0.20250523034308-74f78ae071ee // indirect
|
||||
github.com/pingcap/failpoint v0.0.0-20240528011301-b51a646c7c86 // indirect
|
||||
github.com/pingcap/log v1.1.0 // indirect
|
||||
github.com/pingcap/tidb/pkg/parser v0.0.0-20260418072757-ce92298d1124 // indirect
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
|
||||
github.com/pressly/goose/v3 v3.30.0 // indirect
|
||||
github.com/prometheus/client_golang v1.12.1 // indirect
|
||||
github.com/prometheus/client_model v0.2.0 // indirect
|
||||
github.com/prometheus/common v0.32.1 // indirect
|
||||
github.com/prometheus/procfs v0.23.0 // indirect
|
||||
github.com/quasilyte/go-ruleguard v0.4.5 // indirect
|
||||
github.com/quasilyte/go-ruleguard/dsl v0.3.23 // indirect
|
||||
github.com/quasilyte/gogrep v0.5.0 // indirect
|
||||
github.com/quasilyte/regex/syntax v0.0.0-20210819130434-b3f0c404a727 // indirect
|
||||
github.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567 // indirect
|
||||
github.com/raeperd/recvcheck v0.3.1 // indirect
|
||||
github.com/redis/go-redis/v9 v9.23.0 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
github.com/riza-io/grpc-go v0.2.0 // indirect
|
||||
github.com/rogpeppe/go-internal v1.16.0 // indirect
|
||||
github.com/rs/xid v1.6.0 // indirect
|
||||
github.com/ryancurrah/gomodguard v1.4.1 // indirect
|
||||
github.com/ryancurrah/gomodguard/v2 v2.1.3 // indirect
|
||||
github.com/ryanrolds/sqlclosecheck v0.6.0 // indirect
|
||||
github.com/sagikazarmark/locafero v0.11.0 // indirect
|
||||
github.com/sanposhiho/wastedassign/v2 v2.1.0 // indirect
|
||||
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect
|
||||
github.com/sashamelentyev/interfacebloat v1.1.0 // indirect
|
||||
github.com/sashamelentyev/usestdlibvars v1.29.0 // indirect
|
||||
github.com/securego/gosec/v2 v2.29.0 // indirect
|
||||
github.com/segmentio/asm v1.2.1 // indirect
|
||||
github.com/sethvargo/go-retry v0.5.0 // indirect
|
||||
github.com/shopspring/decimal v1.6.0 // indirect
|
||||
github.com/sirupsen/logrus v1.10.2 // indirect
|
||||
github.com/sivchari/containedctx v1.0.3 // indirect
|
||||
github.com/sonatard/noctx v0.5.1 // indirect
|
||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
|
||||
github.com/sourcegraph/go-diff v0.9.0 // indirect
|
||||
github.com/speakeasy-api/jsonpath v0.6.3 // indirect
|
||||
github.com/speakeasy-api/openapi v1.24.0 // indirect
|
||||
github.com/spf13/afero v1.15.0 // indirect
|
||||
github.com/spf13/cast v1.10.0 // indirect
|
||||
github.com/spf13/cobra v1.10.2 // indirect
|
||||
github.com/spf13/pflag v1.0.10 // indirect
|
||||
github.com/sqlc-dev/doubleclick v1.0.0 // indirect
|
||||
github.com/sqlc-dev/sqlc v1.31.1 // indirect
|
||||
github.com/ssgreg/nlreturn/v2 v2.2.1 // indirect
|
||||
github.com/stbenjam/no-sprintf-host-port v0.3.1 // indirect
|
||||
github.com/stretchr/objx v0.5.3 // indirect
|
||||
github.com/stretchr/testify v1.12.1 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/tetafro/godot v1.5.6 // indirect
|
||||
github.com/tetratelabs/wazero v1.11.0 // indirect
|
||||
github.com/timakin/bodyclose v0.0.0-20260723120731-857993a2939c // indirect
|
||||
github.com/timonwong/loggercheck v0.12.0 // indirect
|
||||
github.com/tinylib/msgp v1.6.4 // indirect
|
||||
github.com/tomarrell/wrapcheck/v2 v2.12.0 // indirect
|
||||
github.com/tommy-muehle/go-mnd/v2 v2.5.1 // indirect
|
||||
github.com/tursodatabase/libsql-client-go v0.0.0-20260528064733-9d5d30a29a60 // indirect
|
||||
github.com/ultraware/funlen v0.2.0 // indirect
|
||||
github.com/ultraware/whitespace v0.2.0 // indirect
|
||||
github.com/uudashr/gocognit v1.2.1 // indirect
|
||||
github.com/uudashr/iface v1.5.1 // indirect
|
||||
github.com/vertica/vertica-sql-go v1.3.9 // indirect
|
||||
github.com/vmware-labs/yaml-jsonpath v0.3.2 // indirect
|
||||
github.com/wasilibs/go-pgquery v0.0.0-20250409022910-10ac41983c07 // indirect
|
||||
github.com/wasilibs/wazero-helpers v0.0.0-20240620070341-3dff1577cd52 // indirect
|
||||
github.com/xen0n/gosmopolitan v1.3.0 // indirect
|
||||
github.com/xo/terminfo v1.0.0 // indirect
|
||||
github.com/yagipy/maintidx v1.0.0 // indirect
|
||||
github.com/yandex-cloud/go-genproto v0.137.0 // indirect
|
||||
github.com/ydb-platform/ydb-go-genproto v0.0.0-20260810123728-f0c151ab31b9 // indirect
|
||||
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.3 // indirect
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.156.1 // indirect
|
||||
github.com/ydb-platform/ydb-go-yc v0.12.5 // indirect
|
||||
github.com/ydb-platform/ydb-go-yc-metadata v0.6.2 // indirect
|
||||
github.com/yeya24/promlinter v0.3.0 // indirect
|
||||
github.com/ykadowak/zerologlint v0.1.5 // indirect
|
||||
github.com/zeebo/xxh3 v1.1.0 // indirect
|
||||
github.com/ziutek/mymysql v1.5.4 // indirect
|
||||
gitlab.com/bosi/decorder v0.4.2 // indirect
|
||||
go-simpler.org/musttag v0.14.0 // indirect
|
||||
go-simpler.org/sloglint v0.12.0 // indirect
|
||||
go.augendre.info/arangolint v0.4.0 // indirect
|
||||
go.augendre.info/fatcontext v0.10.1 // indirect
|
||||
go.opentelemetry.io/otel v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.47.0 // indirect
|
||||
go.uber.org/atomic v1.12.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap v1.28.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.6 // indirect
|
||||
golang.org/x/crypto v0.59.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20261109185158-a52e3aef5920 // indirect
|
||||
golang.org/x/exp/typeparams v0.0.0-20260811152304-ee035b5b010f // indirect
|
||||
golang.org/x/mod v0.42.0 // indirect
|
||||
golang.org/x/net v0.62.0 // indirect
|
||||
golang.org/x/sync v0.25.0 // indirect
|
||||
golang.org/x/sys v0.50.0 // indirect
|
||||
golang.org/x/text v0.44.0 // indirect
|
||||
golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20261110000943-09e21b237f2c // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c // indirect
|
||||
google.golang.org/grpc v1.85.0 // indirect
|
||||
google.golang.org/protobuf v1.36.12 // indirect
|
||||
gopkg.in/ini.v1 v1.67.3 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
honnef.co/go/tools v0.8.1 // indirect
|
||||
howett.net/plist v1.0.1 // indirect
|
||||
modernc.org/libc v1.80.2 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.12.1 // indirect
|
||||
modernc.org/sqlite v1.62.0 // indirect
|
||||
mvdan.cc/gofumpt v0.12.0 // indirect
|
||||
mvdan.cc/unparam v0.0.0-20260823230713-2fa3d841b0c8 // indirect
|
||||
)
|
||||
+1302
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,100 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"backend/internal/adapter/repository/postgres"
|
||||
"backend/internal/adapter/storage"
|
||||
"backend/internal/config"
|
||||
"backend/internal/domain/model"
|
||||
"bytes"
|
||||
"context"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"os"
|
||||
"os/exec"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestFixtureCleanupRejectsForeignMembership(t *testing.T) {
|
||||
if os.Getenv("RUN_ISOLATED_RECONCILIATION") != "1" {
|
||||
t.Skip("explicit isolated stand required")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
dsn, e := config.ReadSecret("/run/secrets/database_url")
|
||||
if e != nil {
|
||||
t.Fatal("database configuration unavailable")
|
||||
}
|
||||
pool, e := pgxpool.New(ctx, dsn)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer pool.Close()
|
||||
c, e := storage.ReadConfig("/run/secrets/s3_credentials")
|
||||
if e != nil {
|
||||
t.Fatal("S3 configuration unavailable")
|
||||
}
|
||||
objects, e := storage.FromConfig(c)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
repo := postgres.New(pool, nil)
|
||||
prefix := "st_" + uuid.NewString()[:8] + uuid.NewString()[:8]
|
||||
own, e := repo.CreateUser(ctx, model.UserDraft{Username: prefix, DisplayName: "Fixture owner", PasswordHash: "disabled-test-account"})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
foreign, e := repo.CreateUser(ctx, model.UserDraft{Username: "other_" + uuid.NewString()[:8], DisplayName: "Independent test user", PasswordHash: "disabled-test-account"})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
draft, e := model.NewChatDraft(foreign.ID, "Foreign-owned fixture boundary", []uuid.UUID{foreign.ID, own.ID})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
chat, e := repo.CreateChat(ctx, draft)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
id := uuid.New()
|
||||
key := "originals/" + id.String()
|
||||
defer func() {
|
||||
clean, cancelClean := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancelClean()
|
||||
for _, statement := range []string{`DELETE FROM attachments WHERE id=$1`, `DELETE FROM chat_members WHERE chat_id=$1`, `DELETE FROM chats WHERE id=$1`} {
|
||||
arg := any(chat.ID)
|
||||
if statement == `DELETE FROM attachments WHERE id=$1` {
|
||||
arg = id
|
||||
}
|
||||
if _, err := pool.Exec(clean, statement, arg); err != nil {
|
||||
t.Error("boundary fixture cleanup failed")
|
||||
}
|
||||
}
|
||||
if _, err := pool.Exec(clean, `DELETE FROM users WHERE id=ANY($1::uuid[])`, []uuid.UUID{own.ID, foreign.ID}); err != nil {
|
||||
t.Error("boundary users cleanup failed")
|
||||
}
|
||||
if err := objects.Remove(clean, key); err != nil {
|
||||
t.Error("boundary original cleanup failed")
|
||||
}
|
||||
}()
|
||||
_, e = repo.ReserveAttachment(ctx, model.Attachment{ID: id, ChatID: chat.ID, OwnerID: own.ID, Filename: "owned.png", ContentType: "image/png", SizeBytes: 3, SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = objects.Put(ctx, key, bytes.NewReader([]byte("abc")), 3, "image/png"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = exec.CommandContext(ctx, "/fixture-cleanup", prefix).Run(); e == nil {
|
||||
t.Fatal("cleanup accepted a fixture referenced by another owner")
|
||||
}
|
||||
if _, e = objects.Stat(ctx, key); e != nil {
|
||||
t.Fatal("rejected cleanup removed the original")
|
||||
}
|
||||
if _, e = repo.GetAttachment(ctx, id); e != nil {
|
||||
t.Fatal("rejected cleanup removed metadata")
|
||||
}
|
||||
remaining, e := repo.GetChat(ctx, chat.ID)
|
||||
if e != nil || !remaining.HasMember(own.ID) || !remaining.HasMember(foreign.ID) {
|
||||
t.Fatal("rejected cleanup changed another user's chat")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"backend/internal/adapter/storage"
|
||||
"backend/internal/domain/port"
|
||||
"bytes"
|
||||
"context"
|
||||
"github.com/google/uuid"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestS3InventoryAndStatReturnComparableVersionMetadata(t *testing.T) {
|
||||
if os.Getenv("RUN_ISOLATED_RECONCILIATION") != "1" {
|
||||
t.Skip("explicit isolated stand required")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
cfg, e := storage.ReadConfig("/run/secrets/s3_credentials")
|
||||
if e != nil {
|
||||
t.Fatal("configuration unavailable")
|
||||
}
|
||||
s, e := storage.FromConfig(cfg)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
key := "originals/" + uuid.NewString()
|
||||
defer func() {
|
||||
if err := s.Remove(context.Background(), key); err != nil {
|
||||
t.Error("object fixture cleanup failed")
|
||||
}
|
||||
}()
|
||||
if e = s.Put(ctx, key, bytes.NewReader([]byte("synthetic-version-probe")), 23, "application/octet-stream"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
stat, e := s.Stat(ctx, key)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var listed port.Object
|
||||
after := ""
|
||||
found := false
|
||||
for page := 0; page < 10; page++ {
|
||||
rows, more, e := s.List(ctx, after)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for _, row := range rows {
|
||||
if row.Key == key {
|
||||
listed = row
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if found || !more {
|
||||
break
|
||||
}
|
||||
after = rows[len(rows)-1].Key
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("own object absent from bounded inventory")
|
||||
}
|
||||
if listed.ETag != stat.ETag || listed.Size != stat.Size || !listed.Modified.Equal(stat.Modified) {
|
||||
t.Fatalf("inconsistent version metadata: etag_equal=%t size_equal=%t list_time=%s stat_time=%s", listed.ETag == stat.ETag, listed.Size == stat.Size, listed.Modified.Format(time.RFC3339Nano), stat.Modified.Format(time.RFC3339Nano))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"image"
|
||||
"image/png"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"backend/internal/adapter/password"
|
||||
"backend/internal/adapter/repository/postgres"
|
||||
"backend/internal/adapter/storage"
|
||||
"backend/internal/application/usecase"
|
||||
"backend/internal/config"
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/port"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
type countedTransport struct {
|
||||
base http.RoundTripper
|
||||
requests, bytes atomic.Int64
|
||||
}
|
||||
|
||||
func (c *countedTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
c.requests.Add(1)
|
||||
response, err := c.base.RoundTrip(r)
|
||||
if err == nil {
|
||||
response.Body = &countedBody{response.Body, &c.bytes}
|
||||
}
|
||||
return response, err
|
||||
}
|
||||
|
||||
type countedBody struct {
|
||||
io.ReadCloser
|
||||
count *atomic.Int64
|
||||
}
|
||||
|
||||
func (c *countedBody) Read(p []byte) (int, error) {
|
||||
n, e := c.ReadCloser.Read(p)
|
||||
c.count.Add(int64(n))
|
||||
return n, e
|
||||
}
|
||||
|
||||
type lostPutResponse struct{ port.Objects }
|
||||
|
||||
func (o lostPutResponse) Put(ctx context.Context, key string, r io.Reader, size int64, mime string) error {
|
||||
if e := o.Objects.Put(ctx, key, r, size, mime); e != nil {
|
||||
return e
|
||||
}
|
||||
return model.ErrUnavailable
|
||||
}
|
||||
|
||||
func TestReconciliationAgainstPostgresAndPrivateS3(t *testing.T) {
|
||||
if os.Getenv("RUN_ISOLATED_RECONCILIATION") != "1" {
|
||||
t.Skip("explicit isolated Compose integration stand required")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second)
|
||||
defer cancel()
|
||||
dsn, e := config.ReadSecret("/run/secrets/database_url")
|
||||
if e != nil {
|
||||
t.Fatal("database configuration unavailable")
|
||||
}
|
||||
pool, e := pgxpool.New(ctx, dsn)
|
||||
if e != nil {
|
||||
t.Fatal("database connection failed")
|
||||
}
|
||||
defer pool.Close()
|
||||
c, e := storage.ReadConfig("/run/secrets/s3_credentials")
|
||||
if e != nil {
|
||||
t.Fatal("S3 configuration unavailable")
|
||||
}
|
||||
counter := &countedTransport{base: &http.Transport{ResponseHeaderTimeout: 3 * time.Second}}
|
||||
native, e := minio.New(c.Endpoint, &minio.Options{Creds: credentials.NewStaticV4(c.Access, c.Secret, ""), Secure: false, Region: "us-east-1", Transport: counter})
|
||||
if e != nil {
|
||||
t.Fatal("S3 client initialization failed")
|
||||
}
|
||||
objects := &storage.S3{Client: native, Bucket: c.Bucket}
|
||||
var existing int
|
||||
if e = pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM users)+(SELECT count(*) FROM chats)+(SELECT count(*) FROM attachments)`).Scan(&existing); e != nil || existing != 0 {
|
||||
t.Fatal("destructive integration requires an empty disposable database")
|
||||
}
|
||||
inventory, _, e := objects.List(ctx, "")
|
||||
if e != nil || len(inventory) != 0 {
|
||||
t.Fatal("destructive integration requires an empty disposable bucket")
|
||||
}
|
||||
// RustFS can list authorized bucket names without global bucket-list privileges.
|
||||
// Verify the concrete forbidden write using a fresh test-owned name.
|
||||
deniedBucket := "forbidden-" + uuid.NewString()
|
||||
if e = native.MakeBucket(ctx, deniedBucket, minio.MakeBucketOptions{Region: "us-east-1"}); minio.ToErrorResponse(e).Code != "AccessDenied" {
|
||||
if e == nil {
|
||||
_ = native.RemoveBucket(ctx, deniedBucket)
|
||||
}
|
||||
t.Fatal("application identity did not reject creating an unrelated bucket")
|
||||
}
|
||||
repo := postgres.New(pool, nil)
|
||||
app := usecase.NewMessenger(repo)
|
||||
prefix := "st_" + uuid.NewString()[:8] + uuid.NewString()[:8]
|
||||
draft, e := model.NewUserDraft(prefix, "Synthetic reconciliation")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
draft.PasswordHash, e = password.New().Hash("synthetic-only-password")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
user, e := repo.CreateUser(ctx, draft)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
chatDraft, e := model.NewChatDraft(user.ID, "Synthetic reconciliation", []uuid.UUID{user.ID})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
chat, e := repo.CreateChat(ctx, chatDraft)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var imageBytes bytes.Buffer
|
||||
if e = png.Encode(&imageBytes, image.NewNRGBA(image.Rect(0, 0, 3, 2))); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
raw := imageBytes.Bytes()
|
||||
sum := sha256.Sum256(raw)
|
||||
sha := hex.EncodeToString(sum[:])
|
||||
ownObjects := []uuid.UUID{}
|
||||
defer func() {
|
||||
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cleanupCancel()
|
||||
for _, id := range ownObjects {
|
||||
if err := objects.Remove(cleanupCtx, usecase.ObjectKey(id)); err != nil {
|
||||
t.Errorf("S3 fixture cleanup failed")
|
||||
}
|
||||
}
|
||||
statements := []string{
|
||||
`DELETE FROM message_attachments WHERE message_id IN (SELECT id FROM messages WHERE sender_id=$1)`,
|
||||
`DELETE FROM idempotency WHERE user_id=$1`,
|
||||
`DELETE FROM messages WHERE sender_id=$1`,
|
||||
`DELETE FROM sessions WHERE user_id=$1`,
|
||||
`DELETE FROM attachments WHERE owner_id=$1`,
|
||||
`DELETE FROM chat_members WHERE user_id=$1`,
|
||||
}
|
||||
for _, statement := range statements {
|
||||
if _, err := pool.Exec(cleanupCtx, statement, user.ID); err != nil {
|
||||
t.Errorf("PostgreSQL fixture cleanup failed")
|
||||
}
|
||||
}
|
||||
if _, err := pool.Exec(cleanupCtx, `DELETE FROM chats WHERE id=$1`, chat.ID); err != nil {
|
||||
t.Errorf("chat cleanup failed")
|
||||
}
|
||||
if _, err := pool.Exec(cleanupCtx, `DELETE FROM users WHERE id=$1`, user.ID); err != nil {
|
||||
t.Errorf("user cleanup failed")
|
||||
}
|
||||
}()
|
||||
reserve := func(name string) model.Attachment {
|
||||
t.Helper()
|
||||
id := uuid.New()
|
||||
ownObjects = append(ownObjects, id)
|
||||
a, err := repo.ReserveAttachment(ctx, model.Attachment{ID: id, ChatID: chat.ID, OwnerID: user.ID, Filename: name, ContentType: "image/png", SizeBytes: int64(len(raw)), SHA256: sha})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return a
|
||||
}
|
||||
put := func(id uuid.UUID) {
|
||||
t.Helper()
|
||||
if err := objects.Put(ctx, usecase.ObjectKey(id), bytes.NewReader(raw), int64(len(raw)), "image/png"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
ready := func(a model.Attachment) {
|
||||
t.Helper()
|
||||
if _, err := repo.SetAttachmentStatus(ctx, a.ID, "uploading", "ready"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
orphan := uuid.New()
|
||||
ownObjects = append(ownObjects, orphan)
|
||||
put(orphan)
|
||||
used := reserve("used.png")
|
||||
put(used.ID)
|
||||
ready(used)
|
||||
if _, e = app.SendMessage(ctx, user.ID, chat.ID, "", uuid.NewString(), []uuid.UUID{used.ID}); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
missing := reserve("missing.png")
|
||||
put(missing.ID)
|
||||
ready(missing)
|
||||
if _, e = app.SendMessage(ctx, user.ID, chat.ID, "", uuid.NewString(), []uuid.UUID{missing.ID}); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = objects.Remove(ctx, usecase.ObjectKey(missing.ID)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
// A real DB trigger injects a failed finalization after the original is stored.
|
||||
triggerName := "fixture_" + uuid.NewString()[:8]
|
||||
_, e = pool.Exec(ctx, `CREATE FUNCTION `+triggerName+`() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.owner_id='`+user.ID.String()+`'::uuid AND NEW.filename='db-failure.png' THEN RAISE EXCEPTION 'synthetic finalization failure'; END IF;RETURN NEW;END;$$;CREATE TRIGGER `+triggerName+` BEFORE UPDATE ON attachments FOR EACH ROW EXECUTE FUNCTION `+triggerName+`();`)
|
||||
if e != nil {
|
||||
t.Fatal("failure injection setup failed")
|
||||
}
|
||||
removeTrigger := func() {
|
||||
if _, err := pool.Exec(context.Background(), `DROP TRIGGER IF EXISTS `+triggerName+` ON attachments;DROP FUNCTION IF EXISTS `+triggerName+`();`); err != nil {
|
||||
t.Error("failure trigger cleanup failed")
|
||||
}
|
||||
}
|
||||
defer removeTrigger()
|
||||
uploader := usecase.NewAttachments(repo, app, objects)
|
||||
if _, e = uploader.Upload(ctx, user.ID, chat.ID, "db-failure.png", "image/png", sha, int64(len(raw)), bytes.NewReader(raw)); !errors.Is(e, model.ErrUnavailable) {
|
||||
t.Fatal("failed DB finalization was not reported")
|
||||
}
|
||||
removeTrigger()
|
||||
var pending uuid.UUID
|
||||
if e = pool.QueryRow(ctx, `SELECT id FROM attachments WHERE owner_id=$1 AND filename='db-failure.png'`, user.ID).Scan(&pending); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
ownObjects = append(ownObjects, pending)
|
||||
pendingMissing := reserve("interrupted.png")
|
||||
// Lost response after an actual S3 PUT is injected at the explicit port boundary.
|
||||
lost := usecase.NewAttachments(repo, app, lostPutResponse{objects})
|
||||
if _, e = lost.Upload(ctx, user.ID, chat.ID, "lost-response.png", "image/png", sha, int64(len(raw)), bytes.NewReader(raw)); !errors.Is(e, model.ErrUnavailable) {
|
||||
t.Fatal("lost PUT response did not report an error")
|
||||
}
|
||||
var lostID uuid.UUID
|
||||
if e = pool.QueryRow(ctx, `SELECT id FROM attachments WHERE owner_id=$1 AND filename='lost-response.png'`, user.ID).Scan(&lostID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
ownObjects = append(ownObjects, lostID)
|
||||
if _, e = pool.Exec(ctx, `UPDATE attachments SET created_at=clock_timestamp()-interval '10 minutes',updated_at=clock_timestamp()-interval '10 minutes' WHERE owner_id=$1`, user.ID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
t.Log("Waiting 61 seconds for the real S3 orphan to exceed the safe minimum grace period")
|
||||
select {
|
||||
case <-time.After(61 * time.Second):
|
||||
case <-ctx.Done():
|
||||
t.Fatal("integration deadline")
|
||||
}
|
||||
fresh := uuid.New()
|
||||
ownObjects = append(ownObjects, fresh)
|
||||
put(fresh)
|
||||
reconciler := usecase.NewReconciler(repo, objects, time.Now)
|
||||
counter.requests.Store(0)
|
||||
counter.bytes.Store(0)
|
||||
dry, e := reconciler.Run(ctx, uuid.Nil, "", time.Minute, false)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if dry.Orphans < 1 || dry.Missing < 1 || dry.Recovered < 2 || dry.Deleted != 0 || dry.Changed != 0 {
|
||||
t.Fatalf("unexpected dry run counts: %+v", dry)
|
||||
}
|
||||
if _, e = objects.Stat(ctx, usecase.ObjectKey(orphan)); e != nil {
|
||||
t.Fatal("dry run deleted orphan")
|
||||
}
|
||||
counter.requests.Store(0)
|
||||
counter.bytes.Store(0)
|
||||
repaired, e := reconciler.Run(ctx, uuid.Nil, "", time.Minute, true)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
requestCount, readBytes := counter.requests.Load(), counter.bytes.Load()
|
||||
if _, e = objects.Stat(ctx, usecase.ObjectKey(orphan)); !errors.Is(e, model.ErrNotFound) {
|
||||
t.Fatal("old orphan remains")
|
||||
}
|
||||
for _, id := range []uuid.UUID{used.ID, pending, lostID, fresh} {
|
||||
if _, err := objects.Stat(ctx, usecase.ObjectKey(id)); err != nil {
|
||||
t.Fatal("fresh, used or recoverable original was removed")
|
||||
}
|
||||
}
|
||||
for id, want := range map[uuid.UUID]string{used.ID: "ready", missing.ID: "missing", pending: "ready", lostID: "ready", pendingMissing.ID: "abandoned"} {
|
||||
a, err := repo.GetAttachment(ctx, id)
|
||||
if err != nil || a.Status != want {
|
||||
t.Fatalf("metadata repair differs for %s: %s", id, a.Status)
|
||||
}
|
||||
}
|
||||
if _, e = uploader.Get(ctx, user.ID, missing.ID); !errors.Is(e, model.ErrUnavailable) {
|
||||
t.Fatal("missing original remained publicly ready")
|
||||
}
|
||||
repeat, e := reconciler.Run(ctx, uuid.Nil, "", time.Minute, true)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if repeat.Deleted != 0 || repeat.Changed != 0 {
|
||||
t.Fatal("repeat repair changed settled data")
|
||||
}
|
||||
put(missing.ID)
|
||||
if _, e = reconciler.Run(ctx, uuid.Nil, "", time.Minute, true); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = uploader.Get(ctx, user.ID, missing.ID); e != nil {
|
||||
t.Fatal("restored matching original did not recover")
|
||||
}
|
||||
encoded, _ := json.Marshal(map[string]any{"dry_run": dry, "apply": repaired, "repeat": repeat, "s3_http_requests": requestCount, "s3_response_bytes": readBytes, "private_application_identity": true})
|
||||
t.Log(string(encoded))
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,111 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/google/uuid"
|
||||
"net/http"
|
||||
|
||||
"backend/internal/domain/model"
|
||||
)
|
||||
|
||||
// Реализация StrictServerInterface: вызвать use-case и перевести результат в
|
||||
// API-модели. Ошибки уходят в writeError, он один решает про HTTP-статус.
|
||||
|
||||
func (h *API) Liveness(context.Context, LivenessRequestObject) (LivenessResponseObject, error) {
|
||||
return Liveness200JSONResponse{Body: Health{Status: Ok}}, nil
|
||||
}
|
||||
|
||||
// Readiness rejects draining instances and unavailable required dependencies.
|
||||
func (h *API) Readiness(ctx context.Context, _ ReadinessRequestObject) (ReadinessResponseObject, error) {
|
||||
if !h.ready.Load() {
|
||||
return nil, errDraining
|
||||
}
|
||||
if err := h.probe(ctx); err != nil {
|
||||
return nil, model.ErrUnavailable
|
||||
}
|
||||
return Readiness200JSONResponse{Body: Health{Status: Ok}}, nil
|
||||
}
|
||||
|
||||
func (h *API) RegisterUser(ctx context.Context, req RegisterUserRequestObject) (RegisterUserResponseObject, error) {
|
||||
if req.Body.Password == nil {
|
||||
return nil, &model.ValidationError{Message: "password is required"}
|
||||
}
|
||||
user, err := h.auth.Register(ctx, req.Body.Username, req.Body.DisplayName, *req.Body.Password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return RegisterUser201JSONResponse{Body: toUser(user)}, nil
|
||||
}
|
||||
|
||||
func (h *API) CurrentUser(ctx context.Context, _ CurrentUserRequestObject) (CurrentUserResponseObject, error) {
|
||||
return CurrentUser200JSONResponse{Body: toUser(currentUser(ctx))}, nil
|
||||
}
|
||||
|
||||
func (h *API) CreateChat(ctx context.Context, req CreateChatRequestObject) (CreateChatResponseObject, error) {
|
||||
chat, err := h.app.CreateChat(ctx, currentUser(ctx).ID, req.Body.Title, req.Body.MemberIds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return CreateChat201JSONResponse{Body: toChat(chat)}, nil
|
||||
}
|
||||
|
||||
func (h *API) ListChats(ctx context.Context, req ListChatsRequestObject) (ListChatsResponseObject, error) {
|
||||
page, err := h.app.ListChats(ctx, currentUser(ctx).ID, req.Params.Limit, req.Params.Cursor)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ListChats200JSONResponse{Body: ChatPage{Items: mapAll(page.Items, toChat), NextCursor: page.NextCursor}}, nil
|
||||
}
|
||||
|
||||
func (h *API) GetChat(ctx context.Context, req GetChatRequestObject) (GetChatResponseObject, error) {
|
||||
chat, err := h.app.GetChat(ctx, currentUser(ctx).ID, req.ChatId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return GetChat200JSONResponse{Body: toChat(chat)}, nil
|
||||
}
|
||||
|
||||
func (h *API) CreateMessage(ctx context.Context, req CreateMessageRequestObject) (CreateMessageResponseObject, error) {
|
||||
r := ctx.Value(sessionRequestKey{}).(*http.Request)
|
||||
ids := []uuid.UUID{}
|
||||
if req.Body.AttachmentIds != nil {
|
||||
ids = *req.Body.AttachmentIds
|
||||
}
|
||||
msg, err := h.app.SendMessage(ctx, currentUser(ctx).ID, req.ChatId, req.Body.Text, r.Header.Get("Idempotency-Key"), ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return CreateMessage201JSONResponse{Body: toMessage(msg)}, nil
|
||||
}
|
||||
|
||||
func (h *API) ListMessages(ctx context.Context, req ListMessagesRequestObject) (ListMessagesResponseObject, error) {
|
||||
page, err := h.app.ListMessages(ctx, currentUser(ctx).ID, req.ChatId, req.Params.Limit, req.Params.Cursor)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ListMessages200JSONResponse{Body: MessagePage{Items: mapAll(page.Items, toMessage), NextCursor: page.NextCursor}}, nil
|
||||
}
|
||||
|
||||
func toUser(u model.User) User {
|
||||
return User{Id: u.ID, Username: u.Username, DisplayName: u.DisplayName, CreatedAt: Timestamp(u.CreatedAt)}
|
||||
}
|
||||
|
||||
func toChat(c model.Chat) Chat {
|
||||
return Chat{Id: c.ID, Title: c.Title, MemberIds: c.MemberIDs, CreatedAt: Timestamp(c.CreatedAt)}
|
||||
}
|
||||
|
||||
func toMessage(m model.Message) Message {
|
||||
ids := m.AttachmentIDs
|
||||
if ids == nil {
|
||||
ids = []uuid.UUID{}
|
||||
}
|
||||
return Message{Id: m.ID, ChatId: m.ChatID, SenderId: m.SenderID, Text: m.Text, CreatedAt: Timestamp(m.CreatedAt), AttachmentIds: ids}
|
||||
}
|
||||
|
||||
func mapAll[T, R any](items []T, f func(T) R) []R {
|
||||
out := make([]R, len(items))
|
||||
for i, item := range items {
|
||||
out[i] = f(item)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"backend/internal/adapter/imagefile"
|
||||
"backend/internal/domain/model"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func toAttachment(a model.Attachment) Attachment {
|
||||
return Attachment{Id: a.ID, ChatId: a.ChatID, OwnerId: a.OwnerID, Filename: a.Filename, ContentType: AttachmentContentType(a.ContentType), SizeBytes: int(a.SizeBytes), Sha256: a.SHA256, Status: AttachmentStatus("ready"), Variants: []Variant{}, ErrorCode: nil, CreatedAt: Timestamp(a.CreatedAt), UpdatedAt: Timestamp(a.UpdatedAt)}
|
||||
}
|
||||
func (h *API) UploadAttachment(ctx context.Context, req UploadAttachmentRequestObject) (UploadAttachmentResponseObject, error) {
|
||||
caller := currentUser(ctx).ID
|
||||
if _, err := h.app.GetChat(ctx, caller, req.ChatId); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
select {
|
||||
case h.uploadGate <- struct{}{}:
|
||||
defer func() { <-h.uploadGate }()
|
||||
case <-ctx.Done():
|
||||
return nil, errOverloaded
|
||||
}
|
||||
r := ctx.Value(sessionRequestKey{}).(*http.Request)
|
||||
if r.ContentLength > model.MaxImageBytes {
|
||||
return nil, errPayloadTooLarge
|
||||
}
|
||||
f, err := imagefile.Inspect(r.Body, req.Params.Filename, r.Header.Get("Content-Type"))
|
||||
if errors.Is(err, imagefile.ErrTooLarge) {
|
||||
return nil, errPayloadTooLarge
|
||||
}
|
||||
if errors.Is(err, imagefile.ErrUnsupported) {
|
||||
return nil, errUnsupportedImage
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Dispose()
|
||||
a, err := h.attachments.Upload(ctx, caller, req.ChatId, req.Params.Filename, f.ContentType, f.SHA256, f.Size, f.File)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return UploadAttachment201JSONResponse{Body: toAttachment(a)}, nil
|
||||
}
|
||||
func (h *API) GetAttachment(ctx context.Context, req GetAttachmentRequestObject) (GetAttachmentResponseObject, error) {
|
||||
a, e := h.attachments.Get(ctx, currentUser(ctx).ID, req.AttachmentId)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return GetAttachment200JSONResponse{Body: toAttachment(a)}, nil
|
||||
}
|
||||
|
||||
// Closing in the response visitor keeps the S3 stream alive until serialization completes.
|
||||
type originalResponse struct {
|
||||
body io.ReadCloser
|
||||
size int64
|
||||
mime string
|
||||
}
|
||||
|
||||
func (r originalResponse) VisitDownloadAttachmentResponse(w http.ResponseWriter) error {
|
||||
defer r.body.Close()
|
||||
w.Header().Set("Content-Type", r.mime)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(r.size, 10))
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.WriteHeader(200)
|
||||
_, err := io.CopyN(w, r.body, r.size)
|
||||
if err != nil {
|
||||
panic(http.ErrAbortHandler)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (h *API) DownloadAttachment(ctx context.Context, req DownloadAttachmentRequestObject) (DownloadAttachmentResponseObject, error) {
|
||||
if _, e := h.attachments.Get(ctx, currentUser(ctx).ID, req.AttachmentId); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if req.Params.Variant != nil && string(*req.Params.Variant) != "original" {
|
||||
return nil, model.ErrNotFound
|
||||
}
|
||||
a, r, e := h.attachments.Content(ctx, currentUser(ctx).ID, req.AttachmentId)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return originalResponse{r, a.SizeBytes, a.ContentType}, nil
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"backend/internal/domain/model"
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
type sessionRequestKey struct{}
|
||||
|
||||
func (h *API) CreateSession(ctx context.Context, _ CreateSessionRequestObject) (CreateSessionResponseObject, error) {
|
||||
r := ctx.Value(sessionRequestKey{}).(*http.Request)
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok || len(username) > 32 || len(password) > 512 || utf8.RuneCountInString(password) > 128 {
|
||||
return nil, model.ErrUnauthorized
|
||||
}
|
||||
s, err := h.auth.Login(ctx, username, password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return CreateSession201JSONResponse{Body: Session{Token: s.Token, TokenType: Bearer, ExpiresAt: Timestamp(s.ExpiresAt), User: toUser(s.User)}}, nil
|
||||
}
|
||||
func (h *API) RevokeSession(ctx context.Context, _ RevokeSessionRequestObject) (RevokeSessionResponseObject, error) {
|
||||
r := ctx.Value(sessionRequestKey{}).(*http.Request)
|
||||
parts := strings.Fields(r.Header.Get("Authorization"))
|
||||
if err := h.auth.Logout(ctx, parts[1]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return RevokeSession204Response{}, nil
|
||||
}
|
||||
func (h *API) requestContext(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
duration := 5 * time.Second
|
||||
if strings.HasSuffix(r.URL.Path, "/attachments") || strings.HasSuffix(r.URL.Path, "/content") {
|
||||
duration = 20 * time.Second
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), duration)
|
||||
defer cancel()
|
||||
if r.URL.Path == "/api/v1/auth/sessions" {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
}
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(ctx, sessionRequestKey{}, r)))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"backend/internal/domain/model"
|
||||
)
|
||||
|
||||
var (
|
||||
errRouteNotFound = errors.New("route not found")
|
||||
errMethodNotAllowed = errors.New("method not allowed")
|
||||
errPayloadTooLarge = errors.New("payload too large")
|
||||
errOverloaded = errors.New("overloaded")
|
||||
errDraining = errors.New("draining")
|
||||
errUnsupportedImage = errors.New("unsupported image")
|
||||
)
|
||||
|
||||
type apiError struct {
|
||||
status int
|
||||
code ErrorErrorCode
|
||||
message string
|
||||
}
|
||||
|
||||
// classify — единственное место, где ошибка превращается в HTTP-статус.
|
||||
func classify(err error) apiError {
|
||||
var invalid *model.ValidationError
|
||||
switch {
|
||||
case errors.As(err, &invalid):
|
||||
return apiError{http.StatusBadRequest, InvalidRequest, invalid.Message}
|
||||
case errors.Is(err, model.ErrUnauthorized):
|
||||
return apiError{http.StatusUnauthorized, Unauthorized, "нужна действующая сессия"}
|
||||
case errors.Is(err, model.ErrNotFound), errors.Is(err, errRouteNotFound):
|
||||
return apiError{http.StatusNotFound, NotFound, "объект не найден"}
|
||||
case errors.Is(err, errMethodNotAllowed):
|
||||
return apiError{http.StatusMethodNotAllowed, InvalidRequest, "метод не поддерживается"}
|
||||
case errors.Is(err, model.ErrUsernameTaken):
|
||||
return apiError{http.StatusConflict, Conflict, "username уже занят"}
|
||||
case errors.Is(err, model.ErrConflict):
|
||||
return apiError{http.StatusConflict, Conflict, "конфликт запроса"}
|
||||
case errors.Is(err, model.ErrUnavailable):
|
||||
return apiError{http.StatusServiceUnavailable, Unavailable, "зависимость недоступна"}
|
||||
case errors.Is(err, errPayloadTooLarge):
|
||||
return apiError{http.StatusRequestEntityTooLarge, PayloadTooLarge, "тело запроса больше допустимого"}
|
||||
case errors.Is(err, errUnsupportedImage):
|
||||
return apiError{http.StatusUnsupportedMediaType, UnsupportedMediaType, "нужен корректный PNG или JPEG с верным Content-Type"}
|
||||
case errors.Is(err, model.ErrStorageFull):
|
||||
return apiError{http.StatusServiceUnavailable, Unavailable, "хранилище заполнено, запись невозможна; чтение работает"}
|
||||
case errors.Is(err, errOverloaded):
|
||||
return apiError{http.StatusServiceUnavailable, Unavailable, "сервер перегружен, повторите позже"}
|
||||
case errors.Is(err, errDraining):
|
||||
return apiError{http.StatusServiceUnavailable, Unavailable, "сервер останавливается"}
|
||||
default:
|
||||
return apiError{http.StatusInternalServerError, InternalError, "внутренняя ошибка"}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *API) writeError(w http.ResponseWriter, r *http.Request, err error) {
|
||||
e := classify(err)
|
||||
if e.status == http.StatusInternalServerError {
|
||||
h.log.Error().Err(err).Str("request_id", requestIDFrom(r.Context())).Msg("unexpected error")
|
||||
}
|
||||
if errors.Is(err, errOverloaded) {
|
||||
w.Header().Set("Retry-After", "1")
|
||||
}
|
||||
var body Error
|
||||
body.Error.Code = e.code
|
||||
body.Error.Message = e.message
|
||||
body.Error.RequestId = requestIDFrom(r.Context())
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(e.status)
|
||||
_ = json.NewEncoder(w).Encode(body)
|
||||
}
|
||||
|
||||
// bodyError — JSON синтаксически верен (это проверил jsonBody), но не
|
||||
// подходит к схеме: лишнее поле или неверный тип.
|
||||
func (h *API) bodyError(w http.ResponseWriter, r *http.Request, _ error) {
|
||||
h.writeError(w, r, &model.ValidationError{Message: "тело запроса не соответствует схеме: лишнее поле или неверный тип"})
|
||||
}
|
||||
|
||||
// paramError — path или query параметр не разобрался (UUID, целое число).
|
||||
func (h *API) paramError(w http.ResponseWriter, r *http.Request, _ error) {
|
||||
h.writeError(w, r, &model.ValidationError{Message: "некорректный параметр запроса"})
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// gate ограничивает одновременную обработку запросов API: не больше inflight
|
||||
// в работе и не больше queue в ожидании слота. Лишние сразу получают 503 с
|
||||
// Retry-After, ждавшие дольше timeout — тоже 503. Так перегрузка превращается
|
||||
// в быстрый предсказуемый отказ, а не в рост горутин, памяти и задержки.
|
||||
type gate struct {
|
||||
slots chan struct{} // nil — без лимита
|
||||
maxQueue int64
|
||||
timeout time.Duration
|
||||
waiting atomic.Int64
|
||||
rejected atomic.Int64
|
||||
}
|
||||
|
||||
func newGate(inflight, queue int, timeout time.Duration) *gate {
|
||||
g := &gate{maxQueue: int64(queue), timeout: timeout}
|
||||
if inflight > 0 {
|
||||
g.slots = make(chan struct{}, inflight)
|
||||
}
|
||||
return g
|
||||
}
|
||||
|
||||
func (g *gate) middleware(reject func(http.ResponseWriter, *http.Request, error)) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if g.slots == nil {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
if !g.acquire(r) {
|
||||
g.rejected.Add(1)
|
||||
reject(w, r, errOverloaded)
|
||||
return
|
||||
}
|
||||
defer func() { <-g.slots }()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (g *gate) acquire(r *http.Request) bool {
|
||||
select {
|
||||
case g.slots <- struct{}{}:
|
||||
return true
|
||||
default:
|
||||
}
|
||||
if g.waiting.Add(1) > g.maxQueue {
|
||||
g.waiting.Add(-1)
|
||||
return false
|
||||
}
|
||||
defer g.waiting.Add(-1)
|
||||
timer := time.NewTimer(g.timeout)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case g.slots <- struct{}{}:
|
||||
return true
|
||||
case <-timer.C:
|
||||
return false
|
||||
case <-r.Context().Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
type gateStats struct {
|
||||
Inflight int `json:"inflight"`
|
||||
Waiting int64 `json:"waiting"`
|
||||
Rejected int64 `json:"rejected"`
|
||||
}
|
||||
|
||||
func (g *gate) stats() gateStats {
|
||||
return gateStats{Inflight: len(g.slots), Waiting: g.waiting.Load(), Rejected: g.rejected.Load()}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// gatedServer пропускает запросы через gate в обработчик, который держит слот,
|
||||
// пока тест не закроет release.
|
||||
func gatedServer(t *testing.T, g *gate) (*httptest.Server, chan struct{}, chan struct{}) {
|
||||
t.Helper()
|
||||
entered, release := make(chan struct{}, 10), make(chan struct{})
|
||||
reject := func(w http.ResponseWriter, _ *http.Request, err error) {
|
||||
if !errors.Is(err, errOverloaded) {
|
||||
t.Errorf("unexpected error %v", err)
|
||||
}
|
||||
w.Header().Set("Retry-After", "1")
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
}
|
||||
h := g.middleware(reject)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
entered <- struct{}{}
|
||||
<-release
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
srv := httptest.NewServer(h)
|
||||
t.Cleanup(srv.Close)
|
||||
return srv, entered, release
|
||||
}
|
||||
|
||||
func get(t *testing.T, url string) int {
|
||||
t.Helper()
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return 0
|
||||
}
|
||||
resp.Body.Close()
|
||||
return resp.StatusCode
|
||||
}
|
||||
|
||||
func waitFor(t *testing.T, cond func() bool) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for !cond() {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("condition not reached")
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGateRejectsBeyondQueueAndRecovers(t *testing.T) {
|
||||
t.Parallel()
|
||||
g := newGate(1, 1, time.Minute)
|
||||
srv, entered, release := gatedServer(t, g)
|
||||
|
||||
statuses := make(chan int, 2)
|
||||
var wg sync.WaitGroup
|
||||
wg.Go(func() { statuses <- get(t, srv.URL) }) // занимает слот
|
||||
<-entered
|
||||
wg.Go(func() { statuses <- get(t, srv.URL) }) // ждёт в очереди
|
||||
waitFor(t, func() bool { return g.waiting.Load() == 1 })
|
||||
|
||||
if code := get(t, srv.URL); code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("third request: %d, want 503", code)
|
||||
}
|
||||
close(release)
|
||||
wg.Wait()
|
||||
close(statuses)
|
||||
for code := range statuses {
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("admitted request got %d", code)
|
||||
}
|
||||
}
|
||||
if code := get(t, srv.URL); code != http.StatusOK {
|
||||
t.Fatalf("after load: %d, want recovery to 200", code)
|
||||
}
|
||||
if g.stats().Rejected != 1 {
|
||||
t.Fatalf("rejected %d", g.stats().Rejected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGateTimesOutQueuedRequest(t *testing.T) {
|
||||
t.Parallel()
|
||||
g := newGate(1, 10, 20*time.Millisecond)
|
||||
srv, entered, release := gatedServer(t, g)
|
||||
defer close(release)
|
||||
|
||||
go get(t, srv.URL)
|
||||
<-entered
|
||||
start := time.Now()
|
||||
if code := get(t, srv.URL); code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("queued request: %d, want 503 after timeout", code)
|
||||
}
|
||||
if time.Since(start) > time.Second {
|
||||
t.Fatal("queue timeout not applied")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"backend/internal/application/usecase"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
// Limits — защитные лимиты HTTP-слоя (трек 5 «управляемая деградация»).
|
||||
// Нулевое значение отключает лимит.
|
||||
type Limits struct {
|
||||
MaxBodyBytes int64 // больше — 413
|
||||
MaxInflight int // одновременно обрабатываемые запросы API
|
||||
MaxQueue int // ждущие свободного слота; больше — сразу 503
|
||||
QueueTimeout time.Duration // дольше ждал слот — 503
|
||||
}
|
||||
|
||||
// API — driving HTTP-адаптер: реализует StrictServerInterface из api.gen.go.
|
||||
//
|
||||
//go:generate go tool oapi-codegen -config ../../../codegen.yaml ../../../../contracts/openapi.json
|
||||
type API struct {
|
||||
app *usecase.Messenger
|
||||
auth *usecase.Auth
|
||||
attachments *usecase.Attachments
|
||||
uploadGate chan struct{}
|
||||
probe func(context.Context) error
|
||||
limits Limits
|
||||
gate *gate
|
||||
storeStats func() any
|
||||
ready atomic.Bool
|
||||
log *zerolog.Logger
|
||||
}
|
||||
|
||||
// New собирает HTTP-адаптер. storeStats отдаёт состояние хранилища для
|
||||
// /debug/stats.
|
||||
func New(app *usecase.Messenger, auth *usecase.Auth, attachments *usecase.Attachments, probe func(context.Context) error, limits Limits, storeStats func() any, log *zerolog.Logger) *API {
|
||||
h := &API{
|
||||
app: app,
|
||||
auth: auth,
|
||||
attachments: attachments,
|
||||
uploadGate: make(chan struct{}, 1),
|
||||
probe: probe,
|
||||
limits: limits,
|
||||
gate: newGate(limits.MaxInflight, limits.MaxQueue, limits.QueueTimeout),
|
||||
storeStats: storeStats,
|
||||
log: log,
|
||||
}
|
||||
h.ready.Store(true)
|
||||
return h
|
||||
}
|
||||
|
||||
// Drain переводит /health/ready в 503 перед остановкой сервера.
|
||||
func (h *API) Drain() { h.ready.Store(false) }
|
||||
|
||||
func (h *API) Router() http.Handler {
|
||||
r := chi.NewRouter()
|
||||
r.Use(requestID, h.recoverer, h.accessLog, h.requestContext)
|
||||
r.NotFound(func(w http.ResponseWriter, r *http.Request) {
|
||||
h.writeError(w, r, errRouteNotFound)
|
||||
})
|
||||
r.MethodNotAllowed(func(w http.ResponseWriter, r *http.Request) {
|
||||
h.writeError(w, r, errMethodNotAllowed)
|
||||
})
|
||||
|
||||
strict := NewStrictHandlerWithOptions(h, nil, StrictHTTPServerOptions{
|
||||
RequestErrorHandlerFunc: h.bodyError,
|
||||
ResponseErrorHandlerFunc: h.writeError,
|
||||
})
|
||||
api := ServerInterfaceWrapper{Handler: strict, ErrorHandlerFunc: h.paramError}
|
||||
|
||||
// Health и статистика — мимо очереди: под перегрузкой они должны отвечать.
|
||||
r.Get("/health/live", api.Liveness)
|
||||
r.Get("/health/ready", api.Readiness)
|
||||
r.Get("/debug/stats", h.stats)
|
||||
|
||||
r.Route("/api/v1", func(r chi.Router) {
|
||||
r.Use(h.gate.middleware(h.writeError))
|
||||
r.With(h.jsonBody).Post("/users", api.RegisterUser)
|
||||
r.Post("/auth/sessions", api.CreateSession)
|
||||
// Сначала аутентификация, потом тело и доступ к ресурсу.
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(h.authenticate, h.validQuery, h.jsonBody)
|
||||
r.Delete("/auth/sessions/current", api.RevokeSession)
|
||||
r.Get("/users/me", api.CurrentUser)
|
||||
r.Post("/chats", api.CreateChat)
|
||||
r.Get("/chats", api.ListChats)
|
||||
r.Get("/chats/{chat_id}", api.GetChat)
|
||||
r.Post("/chats/{chat_id}/messages", api.CreateMessage)
|
||||
r.Get("/chats/{chat_id}/messages", api.ListMessages)
|
||||
r.Post("/chats/{chat_id}/attachments", api.UploadAttachment)
|
||||
r.Get("/attachments/{attachment_id}", api.GetAttachment)
|
||||
r.Get("/attachments/{attachment_id}/content", api.DownloadAttachment)
|
||||
})
|
||||
})
|
||||
return r
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Timestamp подставляется кодогенератором вместо time.Time (codegen.yaml,
|
||||
// type-mapping): RFC 3339 UTC с ровно шестью цифрами дробной части.
|
||||
// time.Time срезает хвостовые нули, а fromisoformat в Python 3.9–3.10
|
||||
// (на нём публичные тесты) понимает дробную часть только из 3 или 6 цифр.
|
||||
type Timestamp time.Time
|
||||
|
||||
const timestampLayout = "2006-01-02T15:04:05.000000Z"
|
||||
|
||||
func (t Timestamp) MarshalJSON() ([]byte, error) {
|
||||
return []byte(`"` + time.Time(t).UTC().Format(timestampLayout) + `"`), nil
|
||||
}
|
||||
|
||||
func (t *Timestamp) UnmarshalJSON(data []byte) error {
|
||||
var parsed time.Time
|
||||
if err := json.Unmarshal(data, &parsed); err != nil {
|
||||
return err
|
||||
}
|
||||
*t = Timestamp(parsed)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Тела запросов с лишними полями — 400 по контракту, а сгенерированный
|
||||
// декодер их молча игнорирует. Строгий разбор подключается методами на
|
||||
// сгенерированных типах.
|
||||
|
||||
func (c *CreateUser) UnmarshalJSON(data []byte) error {
|
||||
type plain CreateUser
|
||||
return decodeStrict(data, (*plain)(c))
|
||||
}
|
||||
|
||||
func (c *CreateChat) UnmarshalJSON(data []byte) error {
|
||||
type plain CreateChat
|
||||
return decodeStrict(data, (*plain)(c))
|
||||
}
|
||||
|
||||
func (c *CreateMessage) UnmarshalJSON(data []byte) error {
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(data, &fields); err != nil {
|
||||
return err
|
||||
}
|
||||
raw, ok := fields["text"]
|
||||
if !ok || bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {
|
||||
return fmt.Errorf("text must be a present string")
|
||||
}
|
||||
if ids, ok := fields["attachment_ids"]; ok && bytes.Equal(bytes.TrimSpace(ids), []byte("null")) {
|
||||
return fmt.Errorf("attachment_ids must be an array")
|
||||
}
|
||||
type plain CreateMessage
|
||||
return decodeStrict(data, (*plain)(c))
|
||||
}
|
||||
|
||||
func decodeStrict(data []byte, dst any) error {
|
||||
dec := json.NewDecoder(bytes.NewReader(data))
|
||||
dec.DisallowUnknownFields()
|
||||
return dec.Decode(dst)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMessageJSONRequiresStringTextAndArrayIDs(t *testing.T) {
|
||||
for _, body := range []string{`{"attachment_ids":[]}`, `{"text":null,"attachment_ids":[]}`, `{"text":"ok","attachment_ids":null}`} {
|
||||
t.Run(body, func(t *testing.T) {
|
||||
var message CreateMessage
|
||||
if err := json.Unmarshal([]byte(body), &message); err == nil {
|
||||
t.Fatal("accepted a missing/null required field")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"runtime/debug"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"backend/internal/domain/model"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type ctxKey int
|
||||
|
||||
const (
|
||||
requestIDKey ctxKey = iota
|
||||
userKey
|
||||
)
|
||||
|
||||
// requestID ставит X-Request-Id в каждый ответ, включая ошибки и health.
|
||||
func requestID(next http.Handler) http.Handler {
|
||||
instance, _ := os.Hostname()
|
||||
if instance == "" {
|
||||
instance = uuid.NewString()
|
||||
}
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
id := uuid.NewString()
|
||||
w.Header().Set("X-Request-Id", id)
|
||||
w.Header().Set("X-Instance-Id", instance)
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), requestIDKey, id)))
|
||||
})
|
||||
}
|
||||
|
||||
func requestIDFrom(ctx context.Context) string {
|
||||
id, _ := ctx.Value(requestIDKey).(string)
|
||||
return id
|
||||
}
|
||||
|
||||
// recoverer превращает панику в 500 без деталей; стек — только в лог.
|
||||
func (h *API) recoverer(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
rec := recover()
|
||||
if rec == nil {
|
||||
return
|
||||
}
|
||||
if rec == http.ErrAbortHandler {
|
||||
panic(rec)
|
||||
}
|
||||
h.log.Error().Interface("panic", rec).Bytes("stack", debug.Stack()).
|
||||
Str("request_id", requestIDFrom(r.Context())).Msg("panic")
|
||||
h.writeError(w, r, errors.New("panic"))
|
||||
}()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// accessLog пишет метод, шаблон маршрута, статус и длительность. Тело, query
|
||||
// и заголовки не логируются: там текст сообщений и идентификаторы.
|
||||
func (h *API) accessLog(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
||||
next.ServeHTTP(ww, r)
|
||||
route := chi.RouteContext(r.Context()).RoutePattern()
|
||||
if route == "" {
|
||||
route = "unmatched"
|
||||
}
|
||||
event := h.log.Info()
|
||||
if ww.Status() >= http.StatusInternalServerError {
|
||||
event = h.log.Warn()
|
||||
}
|
||||
event.Str("request_id", requestIDFrom(r.Context())).
|
||||
Str("method", r.Method).
|
||||
Str("route", route).
|
||||
Int("status", ww.Status()).
|
||||
Dur("duration", time.Since(start)).
|
||||
Msg("request")
|
||||
})
|
||||
}
|
||||
|
||||
// authenticate verifies persisted Bearer sessions for protected business routes.
|
||||
// The session-creation endpoint separately validates Basic credentials.
|
||||
func (h *API) authenticate(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
parts := strings.Fields(r.Header.Get("Authorization"))
|
||||
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
h.writeError(w, r, model.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
user, err := h.auth.Authenticate(r.Context(), parts[1])
|
||||
if err != nil {
|
||||
if errors.Is(err, model.ErrUnauthorized) {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
}
|
||||
h.writeError(w, r, err)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), userKey, user)))
|
||||
})
|
||||
}
|
||||
|
||||
// validQuery отсекает query с битым %-экранированием: url.Values молча
|
||||
// выбросил бы такой параметр, и cursor=%%% превратился бы в «с начала».
|
||||
func (h *API) validQuery(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if _, err := url.ParseQuery(r.URL.RawQuery); err != nil {
|
||||
h.writeError(w, r, &model.ValidationError{Message: "некорректная строка запроса"})
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func currentUser(ctx context.Context) model.User {
|
||||
user, _ := ctx.Value(userKey).(model.User)
|
||||
return user
|
||||
}
|
||||
|
||||
// jsonBody читает тело POST с лимитом размера (иначе 413) и отсекает
|
||||
// синтаксически неверный JSON (400) до кодогенерированного декодера: тот
|
||||
// читает только первое JSON-значение и пропустил бы мусор после него.
|
||||
func (h *API) jsonBody(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost || strings.HasSuffix(r.URL.Path, "/attachments") {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
reader := io.Reader(r.Body)
|
||||
if h.limits.MaxBodyBytes > 0 {
|
||||
reader = http.MaxBytesReader(w, r.Body, h.limits.MaxBodyBytes)
|
||||
}
|
||||
body, err := io.ReadAll(reader)
|
||||
var tooLarge *http.MaxBytesError
|
||||
switch {
|
||||
case errors.As(err, &tooLarge):
|
||||
h.writeError(w, r, errPayloadTooLarge)
|
||||
return
|
||||
case err != nil:
|
||||
h.writeError(w, r, &model.ValidationError{Message: "тело запроса не прочитано"})
|
||||
return
|
||||
case !utf8.Valid(body) || !json.Valid(body):
|
||||
h.writeError(w, r, &model.ValidationError{Message: "некорректный JSON"})
|
||||
return
|
||||
}
|
||||
r.Body = io.NopCloser(bytes.NewReader(body))
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"os"
|
||||
"runtime"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// stats — расширение за пределами контракта (contracts/extensions.md): память
|
||||
// процесса, учтённый объём хранилища и очередь. Нужен для графиков трека 5.
|
||||
func (h *API) stats(w http.ResponseWriter, _ *http.Request) {
|
||||
var mem runtime.MemStats
|
||||
runtime.ReadMemStats(&mem)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"rss_bytes": rssBytes(),
|
||||
"heap_alloc": mem.HeapAlloc,
|
||||
"heap_sys": mem.HeapSys,
|
||||
"go_memory_limit": debug.SetMemoryLimit(-1),
|
||||
"num_gc": mem.NumGC,
|
||||
"goroutines": runtime.NumGoroutine(),
|
||||
"gate": h.gate.stats(),
|
||||
"store": h.storeStats(),
|
||||
})
|
||||
}
|
||||
|
||||
// rssBytes читает VmRSS из /proc (только Linux, то есть в контейнере); иначе 0.
|
||||
func rssBytes() int64 {
|
||||
f, err := os.Open("/proc/self/status")
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
defer f.Close()
|
||||
sc := bufio.NewScanner(f)
|
||||
for sc.Scan() {
|
||||
if kb, ok := strings.CutPrefix(sc.Text(), "VmRSS:"); ok {
|
||||
n, _ := strconv.ParseInt(strings.TrimSpace(strings.TrimSuffix(kb, "kB")), 10, 64)
|
||||
return n * 1024
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRejectsInvalidUTF8BeforeJSONDecoding(t *testing.T) {
|
||||
body := append([]byte(`{"display_name":"`), 0xff)
|
||||
body = append(body, []byte(`"}`)...)
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", bytes.NewReader(body))
|
||||
response := httptest.NewRecorder()
|
||||
h := &API{limits: Limits{MaxBodyBytes: 65536}}
|
||||
called := false
|
||||
requestID(h.jsonBody(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { called = true; w.WriteHeader(204) }))).ServeHTTP(response, request)
|
||||
if response.Code != 400 || called {
|
||||
t.Fatalf("invalid UTF-8 reached decoder: status=%d called=%t", response.Code, called)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package imagefile
|
||||
|
||||
import (
|
||||
"backend/internal/domain/model"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
var ErrTooLarge = errors.New("image too large")
|
||||
var ErrUnsupported = errors.New("invalid image or MIME")
|
||||
|
||||
type File struct {
|
||||
*os.File
|
||||
Size int64
|
||||
SHA256, ContentType string
|
||||
}
|
||||
|
||||
func (f *File) Dispose() { _ = f.Close(); _ = os.Remove(f.Name()) }
|
||||
func Inspect(body io.Reader, filename, mime string) (out *File, err error) {
|
||||
if err = model.ValidateFilename(filename); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if mime != "image/png" && mime != "image/jpeg" {
|
||||
return nil, ErrUnsupported
|
||||
}
|
||||
f, e := os.CreateTemp("", "messenger-upload-*")
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
_ = f.Close()
|
||||
_ = os.Remove(f.Name())
|
||||
}
|
||||
}()
|
||||
hash := sha256.New()
|
||||
n, e := io.Copy(io.MultiWriter(f, hash), io.LimitReader(body, model.MaxImageBytes+1))
|
||||
if e != nil {
|
||||
return nil, &model.ValidationError{Message: "incomplete image upload"}
|
||||
}
|
||||
if n > model.MaxImageBytes {
|
||||
return nil, ErrTooLarge
|
||||
}
|
||||
if _, e = f.Seek(0, io.SeekStart); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
cfg, format, e := image.DecodeConfig(f)
|
||||
if e != nil || "image/"+format != mime {
|
||||
return nil, ErrUnsupported
|
||||
}
|
||||
pixels := int64(cfg.Width) * int64(cfg.Height)
|
||||
if cfg.Width < 1 || cfg.Height < 1 || pixels > model.MaxImagePixels {
|
||||
return nil, ErrTooLarge
|
||||
}
|
||||
if _, e = f.Seek(0, io.SeekStart); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
decoded, actual, e := image.Decode(f)
|
||||
if e != nil || actual != format || decoded.Bounds().Dx() != cfg.Width || decoded.Bounds().Dy() != cfg.Height {
|
||||
return nil, ErrUnsupported
|
||||
}
|
||||
if _, e = f.Seek(0, io.SeekStart); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return &File{f, n, hex.EncodeToString(hash.Sum(nil)), mime}, nil
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package imagefile
|
||||
|
||||
import (
|
||||
"backend/internal/domain/model"
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"hash/crc32"
|
||||
"image"
|
||||
"image/png"
|
||||
"io"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func pngBytes(t *testing.T) []byte {
|
||||
t.Helper()
|
||||
var b bytes.Buffer
|
||||
if e := png.Encode(&b, image.NewNRGBA(image.Rect(0, 0, 3, 2))); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return b.Bytes()
|
||||
}
|
||||
func TestOriginalBytesArePreserved(t *testing.T) {
|
||||
raw := pngBytes(t)
|
||||
f, e := Inspect(bytes.NewReader(raw), "пример.png", "image/png")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer f.Dispose()
|
||||
got, e := io.ReadAll(f)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if !bytes.Equal(got, raw) {
|
||||
t.Fatal("original changed")
|
||||
}
|
||||
}
|
||||
func TestRejectsInvalidImageAndFilename(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, mime string
|
||||
body []byte
|
||||
want error
|
||||
}{
|
||||
{"a.png", "image/jpeg", pngBytes(t), ErrUnsupported},
|
||||
{"a.png", "image/png", []byte("not an image"), ErrUnsupported},
|
||||
{"a.png", "application/octet-stream", pngBytes(t), ErrUnsupported},
|
||||
{"a.png", "image/png", append(pngBytes(t)[:20], 0), ErrUnsupported},
|
||||
} {
|
||||
t.Run(tc.mime+string(tc.body[:1]), func(t *testing.T) {
|
||||
_, e := Inspect(bytes.NewReader(tc.body), tc.name, tc.mime)
|
||||
if !errors.Is(e, tc.want) {
|
||||
t.Fatalf("got %v, want %v", e, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, name := range []string{"../x.png", "a\\b", "a\x00b", "a\nb", ""} {
|
||||
if _, e := Inspect(bytes.NewReader(pngBytes(t)), name, "image/png"); e == nil {
|
||||
t.Fatalf("accepted unsafe filename %q", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestRejectsOversizedStreamBeforeDecoding(t *testing.T) {
|
||||
_, e := Inspect(io.LimitReader(zeroReader{}, model.MaxImageBytes+1), "a.png", "image/png")
|
||||
if !errors.Is(e, ErrTooLarge) {
|
||||
t.Fatalf("got %v", e)
|
||||
}
|
||||
}
|
||||
|
||||
type zeroReader struct{}
|
||||
|
||||
func (zeroReader) Read(p []byte) (int, error) { clear(p); return len(p), nil }
|
||||
func TestRejectsPixelBombBeforeDecoding(t *testing.T) {
|
||||
raw := pngBytes(t)
|
||||
binary.BigEndian.PutUint32(raw[16:20], 50000)
|
||||
binary.BigEndian.PutUint32(raw[20:24], 50000)
|
||||
binary.BigEndian.PutUint32(raw[29:33], crc32.ChecksumIEEE(raw[12:29]))
|
||||
_, e := Inspect(bytes.NewReader(raw), "huge.png", "image/png")
|
||||
if !errors.Is(e, ErrTooLarge) {
|
||||
t.Fatalf("pixel limit did not apply before decode: %v", e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package imagefile
|
||||
|
||||
import (
|
||||
"backend/internal/adapter/password"
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"encoding/binary"
|
||||
"hash/crc32"
|
||||
"io"
|
||||
"os"
|
||||
"runtime"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A normal PNG encoder allocates several full-width filter rows itself.
|
||||
// Construct a tiny, highly compressible adversarial fixture as a stream instead.
|
||||
func extremePNG(t *testing.T, interlaced bool) []byte {
|
||||
t.Helper()
|
||||
const width = 40_000_000
|
||||
const height = 1
|
||||
var idat bytes.Buffer
|
||||
z := zlib.NewWriter(&idat)
|
||||
passes := [][4]int{{0, 0, 1, 1}}
|
||||
if interlaced {
|
||||
passes = [][4]int{{0, 0, 8, 8}, {4, 0, 8, 8}, {0, 4, 4, 8}, {2, 0, 4, 4}, {0, 2, 2, 4}, {1, 0, 2, 2}, {0, 1, 1, 2}}
|
||||
}
|
||||
for _, p := range passes {
|
||||
w := (width - p[0] + p[2] - 1) / p[2]
|
||||
h := (height - p[1] + p[3] - 1) / p[3]
|
||||
if width <= p[0] || height <= p[1] || w <= 0 || h <= 0 {
|
||||
continue
|
||||
}
|
||||
for row := 0; row < h; row++ {
|
||||
if _, e := z.Write([]byte{0}); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e := io.CopyN(z, zeroReader{}, int64(w)*8); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
if e := z.Close(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var out bytes.Buffer
|
||||
out.Write([]byte{137, 80, 78, 71, 13, 10, 26, 10})
|
||||
chunk := func(kind string, data []byte) {
|
||||
var word [4]byte
|
||||
binary.BigEndian.PutUint32(word[:], uint32(len(data)))
|
||||
out.Write(word[:])
|
||||
out.WriteString(kind)
|
||||
out.Write(data)
|
||||
crc := crc32.NewIEEE()
|
||||
_, _ = crc.Write([]byte(kind))
|
||||
_, _ = crc.Write(data)
|
||||
binary.BigEndian.PutUint32(word[:], crc.Sum32())
|
||||
out.Write(word[:])
|
||||
}
|
||||
header := make([]byte, 13)
|
||||
binary.BigEndian.PutUint32(header[:4], width)
|
||||
binary.BigEndian.PutUint32(header[4:8], height)
|
||||
header[8] = 16
|
||||
header[9] = 6
|
||||
if interlaced {
|
||||
header[12] = 1
|
||||
}
|
||||
chunk("IHDR", header)
|
||||
chunk("IDAT", idat.Bytes())
|
||||
chunk("IEND", nil)
|
||||
return out.Bytes()
|
||||
}
|
||||
func TestWorstCaseImagesWithinBudget(t *testing.T) {
|
||||
if os.Getenv("RUN_IMAGE_STRESS") != "1" {
|
||||
t.Skip("explicit isolated memory experiment required")
|
||||
}
|
||||
old := debug.SetMemoryLimit(1536 * 1024 * 1024)
|
||||
defer debug.SetMemoryLimit(old)
|
||||
for _, interlaced := range []bool{false, true} {
|
||||
raw := extremePNG(t, interlaced)
|
||||
runtime.GC()
|
||||
stop := make(chan struct{})
|
||||
var workers sync.WaitGroup
|
||||
for i := 0; i < 3; i++ {
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
if _, e := password.New().Hash("synthetic-concurrent-KDF"); e != nil {
|
||||
t.Error(e)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
for repeat := 0; repeat < 2; repeat++ {
|
||||
f, e := Inspect(bytes.NewReader(raw), "wide.png", "image/png")
|
||||
if e != nil {
|
||||
close(stop)
|
||||
workers.Wait()
|
||||
t.Fatal(e)
|
||||
}
|
||||
f.Dispose()
|
||||
}
|
||||
close(stop)
|
||||
workers.Wait()
|
||||
runtime.GC()
|
||||
}
|
||||
raw, e := os.ReadFile("/proc/self/status")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
peak := int64(0)
|
||||
for _, line := range strings.Split(string(raw), "\n") {
|
||||
if strings.HasPrefix(line, "VmHWM:") {
|
||||
fields := strings.Fields(line)
|
||||
peak, e = strconv.ParseInt(fields[1], 10, 64)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
if peak <= 0 || peak >= 2*1024*1024 {
|
||||
t.Fatalf("RSS high-water mark out of budget: %d KiB", peak)
|
||||
}
|
||||
t.Logf("PASS native RGBA64 40000000x1, normal+Adam7, two sequential validations each, 3 concurrent Argon2 workers; peak_rss_kib=%d hard_limit_kib=2097152", peak)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package password
|
||||
|
||||
import (
|
||||
"backend/internal/domain/port"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"golang.org/x/crypto/argon2"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Argon struct{}
|
||||
|
||||
func New() port.Passwords { return Argon{} }
|
||||
func (Argon) Hash(password string) (string, error) {
|
||||
salt := make([]byte, 16)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
hash := argon2.IDKey([]byte(password), salt, 2, 32*1024, 1, 32)
|
||||
return fmt.Sprintf("argon2id$v19$m32768t2p1$%s$%s", base64.RawStdEncoding.EncodeToString(salt), base64.RawStdEncoding.EncodeToString(hash)), nil
|
||||
}
|
||||
func (Argon) Verify(password, encoded string) bool {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 5 || parts[0] != "argon2id" || parts[1] != "v19" || parts[2] != "m32768t2p1" {
|
||||
return false
|
||||
}
|
||||
salt, e1 := base64.RawStdEncoding.DecodeString(parts[3])
|
||||
want, e2 := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if e1 != nil || e2 != nil || len(salt) != 16 || len(want) != 32 {
|
||||
return false
|
||||
}
|
||||
got := argon2.IDKey([]byte(password), salt, 2, 32*1024, 1, 32)
|
||||
return subtle.ConstantTimeCompare(got, want) == 1
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"backend/internal/adapter/repository/postgres/queries"
|
||||
"backend/internal/domain/model"
|
||||
"context"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func attachment(r queries.Attachment) model.Attachment {
|
||||
return model.Attachment{ID: r.ID, ChatID: r.ChatID, OwnerID: r.OwnerID, Filename: r.Filename, ContentType: r.ContentType, SizeBytes: r.SizeBytes, SHA256: r.Sha256, Status: r.Status, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt}
|
||||
}
|
||||
func (s *Store) ReserveAttachment(ctx context.Context, a model.Attachment) (model.Attachment, error) {
|
||||
tx, e := s.pool.Begin(ctx)
|
||||
if e != nil {
|
||||
return model.Attachment{}, mapErr(e)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
q := s.q.WithTx(tx)
|
||||
if _, e = q.ChargeAttachment(ctx, a.OwnerID); e != nil {
|
||||
return model.Attachment{}, model.ErrStorageFull
|
||||
}
|
||||
r, e := q.InsertAttachment(ctx, queries.InsertAttachmentParams{ID: a.ID, ChatID: a.ChatID, OwnerID: a.OwnerID, Filename: a.Filename, ContentType: a.ContentType, SizeBytes: a.SizeBytes, Sha256: a.SHA256})
|
||||
if e != nil {
|
||||
return model.Attachment{}, mapErr(e)
|
||||
}
|
||||
if e = tx.Commit(ctx); e != nil {
|
||||
return model.Attachment{}, mapErr(e)
|
||||
}
|
||||
return attachment(r), nil
|
||||
}
|
||||
func (s *Store) GetAttachment(ctx context.Context, id uuid.UUID) (model.Attachment, error) {
|
||||
r, e := s.q.GetAttachment(ctx, id)
|
||||
return attachment(r), mapErr(e)
|
||||
}
|
||||
func (s *Store) SetAttachmentStatus(ctx context.Context, id uuid.UUID, from, to string) (bool, error) {
|
||||
n, e := s.q.SetAttachmentStatus(ctx, queries.SetAttachmentStatusParams{ID: id, Status: to, Status_2: from})
|
||||
return n == 1, mapErr(e)
|
||||
}
|
||||
func (s *Store) ReconcileAttachments(ctx context.Context, after uuid.UUID) ([]model.Attachment, bool, error) {
|
||||
rows, e := s.q.ReconcileAttachments(ctx, after)
|
||||
if e != nil {
|
||||
return nil, false, mapErr(e)
|
||||
}
|
||||
more := len(rows) > 100
|
||||
if more {
|
||||
rows = rows[:100]
|
||||
}
|
||||
out := make([]model.Attachment, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = attachment(r)
|
||||
}
|
||||
return out, more, nil
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: attachments.sql
|
||||
|
||||
package queries
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const chargeAttachment = `-- name: ChargeAttachment :one
|
||||
UPDATE users SET attachment_count=attachment_count+1 WHERE id=$1 AND attachment_count<10000 RETURNING id
|
||||
`
|
||||
|
||||
func (q *Queries) ChargeAttachment(ctx context.Context, id uuid.UUID) (uuid.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, chargeAttachment, id)
|
||||
var id_2 uuid.UUID
|
||||
err := row.Scan(&id_2)
|
||||
return id_2, err
|
||||
}
|
||||
|
||||
const getAttachment = `-- name: GetAttachment :one
|
||||
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, created_at, updated_at FROM attachments WHERE id=$1 FOR SHARE
|
||||
`
|
||||
|
||||
func (q *Queries) GetAttachment(ctx context.Context, id uuid.UUID) (Attachment, error) {
|
||||
row := q.db.QueryRow(ctx, getAttachment, id)
|
||||
var i Attachment
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.OwnerID,
|
||||
&i.Filename,
|
||||
&i.ContentType,
|
||||
&i.SizeBytes,
|
||||
&i.Sha256,
|
||||
&i.Status,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertAttachment = `-- name: InsertAttachment :one
|
||||
INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,status)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,'uploading') RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, created_at, updated_at
|
||||
`
|
||||
|
||||
type InsertAttachmentParams struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
OwnerID uuid.UUID
|
||||
Filename string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
Sha256 string
|
||||
}
|
||||
|
||||
func (q *Queries) InsertAttachment(ctx context.Context, arg InsertAttachmentParams) (Attachment, error) {
|
||||
row := q.db.QueryRow(ctx, insertAttachment,
|
||||
arg.ID,
|
||||
arg.ChatID,
|
||||
arg.OwnerID,
|
||||
arg.Filename,
|
||||
arg.ContentType,
|
||||
arg.SizeBytes,
|
||||
arg.Sha256,
|
||||
)
|
||||
var i Attachment
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.OwnerID,
|
||||
&i.Filename,
|
||||
&i.ContentType,
|
||||
&i.SizeBytes,
|
||||
&i.Sha256,
|
||||
&i.Status,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertMessageAttachment = `-- name: InsertMessageAttachment :exec
|
||||
INSERT INTO message_attachments(message_id,attachment_id,ordinal) VALUES($1,$2,$3)
|
||||
`
|
||||
|
||||
type InsertMessageAttachmentParams struct {
|
||||
MessageID uuid.UUID
|
||||
AttachmentID uuid.UUID
|
||||
Ordinal int32
|
||||
}
|
||||
|
||||
func (q *Queries) InsertMessageAttachment(ctx context.Context, arg InsertMessageAttachmentParams) error {
|
||||
_, err := q.db.Exec(ctx, insertMessageAttachment, arg.MessageID, arg.AttachmentID, arg.Ordinal)
|
||||
return err
|
||||
}
|
||||
|
||||
const messageAttachments = `-- name: MessageAttachments :many
|
||||
SELECT attachment_id FROM message_attachments WHERE message_id=$1 ORDER BY ordinal LIMIT 10
|
||||
`
|
||||
|
||||
func (q *Queries) MessageAttachments(ctx context.Context, messageID uuid.UUID) ([]uuid.UUID, error) {
|
||||
rows, err := q.db.Query(ctx, messageAttachments, messageID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []uuid.UUID{}
|
||||
for rows.Next() {
|
||||
var attachment_id uuid.UUID
|
||||
if err := rows.Scan(&attachment_id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, attachment_id)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const reconcileAttachments = `-- name: ReconcileAttachments :many
|
||||
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, created_at, updated_at FROM attachments WHERE id>$1 ORDER BY id LIMIT 101
|
||||
`
|
||||
|
||||
func (q *Queries) ReconcileAttachments(ctx context.Context, id uuid.UUID) ([]Attachment, error) {
|
||||
rows, err := q.db.Query(ctx, reconcileAttachments, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []Attachment{}
|
||||
for rows.Next() {
|
||||
var i Attachment
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.OwnerID,
|
||||
&i.Filename,
|
||||
&i.ContentType,
|
||||
&i.SizeBytes,
|
||||
&i.Sha256,
|
||||
&i.Status,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const setAttachmentStatus = `-- name: SetAttachmentStatus :execrows
|
||||
UPDATE attachments SET status=$2,updated_at=clock_timestamp() WHERE id=$1 AND status=$3
|
||||
`
|
||||
|
||||
type SetAttachmentStatusParams struct {
|
||||
ID uuid.UUID
|
||||
Status string
|
||||
Status_2 string
|
||||
}
|
||||
|
||||
func (q *Queries) SetAttachmentStatus(ctx context.Context, arg SetAttachmentStatusParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, setAttachmentStatus, arg.ID, arg.Status, arg.Status_2)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: core.sql
|
||||
|
||||
package queries
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const authenticateSession = `-- name: AuthenticateSession :one
|
||||
SELECT user_id FROM sessions WHERE token_hash=$1 AND expires_at>clock_timestamp()
|
||||
`
|
||||
|
||||
func (q *Queries) AuthenticateSession(ctx context.Context, tokenHash string) (uuid.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, authenticateSession, tokenHash)
|
||||
var user_id uuid.UUID
|
||||
err := row.Scan(&user_id)
|
||||
return user_id, err
|
||||
}
|
||||
|
||||
const chargeChat = `-- name: ChargeChat :one
|
||||
UPDATE users SET chat_count=chat_count+1 WHERE id=$1 AND chat_count<1000 RETURNING id
|
||||
`
|
||||
|
||||
func (q *Queries) ChargeChat(ctx context.Context, id uuid.UUID) (uuid.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, chargeChat, id)
|
||||
var id_2 uuid.UUID
|
||||
err := row.Scan(&id_2)
|
||||
return id_2, err
|
||||
}
|
||||
|
||||
const chargeMessage = `-- name: ChargeMessage :one
|
||||
UPDATE users SET message_count=message_count+1 WHERE id=$1 AND message_count<1000000 RETURNING id
|
||||
`
|
||||
|
||||
func (q *Queries) ChargeMessage(ctx context.Context, id uuid.UUID) (uuid.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, chargeMessage, id)
|
||||
var id_2 uuid.UUID
|
||||
err := row.Scan(&id_2)
|
||||
return id_2, err
|
||||
}
|
||||
|
||||
const createUser = `-- name: CreateUser :one
|
||||
INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4)
|
||||
RETURNING id,username,display_name,created_at
|
||||
`
|
||||
|
||||
type CreateUserParams struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
PasswordHash string
|
||||
}
|
||||
|
||||
type CreateUserRow struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (CreateUserRow, error) {
|
||||
row := q.db.QueryRow(ctx, createUser,
|
||||
arg.ID,
|
||||
arg.Username,
|
||||
arg.DisplayName,
|
||||
arg.PasswordHash,
|
||||
)
|
||||
var i CreateUserRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Username,
|
||||
&i.DisplayName,
|
||||
&i.CreatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const credentials = `-- name: Credentials :one
|
||||
SELECT id,password_hash FROM users WHERE username=$1
|
||||
`
|
||||
|
||||
type CredentialsRow struct {
|
||||
ID uuid.UUID
|
||||
PasswordHash string
|
||||
}
|
||||
|
||||
func (q *Queries) Credentials(ctx context.Context, username string) (CredentialsRow, error) {
|
||||
row := q.db.QueryRow(ctx, credentials, username)
|
||||
var i CredentialsRow
|
||||
err := row.Scan(&i.ID, &i.PasswordHash)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const deleteExpiredSessions = `-- name: DeleteExpiredSessions :exec
|
||||
DELETE FROM sessions WHERE user_id=$1 AND expires_at<=clock_timestamp()
|
||||
`
|
||||
|
||||
func (q *Queries) DeleteExpiredSessions(ctx context.Context, userID uuid.UUID) error {
|
||||
_, err := q.db.Exec(ctx, deleteExpiredSessions, userID)
|
||||
return err
|
||||
}
|
||||
|
||||
const getChat = `-- name: GetChat :one
|
||||
SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id)::uuid[] AS members
|
||||
FROM chats c WHERE c.id=$1
|
||||
`
|
||||
|
||||
type GetChatRow struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
CreatedAt time.Time
|
||||
Members []uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) GetChat(ctx context.Context, id uuid.UUID) (GetChatRow, error) {
|
||||
row := q.db.QueryRow(ctx, getChat, id)
|
||||
var i GetChatRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Title,
|
||||
&i.CreatedAt,
|
||||
&i.Members,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getUser = `-- name: GetUser :one
|
||||
SELECT id,username,display_name,created_at FROM users WHERE id=$1
|
||||
`
|
||||
|
||||
type GetUserRow struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) GetUser(ctx context.Context, id uuid.UUID) (GetUserRow, error) {
|
||||
row := q.db.QueryRow(ctx, getUser, id)
|
||||
var i GetUserRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Username,
|
||||
&i.DisplayName,
|
||||
&i.CreatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertChat = `-- name: InsertChat :one
|
||||
INSERT INTO chats(id,title) VALUES($1,$2) RETURNING id,title,created_at
|
||||
`
|
||||
|
||||
type InsertChatParams struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
}
|
||||
|
||||
func (q *Queries) InsertChat(ctx context.Context, arg InsertChatParams) (Chat, error) {
|
||||
row := q.db.QueryRow(ctx, insertChat, arg.ID, arg.Title)
|
||||
var i Chat
|
||||
err := row.Scan(&i.ID, &i.Title, &i.CreatedAt)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertMembers = `-- name: InsertMembers :exec
|
||||
INSERT INTO chat_members(chat_id,user_id) SELECT $1,unnest($2::uuid[])
|
||||
`
|
||||
|
||||
type InsertMembersParams struct {
|
||||
ChatID uuid.UUID
|
||||
Column2 []uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) InsertMembers(ctx context.Context, arg InsertMembersParams) error {
|
||||
_, err := q.db.Exec(ctx, insertMembers, arg.ChatID, arg.Column2)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertMessage = `-- name: InsertMessage :one
|
||||
INSERT INTO messages(id,chat_id,sender_id,text) VALUES($1,$2,$3,$4) RETURNING id,chat_id,sender_id,text,created_at
|
||||
`
|
||||
|
||||
type InsertMessageParams struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
}
|
||||
|
||||
func (q *Queries) InsertMessage(ctx context.Context, arg InsertMessageParams) (Message, error) {
|
||||
row := q.db.QueryRow(ctx, insertMessage,
|
||||
arg.ID,
|
||||
arg.ChatID,
|
||||
arg.SenderID,
|
||||
arg.Text,
|
||||
)
|
||||
var i Message
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.SenderID,
|
||||
&i.Text,
|
||||
&i.CreatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertSession = `-- name: InsertSession :one
|
||||
INSERT INTO sessions(token_hash,user_id,expires_at)
|
||||
SELECT $1,$2,$3 WHERE (SELECT count(*) FROM sessions WHERE user_id=$2)<100
|
||||
RETURNING user_id
|
||||
`
|
||||
|
||||
type InsertSessionParams struct {
|
||||
TokenHash string
|
||||
UserID uuid.UUID
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) InsertSession(ctx context.Context, arg InsertSessionParams) (uuid.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, insertSession, arg.TokenHash, arg.UserID, arg.ExpiresAt)
|
||||
var user_id uuid.UUID
|
||||
err := row.Scan(&user_id)
|
||||
return user_id, err
|
||||
}
|
||||
|
||||
const listChats = `-- name: ListChats :many
|
||||
SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id)::uuid[] AS members
|
||||
FROM chats c JOIN chat_members m ON m.chat_id=c.id
|
||||
WHERE m.user_id=$1 AND (c.created_at,c.id)>($2::timestamptz,$3::uuid)
|
||||
ORDER BY c.created_at,c.id LIMIT $4
|
||||
`
|
||||
|
||||
type ListChatsParams struct {
|
||||
MemberID uuid.UUID
|
||||
AfterTime time.Time
|
||||
AfterID uuid.UUID
|
||||
PageLimit int32
|
||||
}
|
||||
|
||||
type ListChatsRow struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
CreatedAt time.Time
|
||||
Members []uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) ListChats(ctx context.Context, arg ListChatsParams) ([]ListChatsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listChats,
|
||||
arg.MemberID,
|
||||
arg.AfterTime,
|
||||
arg.AfterID,
|
||||
arg.PageLimit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []ListChatsRow{}
|
||||
for rows.Next() {
|
||||
var i ListChatsRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Title,
|
||||
&i.CreatedAt,
|
||||
&i.Members,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listMessages = `-- name: ListMessages :many
|
||||
SELECT m.id,m.chat_id,m.sender_id,m.text,m.created_at,
|
||||
ARRAY(SELECT attachment_id FROM message_attachments WHERE message_id=m.id ORDER BY ordinal LIMIT 10)::uuid[] AS attachment_ids
|
||||
FROM messages m WHERE m.chat_id=$1 AND (m.created_at,m.id)>($2::timestamptz,$3::uuid)
|
||||
ORDER BY m.created_at,m.id LIMIT $4
|
||||
`
|
||||
|
||||
type ListMessagesParams struct {
|
||||
ChatID uuid.UUID
|
||||
AfterTime time.Time
|
||||
AfterID uuid.UUID
|
||||
PageLimit int32
|
||||
}
|
||||
|
||||
type ListMessagesRow struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
AttachmentIds []uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) ListMessages(ctx context.Context, arg ListMessagesParams) ([]ListMessagesRow, error) {
|
||||
rows, err := q.db.Query(ctx, listMessages,
|
||||
arg.ChatID,
|
||||
arg.AfterTime,
|
||||
arg.AfterID,
|
||||
arg.PageLimit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []ListMessagesRow{}
|
||||
for rows.Next() {
|
||||
var i ListMessagesRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.SenderID,
|
||||
&i.Text,
|
||||
&i.CreatedAt,
|
||||
&i.AttachmentIds,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const lockSessionOwner = `-- name: LockSessionOwner :one
|
||||
SELECT id FROM users WHERE id=$1 FOR UPDATE
|
||||
`
|
||||
|
||||
func (q *Queries) LockSessionOwner(ctx context.Context, id uuid.UUID) (uuid.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, lockSessionOwner, id)
|
||||
var id_2 uuid.UUID
|
||||
err := row.Scan(&id_2)
|
||||
return id_2, err
|
||||
}
|
||||
|
||||
const revokeSession = `-- name: RevokeSession :exec
|
||||
DELETE FROM sessions WHERE token_hash=$1
|
||||
`
|
||||
|
||||
func (q *Queries) RevokeSession(ctx context.Context, tokenHash string) error {
|
||||
_, err := q.db.Exec(ctx, revokeSession, tokenHash)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
|
||||
package queries
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
type DBTX interface {
|
||||
Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
|
||||
Query(context.Context, string, ...interface{}) (pgx.Rows, error)
|
||||
QueryRow(context.Context, string, ...interface{}) pgx.Row
|
||||
}
|
||||
|
||||
func New(db DBTX) *Queries {
|
||||
return &Queries{db: db}
|
||||
}
|
||||
|
||||
type Queries struct {
|
||||
db DBTX
|
||||
}
|
||||
|
||||
func (q *Queries) WithTx(tx pgx.Tx) *Queries {
|
||||
return &Queries{
|
||||
db: tx,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: idempotency.sql
|
||||
|
||||
package queries
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const replayMessage = `-- name: ReplayMessage :one
|
||||
SELECT m.id,m.chat_id,m.sender_id,m.text,m.created_at,i.payload_hash,
|
||||
ARRAY(SELECT attachment_id FROM message_attachments WHERE message_id=m.id ORDER BY ordinal LIMIT 10)::uuid[] AS attachment_ids
|
||||
FROM idempotency i JOIN messages m ON m.id=i.message_id
|
||||
WHERE i.user_id=$1 AND i.chat_id=$2 AND i.key=$3
|
||||
`
|
||||
|
||||
type ReplayMessageParams struct {
|
||||
UserID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
Key string
|
||||
}
|
||||
|
||||
type ReplayMessageRow struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
PayloadHash string
|
||||
AttachmentIds []uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) ReplayMessage(ctx context.Context, arg ReplayMessageParams) (ReplayMessageRow, error) {
|
||||
row := q.db.QueryRow(ctx, replayMessage, arg.UserID, arg.ChatID, arg.Key)
|
||||
var i ReplayMessageRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.SenderID,
|
||||
&i.Text,
|
||||
&i.CreatedAt,
|
||||
&i.PayloadHash,
|
||||
&i.AttachmentIds,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const reserveKey = `-- name: ReserveKey :one
|
||||
INSERT INTO idempotency(user_id,chat_id,key,payload_hash,message_id,expires_at)
|
||||
VALUES($1,$2,$3,$4,$5,clock_timestamp()+interval '24 hours')
|
||||
ON CONFLICT(user_id,chat_id,key) DO UPDATE SET payload_hash=excluded.payload_hash,
|
||||
message_id=excluded.message_id,expires_at=excluded.expires_at
|
||||
WHERE idempotency.expires_at<=clock_timestamp()
|
||||
RETURNING message_id
|
||||
`
|
||||
|
||||
type ReserveKeyParams struct {
|
||||
UserID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
Key string
|
||||
PayloadHash string
|
||||
MessageID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) ReserveKey(ctx context.Context, arg ReserveKeyParams) (uuid.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, reserveKey,
|
||||
arg.UserID,
|
||||
arg.ChatID,
|
||||
arg.Key,
|
||||
arg.PayloadHash,
|
||||
arg.MessageID,
|
||||
)
|
||||
var message_id uuid.UUID
|
||||
err := row.Scan(&message_id)
|
||||
return message_id, err
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
|
||||
package queries
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Attachment struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
OwnerID uuid.UUID
|
||||
Filename string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
Sha256 string
|
||||
Status string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type Chat struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type ChatMember struct {
|
||||
ChatID uuid.UUID
|
||||
UserID uuid.UUID
|
||||
}
|
||||
|
||||
type Idempotency struct {
|
||||
UserID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
Key string
|
||||
PayloadHash string
|
||||
MessageID uuid.UUID
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type MessageAttachment struct {
|
||||
MessageID uuid.UUID
|
||||
AttachmentID uuid.UUID
|
||||
Ordinal int32
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
TokenHash string
|
||||
UserID uuid.UUID
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
PasswordHash string
|
||||
CreatedAt time.Time
|
||||
ChatCount int32
|
||||
MessageCount int32
|
||||
AttachmentCount int32
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"backend/internal/adapter/repository/postgres/queries"
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/repository"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
//go:generate go tool sqlc generate -f ../../../../db/sqlc/sqlc.yaml
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
q *queries.Queries
|
||||
cache *redis.Client
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool, cache *redis.Client) repository.Persistent {
|
||||
return &Store{pool, queries.New(pool), cache}
|
||||
}
|
||||
func mapErr(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.ErrNotFound
|
||||
}
|
||||
var pg *pgconn.PgError
|
||||
if errors.As(err, &pg) {
|
||||
switch pg.Code {
|
||||
case "23505":
|
||||
return model.ErrUsernameTaken
|
||||
case "23503":
|
||||
return model.ErrUnknownMember
|
||||
case "23514":
|
||||
return &model.ValidationError{Message: "constraint violation"}
|
||||
}
|
||||
}
|
||||
return model.ErrUnavailable
|
||||
}
|
||||
func (s *Store) CreateUser(ctx context.Context, d model.UserDraft) (model.User, error) {
|
||||
row, err := s.q.CreateUser(ctx, queries.CreateUserParams{ID: uuid.New(), Username: d.Username, DisplayName: d.DisplayName, PasswordHash: d.PasswordHash})
|
||||
return model.User{ID: row.ID, Username: row.Username, DisplayName: row.DisplayName, CreatedAt: row.CreatedAt}, mapErr(err)
|
||||
}
|
||||
func (s *Store) GetUser(ctx context.Context, id uuid.UUID) (model.User, error) {
|
||||
key := "profile:" + id.String()
|
||||
if s.cache != nil {
|
||||
c, cancel := context.WithTimeout(ctx, 80*time.Millisecond)
|
||||
raw, err := s.cache.Get(c, key).Bytes()
|
||||
cancel()
|
||||
if err == nil {
|
||||
var u model.User
|
||||
if json.Unmarshal(raw, &u) == nil && u.ID == id {
|
||||
return u, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
row, err := s.q.GetUser(ctx, id)
|
||||
if err != nil {
|
||||
return model.User{}, mapErr(err)
|
||||
}
|
||||
user := model.User{ID: row.ID, Username: row.Username, DisplayName: row.DisplayName, CreatedAt: row.CreatedAt}
|
||||
if s.cache != nil {
|
||||
raw, e := json.Marshal(user)
|
||||
if e == nil {
|
||||
c, cancel := context.WithTimeout(ctx, 80*time.Millisecond)
|
||||
_ = s.cache.Set(c, key, raw, time.Minute).Err()
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
func (s *Store) CreateChat(ctx context.Context, d model.ChatDraft) (model.Chat, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Chat{}, mapErr(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
q := s.q.WithTx(tx)
|
||||
if _, err = q.ChargeChat(ctx, d.Creator); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Chat{}, model.ErrStorageFull
|
||||
}
|
||||
return model.Chat{}, mapErr(err)
|
||||
}
|
||||
row, err := q.InsertChat(ctx, queries.InsertChatParams{ID: uuid.New(), Title: d.Title})
|
||||
if err != nil {
|
||||
return model.Chat{}, mapErr(err)
|
||||
}
|
||||
if err = q.InsertMembers(ctx, queries.InsertMembersParams{ChatID: row.ID, Column2: d.MemberIDs}); err != nil {
|
||||
return model.Chat{}, mapErr(err)
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return model.Chat{}, mapErr(err)
|
||||
}
|
||||
return model.Chat{ID: row.ID, Title: row.Title, CreatedAt: row.CreatedAt, MemberIDs: d.MemberIDs}, nil
|
||||
}
|
||||
func (s *Store) GetChat(ctx context.Context, id uuid.UUID) (model.Chat, error) {
|
||||
r, e := s.q.GetChat(ctx, id)
|
||||
return model.Chat{ID: r.ID, Title: r.Title, CreatedAt: r.CreatedAt, MemberIDs: r.Members}, mapErr(e)
|
||||
}
|
||||
func position(q model.PageQuery) (time.Time, uuid.UUID) {
|
||||
if q.After == nil {
|
||||
return time.Unix(0, 0).UTC(), uuid.Nil
|
||||
}
|
||||
return q.After.CreatedAt, q.After.ID
|
||||
}
|
||||
func (s *Store) ListChats(ctx context.Context, id uuid.UUID, p model.PageQuery) ([]model.Chat, bool, error) {
|
||||
at, aid := position(p)
|
||||
rows, err := s.q.ListChats(ctx, queries.ListChatsParams{MemberID: id, AfterTime: at, AfterID: aid, PageLimit: int32(p.Limit + 1)})
|
||||
if err != nil {
|
||||
return nil, false, mapErr(err)
|
||||
}
|
||||
more := len(rows) > p.Limit
|
||||
if more {
|
||||
rows = rows[:p.Limit]
|
||||
}
|
||||
out := make([]model.Chat, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = model.Chat{ID: r.ID, Title: r.Title, CreatedAt: r.CreatedAt, MemberIDs: r.Members}
|
||||
}
|
||||
return out, more, nil
|
||||
}
|
||||
func (s *Store) CreateMessage(ctx context.Context, d model.MessageDraft) (model.Message, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Message{}, mapErr(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
q := s.q.WithTx(tx)
|
||||
messageID := uuid.New()
|
||||
reserved, e := q.ReserveKey(ctx, queries.ReserveKeyParams{UserID: d.SenderID, ChatID: d.ChatID, Key: d.Key, PayloadHash: d.PayloadHash, MessageID: messageID})
|
||||
if errors.Is(e, pgx.ErrNoRows) {
|
||||
r, e := q.ReplayMessage(ctx, queries.ReplayMessageParams{UserID: d.SenderID, ChatID: d.ChatID, Key: d.Key})
|
||||
if e != nil {
|
||||
return model.Message{}, mapErr(e)
|
||||
}
|
||||
if r.PayloadHash != d.PayloadHash {
|
||||
return model.Message{}, model.ErrConflict
|
||||
}
|
||||
return model.Message{ID: r.ID, ChatID: r.ChatID, SenderID: r.SenderID, Text: r.Text, CreatedAt: r.CreatedAt, AttachmentIDs: r.AttachmentIds}, nil
|
||||
}
|
||||
if e != nil {
|
||||
return model.Message{}, mapErr(e)
|
||||
}
|
||||
messageID = reserved
|
||||
for _, id := range d.AttachmentIDs {
|
||||
a, e := q.GetAttachment(ctx, id)
|
||||
if errors.Is(e, pgx.ErrNoRows) {
|
||||
return model.Message{}, model.ErrNotFound
|
||||
}
|
||||
if e != nil {
|
||||
return model.Message{}, mapErr(e)
|
||||
}
|
||||
if a.ChatID != d.ChatID {
|
||||
return model.Message{}, model.ErrNotFound
|
||||
}
|
||||
if a.Status != "ready" {
|
||||
return model.Message{}, model.ErrConflict
|
||||
}
|
||||
}
|
||||
if _, err = q.ChargeMessage(ctx, d.SenderID); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Message{}, model.ErrStorageFull
|
||||
}
|
||||
return model.Message{}, mapErr(err)
|
||||
}
|
||||
r, err := q.InsertMessage(ctx, queries.InsertMessageParams{ID: messageID, ChatID: d.ChatID, SenderID: d.SenderID, Text: d.Text})
|
||||
if err != nil {
|
||||
return model.Message{}, mapErr(err)
|
||||
}
|
||||
for i, id := range d.AttachmentIDs {
|
||||
if e := q.InsertMessageAttachment(ctx, queries.InsertMessageAttachmentParams{MessageID: messageID, AttachmentID: id, Ordinal: int32(i)}); e != nil {
|
||||
return model.Message{}, mapErr(e)
|
||||
}
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return model.Message{}, mapErr(err)
|
||||
}
|
||||
return model.Message{ID: r.ID, ChatID: r.ChatID, SenderID: r.SenderID, Text: r.Text, CreatedAt: r.CreatedAt, AttachmentIDs: d.AttachmentIDs}, nil
|
||||
}
|
||||
func (s *Store) ListMessages(ctx context.Context, id uuid.UUID, p model.PageQuery) ([]model.Message, bool, error) {
|
||||
at, aid := position(p)
|
||||
rows, err := s.q.ListMessages(ctx, queries.ListMessagesParams{ChatID: id, AfterTime: at, AfterID: aid, PageLimit: int32(p.Limit + 1)})
|
||||
if err != nil {
|
||||
return nil, false, mapErr(err)
|
||||
}
|
||||
more := len(rows) > p.Limit
|
||||
if more {
|
||||
rows = rows[:p.Limit]
|
||||
}
|
||||
out := make([]model.Message, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = model.Message{ID: r.ID, ChatID: r.ChatID, SenderID: r.SenderID, Text: r.Text, CreatedAt: r.CreatedAt, AttachmentIDs: r.AttachmentIds}
|
||||
}
|
||||
return out, more, nil
|
||||
}
|
||||
func (s *Store) Credentials(ctx context.Context, name string) (uuid.UUID, string, error) {
|
||||
r, e := s.q.Credentials(ctx, name)
|
||||
if errors.Is(e, pgx.ErrNoRows) {
|
||||
return uuid.Nil, "", model.ErrUnauthorized
|
||||
}
|
||||
return r.ID, r.PasswordHash, mapErr(e)
|
||||
}
|
||||
func (s *Store) CreateSession(ctx context.Context, hash string, id uuid.UUID, expiry time.Time) error {
|
||||
tx, e := s.pool.Begin(ctx)
|
||||
if e != nil {
|
||||
return mapErr(e)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
q := s.q.WithTx(tx)
|
||||
if _, e = q.LockSessionOwner(ctx, id); e != nil {
|
||||
return mapErr(e)
|
||||
}
|
||||
if e = q.DeleteExpiredSessions(ctx, id); e != nil {
|
||||
return mapErr(e)
|
||||
}
|
||||
if _, e = q.InsertSession(ctx, queries.InsertSessionParams{TokenHash: hash, UserID: id, ExpiresAt: expiry}); e != nil {
|
||||
if errors.Is(e, pgx.ErrNoRows) {
|
||||
return model.ErrStorageFull
|
||||
}
|
||||
return mapErr(e)
|
||||
}
|
||||
return mapErr(tx.Commit(ctx))
|
||||
}
|
||||
func (s *Store) AuthenticateSession(ctx context.Context, hash string) (uuid.UUID, error) {
|
||||
r, e := s.q.AuthenticateSession(ctx, hash)
|
||||
if errors.Is(e, pgx.ErrNoRows) {
|
||||
return uuid.Nil, model.ErrUnauthorized
|
||||
}
|
||||
return r, mapErr(e)
|
||||
}
|
||||
func (s *Store) RevokeSession(ctx context.Context, hash string) error {
|
||||
return mapErr(s.q.RevokeSession(ctx, hash))
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/signer"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct{ Endpoint, Access, Secret, Bucket string }
|
||||
|
||||
func ReadConfig(path string) (Config, error) {
|
||||
var c Config
|
||||
b, e := os.ReadFile(path)
|
||||
if e != nil {
|
||||
return c, fmt.Errorf("S3 credentials unavailable")
|
||||
}
|
||||
if e = json.Unmarshal(b, &c); e != nil {
|
||||
return c, fmt.Errorf("invalid S3 credentials format")
|
||||
}
|
||||
if c.Endpoint == "" || c.Access == "" || c.Secret == "" || c.Bucket == "" {
|
||||
return c, fmt.Errorf("incomplete S3 configuration")
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
func FromConfig(c Config) (*S3, error) { return New(c.Endpoint, c.Access, c.Secret, c.Bucket) }
|
||||
|
||||
// RustFS provides S3 SDKs, but its documented administrative API is separate.
|
||||
// Use the SDK's SigV4 signer; do not implement signing or persist credentials in command arguments.
|
||||
func admin(ctx context.Context, c Config, path string, body []byte) error {
|
||||
r, e := http.NewRequestWithContext(ctx, http.MethodPut, "http://"+c.Endpoint+"/rustfs/admin/v3/"+path, bytes.NewReader(body))
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
sum := sha256.Sum256(body)
|
||||
r.Header.Set("X-Amz-Content-Sha256", hex.EncodeToString(sum[:]))
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
signed := signer.SignV4(*r, c.Access, c.Secret, "", "us-east-1")
|
||||
response, e := (&http.Client{Timeout: 5 * time.Second}).Do(signed)
|
||||
if e != nil {
|
||||
return fmt.Errorf("S3 admin transport failed")
|
||||
}
|
||||
defer response.Body.Close()
|
||||
_, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 64*1024))
|
||||
if response.StatusCode != 200 && response.StatusCode != 204 {
|
||||
return fmt.Errorf("S3 admin operation rejected: HTTP %d", response.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func Bootstrap(ctx context.Context, root, app Config) error {
|
||||
s, e := FromConfig(root)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
exists, e := s.Client.BucketExists(ctx, root.Bucket)
|
||||
if e != nil {
|
||||
return fmt.Errorf("bucket availability check failed")
|
||||
}
|
||||
if !exists {
|
||||
if e = s.Client.MakeBucket(ctx, root.Bucket, minio.MakeBucketOptions{Region: "us-east-1"}); e != nil {
|
||||
return fmt.Errorf("bucket creation failed")
|
||||
}
|
||||
}
|
||||
policy := map[string]any{"Version": "2012-10-17", "Statement": []any{
|
||||
map[string]any{"Effect": "Allow", "Action": []string{"s3:GetBucketLocation", "s3:ListBucket"}, "Resource": []string{"arn:aws:s3:::" + app.Bucket}},
|
||||
map[string]any{"Effect": "Allow", "Action": []string{"s3:PutObject", "s3:GetObject", "s3:DeleteObject"}, "Resource": []string{"arn:aws:s3:::" + app.Bucket + "/originals/*"}},
|
||||
}}
|
||||
raw, _ := json.Marshal(policy)
|
||||
if e = admin(ctx, root, "add-canned-policy?name=messenger", raw); e != nil {
|
||||
return e
|
||||
}
|
||||
raw, _ = json.Marshal(map[string]string{"secretKey": app.Secret, "status": "enabled"})
|
||||
if e = admin(ctx, root, "add-user?accessKey="+url.QueryEscape(app.Access), raw); e != nil {
|
||||
return e
|
||||
}
|
||||
return admin(ctx, root, "set-user-or-group-policy?policyName=messenger&userOrGroup="+url.QueryEscape(app.Access)+"&isGroup=false", nil)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMissingBucketFailsReadiness(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(404) }))
|
||||
defer server.Close()
|
||||
store, err := New(strings.TrimPrefix(server.URL, "http://"), "synthetic-access", "synthetic-secret", "missing")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = store.Ready(context.Background()); err == nil {
|
||||
t.Fatal("missing bucket reported ready")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/port"
|
||||
"context"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type S3 struct {
|
||||
Client *minio.Client
|
||||
Bucket string
|
||||
}
|
||||
|
||||
func New(endpoint, access, secret, bucket string) (*S3, error) {
|
||||
client, err := minio.New(endpoint, &minio.Options{Creds: credentials.NewStaticV4(access, secret, ""), Secure: false, Region: "us-east-1", Transport: &http.Transport{DialContext: (&net.Dialer{Timeout: time.Second}).DialContext, ResponseHeaderTimeout: 3 * time.Second, MaxIdleConnsPerHost: 8}})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &S3{client, bucket}, nil
|
||||
}
|
||||
func mapError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
r := minio.ToErrorResponse(err)
|
||||
if r.Code == "NoSuchKey" || r.Code == "NoSuchObject" || r.Code == "NotFound" {
|
||||
return model.ErrNotFound
|
||||
}
|
||||
return model.ErrUnavailable
|
||||
}
|
||||
func (s *S3) Put(ctx context.Context, key string, r io.Reader, size int64, mime string) error {
|
||||
_, err := s.Client.PutObject(ctx, s.Bucket, key, r, size, minio.PutObjectOptions{ContentType: mime, DisableMultipart: true})
|
||||
return mapError(err)
|
||||
}
|
||||
func (s *S3) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
||||
obj, err := s.Client.GetObject(ctx, s.Bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
if _, err = obj.Stat(); err != nil {
|
||||
_ = obj.Close()
|
||||
return nil, mapError(err)
|
||||
}
|
||||
return obj, nil
|
||||
}
|
||||
func (s *S3) Stat(ctx context.Context, key string) (port.Object, error) {
|
||||
r, e := s.Client.StatObject(ctx, s.Bucket, key, minio.StatObjectOptions{})
|
||||
return port.Object{Key: key, ETag: r.ETag, Size: r.Size, Modified: r.LastModified.UTC().Truncate(time.Second)}, mapError(e)
|
||||
}
|
||||
func (s *S3) Remove(ctx context.Context, key string) error {
|
||||
return mapError(s.Client.RemoveObject(ctx, s.Bucket, key, minio.RemoveObjectOptions{}))
|
||||
}
|
||||
func (s *S3) List(ctx context.Context, after string) ([]port.Object, bool, error) {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
out := []port.Object{}
|
||||
for r := range s.Client.ListObjects(ctx, s.Bucket, minio.ListObjectsOptions{Prefix: "originals/", StartAfter: after, Recursive: true, MaxKeys: 100}) {
|
||||
if r.Err != nil {
|
||||
return nil, false, mapError(r.Err)
|
||||
}
|
||||
// HTTP Last-Modified has second precision; RustFS inventory also carries milliseconds.
|
||||
out = append(out, port.Object{Key: r.Key, ETag: r.ETag, Size: r.Size, Modified: r.LastModified.UTC().Truncate(time.Second)})
|
||||
if len(out) > 100 {
|
||||
return out[:100], true, nil
|
||||
}
|
||||
}
|
||||
return out, false, nil
|
||||
}
|
||||
func (s *S3) Ready(ctx context.Context) error {
|
||||
exists, err := s.Client.BucketExists(ctx, s.Bucket)
|
||||
if err != nil || !exists {
|
||||
return model.ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package usecase
|
||||
|
||||
import (
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/port"
|
||||
"backend/internal/domain/repository"
|
||||
"context"
|
||||
"github.com/google/uuid"
|
||||
"io"
|
||||
)
|
||||
|
||||
type Attachments struct {
|
||||
repo repository.AttachmentRepository
|
||||
messenger *Messenger
|
||||
objects port.Objects
|
||||
}
|
||||
|
||||
func NewAttachments(r repository.AttachmentRepository, m *Messenger, o port.Objects) *Attachments {
|
||||
return &Attachments{r, m, o}
|
||||
}
|
||||
func ObjectKey(id uuid.UUID) string { return "originals/" + id.String() }
|
||||
func (a *Attachments) Upload(ctx context.Context, caller, chat uuid.UUID, name, mime, sha string, size int64, body io.Reader) (model.Attachment, error) {
|
||||
if _, e := a.messenger.GetChat(ctx, caller, chat); e != nil {
|
||||
return model.Attachment{}, e
|
||||
}
|
||||
row, e := a.repo.ReserveAttachment(ctx, model.Attachment{ID: uuid.New(), ChatID: chat, OwnerID: caller, Filename: name, ContentType: mime, SHA256: sha, SizeBytes: size})
|
||||
if e != nil {
|
||||
return model.Attachment{}, e
|
||||
}
|
||||
if e = a.objects.Put(ctx, ObjectKey(row.ID), body, size, mime); e != nil {
|
||||
return model.Attachment{}, model.ErrUnavailable
|
||||
}
|
||||
ok, e := a.repo.SetAttachmentStatus(ctx, row.ID, "uploading", "ready")
|
||||
if e != nil {
|
||||
return model.Attachment{}, e
|
||||
}
|
||||
if !ok {
|
||||
return model.Attachment{}, model.ErrUnavailable
|
||||
}
|
||||
return a.repo.GetAttachment(ctx, row.ID)
|
||||
}
|
||||
func (a *Attachments) Get(ctx context.Context, caller, id uuid.UUID) (model.Attachment, error) {
|
||||
row, e := a.repo.GetAttachment(ctx, id)
|
||||
if e != nil {
|
||||
return model.Attachment{}, e
|
||||
}
|
||||
if _, e = a.messenger.GetChat(ctx, caller, row.ChatID); e != nil {
|
||||
return model.Attachment{}, e
|
||||
}
|
||||
if row.Status != "ready" {
|
||||
return model.Attachment{}, model.ErrUnavailable
|
||||
}
|
||||
return row, nil
|
||||
}
|
||||
func (a *Attachments) Content(ctx context.Context, caller, id uuid.UUID) (model.Attachment, io.ReadCloser, error) {
|
||||
row, e := a.Get(ctx, caller, id)
|
||||
if e != nil {
|
||||
return row, nil, e
|
||||
}
|
||||
info, e := a.objects.Stat(ctx, ObjectKey(id))
|
||||
if e != nil || info.Size != row.SizeBytes {
|
||||
return row, nil, model.ErrUnavailable
|
||||
}
|
||||
r, e := a.objects.Get(ctx, ObjectKey(id))
|
||||
if e != nil {
|
||||
return row, nil, model.ErrUnavailable
|
||||
}
|
||||
return row, r, nil
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package usecase
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/port"
|
||||
)
|
||||
|
||||
type Auth struct {
|
||||
sessions port.Sessions
|
||||
passwords port.Passwords
|
||||
messenger *Messenger
|
||||
ttl time.Duration
|
||||
now func() time.Time
|
||||
}
|
||||
type Session struct {
|
||||
Token string
|
||||
ExpiresAt time.Time
|
||||
User model.User
|
||||
}
|
||||
|
||||
func NewAuth(s port.Sessions, p port.Passwords, m *Messenger, ttl time.Duration, now func() time.Time) *Auth {
|
||||
return &Auth{s, p, m, ttl, now}
|
||||
}
|
||||
func (a *Auth) Register(ctx context.Context, username, name, password string) (model.User, error) {
|
||||
if n := utf8.RuneCountInString(password); n < 12 || n > 128 || !utf8.ValidString(password) {
|
||||
return model.User{}, &model.ValidationError{Message: "password: 12–128 Unicode characters"}
|
||||
}
|
||||
draft, err := model.NewUserDraft(username, name)
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
hash, err := a.passwords.Hash(password)
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
draft.PasswordHash = hash
|
||||
return a.messenger.repo.CreateUser(ctx, draft)
|
||||
}
|
||||
func (a *Auth) Login(ctx context.Context, username, password string) (Session, error) {
|
||||
id, hash, err := a.sessions.Credentials(ctx, username)
|
||||
if err != nil {
|
||||
return Session{}, err
|
||||
}
|
||||
if !a.passwords.Verify(password, hash) {
|
||||
return Session{}, model.ErrUnauthorized
|
||||
}
|
||||
user, err := a.messenger.repo.GetUser(ctx, id)
|
||||
if err != nil {
|
||||
return Session{}, err
|
||||
}
|
||||
raw := make([]byte, 32)
|
||||
if _, err = rand.Read(raw); err != nil {
|
||||
return Session{}, err
|
||||
}
|
||||
token := base64.RawURLEncoding.EncodeToString(raw)
|
||||
expires := a.now().UTC().Add(a.ttl)
|
||||
if err = a.sessions.CreateSession(ctx, TokenHash(token), id, expires); err != nil {
|
||||
return Session{}, err
|
||||
}
|
||||
return Session{token, expires, user}, nil
|
||||
}
|
||||
func TokenHash(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
func (a *Auth) Authenticate(ctx context.Context, token string) (model.User, error) {
|
||||
if len(token) != 43 {
|
||||
return model.User{}, model.ErrUnauthorized
|
||||
}
|
||||
id, err := a.sessions.AuthenticateSession(ctx, TokenHash(token))
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
return a.messenger.repo.GetUser(ctx, id)
|
||||
}
|
||||
func (a *Auth) Logout(ctx context.Context, token string) error {
|
||||
return a.sessions.RevokeSession(ctx, TokenHash(token))
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package usecase
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/repository"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const chatsCursorScope = "chats"
|
||||
|
||||
// Page — страница списка; NextCursor == nil, если следующей записи нет.
|
||||
type Page[T any] struct {
|
||||
Items []T
|
||||
NextCursor *string
|
||||
}
|
||||
|
||||
type Messenger struct {
|
||||
repo repository.Repository
|
||||
}
|
||||
|
||||
func NewMessenger(repo repository.Repository) *Messenger {
|
||||
return &Messenger{repo: repo}
|
||||
}
|
||||
|
||||
func (m *Messenger) CreateChat(ctx context.Context, caller uuid.UUID, title string, memberIDs []uuid.UUID) (model.Chat, error) {
|
||||
draft, err := model.NewChatDraft(caller, title, memberIDs)
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
return m.repo.CreateChat(ctx, draft)
|
||||
}
|
||||
|
||||
func (m *Messenger) ListChats(ctx context.Context, caller uuid.UUID, limit *int, cursor *string) (Page[model.Chat], error) {
|
||||
q, err := model.NewPageQuery(limit, cursor, chatsCursorScope)
|
||||
if err != nil {
|
||||
return Page[model.Chat]{}, err
|
||||
}
|
||||
chats, more, err := m.repo.ListChats(ctx, caller, q)
|
||||
if err != nil {
|
||||
return Page[model.Chat]{}, err
|
||||
}
|
||||
return newPage(chats, more, chatsCursorScope, model.Chat.Position), nil
|
||||
}
|
||||
|
||||
// GetChat отдаёт чат только участнику; постороннему — ErrNotFound, чтобы не
|
||||
// раскрывать существование чужого чата.
|
||||
func (m *Messenger) GetChat(ctx context.Context, caller, chatID uuid.UUID) (model.Chat, error) {
|
||||
chat, err := m.repo.GetChat(ctx, chatID)
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
if !chat.HasMember(caller) {
|
||||
return model.Chat{}, model.ErrNotFound
|
||||
}
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
// SendMessage сначала проверяет доступ, затем тело: посторонний получает 404
|
||||
// даже на невалидное сообщение. Проверка членства и запись не атомарны, но
|
||||
// участники чата неизменяемы, а чаты не удаляются, поэтому гонки здесь нет.
|
||||
func (m *Messenger) SendMessage(ctx context.Context, caller, chatID uuid.UUID, text, key string, attachments []uuid.UUID) (model.Message, error) {
|
||||
if _, err := m.GetChat(ctx, caller, chatID); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
draft, err := model.NewMessageDraft(chatID, caller, text, attachments)
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
draft, err = model.WithKey(draft, key)
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
return m.repo.CreateMessage(ctx, draft)
|
||||
}
|
||||
|
||||
func (m *Messenger) ListMessages(ctx context.Context, caller, chatID uuid.UUID, limit *int, cursor *string) (Page[model.Message], error) {
|
||||
if _, err := m.GetChat(ctx, caller, chatID); err != nil {
|
||||
return Page[model.Message]{}, err
|
||||
}
|
||||
scope := "messages:" + chatID.String()
|
||||
q, err := model.NewPageQuery(limit, cursor, scope)
|
||||
if err != nil {
|
||||
return Page[model.Message]{}, err
|
||||
}
|
||||
messages, more, err := m.repo.ListMessages(ctx, chatID, q)
|
||||
if err != nil {
|
||||
return Page[model.Message]{}, err
|
||||
}
|
||||
return newPage(messages, more, scope, model.Message.Position), nil
|
||||
}
|
||||
|
||||
func newPage[T any](items []T, more bool, scope string, position func(T) model.Position) Page[T] {
|
||||
page := Page[T]{Items: items}
|
||||
if more && len(items) > 0 {
|
||||
next := model.EncodeCursor(scope, position(items[len(items)-1]))
|
||||
page.NextCursor = &next
|
||||
}
|
||||
return page
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package usecase
|
||||
|
||||
import (
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/port"
|
||||
"backend/internal/domain/repository"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"github.com/google/uuid"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ReconcileReport struct {
|
||||
Metadata, Objects, Orphans, Missing, Recovered, Fresh, Deleted, Changed int
|
||||
NextMetadata, NextObject string
|
||||
}
|
||||
type Reconciler struct {
|
||||
repo repository.AttachmentRepository
|
||||
objects port.Objects
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewReconciler(repo repository.AttachmentRepository, objects port.Objects, now func() time.Time) *Reconciler {
|
||||
return &Reconciler{repo, objects, now}
|
||||
}
|
||||
func (r *Reconciler) Run(ctx context.Context, after uuid.UUID, objectAfter string, grace time.Duration, apply bool) (report ReconcileReport, runErr error) {
|
||||
report = ReconcileReport{}
|
||||
defer func() {
|
||||
if runErr != nil {
|
||||
report.NextMetadata = ""
|
||||
report.NextObject = ""
|
||||
}
|
||||
}()
|
||||
if grace < time.Minute {
|
||||
return report, &model.ValidationError{Message: "reconciliation grace must be at least 60 seconds"}
|
||||
}
|
||||
now := r.now().UTC()
|
||||
old := func(t time.Time) bool { age := now.Sub(t); return !t.IsZero() && age >= grace && age >= 0 }
|
||||
rows, more, e := r.repo.ReconcileAttachments(ctx, after)
|
||||
if e != nil {
|
||||
return report, e
|
||||
}
|
||||
for _, a := range rows {
|
||||
report.Metadata++
|
||||
if more {
|
||||
report.NextMetadata = a.ID.String()
|
||||
}
|
||||
if !old(a.CreatedAt) {
|
||||
report.Fresh++
|
||||
continue
|
||||
}
|
||||
info, e := r.objects.Stat(ctx, ObjectKey(a.ID))
|
||||
target := a.Status
|
||||
if errors.Is(e, model.ErrNotFound) {
|
||||
switch a.Status {
|
||||
case "ready":
|
||||
report.Missing++
|
||||
target = "missing"
|
||||
case "uploading":
|
||||
report.Missing++
|
||||
target = "abandoned"
|
||||
}
|
||||
} else if e != nil {
|
||||
return report, e
|
||||
} else if a.Status != "ready" {
|
||||
valid := false
|
||||
if info.Size == a.SizeBytes {
|
||||
body, err := r.objects.Get(ctx, ObjectKey(a.ID))
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
hash := sha256.New()
|
||||
n, err := io.Copy(hash, io.LimitReader(body, a.SizeBytes+1))
|
||||
_ = body.Close()
|
||||
if err != nil {
|
||||
return report, model.ErrUnavailable
|
||||
}
|
||||
valid = n == a.SizeBytes && hex.EncodeToString(hash.Sum(nil)) == a.SHA256
|
||||
}
|
||||
if valid {
|
||||
report.Recovered++
|
||||
target = "ready"
|
||||
} else {
|
||||
report.Missing++
|
||||
target = "missing"
|
||||
}
|
||||
} else if info.Size != a.SizeBytes {
|
||||
report.Missing++
|
||||
target = "missing"
|
||||
}
|
||||
if apply && target != a.Status {
|
||||
changed, e := r.repo.SetAttachmentStatus(ctx, a.ID, a.Status, target)
|
||||
if e != nil {
|
||||
return report, e
|
||||
}
|
||||
if changed {
|
||||
report.Changed++
|
||||
}
|
||||
}
|
||||
}
|
||||
objects, more, e := r.objects.List(ctx, objectAfter)
|
||||
if e != nil {
|
||||
return report, e
|
||||
}
|
||||
for _, o := range objects {
|
||||
report.Objects++
|
||||
if more {
|
||||
report.NextObject = o.Key
|
||||
}
|
||||
if !old(o.Modified) {
|
||||
report.Fresh++
|
||||
continue
|
||||
}
|
||||
raw, ok := strings.CutPrefix(o.Key, "originals/")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
id, e := uuid.Parse(raw)
|
||||
if e != nil || ObjectKey(id) != o.Key {
|
||||
continue
|
||||
}
|
||||
if _, e = r.repo.GetAttachment(ctx, id); e == nil {
|
||||
continue
|
||||
} else if !errors.Is(e, model.ErrNotFound) {
|
||||
return report, e
|
||||
}
|
||||
report.Orphans++
|
||||
if !apply {
|
||||
continue
|
||||
}
|
||||
fresh, e := r.objects.Stat(ctx, o.Key)
|
||||
if errors.Is(e, model.ErrNotFound) {
|
||||
continue
|
||||
}
|
||||
if e != nil {
|
||||
return report, e
|
||||
}
|
||||
if fresh.ETag != o.ETag || fresh.Size != o.Size || !fresh.Modified.Equal(o.Modified) || !old(fresh.Modified) {
|
||||
report.Fresh++
|
||||
continue
|
||||
}
|
||||
if _, e = r.repo.GetAttachment(ctx, id); e == nil {
|
||||
continue
|
||||
} else if !errors.Is(e, model.ErrNotFound) {
|
||||
return report, e
|
||||
}
|
||||
// Object keys are random UUIDs, immutable and never reused by the upload API.
|
||||
// An absent metadata row cannot later adopt an old inventory key.
|
||||
if e = r.objects.Remove(ctx, o.Key); e != nil {
|
||||
return report, e
|
||||
}
|
||||
report.Deleted++
|
||||
}
|
||||
return report, nil
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package usecase
|
||||
|
||||
import (
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/port"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"github.com/google/uuid"
|
||||
"io"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type fixtureRepo struct {
|
||||
rows map[uuid.UUID]model.Attachment
|
||||
failure error
|
||||
more bool
|
||||
}
|
||||
|
||||
func (f *fixtureRepo) ReserveAttachment(context.Context, model.Attachment) (model.Attachment, error) {
|
||||
panic("not used")
|
||||
}
|
||||
func (f *fixtureRepo) GetAttachment(_ context.Context, id uuid.UUID) (model.Attachment, error) {
|
||||
if f.failure != nil {
|
||||
return model.Attachment{}, f.failure
|
||||
}
|
||||
a, ok := f.rows[id]
|
||||
if !ok {
|
||||
return a, model.ErrNotFound
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
func (f *fixtureRepo) SetAttachmentStatus(_ context.Context, id uuid.UUID, from, to string) (bool, error) {
|
||||
a := f.rows[id]
|
||||
if a.Status != from {
|
||||
return false, nil
|
||||
}
|
||||
a.Status = to
|
||||
f.rows[id] = a
|
||||
return true, nil
|
||||
}
|
||||
func (f *fixtureRepo) ReconcileAttachments(context.Context, uuid.UUID) ([]model.Attachment, bool, error) {
|
||||
out := []model.Attachment{}
|
||||
for _, a := range f.rows {
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, f.more, f.failure
|
||||
}
|
||||
|
||||
type fixtureObjects struct {
|
||||
items map[string]port.Object
|
||||
content []byte
|
||||
failure error
|
||||
removed int
|
||||
changed bool
|
||||
}
|
||||
|
||||
func (f *fixtureObjects) Put(context.Context, string, io.Reader, int64, string) error {
|
||||
panic("not used")
|
||||
}
|
||||
func (f *fixtureObjects) Get(context.Context, string) (io.ReadCloser, error) {
|
||||
return io.NopCloser(bytes.NewReader(f.content)), f.failure
|
||||
}
|
||||
func (f *fixtureObjects) Stat(_ context.Context, key string) (port.Object, error) {
|
||||
if f.failure != nil {
|
||||
return port.Object{}, f.failure
|
||||
}
|
||||
o, ok := f.items[key]
|
||||
if !ok {
|
||||
return o, model.ErrNotFound
|
||||
}
|
||||
if f.changed {
|
||||
o.ETag = "changed"
|
||||
}
|
||||
return o, nil
|
||||
}
|
||||
func (f *fixtureObjects) Remove(_ context.Context, key string) error {
|
||||
delete(f.items, key)
|
||||
f.removed++
|
||||
return nil
|
||||
}
|
||||
func (f *fixtureObjects) List(context.Context, string) ([]port.Object, bool, error) {
|
||||
out := []port.Object{}
|
||||
for _, o := range f.items {
|
||||
out = append(out, o)
|
||||
}
|
||||
return out, false, f.failure
|
||||
}
|
||||
|
||||
var fixedNow = time.Date(2026, 11, 12, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
func TestOrphanCleanupHonorsGraceAndDryRun(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
age time.Duration
|
||||
apply, used, changed bool
|
||||
wantDeleted int
|
||||
}{
|
||||
{name: "old dry run", age: 2 * time.Minute},
|
||||
{name: "old apply", age: 2 * time.Minute, apply: true, wantDeleted: 1},
|
||||
{name: "fresh protected", age: 10 * time.Second, apply: true},
|
||||
{name: "future timestamp protected", age: -time.Minute, apply: true},
|
||||
{name: "referenced protected", age: 2 * time.Minute, apply: true, used: true},
|
||||
{name: "changed inventory protected", age: 2 * time.Minute, apply: true, changed: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
id := uuid.MustParse("00000000-0000-0000-0000-000000000001")
|
||||
key := ObjectKey(id)
|
||||
repo := &fixtureRepo{rows: map[uuid.UUID]model.Attachment{}}
|
||||
if tc.used {
|
||||
repo.rows[id] = model.Attachment{ID: id, Status: "ready", CreatedAt: fixedNow}
|
||||
}
|
||||
objects := &fixtureObjects{items: map[string]port.Object{key: {Key: key, ETag: "original", Modified: fixedNow.Add(-tc.age)}}, changed: tc.changed}
|
||||
report, e := NewReconciler(repo, objects, func() time.Time { return fixedNow }).Run(context.Background(), uuid.Nil, "", time.Minute, tc.apply)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if objects.removed != tc.wantDeleted {
|
||||
t.Fatalf("deleted %d, want %d; report=%+v", objects.removed, tc.wantDeleted, report)
|
||||
}
|
||||
if tc.wantDeleted > 0 {
|
||||
_, e = NewReconciler(repo, objects, func() time.Time { return fixedNow }).Run(context.Background(), uuid.Nil, "", time.Minute, true)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if objects.removed != 1 {
|
||||
t.Fatal("second run deleted something twice")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestMissingAndPendingMetadataRepair(t *testing.T) {
|
||||
for _, status := range []string{"ready", "uploading", "missing"} {
|
||||
t.Run(status, func(t *testing.T) {
|
||||
id := uuid.New()
|
||||
raw := []byte("original bytes")
|
||||
sum := sha256.Sum256(raw)
|
||||
repo := &fixtureRepo{rows: map[uuid.UUID]model.Attachment{id: {ID: id, Status: status, CreatedAt: fixedNow.Add(-2 * time.Minute), UpdatedAt: fixedNow.Add(-2 * time.Minute), SizeBytes: int64(len(raw)), SHA256: hex.EncodeToString(sum[:])}}}
|
||||
objects := &fixtureObjects{items: map[string]port.Object{}, content: raw}
|
||||
want := "missing"
|
||||
if status != "ready" {
|
||||
objects.items[ObjectKey(id)] = port.Object{Key: ObjectKey(id), Size: int64(len(raw)), Modified: fixedNow.Add(-2 * time.Minute)}
|
||||
want = "ready"
|
||||
}
|
||||
_, e := NewReconciler(repo, objects, func() time.Time { return fixedNow }).Run(context.Background(), uuid.Nil, "", time.Minute, true)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if got := repo.rows[id].Status; got != want {
|
||||
t.Fatalf("status %s, want %s", got, want)
|
||||
}
|
||||
if objects.removed != 0 {
|
||||
t.Fatal("metadata repair removed original")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestDependencyFailureNeverDeletes(t *testing.T) {
|
||||
repo := &fixtureRepo{rows: map[uuid.UUID]model.Attachment{}, failure: model.ErrUnavailable}
|
||||
objects := &fixtureObjects{items: map[string]port.Object{}}
|
||||
_, e := NewReconciler(repo, objects, func() time.Time { return fixedNow }).Run(context.Background(), uuid.Nil, "", time.Minute, true)
|
||||
if !errors.Is(e, model.ErrUnavailable) {
|
||||
t.Fatalf("expected dependency error, got %v", e)
|
||||
}
|
||||
if objects.removed != 0 {
|
||||
t.Fatal("deleted during failed inventory")
|
||||
}
|
||||
}
|
||||
func TestFailureDoesNotReturnCursorPastFailedRecord(t *testing.T) {
|
||||
id := uuid.New()
|
||||
repo := &fixtureRepo{rows: map[uuid.UUID]model.Attachment{id: {ID: id, Status: "ready", CreatedAt: fixedNow.Add(-2 * time.Minute)}}, more: true}
|
||||
objects := &fixtureObjects{failure: model.ErrUnavailable}
|
||||
report, err := NewReconciler(repo, objects, func() time.Time { return fixedNow }).Run(context.Background(), uuid.Nil, "", time.Minute, true)
|
||||
if !errors.Is(err, model.ErrUnavailable) {
|
||||
t.Fatalf("expected failure, got %v", err)
|
||||
}
|
||||
if report.NextMetadata != "" || report.NextObject != "" {
|
||||
t.Fatal("failed inventory must restart rather than skip the failed item")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// Config приходит только из окружения (12-factor): в контейнер не копируются
|
||||
// ни .env, ни файлы конфигурации. Значения по умолчанию — ниже.
|
||||
type Config struct {
|
||||
Host string `mapstructure:"APP_HOST"`
|
||||
Port int `mapstructure:"APP_PORT"`
|
||||
Env string `mapstructure:"APP_ENV"`
|
||||
LogLevel string `mapstructure:"LOG_LEVEL"`
|
||||
ShutdownTimeout time.Duration `mapstructure:"SHUTDOWN_TIMEOUT"`
|
||||
MaxBodyBytes int64 `mapstructure:"MAX_BODY_BYTES"`
|
||||
MaxInflight int `mapstructure:"MAX_INFLIGHT"`
|
||||
MaxQueue int `mapstructure:"MAX_QUEUE"`
|
||||
QueueTimeout time.Duration `mapstructure:"QUEUE_TIMEOUT"`
|
||||
DatabaseURLFile string `mapstructure:"DATABASE_URL_FILE"`
|
||||
CacheURLFile string `mapstructure:"CACHE_URL_FILE"`
|
||||
SessionTTLSeconds int `mapstructure:"SESSION_TTL_SECONDS"`
|
||||
MaxConns int32 `mapstructure:"PG_MAX_CONNS"`
|
||||
}
|
||||
|
||||
var defaults = map[string]any{
|
||||
"APP_HOST": "0.0.0.0",
|
||||
"APP_PORT": 8080,
|
||||
"APP_ENV": "lab",
|
||||
"LOG_LEVEL": "info",
|
||||
"SHUTDOWN_TIMEOUT": "8s",
|
||||
"MAX_BODY_BYTES": 64 << 10,
|
||||
"MAX_INFLIGHT": 4,
|
||||
"MAX_QUEUE": 32,
|
||||
"QUEUE_TIMEOUT": "1s",
|
||||
"DATABASE_URL_FILE": "/run/secrets/database_url",
|
||||
"CACHE_URL_FILE": "/run/secrets/cache_url",
|
||||
"SESSION_TTL_SECONDS": 3600,
|
||||
"PG_MAX_CONNS": 8,
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
v := viper.New()
|
||||
for key, value := range defaults {
|
||||
v.SetDefault(key, value)
|
||||
}
|
||||
v.AutomaticEnv()
|
||||
var cfg Config
|
||||
if err := v.Unmarshal(&cfg); err != nil {
|
||||
return Config{}, fmt.Errorf("parse config: %w", err)
|
||||
}
|
||||
if cfg.ShutdownTimeout <= 0 || cfg.ShutdownTimeout > 9*time.Second {
|
||||
return Config{}, fmt.Errorf("SHUTDOWN_TIMEOUT must be in (0, 9s]: docker stop ждёт 10 с")
|
||||
}
|
||||
if cfg.SessionTTLSeconds < 1 || cfg.SessionTTLSeconds > 86400 {
|
||||
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS must be 1..86400")
|
||||
}
|
||||
if cfg.MaxConns < 1 || cfg.MaxConns > 64 {
|
||||
return Config{}, fmt.Errorf("PG_MAX_CONNS must be 1..64")
|
||||
}
|
||||
if cfg.MaxInflight < 1 || cfg.MaxInflight > 4 || cfg.MaxQueue < 0 || cfg.MaxQueue > 128 || cfg.QueueTimeout <= 0 || cfg.QueueTimeout > 2*time.Second {
|
||||
return Config{}, fmt.Errorf("HTTP gate exceeds the tested resource budget")
|
||||
}
|
||||
if cfg.MaxBodyBytes < 1 || cfg.MaxBodyBytes > 65536 {
|
||||
return Config{}, fmt.Errorf("MAX_BODY_BYTES must be 1..65536")
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (c Config) Addr() string { return fmt.Sprintf("%s:%d", c.Host, c.Port) }
|
||||
|
||||
func ReadSecret(path string) (string, error) {
|
||||
b, e := os.ReadFile(path)
|
||||
if e != nil {
|
||||
return "", fmt.Errorf("required secret file unavailable")
|
||||
}
|
||||
v := strings.TrimSpace(string(b))
|
||||
if v == "" {
|
||||
return "", fmt.Errorf("required secret is empty")
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package config
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestRejectsConfigurationOutsideResourceBudget(t *testing.T) {
|
||||
for _, tc := range []struct{ key, value string }{{"MAX_INFLIGHT", "0"}, {"MAX_INFLIGHT", "5"}, {"MAX_QUEUE", "-1"}, {"MAX_QUEUE", "129"}, {"QUEUE_TIMEOUT", "0s"}, {"QUEUE_TIMEOUT", "3s"}, {"MAX_BODY_BYTES", "0"}, {"MAX_BODY_BYTES", "65537"}, {"PG_MAX_CONNS", "0"}, {"PG_MAX_CONNS", "65"}, {"SESSION_TTL_SECONDS", "0"}, {"SESSION_TTL_SECONDS", "86401"}} {
|
||||
t.Run(tc.key+tc.value, func(t *testing.T) {
|
||||
t.Setenv(tc.key, tc.value)
|
||||
if _, e := Load(); e == nil {
|
||||
t.Fatal("accepted configuration beyond tested bounds")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestPoolSizeIsConfigurableWithinBounds(t *testing.T) {
|
||||
t.Setenv("PG_MAX_CONNS", "1")
|
||||
cfg, e := Load()
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if cfg.MaxConns != 1 {
|
||||
t.Fatal("configured pool size ignored")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const MaxImageBytes int64 = 10 * 1024 * 1024
|
||||
const MaxImagePixels int64 = 40_000_000
|
||||
|
||||
type Attachment struct {
|
||||
ID, ChatID, OwnerID uuid.UUID
|
||||
Filename, ContentType, SHA256, Status string
|
||||
SizeBytes int64
|
||||
CreatedAt, UpdatedAt time.Time
|
||||
}
|
||||
|
||||
func ValidateFilename(name string) error {
|
||||
if !utf8.ValidString(name) || utf8.RuneCountInString(name) < 1 || utf8.RuneCountInString(name) > 255 || strings.TrimSpace(name) == "" {
|
||||
return invalidf("filename: 1–255 characters required")
|
||||
}
|
||||
for _, r := range name {
|
||||
if r == '/' || r == '\\' || unicode.IsControl(r) {
|
||||
return invalidf("filename: invalid character")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const maxChatMembers = 100
|
||||
|
||||
// Chat неизменяем после создания: участники задаются один раз, удаления в API нет.
|
||||
type Chat struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
MemberIDs []uuid.UUID
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func (c Chat) HasMember(userID uuid.UUID) bool {
|
||||
return slices.Contains(c.MemberIDs, userID)
|
||||
}
|
||||
|
||||
// ChatDraft — проверенные данные нового чата. Существование участников
|
||||
// проверяет хранилище атомарно с созданием.
|
||||
type ChatDraft struct {
|
||||
Creator uuid.UUID
|
||||
Title string
|
||||
MemberIDs []uuid.UUID
|
||||
}
|
||||
|
||||
func NewChatDraft(creator uuid.UUID, title string, memberIDs []uuid.UUID) (ChatDraft, error) {
|
||||
if err := requireText("title", title, 1, 100); err != nil {
|
||||
return ChatDraft{}, err
|
||||
}
|
||||
if len(memberIDs) == 0 || len(memberIDs) > maxChatMembers {
|
||||
return ChatDraft{}, invalidf("member_ids: от 1 до %d участников", maxChatMembers)
|
||||
}
|
||||
seen := make(map[uuid.UUID]struct{}, len(memberIDs))
|
||||
for _, id := range memberIDs {
|
||||
if _, dup := seen[id]; dup {
|
||||
return ChatDraft{}, invalidf("member_ids: повторяющийся участник")
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
if _, ok := seen[creator]; !ok {
|
||||
return ChatDraft{}, invalidf("member_ids: должен содержать создателя чата")
|
||||
}
|
||||
return ChatDraft{Creator: creator, Title: title, MemberIDs: slices.Clone(memberIDs)}, nil
|
||||
}
|
||||
|
||||
func (c Chat) Position() Position { return Position{CreatedAt: c.CreatedAt, ID: c.ID} }
|
||||
@@ -0,0 +1,32 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrUnavailable = errors.New("dependency unavailable")
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
ErrUsernameTaken = errors.New("username taken")
|
||||
// ErrStorageFull — исчерпан бюджет памяти хранилища. Подтверждённые данные
|
||||
// не вытесняются, поэтому новые записи отклоняются, а чтение продолжает работать.
|
||||
ErrStorageFull = errors.New("storage full")
|
||||
// ErrUnknownMember возвращает хранилище, если среди участников нового чата
|
||||
// есть несуществующий пользователь; для клиента это ошибка ввода (400).
|
||||
ErrUnknownMember error = &ValidationError{Message: "member_ids: неизвестный пользователь"}
|
||||
)
|
||||
|
||||
// ValidationError — нарушение правил входных данных; Message безопасно
|
||||
// показывать клиенту.
|
||||
type ValidationError struct {
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e *ValidationError) Error() string { return e.Message }
|
||||
|
||||
func invalidf(format string, args ...any) error {
|
||||
return &ValidationError{Message: fmt.Sprintf(format, args...)}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const MaxMessageRunes = 4000
|
||||
|
||||
type Message struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
AttachmentIDs []uuid.UUID
|
||||
}
|
||||
|
||||
// MessageDraft — проверенное сообщение; отправитель берётся из идентификации,
|
||||
// а не из тела запроса.
|
||||
type MessageDraft struct {
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
Key string
|
||||
PayloadHash string
|
||||
AttachmentIDs []uuid.UUID
|
||||
}
|
||||
|
||||
var keyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
func WithKey(d MessageDraft, key string) (MessageDraft, error) {
|
||||
if !keyPattern.MatchString(key) {
|
||||
return MessageDraft{}, invalidf("Idempotency-Key: 1–128 ASCII characters required")
|
||||
}
|
||||
canonical, _ := json.Marshal(struct {
|
||||
Text string
|
||||
Attachments []uuid.UUID
|
||||
}{d.Text, d.AttachmentIDs})
|
||||
sum := sha256.Sum256(canonical)
|
||||
d.Key = key
|
||||
d.PayloadHash = hex.EncodeToString(sum[:])
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func NewMessageDraft(chatID, senderID uuid.UUID, text string, attachments ...[]uuid.UUID) (MessageDraft, error) {
|
||||
ids := []uuid.UUID{}
|
||||
if len(attachments) > 0 {
|
||||
ids = slices.Clone(attachments[0])
|
||||
if ids == nil {
|
||||
ids = []uuid.UUID{}
|
||||
}
|
||||
}
|
||||
if len(ids) > 10 {
|
||||
return MessageDraft{}, invalidf("attachment_ids: at most 10")
|
||||
}
|
||||
seen := map[uuid.UUID]bool{}
|
||||
for _, id := range ids {
|
||||
if seen[id] {
|
||||
return MessageDraft{}, invalidf("attachment_ids: duplicate")
|
||||
}
|
||||
seen[id] = true
|
||||
}
|
||||
if len(ids) == 0 || strings.TrimSpace(text) != "" {
|
||||
if err := requireText("text", text, 1, MaxMessageRunes); err != nil {
|
||||
return MessageDraft{}, err
|
||||
}
|
||||
} else if !utf8.ValidString(text) || utf8.RuneCountInString(text) > MaxMessageRunes || strings.ContainsRune(text, 0) {
|
||||
return MessageDraft{}, invalidf("text: invalid optional text")
|
||||
}
|
||||
return MessageDraft{ChatID: chatID, SenderID: senderID, Text: text, AttachmentIDs: ids}, nil
|
||||
}
|
||||
|
||||
func (m Message) Position() Position { return Position{CreatedAt: m.CreatedAt, ID: m.ID} }
|
||||
@@ -0,0 +1,126 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func isValidationError(err error) bool {
|
||||
var v *ValidationError
|
||||
return errors.As(err, &v)
|
||||
}
|
||||
|
||||
func TestNewUserDraft(t *testing.T) {
|
||||
t.Parallel()
|
||||
cases := []struct {
|
||||
name, username, display string
|
||||
ok bool
|
||||
}{
|
||||
{"minimal", "abc", "A", true},
|
||||
{"max username 32", strings.Repeat("a", 32), "A", true},
|
||||
{"username too short", "ab", "A", false},
|
||||
{"username too long", strings.Repeat("a", 33), "A", false},
|
||||
{"uppercase rejected", "Alice", "A", false},
|
||||
{"cyrillic username rejected", "алиса", "A", false},
|
||||
{"display 100 emoji ok", "abc", strings.Repeat("😀", 100), true},
|
||||
{"display 101 code points rejected", "abc", strings.Repeat("ж", 101), false},
|
||||
{"display whitespace only", "abc", " \t\n", false},
|
||||
{"display empty", "abc", "", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
_, err := NewUserDraft(tc.username, tc.display)
|
||||
if tc.ok && err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !tc.ok && !isValidationError(err) {
|
||||
t.Fatalf("want ValidationError, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewChatDraft(t *testing.T) {
|
||||
t.Parallel()
|
||||
me, other := uuid.New(), uuid.New()
|
||||
tooMany := []uuid.UUID{me}
|
||||
for range 100 {
|
||||
tooMany = append(tooMany, uuid.New())
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
members []uuid.UUID
|
||||
ok bool
|
||||
}{
|
||||
{"creator only", []uuid.UUID{me}, true},
|
||||
{"two members", []uuid.UUID{me, other}, true},
|
||||
{"empty", nil, false},
|
||||
{"creator missing", []uuid.UUID{other}, false},
|
||||
{"duplicate member", []uuid.UUID{me, other, other}, false},
|
||||
{"over 100 members", tooMany, false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
_, err := NewChatDraft(me, "Чат", tc.members)
|
||||
if tc.ok != (err == nil) {
|
||||
t.Fatalf("ok=%v, err=%v", tc.ok, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewMessageDraftLimitsInCodePoints(t *testing.T) {
|
||||
t.Parallel()
|
||||
if _, err := NewMessageDraft(uuid.New(), uuid.New(), strings.Repeat("👋", MaxMessageRunes)); err != nil {
|
||||
t.Fatalf("4000 four-byte code points must pass: %v", err)
|
||||
}
|
||||
if _, err := NewMessageDraft(uuid.New(), uuid.New(), strings.Repeat("a", MaxMessageRunes+1)); !isValidationError(err) {
|
||||
t.Fatalf("4001 code points must be rejected, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCursorRoundTripAndScope(t *testing.T) {
|
||||
t.Parallel()
|
||||
pos := Position{CreatedAt: time.Date(2026, 9, 1, 12, 0, 0, 123456000, time.UTC), ID: uuid.New()}
|
||||
cursor := EncodeCursor("messages:a", pos)
|
||||
|
||||
q, err := NewPageQuery(nil, &cursor, "messages:a")
|
||||
if err != nil || q.After == nil || *q.After != pos || q.Limit != DefaultPageLimit {
|
||||
t.Fatalf("round trip failed: %+v, %v", q, err)
|
||||
}
|
||||
if _, err := NewPageQuery(nil, &cursor, "messages:b"); !isValidationError(err) {
|
||||
t.Fatalf("cursor of another resource must be rejected, got %v", err)
|
||||
}
|
||||
for _, bad := range []string{"", "!!!", EncodeCursor("x", pos)[:5]} {
|
||||
if _, err := NewPageQuery(nil, &bad, "messages:a"); !isValidationError(err) {
|
||||
t.Fatalf("garbage cursor %q must be rejected, got %v", bad, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPageLimitBounds(t *testing.T) {
|
||||
t.Parallel()
|
||||
for limit, ok := range map[int]bool{0: false, 1: true, 100: true, 101: false, -1: false} {
|
||||
_, err := NewPageQuery(&limit, nil, "chats")
|
||||
if ok != (err == nil) {
|
||||
t.Errorf("limit=%d: ok=%v, err=%v", limit, ok, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPositionOrderTiesBrokenByID(t *testing.T) {
|
||||
t.Parallel()
|
||||
at := time.Now()
|
||||
low := Position{CreatedAt: at, ID: uuid.MustParse("00000000-0000-4000-8000-000000000001")}
|
||||
high := Position{CreatedAt: at, ID: uuid.MustParse("ffffffff-0000-4000-8000-000000000000")}
|
||||
later := Position{CreatedAt: at.Add(time.Microsecond), ID: low.ID}
|
||||
if !high.After(low) || low.After(high) || !later.After(high) || low.After(low) {
|
||||
t.Fatal("order must be (created_at, id) ascending")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultPageLimit = 50
|
||||
MaxPageLimit = 100
|
||||
)
|
||||
|
||||
// Position — ключ keyset-пагинации: история упорядочена по (created_at, id).
|
||||
type Position struct {
|
||||
CreatedAt time.Time
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
// After сообщает, стоит ли p строго после other в порядке (created_at, id).
|
||||
func (p Position) After(other Position) bool {
|
||||
if !p.CreatedAt.Equal(other.CreatedAt) {
|
||||
return p.CreatedAt.After(other.CreatedAt)
|
||||
}
|
||||
return bytes.Compare(p.ID[:], other.ID[:]) > 0
|
||||
}
|
||||
|
||||
// PageQuery — проверенный запрос страницы: limit 1–100 и позиция после
|
||||
// последнего элемента предыдущей страницы (nil — с начала).
|
||||
type PageQuery struct {
|
||||
Limit int
|
||||
After *Position
|
||||
}
|
||||
|
||||
// NewPageQuery проверяет limit и курсор. scope привязывает курсор к ресурсу:
|
||||
// курсор истории одного чата не подходит к другому чату или к списку чатов.
|
||||
func NewPageQuery(limit *int, cursor *string, scope string) (PageQuery, error) {
|
||||
q := PageQuery{Limit: DefaultPageLimit}
|
||||
if limit != nil {
|
||||
if *limit < 1 || *limit > MaxPageLimit {
|
||||
return PageQuery{}, invalidf("limit: от 1 до %d", MaxPageLimit)
|
||||
}
|
||||
q.Limit = *limit
|
||||
}
|
||||
if cursor != nil {
|
||||
pos, err := decodeCursor(*cursor, scope)
|
||||
if err != nil {
|
||||
return PageQuery{}, err
|
||||
}
|
||||
q.After = &pos
|
||||
}
|
||||
return q, nil
|
||||
}
|
||||
|
||||
// EncodeCursor делает непрозрачную для клиента строку из позиции и scope.
|
||||
func EncodeCursor(scope string, p Position) string {
|
||||
raw := scope + "|" + strconv.FormatInt(p.CreatedAt.UnixMicro(), 10) + "|" + p.ID.String()
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
func decodeCursor(cursor, scope string) (Position, error) {
|
||||
errBad := invalidf("cursor: некорректное значение")
|
||||
raw, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return Position{}, errBad
|
||||
}
|
||||
parts := strings.Split(string(raw), "|")
|
||||
if len(parts) != 3 || parts[0] != scope {
|
||||
return Position{}, errBad
|
||||
}
|
||||
micros, err := strconv.ParseInt(parts[1], 10, 64)
|
||||
if err != nil {
|
||||
return Position{}, errBad
|
||||
}
|
||||
id, err := uuid.Parse(parts[2])
|
||||
if err != nil {
|
||||
return Position{}, errBad
|
||||
}
|
||||
return Position{CreatedAt: time.UnixMicro(micros).UTC(), ID: id}, nil
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package model
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestRejectsNULInPersistedText(t *testing.T) {
|
||||
for _, field := range []string{"display_name", "title", "text"} {
|
||||
t.Run(field, func(t *testing.T) {
|
||||
if err := requireText(field, "a\x00b", 1, 4000); err == nil {
|
||||
t.Fatal("PostgreSQL text must reject NUL as a validation error")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// requireText проверяет обязательную строку: длина в Unicode code points
|
||||
// (не в байтах) и запрет строк только из пробельных символов.
|
||||
func requireText(field, value string, minLen, maxLen int) error {
|
||||
if strings.ContainsRune(value, 0) {
|
||||
return invalidf("%s: NUL недопустим в PostgreSQL text", field)
|
||||
}
|
||||
if !utf8.ValidString(value) {
|
||||
return invalidf("%s: некорректный UTF-8", field)
|
||||
}
|
||||
if strings.TrimSpace(value) == "" {
|
||||
return invalidf("%s: пустая строка", field)
|
||||
}
|
||||
if n := utf8.RuneCountInString(value); n < minLen || n > maxLen {
|
||||
return invalidf("%s: длина должна быть от %d до %d символов", field, minLen, maxLen)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
type User struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// UserDraft — проверенные данные нового пользователя; ID и время назначает хранилище.
|
||||
type UserDraft struct {
|
||||
Username string
|
||||
DisplayName string
|
||||
PasswordHash string
|
||||
}
|
||||
|
||||
func NewUserDraft(username, displayName string) (UserDraft, error) {
|
||||
if !usernamePattern.MatchString(username) {
|
||||
return UserDraft{}, invalidf("username: допустимо [a-z0-9_], от 3 до 32 символов")
|
||||
}
|
||||
if err := requireText("display_name", displayName, 1, 100); err != nil {
|
||||
return UserDraft{}, err
|
||||
}
|
||||
return UserDraft{Username: username, DisplayName: displayName}, nil
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package port
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/google/uuid"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Passwords interface {
|
||||
Hash(string) (string, error)
|
||||
Verify(string, string) bool
|
||||
}
|
||||
type Sessions interface {
|
||||
Credentials(context.Context, string) (uuid.UUID, string, error)
|
||||
CreateSession(context.Context, string, uuid.UUID, time.Time) error
|
||||
AuthenticateSession(context.Context, string) (uuid.UUID, error)
|
||||
RevokeSession(context.Context, string) error
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package port
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Object struct {
|
||||
Key, ETag string
|
||||
Size int64
|
||||
Modified time.Time
|
||||
}
|
||||
type Objects interface {
|
||||
Put(context.Context, string, io.Reader, int64, string) error
|
||||
Get(context.Context, string) (io.ReadCloser, error)
|
||||
Stat(context.Context, string) (Object, error)
|
||||
Remove(context.Context, string) error
|
||||
List(context.Context, string) ([]Object, bool, error)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// Package repository — порт персистентности. В lab1 его реализует хранилище
|
||||
// в памяти процесса, с lab2 — PostgreSQL; ядро от этой замены не меняется.
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/port"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Repository assigns IDs and database timestamps. Keyset order is (created_at, id);
|
||||
// concurrent commits do not provide insertion order or a traversal snapshot.
|
||||
// Каждый метод атомарен сам по себе.
|
||||
type Repository interface {
|
||||
UserRepository
|
||||
ChatRepository
|
||||
MessageRepository
|
||||
AttachmentRepository
|
||||
}
|
||||
|
||||
type AttachmentRepository interface {
|
||||
ReserveAttachment(context.Context, model.Attachment) (model.Attachment, error)
|
||||
GetAttachment(context.Context, uuid.UUID) (model.Attachment, error)
|
||||
SetAttachmentStatus(context.Context, uuid.UUID, string, string) (bool, error)
|
||||
ReconcileAttachments(context.Context, uuid.UUID) ([]model.Attachment, bool, error)
|
||||
}
|
||||
|
||||
type Persistent interface {
|
||||
Repository
|
||||
port.Sessions
|
||||
}
|
||||
|
||||
type UserRepository interface {
|
||||
// CreateUser: model.ErrUsernameTaken, model.ErrStorageFull.
|
||||
CreateUser(ctx context.Context, draft model.UserDraft) (model.User, error)
|
||||
// GetUser: model.ErrNotFound.
|
||||
GetUser(ctx context.Context, id uuid.UUID) (model.User, error)
|
||||
}
|
||||
|
||||
type ChatRepository interface {
|
||||
// CreateChat: model.ErrUnknownMember, model.ErrStorageFull.
|
||||
CreateChat(ctx context.Context, draft model.ChatDraft) (model.Chat, error)
|
||||
// GetChat: model.ErrNotFound.
|
||||
GetChat(ctx context.Context, id uuid.UUID) (model.Chat, error)
|
||||
// ListChats возвращает чаты участника и признак, что есть следующая страница.
|
||||
ListChats(ctx context.Context, memberID uuid.UUID, q model.PageQuery) ([]model.Chat, bool, error)
|
||||
}
|
||||
|
||||
type MessageRepository interface {
|
||||
// CreateMessage: model.ErrNotFound (нет чата), model.ErrStorageFull.
|
||||
CreateMessage(ctx context.Context, draft model.MessageDraft) (model.Message, error)
|
||||
// ListMessages возвращает страницу истории и признак следующей страницы.
|
||||
ListMessages(ctx context.Context, chatID uuid.UUID, q model.PageQuery) ([]model.Message, bool, error)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
// New — JSON-логи в stdout, их собирает docker logs.
|
||||
func New(level string) zerolog.Logger {
|
||||
lvl, err := zerolog.ParseLevel(level)
|
||||
if err != nil || level == "" {
|
||||
lvl = zerolog.InfoLevel
|
||||
}
|
||||
zerolog.TimeFieldFormat = time.RFC3339Nano
|
||||
return zerolog.New(os.Stdout).Level(lvl).With().Timestamp().Logger()
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
httpServer *http.Server
|
||||
}
|
||||
|
||||
func New(addr string, handler http.Handler) *Server {
|
||||
return &Server{httpServer: &http.Server{
|
||||
Addr: addr,
|
||||
Handler: handler,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 15 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
MaxHeaderBytes: 16 << 10,
|
||||
}}
|
||||
}
|
||||
|
||||
func (s *Server) ListenAndServe() error { return s.httpServer.ListenAndServe() }
|
||||
|
||||
// Shutdown сразу закрывает слушающий сокет (новые соединения не принимаются)
|
||||
// и ждёт завершения начатых запросов, но не дольше ctx.
|
||||
func (s *Server) Shutdown(ctx context.Context) error { return s.httpServer.Shutdown(ctx) }
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
name: vp-lab4-medvedev
|
||||
x-api: &api
|
||||
image: vp-medvedev-lab4:local
|
||||
build: .
|
||||
cpus: ${API_CPUS:-1}
|
||||
mem_limit: ${API_MEMORY:-2g}
|
||||
deploy:
|
||||
replicas: ${API_REPLICAS:-2}
|
||||
stop_grace_period: 10s
|
||||
environment:
|
||||
APP_PORT: 8080
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
PG_MAX_CONNS: ${PG_MAX_CONNS:-8}
|
||||
GOMEMLIMIT: ${GO_MEMORY_LIMIT:-1536MiB}
|
||||
secrets: [database_url, cache_url, s3_credentials]
|
||||
depends_on:
|
||||
migrate: {condition: service_completed_successfully}
|
||||
valkey: {condition: service_started}
|
||||
bootstrap-s3: {condition: service_completed_successfully}
|
||||
networks: [private]
|
||||
services:
|
||||
image-memory:
|
||||
image: vp-medvedev-lab4:local
|
||||
profiles: [tools]
|
||||
entrypoint: [/image-memory.test]
|
||||
command: [-test.v,-test.run,TestWorstCaseImagesWithinBudget,-test.timeout,120s]
|
||||
environment:
|
||||
RUN_IMAGE_STRESS: '1'
|
||||
GOMEMLIMIT: 1536MiB
|
||||
cpus: 2
|
||||
mem_limit: 2g
|
||||
integration:
|
||||
image: vp-medvedev-lab4:local
|
||||
profiles: [tools]
|
||||
entrypoint: [/integration.test]
|
||||
command: [-test.v,-test.run,'Test(ReconciliationAgainstPostgresAndPrivateS3|S3InventoryAndStatReturnComparableVersionMetadata|FixtureCleanupRejectsForeignMembership)',-test.timeout,150s]
|
||||
environment:
|
||||
RUN_ISOLATED_RECONCILIATION: '1'
|
||||
cpus: 0.5
|
||||
mem_limit: 512m
|
||||
secrets: [database_url,s3_credentials]
|
||||
networks: [private]
|
||||
fixture-cleanup:
|
||||
image: vp-medvedev-lab4:local
|
||||
profiles: [tools]
|
||||
entrypoint: [/fixture-cleanup]
|
||||
secrets: [database_url,s3_credentials]
|
||||
networks: [private]
|
||||
postgres:
|
||||
image: postgres:18.6@sha256:74935e72241653ca55e0414067e6d8763aceb8a810eb51b452253ec3dcfc4336
|
||||
cpus: 2
|
||||
mem_limit: 768m
|
||||
environment:
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_DB: messenger
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/pg_password
|
||||
secrets: [pg_password]
|
||||
volumes: [postgres:/var/lib/postgresql]
|
||||
healthcheck:
|
||||
test: [CMD-SHELL, pg_isready -U messenger -d messenger]
|
||||
interval: 2s
|
||||
timeout: 2s
|
||||
retries: 30
|
||||
networks: [private]
|
||||
valkey:
|
||||
image: valkey/valkey:9@sha256:418652cfb58ef879d4978c33553735d7147016032d5aefaa14c828e611eb9dfd
|
||||
cpus: 0.25
|
||||
mem_limit: 128m
|
||||
command: [valkey-server, /run/secrets/valkey_conf]
|
||||
secrets: [valkey_conf]
|
||||
volumes: [valkey:/data]
|
||||
networks: [private]
|
||||
migrate:
|
||||
image: vp-medvedev-lab4:local
|
||||
build: .
|
||||
command: [-migrate]
|
||||
cpus: 0.5
|
||||
mem_limit: 256m
|
||||
secrets: [database_url]
|
||||
depends_on:
|
||||
postgres: {condition: service_healthy}
|
||||
networks: [private]
|
||||
api:
|
||||
<<: *api
|
||||
lb:
|
||||
image: haproxy:3.2-alpine@sha256:1c3568e520453cc8ba98c39501febcf450429c80e6cc27ecad779961d76e597c
|
||||
cpus: 0.5
|
||||
mem_limit: 128m
|
||||
ports: ['127.0.0.1:${PUBLIC_PORT:-28204}:8080']
|
||||
volumes: ['./config/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro']
|
||||
depends_on:
|
||||
api: {condition: service_started}
|
||||
networks: [private]
|
||||
s3:
|
||||
image: rustfs/rustfs:1.0.0-rc.1@sha256:f53d700fc16809070326f6ab3fb565d48e722364a7bd5a12e47d0a5abe079ce6
|
||||
cpus: 1
|
||||
mem_limit: 768m
|
||||
environment:
|
||||
RUSTFS_ACCESS_KEY_FILE: /run/secrets/s3_access
|
||||
RUSTFS_SECRET_KEY_FILE: /run/secrets/s3_secret
|
||||
RUSTFS_VOLUMES: /data
|
||||
RUSTFS_CONSOLE_ENABLE: 'false'
|
||||
secrets: [s3_access,s3_secret]
|
||||
volumes: [s3:/data]
|
||||
healthcheck:
|
||||
test: [CMD,curl,-f,http://127.0.0.1:9000/health]
|
||||
interval: 2s
|
||||
timeout: 2s
|
||||
retries: 40
|
||||
networks: [private]
|
||||
bootstrap-s3:
|
||||
image: vp-medvedev-lab4:local
|
||||
build: .
|
||||
command: [-bootstrap-s3]
|
||||
cpus: 0.5
|
||||
mem_limit: 256m
|
||||
secrets: [database_url,s3_root,s3_credentials]
|
||||
depends_on:
|
||||
s3: {condition: service_healthy}
|
||||
networks: [private]
|
||||
volumes:
|
||||
postgres:
|
||||
valkey:
|
||||
s3:
|
||||
networks:
|
||||
private:
|
||||
secrets:
|
||||
pg_password: {file: .local/pg_password}
|
||||
database_url: {file: .local/database_url}
|
||||
cache_url: {file: .local/cache_url}
|
||||
valkey_conf: {file: .local/valkey.conf}
|
||||
s3_access: {file: .local/s3_access}
|
||||
s3_secret: {file: .local/s3_secret}
|
||||
s3_root: {file: .local/s3_root}
|
||||
s3_credentials: {file: .local/s3_credentials}
|
||||
@@ -0,0 +1,27 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
maxconn 256
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
timeout connect 1s
|
||||
timeout client 20s
|
||||
timeout server 25s
|
||||
retries 0
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
resolve_retries 2
|
||||
timeout resolve 1s
|
||||
timeout retry 1s
|
||||
hold valid 1s
|
||||
hold obsolete 1s
|
||||
frontend public
|
||||
bind :8080
|
||||
default_backend api
|
||||
backend api
|
||||
balance roundrobin
|
||||
option httpchk
|
||||
http-check send meth GET uri /health/ready
|
||||
http-check expect status 200
|
||||
default-server inter 500ms fall 2 rise 1
|
||||
server-template replica 1-4 api:8080 check resolvers docker resolve-prefer ipv4 init-addr none
|
||||
@@ -0,0 +1,71 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: api
|
||||
spec:
|
||||
clusterIP: None
|
||||
selector: {app: api}
|
||||
ports: [{name: http, port: 8080, targetPort: http}]
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: api
|
||||
labels: {app: api}
|
||||
spec:
|
||||
replicas: 2
|
||||
revisionHistoryLimit: 2
|
||||
strategy:
|
||||
rollingUpdate: {maxSurge: 1, maxUnavailable: 0}
|
||||
selector:
|
||||
matchLabels: {app: api}
|
||||
template:
|
||||
metadata:
|
||||
labels: {app: api}
|
||||
spec:
|
||||
automountServiceAccountToken: false
|
||||
terminationGracePeriodSeconds: 35
|
||||
securityContext: {runAsNonRoot: true, runAsUser: 65532, fsGroup: 65532}
|
||||
containers:
|
||||
- name: api
|
||||
image: vp-messenger:local
|
||||
imagePullPolicy: Never
|
||||
ports: [{name: http, containerPort: 8080}]
|
||||
env:
|
||||
- {name: APP_HOST, value: 0.0.0.0}
|
||||
- {name: APP_PORT, value: '8080'}
|
||||
- {name: PG_MAX_CONNS, value: '8'}
|
||||
- {name: SESSION_TTL_SECONDS, value: '3600'}
|
||||
- {name: GOMEMLIMIT, value: 400MiB}
|
||||
resources:
|
||||
requests: {cpu: 100m, memory: 128Mi}
|
||||
limits: {cpu: '1', memory: 512Mi}
|
||||
securityContext:
|
||||
allowPrivilegeEscalation: false
|
||||
capabilities: {drop: [ALL]}
|
||||
lifecycle:
|
||||
preStop:
|
||||
sleep: {seconds: 15}
|
||||
readinessProbe:
|
||||
httpGet: {path: /health/ready, port: http}
|
||||
periodSeconds: 1
|
||||
timeoutSeconds: 2
|
||||
failureThreshold: 1
|
||||
livenessProbe:
|
||||
httpGet: {path: /health/live, port: http}
|
||||
periodSeconds: 5
|
||||
timeoutSeconds: 2
|
||||
startupProbe:
|
||||
httpGet: {path: /health/live, port: http}
|
||||
periodSeconds: 1
|
||||
failureThreshold: 60
|
||||
volumeMounts: [{name: credentials, mountPath: /run/secrets, readOnly: true}]
|
||||
volumes:
|
||||
- name: credentials
|
||||
secret:
|
||||
secretName: app-config
|
||||
defaultMode: 0440
|
||||
items:
|
||||
- {key: database_url, path: database_url}
|
||||
- {key: cache_url, path: cache_url}
|
||||
- {key: s3_credentials, path: s3_credentials}
|
||||
@@ -0,0 +1,9 @@
|
||||
apiVersion: kustomize.config.k8s.io/v1beta1
|
||||
kind: Kustomization
|
||||
namespace: messenger
|
||||
resources: [namespace.yaml, stores.yaml, api.yaml, pingap.yaml, s3.yaml]
|
||||
configMapGenerator:
|
||||
- name: pingap-config
|
||||
files: [pingap.toml]
|
||||
generatorOptions:
|
||||
disableNameSuffixHash: true
|
||||
@@ -0,0 +1,6 @@
|
||||
apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: messenger
|
||||
labels:
|
||||
app.kubernetes.io/part-of: vp-coursework
|
||||
@@ -0,0 +1,20 @@
|
||||
[basic]
|
||||
threads = 1
|
||||
grace_period = "8s"
|
||||
graceful_shutdown_timeout = "10s"
|
||||
|
||||
[upstreams.api]
|
||||
addrs = ["api.messenger.svc.cluster.local:8080"]
|
||||
discovery = "dns"
|
||||
update_frequency = "1s"
|
||||
health_check = "http://api/health/ready?connection_timeout=1s&read_timeout=1s&check_frequency=1s&success=1&failure=1"
|
||||
connection_timeout = "1s"
|
||||
read_timeout = "25s"
|
||||
|
||||
[locations.api]
|
||||
path = "/"
|
||||
upstream = "api"
|
||||
|
||||
[servers.http]
|
||||
addr = "0.0.0.0:8080"
|
||||
locations = ["api"]
|
||||
@@ -0,0 +1,35 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata: {name: pingap}
|
||||
spec:
|
||||
type: LoadBalancer
|
||||
allocateLoadBalancerNodePorts: false
|
||||
selector: {app: pingap}
|
||||
ports: [{name: http, port: 80, targetPort: http}]
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: pingap}
|
||||
spec:
|
||||
replicas: 1
|
||||
selector: {matchLabels: {app: pingap}}
|
||||
template:
|
||||
metadata: {labels: {app: pingap}}
|
||||
spec:
|
||||
automountServiceAccountToken: false
|
||||
terminationGracePeriodSeconds: 25
|
||||
containers:
|
||||
- name: pingap
|
||||
image: vp-pingap:local
|
||||
imagePullPolicy: Never
|
||||
args: [-c, /etc/pingap/pingap.toml, --autoreload, --strict]
|
||||
ports: [{name: http, containerPort: 8080}]
|
||||
resources:
|
||||
requests: {cpu: 50m, memory: 32Mi}
|
||||
limits: {cpu: 500m, memory: 128Mi}
|
||||
readinessProbe:
|
||||
tcpSocket: {port: http}
|
||||
periodSeconds: 1
|
||||
volumeMounts: [{name: configuration, mountPath: /etc/pingap, readOnly: true}]
|
||||
volumes:
|
||||
- {name: configuration, configMap: {name: pingap-config}}
|
||||
@@ -0,0 +1,53 @@
|
||||
apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata: {name: s3}
|
||||
spec:
|
||||
accessModes: [ReadWriteOnce]
|
||||
resources: {requests: {storage: 2Gi}}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata: {name: s3}
|
||||
spec:
|
||||
selector: {app: s3}
|
||||
ports: [{port: 9000, targetPort: 9000}]
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: s3}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: Recreate}
|
||||
selector: {matchLabels: {app: s3}}
|
||||
template:
|
||||
metadata: {labels: {app: s3}}
|
||||
spec:
|
||||
automountServiceAccountToken: false
|
||||
terminationGracePeriodSeconds: 20
|
||||
containers:
|
||||
- name: s3
|
||||
image: vp-s3:local
|
||||
imagePullPolicy: Never
|
||||
env:
|
||||
- {name: RUSTFS_ACCESS_KEY_FILE, value: /run/secrets/s3_access}
|
||||
- {name: RUSTFS_SECRET_KEY_FILE, value: /run/secrets/s3_secret}
|
||||
- {name: RUSTFS_VOLUMES, value: /data}
|
||||
- {name: RUSTFS_CONSOLE_ENABLE, value: 'false'}
|
||||
resources:
|
||||
requests: {cpu: 100m, memory: 128Mi}
|
||||
limits: {cpu: '1', memory: 768Mi}
|
||||
readinessProbe:
|
||||
httpGet: {path: /health, port: 9000}
|
||||
periodSeconds: 2
|
||||
timeoutSeconds: 2
|
||||
volumeMounts:
|
||||
- {name: data, mountPath: /data}
|
||||
- {name: credentials, mountPath: /run/secrets, readOnly: true}
|
||||
volumes:
|
||||
- {name: data, persistentVolumeClaim: {claimName: s3}}
|
||||
- name: credentials
|
||||
secret:
|
||||
secretName: storage-root
|
||||
items:
|
||||
- {key: s3_access, path: s3_access}
|
||||
- {key: s3_secret, path: s3_secret}
|
||||
@@ -0,0 +1,96 @@
|
||||
apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata: {name: postgres}
|
||||
spec:
|
||||
accessModes: [ReadWriteOnce]
|
||||
resources: {requests: {storage: 1Gi}}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata: {name: valkey}
|
||||
spec:
|
||||
accessModes: [ReadWriteOnce]
|
||||
resources: {requests: {storage: 1Gi}}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata: {name: postgres}
|
||||
spec:
|
||||
selector: {app: postgres}
|
||||
ports: [{port: 5432, targetPort: 5432}]
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata: {name: valkey}
|
||||
spec:
|
||||
selector: {app: valkey}
|
||||
ports: [{port: 6379, targetPort: 6379}]
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: postgres}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: Recreate}
|
||||
selector: {matchLabels: {app: postgres}}
|
||||
template:
|
||||
metadata: {labels: {app: postgres}}
|
||||
spec:
|
||||
automountServiceAccountToken: false
|
||||
terminationGracePeriodSeconds: 20
|
||||
containers:
|
||||
- name: postgres
|
||||
image: vp-postgres:local
|
||||
imagePullPolicy: Never
|
||||
env:
|
||||
- {name: POSTGRES_USER, value: messenger}
|
||||
- {name: POSTGRES_DB, value: messenger}
|
||||
- {name: POSTGRES_PASSWORD_FILE, value: /run/secrets/pg_password}
|
||||
resources:
|
||||
requests: {cpu: 100m, memory: 128Mi}
|
||||
limits: {cpu: '2', memory: 768Mi}
|
||||
readinessProbe:
|
||||
exec: {command: [pg_isready, -h, 127.0.0.1, -U, messenger, -d, messenger]}
|
||||
periodSeconds: 2
|
||||
volumeMounts:
|
||||
- {name: data, mountPath: /var/lib/postgresql}
|
||||
- {name: credentials, mountPath: /run/secrets, readOnly: true}
|
||||
volumes:
|
||||
- {name: data, persistentVolumeClaim: {claimName: postgres}}
|
||||
- name: credentials
|
||||
secret:
|
||||
secretName: app-config
|
||||
items: [{key: pg_password, path: pg_password}]
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: valkey}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: Recreate}
|
||||
selector: {matchLabels: {app: valkey}}
|
||||
template:
|
||||
metadata: {labels: {app: valkey}}
|
||||
spec:
|
||||
automountServiceAccountToken: false
|
||||
terminationGracePeriodSeconds: 10
|
||||
containers:
|
||||
- name: valkey
|
||||
image: vp-valkey:local
|
||||
imagePullPolicy: Never
|
||||
command: [valkey-server, /run/secrets/valkey_conf]
|
||||
resources:
|
||||
requests: {cpu: 50m, memory: 32Mi}
|
||||
limits: {cpu: 250m, memory: 128Mi}
|
||||
readinessProbe:
|
||||
tcpSocket: {port: 6379}
|
||||
periodSeconds: 2
|
||||
volumeMounts:
|
||||
- {name: data, mountPath: /data}
|
||||
- {name: credentials, mountPath: /run/secrets, readOnly: true}
|
||||
volumes:
|
||||
- {name: data, persistentVolumeClaim: {claimName: valkey}}
|
||||
- name: credentials
|
||||
secret:
|
||||
secretName: app-config
|
||||
items: [{key: valkey_conf, path: valkey_conf}]
|
||||
@@ -0,0 +1,60 @@
|
||||
# Лабораторная 4. Приватные S3-вложения
|
||||
|
||||
Автор: Медведев Андрей Михайлович, БПИ2303. Целевая оценка: 5, трек 2 «Согласованность двух хранилищ». Оценка преподавателя не подменяется результатом тестов.
|
||||
|
||||
Сохранены обязательные возможности третьей лабы: две API-реплики, HAProxy, PostgreSQL, общие сессии, Valkey и атомарная идемпотентность сообщений. Добавлен RustFS 1.0.0-rc.1 с закреплённым digest, minio-go/v7, доменная модель Attachment, таблицы вложений и связей с сообщениями, ограниченный streaming upload и reconciler. Исходный skeleton: https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4. Запуск описан в [RUN.md](RUN.md). Код и отчёт подготовлены с помощью Codex и прошли независимое ревью.
|
||||
|
||||
## Данные, доступ и согласованность
|
||||
|
||||
Оригинал хранится только в приватном S3, метаданные в PostgreSQL. Имя файла используется для отображения, ключ S3 генерируется из случайного серверного UUID и не переиспользуется. API работает с отдельной IAM-учётной записью: разрешены операции только своего bucket/prefix, создание постороннего bucket запрещено. Root credentials доступны bootstrap, но не API; административный порт наружу не публикуется.
|
||||
|
||||
При upload сначала проверяются сессия, членство и filename. Поток сохраняется во временный файл с лимитом 10 МиБ + 1 байт и SHA-256. PNG/JPEG проверяются по содержимому: сначала DecodeConfig и предел 40 млн пикселей, затем полноценный decoder обнаруживает повреждения. Подмена MIME, опасное имя, превышение bytes и pixel bomb не становятся 500. Временный файл удаляется после запроса; локальная файловая система API не является постоянным хранилищем.
|
||||
|
||||
До S3 PUT в БД создаётся устойчивое намерение uploading. После успешного PUT метаданные атомарно переводятся в ready, и только затем возвращается 201. Неопределённый ответ S3 или ошибка финализации БД сохраняют намерение для сверки. Сетевых вызовов S3 внутри SQL-транзакции нет.
|
||||
|
||||
Состояния uploading, missing и abandoned внутренние: публичная схема этой лабы возвращает только ready. Для missing API возвращает ограниченную ошибку 503, а не ложные готовые метаданные. Download проверяет членство, наличие оригинала и размер до отправки headers, передаёт bytes без redirect и проверяет полноту потока через CopyN. Другой участник чата получает исходные bytes, посторонний получает 404. Привязка файла другого чата запрещена.
|
||||
|
||||
Сообщение с пустым text допустимо при наличии вложения. Массив содержит не более десяти уникальных ID. Отсутствующий attachment_ids и [] имеют одинаковую семантику для идемпотентности. Обязательное string-поле text не может быть пропущено или заменено null. История читает ID вложений в SQL, без неограниченного fetch-all.
|
||||
|
||||
## Проверенные критерии
|
||||
|
||||
| Критерий | Результат | Доказательство |
|
||||
| --- | --- | --- |
|
||||
| Обязательный API | Публичный upload/message/download smoke прошёл | evidence/smoke.txt |
|
||||
| Негативные сценарии | Чужой чат/файл, другой чат, MIME, повреждение, filename, 10 МиБ + 1, JSON null проверены | evidence/acceptance.txt |
|
||||
| Приватность | Анонимный прямой S3 GET запрещён, посторонний bucket создать нельзя | acceptance и integration |
|
||||
| Сохранность | Оригинал, метаданные и сессия пережили полный restart | evidence/persistence.txt |
|
||||
| Другой API | Failover читает оригинал через оставшуюся реплику | evidence/failover-1.txt, evidence/failover-2.txt |
|
||||
| Ограничение RAM | Десять одновременных попыток upload, контроль исходных bytes и cgroup memory.peak | evidence/concurrent-images/run-r1sasy/ |
|
||||
| Экстремальное изображение | RGBA64 40 млн × 1, PNG и Adam7, повторы и три KDF-worker | evidence/image-memory-FaWPgn/ |
|
||||
| Реальные частичные отказы | Ошибка SQL после PUT, потерянный ответ PUT, отсутствующий оригинал, orphan | evidence/reconciliation/run-KKAVrN/ |
|
||||
| Dry-run и повтор | Dry-run ничего не меняет; повтор после apply ничего не меняет | evidence/reconciliation/run-KKAVrN/tests.txt |
|
||||
| Защита чужих данных | Cleanup отвергает смешанное членство до удаления оригиналов | отдельный integration regression |
|
||||
|
||||
## Память и десять загрузок
|
||||
|
||||
Одна реплика одновременно декодирует только одно изображение; общая API-очередь ограничена. Контейнер API имеет hard limit 2 ГиБ и GOMEMLIMIT=1536MiB. Это покрывает worst-case штатного Go PNG decoder: полный 16-bit raster, строки фильтров и Adam7, плюс до трёх параллельных Argon2 по 32 МиБ. Проверялись исходники именно Go 1.27.2, а не только число пикселей.
|
||||
|
||||
В отдельном процессе прошли четыре проверки RGBA64 40 000 000 × 1: два обычных PNG и два Adam7, с тремя параллельными KDF-worker. Измеренный VmHWM составил 1 538 856 КиБ, примерно 1,47 ГиБ, ниже hard limit 2 ГиБ. Все входные bytes оставались меньше 10 МиБ; fixture специально сжимает одинаковые пиксели, поэтому проверка декодирования нужна независимо от размера файла.
|
||||
|
||||
Другой эксперимент одновременно начал десять PNG-upload по 3 148 214 байт. Восемь завершились 201, две попытки получили документированную 503 из-за ограниченной очереди. Все сохранённые оригиналы скачаны и побайтно проверены. Cgroup memory.peak двух реплик составил 78 458 880 и 78 077 952 байта. Это измерение данного входа; максимальный декодированный PNG проверялся отдельным экспериментом выше.
|
||||
|
||||
## Исследование согласованности
|
||||
|
||||
Reconciler обходит не более 100 metadata и 100 объектов за вызов, возвращает продолжение только для успешно обработанной страницы. При ошибке continuation очищается: оператор повторяет страницу с начала, а не пропускает неуспешный элемент. По умолчанию выполняется dry-run; apply задаётся явно.
|
||||
|
||||
Grace period по умолчанию 10 минут, минимально 60 секунд при upload deadline 20 секунд. Свежие и будущие timestamps не разрешают очистку. Список S3 и HEAD нормализуются к UTC-секундам: RustFS возвращает миллисекунды в inventory и целые секунды в HTTP Last-Modified. Перед удалением дополнительно сверяются ETag, размер, возраст и отсутствие текущих metadata. Любой учтённый объект, включая используемое вложение, защищён от orphan cleanup.
|
||||
|
||||
Эксперимент выполнен в отдельном случайном Compose-проекте с собственными volumes и изначально пустыми DB/bucket. Настоящий PostgreSQL trigger вызвал отказ финализации после реального PUT. Также потерян ответ уже выполненного PUT, удалён оригинал используемого вложения, оставлено прерванное намерение и создан старый orphan. Новый объект создан непосредственно перед сверкой, чтобы проверить grace.
|
||||
|
||||
Dry-run увидел 5 metadata, 5 объектов, один orphan, два missing и две восстановимые загрузки; изменений не сделал. Apply удалил один старый orphan и изменил четыре metadata, восстановив две загрузки. Свежий объект и используемый оригинал сохранились. Повтор дал ноль удалений и изменений. После возвращения корректного оригинала missing-вложение снова стало ready; metadata и сообщения при этом не удалялись.
|
||||
|
||||
Для apply измерено 12 реальных S3 HTTP-запросов и 2227 прочитанных bytes на данном наборе. Это стоимость небольшого сценария и конечный размер одного batch; обход большого bucket потребует последовательного продолжения страниц. Исходные счётчики сохранены. Уборка integration-проекта завершилась до публикации PASS.
|
||||
|
||||
## Генерация и ограничения
|
||||
|
||||
Нормативный OpenAPI и публичные тесты сохранены. Для oapi-codegen используется его штатный Overlay: два бинарных MIME не должны порождать дублирующиеся Body-поля, а anyOf здесь выражает проверку содержимого, а не разные Go-типы. HTTP-адаптер принимает и проверяет PNG и JPEG; обязательные поля и правило text-or-attachment проверяются runtime и тестами.
|
||||
|
||||
Один Docker-host, PostgreSQL, HAProxy и S3 остаются единичными компонентами. Шифрование транспорта относится к следующей лабораторной; этот стенд привязан к localhost и синтетическим данным. Прерванный upload может оставить устойчивое намерение до сверки. Повторный POST загрузки может создать другое вложение; контракт не обещает идемпотентность upload. Сверка orphan/missing не заменяет полный scrub checksum всех ready-объектов.
|
||||
|
||||
На защите показать 201 только после устойчивой записи, download через другую реплику, чужой 404 и закрытый прямой S3 GET. Затем объяснить невозможность общей SQL/S3-транзакции, показать dry-run/apply/repeat и границы RAM, не называя один host отказоустойчивым кластером.
|
||||
@@ -0,0 +1,89 @@
|
||||
# Запуск лабораторной 4
|
||||
|
||||
> Историческая инструкция Compose/HAProxy. Основной путь теперь описан в ../../RUN.md. Для старых action helpers явно задайте VP_RUNTIME=compose; прежние runners сохранены как student-tests/reconciliation-compose.ts и concurrent-images-compose.ts. Числа этого варианта не являются измерениями k3s/Pingap.
|
||||
|
||||
Автор: Медведев Андрей Михайлович, БПИ2303. Исходное задание и контракт сохранены в README.md и contracts/. Реализация находится в backend/, дополнительные проверки в student-tests/.
|
||||
|
||||
Нужны Docker Engine с Compose, Bun 1.4 и Python 3.9+. Для Go-тестов на хосте нужен Go 1.27.2 или новее. Проверенный стенд: Linux x86_64, Docker 29.9.2, Compose 5.6.1, Bun 1.4.4; образ компилируется Go 1.27.2. Образы PostgreSQL 18.6 и Valkey 9 закреплены digest в compose.yaml.
|
||||
|
||||
Команды выполняются из этого каталога. scripts/compose.sh закрепляет manifest и имя vp-lab4-medvedev, чтобы переменные другого проекта не перенаправили операции.
|
||||
|
||||
```sh
|
||||
bun --no-env-file scripts/bootstrap.ts
|
||||
./scripts/compose.sh up -d --build
|
||||
BASE_URL=http://127.0.0.1:28204 bun --no-env-file student-tests/wait.ts
|
||||
python3 -m venv .venv
|
||||
.venv/bin/pip install -r requirements-dev.txt
|
||||
make check
|
||||
make validate PYTHON=.venv/bin/python
|
||||
make test BASE_URL=http://127.0.0.1:28204
|
||||
BASE_URL=http://127.0.0.1:28204 bun --no-env-file student-tests/acceptance.ts
|
||||
make test-persistence BASE_URL=http://127.0.0.1:28204 ACTION_SCRIPT=scripts/restart.sh
|
||||
cd backend
|
||||
go test -race ./...
|
||||
go tool golangci-lint run
|
||||
go generate ./...
|
||||
```
|
||||
|
||||
Bootstrap создаёт отдельные случайные учебные credentials в .local/ и не печатает их. Каталог исключён из git и Docker context. Существующие файлы не перезаписываются. Миграции запускает отдельный service migrate; API не выполняет их конкурентно.
|
||||
|
||||
HTTP доступен только через localhost. Все данные тестов синтетические; публичные тесты сохраняют свой набор данных для демонстрации, дополнительные acceptance-тесты удаляют только свой случайный набор. Пароли и сессии не выводятся в отчёты.
|
||||
|
||||
Обычная остановка сохраняет volumes:
|
||||
|
||||
```sh
|
||||
./scripts/compose.sh stop
|
||||
```
|
||||
|
||||
Повторный запуск с сохранением данных:
|
||||
|
||||
```sh
|
||||
./scripts/compose.sh up -d
|
||||
```
|
||||
|
||||
Только для намеренного полного сброса собственных учебных данных:
|
||||
|
||||
```sh
|
||||
./scripts/compose.sh down --volumes
|
||||
```
|
||||
|
||||
Для проверки отказа запустите публичный сценарий. Он передаёт реальный TARGET_INSTANCE_ID hook-скрипту; после проверки верните обе реплики и дождитесь готовности.
|
||||
|
||||
```sh
|
||||
make test-failover BASE_URL=http://127.0.0.1:28204 ACTION_SCRIPT=scripts/stop-one.sh
|
||||
./scripts/compose.sh up -d
|
||||
BASE_URL=http://127.0.0.1:28204 bun --no-env-file student-tests/wait.ts
|
||||
```
|
||||
|
||||
Чтобы проверить вторую реплику, повторите сценарий после восстановления; фактический остановленный контейнер записывается в evidence/stop-one-after.txt.
|
||||
|
||||
Отказ S3 с восстановлением и проверкой подтверждённого оригинала:
|
||||
|
||||
```sh
|
||||
FAIL_S3=1 BASE_URL=http://127.0.0.1:28204 bun --no-env-file student-tests/acceptance.ts
|
||||
```
|
||||
|
||||
Исследование трека 2 запускайте через изолирующий runner. Он создаёт отдельный случайный Compose-проект с пустыми DB/bucket, воспроизводит настоящие частичные отказы и dry-run/apply/repeat, затем удаляет только свой проект. Результаты появляются в новом evidence/reconciliation/run-*.
|
||||
|
||||
```sh
|
||||
bun --no-env-file student-tests/reconciliation.ts
|
||||
```
|
||||
|
||||
Не запускайте integration service напрямую на демонстрационной БД: тест сверяет весь изолированный набор. Для обычной сверки доступен CLI с ограничением 100 metadata и 100 объектов на вызов. Первая команда ничего не меняет; вторая явно применяет безопасные исправления.
|
||||
|
||||
```sh
|
||||
./scripts/compose.sh run --rm --no-deps api -reconcile
|
||||
./scripts/compose.sh run --rm --no-deps api -reconcile -apply
|
||||
```
|
||||
|
||||
CLI возвращает поля продолжения metadata/object. Для следующей страницы передайте их через -after и -object-after; при ошибке повторите страницу с прежними курсорами. Default grace равен 10 минутам, минимальный -grace равен 60s.
|
||||
|
||||
Проверки памяти выполняются на omarchy без игры. Сначала соберите обычный образ и дождитесь готовности. Генератор создаёт только синтетический PNG в .local/; скрипт одновременно начинает десять upload и проверяет исходные bytes всех успешных загрузок. Отдельный процесс декодирует экстремальные PNG вместе с KDF-worker.
|
||||
|
||||
```sh
|
||||
go run ./student-tests/image-fixtures/main.go
|
||||
BASE_URL=http://127.0.0.1:28204 bun --no-env-file student-tests/concurrent-images.ts
|
||||
./student-tests/image-memory.sh
|
||||
```
|
||||
|
||||
Команда генератора выполняется из корня лабы. Поля продолжения CLI называются NextMetadata и NextObject. Подтверждённые результаты и ограничения перечислены в REPORT.md. Автоматические проверки не выставляют оценку преподавателя.
|
||||
@@ -0,0 +1,15 @@
|
||||
# Implementation plan and boundaries
|
||||
|
||||
Archived: this inherited lab2 plan is retained as historical context only. The completed lab4 implementation, results and limitations are documented in ../../REPORT.md; startup instructions are in ../../RUN.md.
|
||||
|
||||
This repository carries our lab1 domain, pagination, HTTP/error handling, bounded queue and shutdown code into the original lab2 skeleton. The lab1 memory adapter and its obsolete HTTP identity tests are not carried forward.
|
||||
|
||||
PostgreSQL is authoritative for users, passwords, sessions, chats, membership and messages. Valkey caches immutable public profiles for 60 seconds; no chat/message/session cache is used. Authentication always reads the session from PostgreSQL, and cache failure falls back to PostgreSQL within an 80 ms budget. Logout deletes the persisted token hash. Cache contents contain no password or bearer token.
|
||||
|
||||
Transactions: chat allocation + chat row + membership; sender quota + message; session owner lock + expiry cleanup + session insertion. PostgreSQL constraints enforce username uniqueness and foreign keys. Maximums: 1000 created chats and 1,000,000 messages per owner; 100 unexpired sessions. No user data is silently deleted. The history index covers `(chat_id,created_at,id)` and queries fetch only `limit+1` rows. Keyset traversal is not a snapshot; writes whose wall-clock timestamps fall before a consumed cursor can be missed during concurrent traversal.
|
||||
|
||||
Argon2id uses a random 16-byte salt, 32 MiB, two iterations, one lane, 32-byte result. Tokens use 32 random bytes; PostgreSQL stores only SHA-256 of the token. SHA-256 is appropriate for high-entropy tokens, not passwords. The API gate bounds concurrent KDF calls to four. PostgreSQL pool: eight connections, statement timeout 2 s, lock timeout 1 s, connect timeout 1 s; request context 5 s.
|
||||
|
||||
Readiness checks PostgreSQL. Valkey is optional to safe operation; its absence is observable through cache hit statistics and failure tests, not an anonymous-authentication fallback. HTTP is bound to localhost and uses only generated synthetic data.
|
||||
|
||||
Research: compare history queries over at least 100,000 skewed messages; restore a backup into a new database, compare row counts and selected message bytes. See `REPORT.md` for actual results; planned experiments are not evidence.
|
||||
@@ -0,0 +1,16 @@
|
||||
# Closure review: VP laboratories 2–4
|
||||
|
||||
Проверено независимым агентом 12.11.2026. Объём — закрытие ранее найденных P1/P2 в текущих исходниках и operational helpers; полного повторного аудита не проводилось.
|
||||
|
||||
**Подтверждённых оставшихся ошибок в проверенном объёме не обнаружено.**
|
||||
|
||||
- Compose wrappers закрепляют файл и проект через явные `-f`/`-p`; research lab3 и reconciliation используют отдельные случайные проекты.
|
||||
- Reconciliation runner создаёт отдельные volumes, а destructive integration дополнительно требует пустые DB/bucket. Штатный профиль включает reconciliation, S3 metadata и foreign-membership regression.
|
||||
- Fixture cleanup проверяет чужое членство и подтверждает SQL COMMIT до удаления S3-оригиналов. Отказ SQL сохраняет байты.
|
||||
- Game guards разрешают измерения только при exit status `1`; активная игра и неизвестное состояние блокируют запуск.
|
||||
- Evidence сохраняется в отдельных каталогах запуска; итоговый PASS появляется после cleanup. Основная ошибка и ошибки уборки учитываются отдельно.
|
||||
- Monitor имеет немедленный rejection handler и завершается до cleanup. Rolling workload joined при отказе; замены проверяют readiness, продолжающиеся успешные записи и незавершённость нагрузки.
|
||||
- JSON middleware отвергает некорректный UTF-8 до декодирования; regression присутствует во всех трёх лабораторных.
|
||||
- В прочитанных acceptance2/3 уже используются `$fixture$` и PASS после cleanup. Их новое выполнение в это ревью не входило.
|
||||
|
||||
Проверка выполнена чтением кода, текущего плана и diff. Стенды, тесты, сборки и измерительные helpers не запускались; результаты автора повторно не подтверждались. Секреты и `.local` не читались. Единственное изменение ревьюера — этот файл.
|
||||
@@ -0,0 +1,115 @@
|
||||
14b7f3ced177639c80c8c9b113bef7d4783940b628f14d8bb6fc634eaa3d19e0 .dockerignore
|
||||
a45d7932ef14130aff8020bce79f043cccaf9692d697088a754d309a03f7d3e8 .github/workflows/contracts.yml
|
||||
b85d1e62d1f6d9c478cd1ce31c123c31c09a9c8b0565cf236f39a928a20a640b .gitignore
|
||||
2ba8ae54fd153e8aeb837f4366e14738934b740985702fe6e1086ea10a6dad55 Dockerfile
|
||||
c05bd07058ae0949dd4905afdae7674bc7e3e63863a6cdf8b72661140d445826 Makefile
|
||||
215578dee14bcef1b66759a68543083e0a624611efcdb785197307b50cb7725d backend/.golangci.yaml
|
||||
aef8d4a63db2a98602ec359a7d8b64e3922899d47da822558efc5d0b1dcda353 backend/cmd/app/main.go
|
||||
635e713dd67d866c95616cbeac0850614dfff05be60fdeef9b9b44f39cc3c864 backend/cmd/fixture-cleanup/main.go
|
||||
e4d37ce5c5a9f969f696833cd59a6e1b86f99fb2b0de69101a1aa5f4a539aebe backend/codegen.yaml
|
||||
33044d905354f24fff194fefd35ee9327d63d6e5062ded8496e518b6ce38dbea backend/db/migrate.go
|
||||
b6bd8c70d51aed6c966e07eebffd262af2e694c8b3479c70bbf9a9eacf5a7aad backend/db/migrations/00001_core.sql
|
||||
97c98785547db8391c1fa0a685e4d4bcc810b8f79055c0e2fc6ef473cd38b37b backend/db/migrations/00002_idempotency.sql
|
||||
a2893c49bfd1ddbf23bb24d675df2d757cbe44371554437265fd149c87d28bfd backend/db/migrations/00003_attachments.sql
|
||||
d60f5c7dab257f02aadfd1c844c25041df87719f69144ca38abab0dd7567a701 backend/db/sqlc/queries/attachments.sql
|
||||
1aed3d0d2fc04650351d86d15837cf3239636844727e799aabf5ddd534429f33 backend/db/sqlc/queries/core.sql
|
||||
5bdec86e85705f7805fb603e2c792bb87c11cf3156952fa48e7bcee35fd683ca backend/db/sqlc/queries/idempotency.sql
|
||||
803b161e063692398c93152b11a08f9e42e1bf3c72a1e64553b82c494545fd10 backend/db/sqlc/sqlc.yaml
|
||||
e666da2959b31befed713a8366237de53070a565f93850d6daae7a582a038819 backend/generator-overlay.yaml
|
||||
0b8da0a50d49decdd1b36c920363f5908b372a786a85bd6c2b789ce781ac8f91 backend/go.mod
|
||||
b981fecb6445955924c2162a1ca9a6877820143af458df963624b3ceb583b861 backend/go.sum
|
||||
d8444d4268fe136e23c804d4b92b8cef408678708078e991bd5c5731961cf8a6 backend/integration/fixture_cleanup_test.go
|
||||
598e973575d57c6ee563f0b15d0111d37b27de6774c6f486c998dbc70594f15d backend/integration/object_metadata_test.go
|
||||
d82aff3472ac7913ce0440390cae6533b79f8f52dee22243c3760f15c6f01ea8 backend/integration/reconcile_test.go
|
||||
aaf3d2b659463a2e7ae99b2a71a1891699aec5d86e05f7d249f6e78f6b188656 backend/internal/adapter/handler/api.gen.go
|
||||
9d9f109e13c9322287b29ed18e7913e0e8d5a9ef2dc4be23f10c7686de3f70fe backend/internal/adapter/handler/api.go
|
||||
5e156e1ebaae3b47576216014621b162f236de1b34696154c312ce68c3e70cde backend/internal/adapter/handler/attachments.go
|
||||
3889f58ac4c58b798192776ea05455d52735a2c024ba664ab9af5eb405187557 backend/internal/adapter/handler/auth.go
|
||||
39a5b916112fd9cc2be9979b6e78d6305e7c3c8ab5fa462f1b8e9f18c88c1a4a backend/internal/adapter/handler/errors.go
|
||||
b662058ebc59010f30d21da12404837aa2329fe5e5590761efdd9140c1d24e9c backend/internal/adapter/handler/gate.go
|
||||
f7938bdeb5617ed3611303c54818000de9861dde5915fa2c6fa0f74e1fa33268 backend/internal/adapter/handler/gate_test.go
|
||||
dc5a9abe76b57c3514c67feb7b98654bc058d3329c35724aef0b6a50476d0ebf backend/internal/adapter/handler/handler.go
|
||||
d6458b8e8e4426816ec8c855ff6c8d88a151161bc1560e4b98df0ea4b0dbf6be backend/internal/adapter/handler/json.go
|
||||
8dd976c4cad81ee531c76165787b2c8b6052057d934ae4b09b60d8a261cf30e5 backend/internal/adapter/handler/message_json_test.go
|
||||
256221524d19e057ab2a330e08f1c5b0bd5fc95b8d19391f69fd286e5aa8ba54 backend/internal/adapter/handler/middleware.go
|
||||
5cd375e5a0db8cc3596293d323e635b86fef22d8ec680f310ab5a460f8176f64 backend/internal/adapter/handler/stats.go
|
||||
eac6a14b5f3b0ea9aa5329337afc6db27e17f5c17999874da9ce3592dc7a4205 backend/internal/adapter/handler/utf8_test.go
|
||||
8a9b399b22573992fd7fd4c87096f953b46c1bc7cad4e09c023923919d755375 backend/internal/adapter/imagefile/image.go
|
||||
a2dc0d3797a5c2ac7ad46a7453a34ea13aba94c3385d2692032705610026dc71 backend/internal/adapter/imagefile/image_test.go
|
||||
3d7b0671f57ce5e01fa7e175a86c16a51d56d8f11ec6d3bfb09b2c8bfe8c04d8 backend/internal/adapter/imagefile/stress_test.go
|
||||
94643bf4b61ca390f8dd56a241e02e1325a994fc40887ffa0e2b8f8e5aebb4c7 backend/internal/adapter/password/argon.go
|
||||
e258ba0e4c514505b4467313dc18d18aa06e07c9238bc112d42ebac411f906d3 backend/internal/adapter/repository/postgres/attachments.go
|
||||
e4221361ac49186f787d0b467a17e471e584affc449fa8c91884a97d0d421b77 backend/internal/adapter/repository/postgres/queries/attachments.sql.go
|
||||
9a0e082263cbea39535de9c7c72c41a39a551efc9ee57fdd7b08856831d074b3 backend/internal/adapter/repository/postgres/queries/core.sql.go
|
||||
4863732830879d4162be215ff245375b953359de23bcd821ed7abc5c32a36c0f backend/internal/adapter/repository/postgres/queries/db.go
|
||||
cf6fbc316e93339e0f938c7ca82007e29c3e32f1a21ee1433a2ce8784697f002 backend/internal/adapter/repository/postgres/queries/idempotency.sql.go
|
||||
eb333104c380aec10108d517d16e7509905e55066f68e71fea64822506cfbba2 backend/internal/adapter/repository/postgres/queries/models.go
|
||||
9cfa4a240f3fa0f1b3b4bef23a3017dd1565d6dc179341282f0931b1f0d33549 backend/internal/adapter/repository/postgres/repository.go
|
||||
0ba63ca0efdd530cfe6fffd8f7937bb87cf243987029ed39452c01bdcaf9b41a backend/internal/adapter/storage/bootstrap.go
|
||||
a6c79cba7af74ce67e69678085e5bb267a47f9dd7be57daf003ba03951274a5c backend/internal/adapter/storage/readiness_test.go
|
||||
99a717604c71da5c181bef74612a603abe3cfc913ccb3da84ed581a57a11ccd8 backend/internal/adapter/storage/s3.go
|
||||
fc2b3197aea8f80407467fb75c7750012fc531e94169d20d34329d5044a3e7ad backend/internal/application/usecase/attachments.go
|
||||
93802954db2c8eda3782acc71bca817947fd556986d3f6552c78c4b346d988ca backend/internal/application/usecase/auth.go
|
||||
c58aba0d3f5d0ab92fab5d2771b90a3af5ad06e6afe0c7cc46f481a429e89f48 backend/internal/application/usecase/messenger.go
|
||||
bedf7a3a26af4adad8c489d1d90060aac8911163c5811af62058bb4642d28937 backend/internal/application/usecase/reconcile.go
|
||||
fdbcfad86851fc97a3cf635b6d884c41b43084eedc42b3c4847790c5eaad4a6f backend/internal/application/usecase/reconcile_test.go
|
||||
58795b18980c4dd938c73721ab937d06410af94edc156b7a7aa9b2c4c2388238 backend/internal/config/config.go
|
||||
390e3b5a4682719a0b25a8eb9aefeda9a9d1c774d3f8d1f08062c79a58d8859a backend/internal/config/config_test.go
|
||||
514c7345091f290f93e70db13f23e4beb82d3e362def2aed171d108b5226296e backend/internal/domain/model/attachment.go
|
||||
3f7454f48ef442c277fd2741ce5aeeccf03d590bd2d31b9b89fa39f0ba05de7f backend/internal/domain/model/chat.go
|
||||
bd55666ad90ecaba3b0a1496ba5499580c0c67446284ce0b83e4dd7633cecbae backend/internal/domain/model/errors.go
|
||||
0e0126663d2de04c9d14c8c7427f42a9fb733e3b170ceee7ed86c2138f51b23c backend/internal/domain/model/message.go
|
||||
77bb8767ac1352bd3551e724eaaeaad4fe93eae248cc8c3008ee8b1c08adddca backend/internal/domain/model/model_test.go
|
||||
cd6a07579bff01aa0d8a11b34fd000a804142b321cef302d386bdb95e9c7f953 backend/internal/domain/model/page.go
|
||||
8c245eef99a97261daf0aa16fec9edd7bcd3253ec4144c50b4f8e56e45e2186e backend/internal/domain/model/postgres_text_test.go
|
||||
c9410cacd9d1b2fd7f3f2cb7e4112e637ecc494f6e4b6da649f936ce0c9a0457 backend/internal/domain/model/text.go
|
||||
c20c8b8d8a9c0327a3a24afd74f3051d78caed1d2f0851baf340ef61ac502a92 backend/internal/domain/model/user.go
|
||||
465c1a1f19075b6f8301eef8dbd7fd9a8d20255716d72c97e946db04c2850dda backend/internal/domain/port/auth.go
|
||||
4d22b5ef5ff6fa13404884c160fe52bd7cef4099f84b29268137c27034a0f3ec backend/internal/domain/port/objects.go
|
||||
65230d87c38bd73cb5503b5b57f63da7b8af7b478794b0c2016cdcb198659a6e backend/internal/domain/repository/repository.go
|
||||
d839f31015eee692065c31d2538a4cb4c841b0d89e690f0ab8baf80168510556 backend/pkg/logger/logger.go
|
||||
3ce957e4e45a94453610217007a9dbf0e8b9723346ff9cc8a3e5aa8ff3676527 backend/pkg/server/server.go
|
||||
5368758f38e47f42c864b207f4baa05d5086773fa397b035dd2784d385e5c4a0 compose.example.yaml
|
||||
8acaa30f1744815213d6f4993d2af006e1d6d3a281de06e405f365e59704b576 compose.yaml
|
||||
5fbd83685515fa68b463fd887b66f23cd2ffab9283c9ece6d015cc5634c7f5bd config/haproxy.cfg
|
||||
381cc18c03789e935b391d007fb5843964be9cfd9f7530cb6b1996ed4a1c4c37 contracts/examples.json
|
||||
baaeb5a2233096a50d791f521bfc6dd66a23e516f81833c2b17c554cc0bab5d8 contracts/infrastructure.json
|
||||
c5c0ebdcf205018126c5bb91e2512b11f543827e76baa21d776210d05a0b2cca contracts/openapi.json
|
||||
fc00ac1974a40a1b2f3e2f28a9c9cc9bbe71ceea22f8161b9d42938f37c43fc1 deploy/k3s/api.yaml
|
||||
856b6c96722f4bd19d2e78a569caa579587d65ee21060b754a70e52890008802 deploy/k3s/kustomization.yaml
|
||||
e1d475e64e0092e5c92c6ace235c70b92cd2b42b83a420e2edf880a3fb50b8b8 deploy/k3s/namespace.yaml
|
||||
e436503ba6893e1f5fe0f1819471d5be2612d07b66790277293ef7e4ed7041d6 deploy/k3s/pingap.toml
|
||||
2542ef86087c55961f8d66ac70f8d9f616211b95d67d44e9fba8a4d700e53e16 deploy/k3s/pingap.yaml
|
||||
ad223fa37fd7ebfe51841065f24df2ff08d6c684d76292cda07009e1f965179b deploy/k3s/s3.yaml
|
||||
6dff977e5f1541e4713967844474a43c2150117a3ea666f737c788b6e7c234ee deploy/k3s/stores.yaml
|
||||
8c086fd540092b3e31a945a416632bcda6c4bea39253f86b076f791b362cf5e4 examples/requests.http
|
||||
7d0945d93e302c34c3f26455b152f9d657110ee0a94a5074d85963bc7aa60526 lab.json
|
||||
4cefdb67007caf026d1613be7c519c01b4c8343db7c4f4b618677e01cf113525 requirements-dev.txt
|
||||
eec21c7e9d66fce3003d2697dc2ff1394c8011e3d6c0a3312fbf265d2e2a754e scripts/bootstrap.ts
|
||||
7c4402c2a6ab80d3b4676e1866d6ecc87b6daea14c080bcb9be9a7e8b959d671 scripts/check_contract.py
|
||||
25d09f931d7f860868f190c1c01bfaf82cd1bf38da654d84653a758b95298098 scripts/compose.sh
|
||||
35a7507a45f2672095ae7a31a2e347421f16a81e78a76ccd4bf2c8e149dddb14 scripts/k3s-model.ts
|
||||
4951d81ca55099c7459106392bccc72fdaeeb090bc85bc38e01b42425bbba77d scripts/k3s.ts
|
||||
f9eaabbb88f14a49fdd8bd09de18de6959eefae9fb935a661afc0d500ef47a8c scripts/kube.sh
|
||||
0328246ba75defbced992104e986fde973f63e3830d83251eced5953263e944b scripts/restart.example.sh
|
||||
1e9cb8fb26d6a660511ad7c247e34656b79e2f168f0f00ff7b888cd581763567 scripts/restart.sh
|
||||
1bcf34394520b89d95b7605ec56675be799eea920e83cfbba306d5dc0a6d9811 scripts/stop-one.example.sh
|
||||
623ec85f2918c814dd7c12de14fe06c89bd9277afb60b431e59356aa45e6c876 scripts/stop-one.sh
|
||||
63b69b19641e8f9e27a9b159bf8c67c612e3476193c17e93541ca6cfd48ff2fd scripts/up.sh
|
||||
4e981acbfc10dac58817bf922d5896e996798551fedc1b2385130e1cddb13d54 scripts/validate_openapi.py
|
||||
5f3130f3fc92e1be86c794e00ff501fc9db1c90c746fa7ad76193a59cb7bb9ba student-tests/acceptance.ts
|
||||
ab73689e5693be18ffdeba3a085253454665bcf0bf8dd2b845ddd69c077a7878 student-tests/concurrent-images-compose.ts
|
||||
6f5a358cab227cfa2ea0d231a3fab6ad52f736b946be5d104a0f7e514b9c0dbb student-tests/concurrent-images.ts
|
||||
a29029cacac8368e9343d52cd331e458c0b26ceb2e863ac0db825eb94643a43e student-tests/image-fixtures/main.go
|
||||
105625230f8b5dda46fd116b18fe7cfaf64ba09445e3dabe4b8af1a9ae0fa182 student-tests/image-memory.sh
|
||||
4693f4d130bdaa88fe5d61258b55f56844c7d67ee72b819ef4997b80d852cb95 student-tests/k3s-model.test.ts
|
||||
41849faeeb5ea371eb56f0dc500f658ab46d142451727816501bb134b4b6e31e student-tests/kube-stdin.ts
|
||||
b58aff883d63e0098c4f0cf7e0aab1c1d280026e9d67cdf8ae4faf4ae119f958 student-tests/reconciliation-compose.ts
|
||||
09579bfe7e5d75e4b91342ae62c169e82199db5f6ea2344d4b960000ff01c4a2 student-tests/reconciliation.ts
|
||||
7de6e4f405cb165f56e48f40889adc5ff39c9a8ec253de48e5633a0d961d960a student-tests/restart-evidence.ts
|
||||
9dff91ee5a9876d5c4758d66a65b3b42c29a6d3071c7e510babae561a84cf35b student-tests/wait.ts
|
||||
8d50976fc7c7bbb81e88a152f613c61ab25eaf53dba33c6a9dfab19f868d546d tests/client.py
|
||||
a9a4f89181c8e0fda6ce42e1a1af32fb42d8e3ae519e314207127c9b9b448b13 tests/image_probe.py
|
||||
6d3511ea719c7a7e841083e73d435c86dcbfd9f4e5c2a07d62eb9614b01d9933 tests/load.py
|
||||
1f96663a174b3978d24eff66f2741f5f8c9b788d3242261d37a972720c52788b tests/resilience.py
|
||||
52ac38eb343ff7d43e7543588e1da58ca06c9fce74b2b0d0bf0e4982bc23c1db tests/smoke.py
|
||||
@@ -0,0 +1 @@
|
||||
PASS lab4: 456 HTTP assertions, registration race, rollback, pagination, authentication, concurrent idempotency and replica sharing; fixture cleanup completed
|
||||
@@ -0,0 +1,179 @@
|
||||
#1 [internal] load local bake definitions
|
||||
#1 reading from stdin 1.53kB done
|
||||
#1 DONE 0.0s
|
||||
|
||||
#2 [api internal] load build definition from Dockerfile
|
||||
#2 transferring dockerfile: 2.18kB 0.1s done
|
||||
#2 transferring dockerfile: 2.18kB 0.1s done
|
||||
#2 DONE 0.2s
|
||||
|
||||
#3 [api] resolve image config for docker-image://docker.io/docker/dockerfile:1
|
||||
#3 DONE 0.8s
|
||||
|
||||
#4 [bootstrap-s3] docker-image://docker.io/docker/dockerfile:1@sha256:4edf897a3ffa55b89f906fc8cc78afdb3f1834cc9c7083565e611a8a7d5fe99e
|
||||
#4 resolve docker.io/docker/dockerfile:1@sha256:4edf897a3ffa55b89f906fc8cc78afdb3f1834cc9c7083565e611a8a7d5fe99e
|
||||
#4 resolve docker.io/docker/dockerfile:1@sha256:4edf897a3ffa55b89f906fc8cc78afdb3f1834cc9c7083565e611a8a7d5fe99e 0.3s done
|
||||
#4 resolve docker.io/docker/dockerfile:1@sha256:4edf897a3ffa55b89f906fc8cc78afdb3f1834cc9c7083565e611a8a7d5fe99e 0.3s done
|
||||
#4 CACHED
|
||||
|
||||
#5 [api internal] load metadata for gcr.io/distroless/static-debian13:nonroot@sha256:e2e927ec666bae08560abb3c55d0659eceabb657f56b6782ab500a9fc7f555e3
|
||||
#5 ...
|
||||
|
||||
#6 [migrate internal] load metadata for docker.io/library/golang:1.27.2-alpine@sha256:f92b6ef800e499660581efdabdf25d9d817a9d124eaf900924f0504e7e27e12d
|
||||
#6 DONE 0.4s
|
||||
|
||||
#5 [migrate internal] load metadata for gcr.io/distroless/static-debian13:nonroot@sha256:e2e927ec666bae08560abb3c55d0659eceabb657f56b6782ab500a9fc7f555e3
|
||||
#5 DONE 1.2s
|
||||
|
||||
#7 [bootstrap-s3 internal] load .dockerignore
|
||||
#7 transferring context: 226B done
|
||||
#7 DONE 0.1s
|
||||
|
||||
#8 [migrate internal] load build context
|
||||
#8 DONE 0.0s
|
||||
|
||||
#9 [migrate stage-1 1/5] FROM gcr.io/distroless/static-debian13:nonroot@sha256:e2e927ec666bae08560abb3c55d0659eceabb657f56b6782ab500a9fc7f555e3
|
||||
#9 resolve gcr.io/distroless/static-debian13:nonroot@sha256:e2e927ec666bae08560abb3c55d0659eceabb657f56b6782ab500a9fc7f555e3
|
||||
#9 ...
|
||||
|
||||
#8 [api internal] load build context
|
||||
#8 DONE 0.0s
|
||||
|
||||
#9 [api stage-1 1/5] FROM gcr.io/distroless/static-debian13:nonroot@sha256:e2e927ec666bae08560abb3c55d0659eceabb657f56b6782ab500a9fc7f555e3
|
||||
#9 ...
|
||||
|
||||
#8 [bootstrap-s3 internal] load build context
|
||||
#8 DONE 0.0s
|
||||
|
||||
#9 [bootstrap-s3 stage-1 1/5] FROM gcr.io/distroless/static-debian13:nonroot@sha256:e2e927ec666bae08560abb3c55d0659eceabb657f56b6782ab500a9fc7f555e3
|
||||
#9 resolve gcr.io/distroless/static-debian13:nonroot@sha256:e2e927ec666bae08560abb3c55d0659eceabb657f56b6782ab500a9fc7f555e3 0.6s done
|
||||
#9 resolve gcr.io/distroless/static-debian13:nonroot@sha256:e2e927ec666bae08560abb3c55d0659eceabb657f56b6782ab500a9fc7f555e3 0.6s done
|
||||
#9 DONE 0.7s
|
||||
|
||||
#10 [bootstrap-s3 build 1/4] FROM docker.io/library/golang:1.27.2-alpine@sha256:f92b6ef800e499660581efdabdf25d9d817a9d124eaf900924f0504e7e27e12d
|
||||
#10 resolve docker.io/library/golang:1.27.2-alpine@sha256:f92b6ef800e499660581efdabdf25d9d817a9d124eaf900924f0504e7e27e12d 0.6s done
|
||||
#10 DONE 0.8s
|
||||
|
||||
#8 [bootstrap-s3 internal] load build context
|
||||
#8 transferring context: 226.80kB 0.1s done
|
||||
#8 transferring context: 226.80kB 0.1s done
|
||||
#8 DONE 0.2s
|
||||
|
||||
#11 [migrate build 2/4] WORKDIR /src
|
||||
#11 CACHED
|
||||
|
||||
#12 [migrate build 3/4] COPY backend/ ./
|
||||
#12 DONE 0.7s
|
||||
|
||||
#13 [api build 4/4] RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build go build -trimpath -ldflags='-s -w' -o /out/messenger ./cmd/app && go build -trimpath -ldflags='-s -w' -o /out/fixture-cleanup ./cmd/fixture-cleanup && go test -c -o /out/integration.test ./integration && go test -c -o /out/image-memory.test ./internal/adapter/imagefile
|
||||
#13 DONE 21.7s
|
||||
|
||||
#9 [api stage-1 1/5] FROM gcr.io/distroless/static-debian13:nonroot@sha256:e2e927ec666bae08560abb3c55d0659eceabb657f56b6782ab500a9fc7f555e3
|
||||
#9 CACHED
|
||||
|
||||
#14 [api stage-1 2/5] COPY --from=build /out/messenger /messenger
|
||||
#14 DONE 0.9s
|
||||
|
||||
#15 [bootstrap-s3 stage-1 3/5] COPY --from=build /out/fixture-cleanup /fixture-cleanup
|
||||
#15 DONE 1.0s
|
||||
|
||||
#16 [migrate stage-1 4/5] COPY --from=build /out/integration.test /integration.test
|
||||
#16 DONE 1.1s
|
||||
|
||||
#17 [api stage-1 5/5] COPY --from=build /out/image-memory.test /image-memory.test
|
||||
#17 DONE 0.9s
|
||||
|
||||
#18 [api] exporting to image
|
||||
#18 exporting layers
|
||||
#18 exporting layers 5.9s done
|
||||
#18 exporting manifest sha256:8176b66808e39191ba7edafd147522c633535b17174d03735165865b85f90f88
|
||||
#18 exporting manifest sha256:8176b66808e39191ba7edafd147522c633535b17174d03735165865b85f90f88 0.8s done
|
||||
#18 exporting config sha256:e93e6eb0c8ca16048ed0f6dc3f1a9a5f1e7b94587fbe1b9019eb15bacd2a85c4
|
||||
#18 ...
|
||||
|
||||
#19 [bootstrap-s3] exporting to image
|
||||
#19 exporting layers 6.0s done
|
||||
#19 exporting manifest sha256:e9611781e6240078a930027fa2b70aab3a601e04702d7870f8f3d0599ceb3f71 0.6s done
|
||||
#19 exporting config sha256:007cf7385134755ce2d37d87c847ff13bf5a8275bf83fef9d2fcddfdfbc36810 1.0s done
|
||||
#19 ...
|
||||
|
||||
#18 [api] exporting to image
|
||||
#18 exporting config sha256:e93e6eb0c8ca16048ed0f6dc3f1a9a5f1e7b94587fbe1b9019eb15bacd2a85c4 1.0s done
|
||||
#18 exporting attestation manifest sha256:c7c98f08901cf6f4a22ba2e8b689859a007cc9a52611b4c5c2fc0b5cb906b982
|
||||
#18 exporting attestation manifest sha256:c7c98f08901cf6f4a22ba2e8b689859a007cc9a52611b4c5c2fc0b5cb906b982 0.9s done
|
||||
#18 exporting manifest list sha256:8f19d6fd4b6908886d27c1a2557b03364afbccb91fb97d937d6afb045e332072
|
||||
#18 exporting manifest list sha256:8f19d6fd4b6908886d27c1a2557b03364afbccb91fb97d937d6afb045e332072 0.7s done
|
||||
#18 naming to docker.io/library/vp-medvedev-lab4:local
|
||||
#18 naming to docker.io/library/vp-medvedev-lab4:local 0.1s done
|
||||
#18 unpacking to docker.io/library/vp-medvedev-lab4:local
|
||||
#18 ...
|
||||
|
||||
#20 [migrate] exporting to image
|
||||
#20 exporting layers 5.9s done
|
||||
#20 exporting manifest sha256:b457e695713009537a9ee2ae37996482a8d5f2d01456f66ff203fb516c8f0a2b 0.7s done
|
||||
#20 exporting config sha256:a677c9748c168efefb25140409d7010339b861a005b02d4cbb26d47ee580d114 1.0s done
|
||||
#20 exporting attestation manifest sha256:e57efb6bede2ce57d86300a0551ff9b644efac234fda2928ed6d33a11a517486 0.9s done
|
||||
#20 exporting manifest list sha256:3f46ddb8992950880aa0daaea06f34c970d5284c8e6dd767c83b584dd7c854fa 0.7s done
|
||||
#20 naming to docker.io/library/vp-medvedev-lab4:local 0.1s done
|
||||
#20 ...
|
||||
|
||||
#19 [bootstrap-s3] exporting to image
|
||||
#19 exporting attestation manifest sha256:0fa4bfe822df1cf87673a58d1975372d00aac68690200d43ace41421ccc84873 0.9s done
|
||||
#19 exporting manifest list sha256:329e3935ab50104fe74f40359fa530a9322066d35c92349ffd1efd8f169e7168 0.7s done
|
||||
#19 naming to docker.io/library/vp-medvedev-lab4:local 0.2s done
|
||||
#19 ...
|
||||
|
||||
#20 [migrate] exporting to image
|
||||
#20 unpacking to docker.io/library/vp-medvedev-lab4:local 3.9s done
|
||||
#20 DONE 14.1s
|
||||
|
||||
#19 [bootstrap-s3] exporting to image
|
||||
#19 unpacking to docker.io/library/vp-medvedev-lab4:local 4.0s done
|
||||
#19 DONE 14.2s
|
||||
|
||||
#18 [api] exporting to image
|
||||
#18 unpacking to docker.io/library/vp-medvedev-lab4:local 4.2s done
|
||||
#18 DONE 14.8s
|
||||
|
||||
#21 [migrate] resolving provenance for metadata file
|
||||
#21 DONE 0.8s
|
||||
|
||||
#22 [bootstrap-s3] resolving provenance for metadata file
|
||||
#22 DONE 0.6s
|
||||
|
||||
#23 [api] resolving provenance for metadata file
|
||||
#23 DONE 0.0s
|
||||
Image vp-medvedev-lab4:local Building
|
||||
Image vp-medvedev-lab4:local Building
|
||||
Image vp-medvedev-lab4:local Building
|
||||
Image vp-medvedev-lab4:local Built
|
||||
Image vp-medvedev-lab4:local Built
|
||||
Image vp-medvedev-lab4:local Built
|
||||
Container vp-lab4-medvedev-s3-1 Running
|
||||
Container vp-lab4-medvedev-lb-1 Running
|
||||
Container vp-lab4-medvedev-valkey-1 Running
|
||||
Container vp-lab4-medvedev-postgres-1 Running
|
||||
Container vp-lab4-medvedev-migrate-1 Recreate
|
||||
Container vp-lab4-medvedev-bootstrap-s3-1 Recreate
|
||||
Container vp-lab4-medvedev-migrate-1 Recreated
|
||||
Container vp-lab4-medvedev-bootstrap-s3-1 Recreated
|
||||
Container vp-lab4-medvedev-api-1 Recreate
|
||||
Container vp-lab4-medvedev-api-2 Recreate
|
||||
Container vp-lab4-medvedev-api-1 Recreated
|
||||
Container vp-lab4-medvedev-api-2 Recreated
|
||||
Container vp-lab4-medvedev-s3-1 Waiting
|
||||
Container vp-lab4-medvedev-postgres-1 Waiting
|
||||
Container vp-lab4-medvedev-postgres-1 Healthy
|
||||
Container vp-lab4-medvedev-s3-1 Healthy
|
||||
Container vp-lab4-medvedev-bootstrap-s3-1 Starting
|
||||
Container vp-lab4-medvedev-migrate-1 Starting
|
||||
Container vp-lab4-medvedev-bootstrap-s3-1 Started
|
||||
Container vp-lab4-medvedev-migrate-1 Started
|
||||
Container vp-lab4-medvedev-bootstrap-s3-1 Waiting
|
||||
Container vp-lab4-medvedev-migrate-1 Waiting
|
||||
Container vp-lab4-medvedev-migrate-1 Exited
|
||||
Container vp-lab4-medvedev-bootstrap-s3-1 Exited
|
||||
Container vp-lab4-medvedev-api-2 Starting
|
||||
Container vp-lab4-medvedev-api-2 Started
|
||||
Container vp-lab4-medvedev-api-1 Starting
|
||||
Container vp-lab4-medvedev-api-1 Started
|
||||
@@ -0,0 +1,2 @@
|
||||
/mnt/data/home/bench-saves/vp-labs-vuIKezo9/lab4/.venv/bin/python scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
@@ -0,0 +1 @@
|
||||
{"run_id":"st_70749fb9561e4802","started_at":"2026-11-12T13:25:42.299Z","state":"started"}
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"run_id": "st_70749fb9561e4802",
|
||||
"complete": true,
|
||||
"result": {
|
||||
"attempts": 10,
|
||||
"image_bytes": 3148214,
|
||||
"success": 8,
|
||||
"rejected_503": 2,
|
||||
"peaks": [
|
||||
{
|
||||
"instance": "1ef16485f31f",
|
||||
"memory_peak_bytes": 78458880
|
||||
},
|
||||
{
|
||||
"instance": "262b3ae02f80",
|
||||
"memory_peak_bytes": 78077952
|
||||
}
|
||||
],
|
||||
"samples": [
|
||||
{
|
||||
"name": "vp-lab4-medvedev-api-1",
|
||||
"cpu_percent": "2.54%",
|
||||
"memory": "49.75MiB / 2GiB"
|
||||
},
|
||||
{
|
||||
"name": "vp-lab4-medvedev-api-2",
|
||||
"cpu_percent": "0.59%",
|
||||
"memory": "41.94MiB / 2GiB"
|
||||
},
|
||||
{
|
||||
"name": "vp-lab4-medvedev-api-1",
|
||||
"cpu_percent": "4.00%",
|
||||
"memory": "60.55MiB / 2GiB"
|
||||
},
|
||||
{
|
||||
"name": "vp-lab4-medvedev-api-2",
|
||||
"cpu_percent": "0.73%",
|
||||
"memory": "58.75MiB / 2GiB"
|
||||
}
|
||||
],
|
||||
"originals_verified": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://127.0.0.1:28204"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 118, "failed_attempts": 2, "first_recovery_seconds": 3.378}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1,4 @@
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://127.0.0.1:28204"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 124, "failed_attempts": 1, "first_recovery_seconds": 2.158}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1,17 @@
|
||||
? backend/cmd/app [no test files]
|
||||
? backend/cmd/fixture-cleanup [no test files]
|
||||
? backend/db [no test files]
|
||||
ok backend/integration (cached)
|
||||
ok backend/internal/adapter/handler 1.036s
|
||||
ok backend/internal/adapter/imagefile (cached)
|
||||
? backend/internal/adapter/password [no test files]
|
||||
? backend/internal/adapter/repository/postgres [no test files]
|
||||
? backend/internal/adapter/repository/postgres/queries [no test files]
|
||||
ok backend/internal/adapter/storage (cached)
|
||||
ok backend/internal/application/usecase (cached)
|
||||
ok backend/internal/config 1.013s
|
||||
ok backend/internal/domain/model (cached)
|
||||
? backend/internal/domain/port [no test files]
|
||||
? backend/internal/domain/repository [no test files]
|
||||
? backend/pkg/logger [no test files]
|
||||
? backend/pkg/server [no test files]
|
||||
@@ -0,0 +1,10 @@
|
||||
Network vp-lab4-medvedev_default Creating
|
||||
Network vp-lab4-medvedev_default Creating
|
||||
Network vp-lab4-medvedev_default Created
|
||||
Network vp-lab4-medvedev_default Created
|
||||
Container vp-lab4-medvedev-image-memory-run-39a8f5fa6633 Creating
|
||||
Container vp-lab4-medvedev-image-memory-run-39a8f5fa6633 Created
|
||||
=== RUN TestWorstCaseImagesWithinBudget
|
||||
stress_test.go:42: PASS native RGBA64 40000000x1, normal+Adam7, two sequential validations each, 3 concurrent Argon2 workers; peak_rss_kib=1538856 hard_limit_kib=2097152
|
||||
--- PASS: TestWorstCaseImagesWithinBudget (4.70s)
|
||||
PASS
|
||||
@@ -0,0 +1 @@
|
||||
{"state":"complete"}
|
||||
@@ -0,0 +1 @@
|
||||
8a9b399b22573992fd7fd4c87096f953b46c1bc7cad4e09c023923919d755375 backend/internal/adapter/imagefile/image.go
|
||||
@@ -0,0 +1,13 @@
|
||||
# Independent runtime review
|
||||
|
||||
Scope: approved lab3/lab4 k3s + Pingap migration, scripts/k3s.ts, scripts/k3s-model.ts, new unit tests and native research/concurrent-images/reconciliation call sites. Reviewer: independent agent /root/lab1_review, read-only. Backend and original course contracts were outside the implementation diff.
|
||||
|
||||
No confirmed remaining P1/P2 findings in the reviewed scope. Confirmed prior findings were corrected: Pingap shutdown grace, pinned manifest/config identities, scoped kubectl arguments, game guard at the native memory Job, partial-claim ownership and native CRI verification of stopped Pod processes.
|
||||
|
||||
Closure review checked withCleanup preserving primary and teardown errors, ready waiting for managed terminating Pods, restart pairing evidence by run_id and rejecting reused original UIDs, and the lab4 hard2048MiB/soft1536MiB image budget. Runtime/model copies in both labs matched. Reviewer ran no live operations or tests; author test output is separate.
|
||||
|
||||
Live tests are author evidence, separate from read-only review. Archive validation, teacher acceptance and an awarded grade are not inferred from this review.
|
||||
|
||||
Follow-up review checked the lab4 outage test timeout: no assignment/contract/public test requires8seconds for upload dependency failure. The handler budgets20seconds and the student client now waits at most25seconds, still requiring HTTP502/503 and a complete response. Public failover deadlines remain unchanged. Both acceptance helpers annotate their current operation and preserve the original error as cause. No blocker found; reviewer performed no live test.
|
||||
|
||||
Fresh measurement/report review checked concurrent-images/run-Y14n1Y and image-memory-6l7yZ5 against REPORT.md and actual source:8 successful originals out of10,2 bounded503,68,116,480/68,026,368-byte cgroup peaks;1555800KiB VmHWM over5.34s for normal/Adam7 with3 Argon2 workers. Image source hash matches. Job2CPU/2Gi and soft1536MiB agree with runtime. No confirmed issue found; RSS and cgroup memory are correctly distinguished.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user