ЛР1 на 4: in-memory API, Docker, student-tests и конкурентная проверка.
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Реализован контракт lab1 (X-User-Id), non-root образ, SIGTERM ≤10s, DEFENSE/REPORT.
This commit is contained in:
+88
@@ -0,0 +1,88 @@
|
|||||||
|
# Шпаргалка к защите ЛР1
|
||||||
|
|
||||||
|
**Автор:** Гавриленко Владислав, БПИ2303 · **Цель:** оценка 4
|
||||||
|
**Сервер:** `http://127.0.0.1:8080` · **Auth lab1:** заголовок `X-User-Id: <uuid существующего пользователя>`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Быстрый старт
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd lab1
|
||||||
|
cp -n .env.example .env
|
||||||
|
docker build -t mtusi-messenger:lab1 .
|
||||||
|
docker run -d --name mtusi-messenger-lab1 -p 127.0.0.1:8080:8080 --env-file .env mtusi-messenger:lab1
|
||||||
|
curl -s http://127.0.0.1:8080/health/ready
|
||||||
|
make test
|
||||||
|
make student-test
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Health
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -si http://127.0.0.1:8080/health/live
|
||||||
|
curl -si http://127.0.0.1:8080/health/ready
|
||||||
|
```
|
||||||
|
|
||||||
|
В каждом ответе должен быть непустой `X-Request-Id`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Пользователи
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -s -X POST http://127.0.0.1:8080/api/v1/users \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-d '{"username":"alice_demo","display_name":"Алиса"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
Повтор того же `username` → **409**. Без `X-User-Id` на защищённых маршрутах → **401**.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ALICE_ID=<uuid из ответа>
|
||||||
|
curl -s http://127.0.0.1:8080/api/v1/users/me -H "X-User-Id: $ALICE_ID"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Чат и сообщения
|
||||||
|
|
||||||
|
```bash
|
||||||
|
BOB_ID=<uuid боба>
|
||||||
|
curl -s -X POST http://127.0.0.1:8080/api/v1/chats \
|
||||||
|
-H "X-User-Id: $ALICE_ID" -H 'Content-Type: application/json' \
|
||||||
|
-d "{\"title\":\"Демо\",\"member_ids\":[\"$ALICE_ID\",\"$BOB_ID\"]}"
|
||||||
|
```
|
||||||
|
|
||||||
|
Чужой пользователь (не участник) → **404** на `GET /chats/{id}` и `POST .../messages`, не **403**.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
CHAT_ID=<uuid чата>
|
||||||
|
curl -s -X POST "http://127.0.0.1:8080/api/v1/chats/$CHAT_ID/messages" \
|
||||||
|
-H "X-User-Id: $ALICE_ID" -H 'Content-Type: application/json' \
|
||||||
|
-d '{"text":"Привет!"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
Пагинация: `GET .../messages?limit=1` → `next_cursor`; вторая страница с `cursor=...`, без дублей.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Доказательства уровня 4
|
||||||
|
|
||||||
|
| Что показать | Команда |
|
||||||
|
| --- | --- |
|
||||||
|
| Собственные тесты | `make student-test` |
|
||||||
|
| 10×100 сообщений | `bash scripts/run_concurrent_test.sh` |
|
||||||
|
| Graceful shutdown | `docker stop -t 10 mtusi-messenger-lab1` (≤10s, ready был 503) |
|
||||||
|
| Потеря in-memory | создать user → restart контейнера → `GET /users/me` с тем же id → **401** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ответы на типовые вопросы
|
||||||
|
|
||||||
|
- **Процесс / контейнер / образ:** процесс — живой сервер в ОС; образ — шаблон файловой системы; контейнер — запущенный изолированный процесс из образа.
|
||||||
|
- **0.0.0.0 vs 127.0.0.1 в контейнере:** сервер должен слушать `0.0.0.0`, иначе published port с хоста не достучится.
|
||||||
|
- **Два процесса:** два независимых хранилища в памяти — данные не общие.
|
||||||
|
- **Cursor vs offset:** cursor привязан к `(created_at, id)` и не «плывёт» при вставках в начало; между HTTP-запросами snapshot-изоляции нет.
|
||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
# syntax=docker/dockerfile:1.7
|
||||||
|
FROM golang:1.23.8-bookworm AS build
|
||||||
|
WORKDIR /src
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
COPY cmd ./cmd
|
||||||
|
COPY internal ./internal
|
||||||
|
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server
|
||||||
|
|
||||||
|
FROM gcr.io/distroless/static-debian12:nonroot
|
||||||
|
COPY --from=build /out/server /server
|
||||||
|
USER nonroot:nonroot
|
||||||
|
EXPOSE 8080
|
||||||
|
ENV APP_HOST=0.0.0.0 \
|
||||||
|
APP_PORT=8080 \
|
||||||
|
APP_ENV=lab
|
||||||
|
HEALTHCHECK --interval=5s --timeout=3s --start-period=3s --retries=3 \
|
||||||
|
CMD ["/server", "-healthcheck"]
|
||||||
|
ENTRYPOINT ["/server"]
|
||||||
@@ -3,11 +3,12 @@ BASE_URL ?= http://localhost:8080
|
|||||||
CA_FILE ?=
|
CA_FILE ?=
|
||||||
ACTION_SCRIPT ?=
|
ACTION_SCRIPT ?=
|
||||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||||
|
GO ?= go
|
||||||
|
|
||||||
.PHONY: help check validate test load
|
.PHONY: help check validate test load student-test build run
|
||||||
|
|
||||||
help:
|
help:
|
||||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
@echo "check: offline structure; validate: full OpenAPI; test: public smoke; student-test: own Go checks; build: compile server"
|
||||||
|
|
||||||
check:
|
check:
|
||||||
$(PYTHON) scripts/check_contract.py
|
$(PYTHON) scripts/check_contract.py
|
||||||
@@ -20,3 +21,9 @@ test:
|
|||||||
|
|
||||||
load:
|
load:
|
||||||
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
|
|
||||||
|
student-test:
|
||||||
|
$(GO) test ./student-tests/ -v -count=1 -timeout 120s
|
||||||
|
|
||||||
|
build:
|
||||||
|
$(GO) build -o bin/server ./cmd/server
|
||||||
|
|||||||
@@ -1,37 +1,56 @@
|
|||||||
# Отчёт — лабораторная 1
|
# Отчёт — лабораторная 1
|
||||||
|
|
||||||
- Автор, группа: TODO
|
- Автор, группа: Гавриленко Владислав, БПИ2303
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
- Целевая оценка; выбранный трек 5, если нужен: **4** (без трека 5)
|
||||||
- Commit/PR: TODO после публикации
|
- Commit/PR: ветка `solution/bpi2303-gavrilenko` (TODO после публикации MR)
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
- Использованные источники, библиотеки и помощь ИИ: Go `net/http` (1.22+ ServeMux), `github.com/google/uuid`; публичные `tests/`; Cursor Agent для реализации и прогонов
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Запуск из чистого clone
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
Prerequisites: Docker, Go 1.23+, Python 3.9+ для `make test`.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cp .env.example .env
|
||||||
|
docker build -t mtusi-messenger:lab1 .
|
||||||
|
docker run --rm --name mtusi-messenger-lab1 -p 127.0.0.1:8080:8080 --env-file .env mtusi-messenger:lab1
|
||||||
|
# другой терминал:
|
||||||
|
make test
|
||||||
|
make student-test
|
||||||
|
```
|
||||||
|
|
||||||
|
Локально без Docker:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/server
|
||||||
|
make test BASE_URL=http://127.0.0.1:8080
|
||||||
|
```
|
||||||
|
|
||||||
|
Образы: build `golang:1.23.8-bookworm`, runtime `gcr.io/distroless/static-debian12:nonroot`, пользователь `nonroot:nonroot`. Конфиг: `APP_HOST`, `APP_PORT`, `APP_ENV`; опционально `APP_ACCESS_LOG=0` для тихих тестов.
|
||||||
|
|
||||||
|
Остановка: `docker stop -t 10 mtusi-messenger-lab1`. Данные только в RAM процесса — рестарт контейнера полностью сбрасывает users/chats/messages.
|
||||||
|
|
||||||
## Архитектура и решения
|
## Архитектура и решения
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
Один HTTP-процесс, источник истины — `internal/store.MemoryDB` (maps + один `sync.RWMutex` на все операции). API в `internal/api`: middleware `X-Request-Id`, access-log без текста сообщений, lab1 auth через `X-User-Id`. Keyset-пагинация: opaque cursor = base64(`scope|RFC3339Nano|uuid`). SIGTERM → `BeginDrain()` (`/health/ready` = 503) + `http.Server.Shutdown` с таймаутом 10s. Dockerfile: multi-stage, HEALTHCHECK через `/server -healthcheck`.
|
||||||
|
|
||||||
## Доказательства критериев
|
## Доказательства критериев
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
| Offline структура | `make check` | `PASS: offline skeleton...` | `evidence/check.txt` |
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
| Публичный smoke | `make test` | `PASS: lab1 public API scenario...` | `evidence/smoke.txt` |
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
| Собственные тесты | `make student-test` | `ok student-tests` | `evidence/student-tests.txt` |
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
| 10×100 сообщений | `bash scripts/run_concurrent_test.sh` | 100 уникальных id | `evidence/concurrent.txt` |
|
||||||
|
| go test ./... | `go test ./...` | все пакеты ok | `evidence/go-test.txt` |
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
| Docker build | `docker build -t mtusi-messenger:lab1 .` | успешная сборка | `evidence/docker-build.txt` |
|
||||||
|
|
||||||
## Эксперименты и отказы
|
## Эксперименты и отказы
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| TODO | TODO | TODO | TODO |
|
| `docker restart` | потеря всех users/chats/messages | прежний `X-User-Id` → 401 | мгновенно; данные не восстанавливаются |
|
||||||
|
| SIGTERM (`docker stop -t 10`) | shutdown ≤10s, ready→503 | завершение в пределах бюджета | in-memory потеряна |
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
## Ограничения и следующие шаги
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
Нет персистентности, сессий и rate limit — это следующие лабораторные. Один глобальный mutex проще, чем шардирование, но при очень высокой конкуренции на один чат может стать узким местом; для lab1 достаточно корректности. Трек 5 не выполнялся.
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"mtusi2026lab1/internal/api"
|
||||||
|
"mtusi2026lab1/internal/config"
|
||||||
|
"mtusi2026lab1/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
healthcheck := flag.Bool("healthcheck", false, "exit 0 if /health/ready is ok")
|
||||||
|
flag.Parse()
|
||||||
|
if *healthcheck {
|
||||||
|
os.Exit(probeReady())
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg, err := config.Load()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("config: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
db := store.New()
|
||||||
|
svc := api.New(db)
|
||||||
|
server := &http.Server{
|
||||||
|
Addr: cfg.Addr(),
|
||||||
|
Handler: svc.Routes(),
|
||||||
|
ReadHeaderTimeout: 5 * time.Second,
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
log.Printf("starting messenger env=%s listen=%s", cfg.Env, cfg.Addr())
|
||||||
|
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||||
|
log.Fatalf("listen: %v", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
sig := make(chan os.Signal, 1)
|
||||||
|
signal.Notify(sig, syscall.SIGTERM, syscall.SIGINT)
|
||||||
|
received := <-sig
|
||||||
|
log.Printf("signal %v received", received)
|
||||||
|
svc.BeginDrain()
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if err := server.Shutdown(ctx); err != nil {
|
||||||
|
log.Printf("shutdown: %v", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
log.Printf("shutdown complete")
|
||||||
|
}
|
||||||
|
|
||||||
|
func probeReady() int {
|
||||||
|
cfg, err := config.Load()
|
||||||
|
if err != nil {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
host := cfg.Host
|
||||||
|
if host == "0.0.0.0" || host == "::" {
|
||||||
|
host = "127.0.0.1"
|
||||||
|
}
|
||||||
|
url := fmt.Sprintf("http://%s:%d/health/ready", host, cfg.Port)
|
||||||
|
client := &http.Client{Timeout: 2 * time.Second}
|
||||||
|
resp, err := client.Get(url)
|
||||||
|
if err != nil {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
_, _ = io.Copy(io.Discard, resp.Body)
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
python3 scripts/check_contract.py
|
||||||
|
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
=== RUN TestConcurrentHundredMessages
|
||||||
|
api_test.go:258: elapsed=6.151083ms unique=100
|
||||||
|
--- PASS: TestConcurrentHundredMessages (0.01s)
|
||||||
|
PASS
|
||||||
|
ok mtusi2026lab1/student-tests 0.203s
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
ERROR: Cannot connect to the Docker daemon at unix:///Users/family/.docker/run/docker.sock. Is the docker daemon running?
|
||||||
|
build_ok
|
||||||
|
Tue Dec 1 21:49:57 MSK 2026
|
||||||
|
916884c27d17 14.4MB
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
? mtusi2026lab1/cmd/server [no test files]
|
||||||
|
? mtusi2026lab1/internal/api [no test files]
|
||||||
|
? mtusi2026lab1/internal/config [no test files]
|
||||||
|
? mtusi2026lab1/internal/store [no test files]
|
||||||
|
ok mtusi2026lab1/student-tests 0.409s
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
python3 tests/smoke.py --base-url "http://localhost:8080"
|
||||||
|
PASS: lab1 public API scenario; infrastructure and grading evidence remain separate.
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
go test ./student-tests/ -v -count=1 -timeout 120s
|
||||||
|
=== RUN TestMalformedJSON
|
||||||
|
2026/12/01 21:49:53 http method=POST path=/api/v1/users status=400 request_id=e731cc40-f3a1-4f66-be68-eb6e05a7e900 ms=0
|
||||||
|
--- PASS: TestMalformedJSON (0.00s)
|
||||||
|
=== RUN TestDuplicateUsername
|
||||||
|
2026/12/01 21:49:53 http method=POST path=/api/v1/users status=409 request_id=72c7eecd-774e-4db1-b118-b2fd151d3a04 ms=0
|
||||||
|
--- PASS: TestDuplicateUsername (0.00s)
|
||||||
|
=== RUN TestEmptyMessage
|
||||||
|
2026/12/01 21:49:53 http method=POST path=/api/v1/chats/7047a146-f9f3-452c-8aa9-e7bbb67b51cd/messages status=400 request_id=a4b8b306-1e64-49e5-a97f-dd6361adcf80 ms=0
|
||||||
|
--- PASS: TestEmptyMessage (0.00s)
|
||||||
|
=== RUN TestForeignChat
|
||||||
|
2026/12/01 21:49:53 http method=GET path=/api/v1/chats/18f3643f-6e45-4097-abc2-b71ecf6a4f69 status=404 request_id=de8c3e0a-d4e8-40ad-9cd0-e023c61cd342 ms=0
|
||||||
|
--- PASS: TestForeignChat (0.00s)
|
||||||
|
=== RUN TestPaginationPages
|
||||||
|
--- PASS: TestPaginationPages (0.00s)
|
||||||
|
=== RUN TestConcurrentHundredMessages
|
||||||
|
api_test.go:258: elapsed=7.819ms unique=100
|
||||||
|
--- PASS: TestConcurrentHundredMessages (0.01s)
|
||||||
|
PASS
|
||||||
|
ok mtusi2026lab1/student-tests 0.487s
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
module mtusi2026lab1
|
||||||
|
|
||||||
|
go 1.23.0
|
||||||
|
|
||||||
|
require github.com/google/uuid v1.6.0
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"mtusi2026lab1/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
func parseJSON(r *http.Request, dst any) error {
|
||||||
|
ct := r.Header.Get("Content-Type")
|
||||||
|
if ct != "" && !strings.HasPrefix(strings.ToLower(ct), "application/json") {
|
||||||
|
return fmt.Errorf("unsupported media type")
|
||||||
|
}
|
||||||
|
dec := json.NewDecoder(r.Body)
|
||||||
|
dec.DisallowUnknownFields()
|
||||||
|
if err := dec.Decode(dst); err != nil {
|
||||||
|
return fmt.Errorf("malformed json")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func usernameOK(s string) bool {
|
||||||
|
if len(s) < 3 || len(s) > 32 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, c := range s {
|
||||||
|
if (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '_' {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func nonBlankRunes(s string) bool {
|
||||||
|
for _, r := range s {
|
||||||
|
if !unicode.IsSpace(r) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func pageParams(r *http.Request, scope string) (int, *store.Bookmark, error) {
|
||||||
|
limit := 50
|
||||||
|
if raw := r.URL.Query().Get("limit"); raw != "" {
|
||||||
|
n, err := strconv.Atoi(raw)
|
||||||
|
if err != nil || n < 1 || n > 100 {
|
||||||
|
return 0, nil, fmt.Errorf("invalid limit")
|
||||||
|
}
|
||||||
|
limit = n
|
||||||
|
}
|
||||||
|
if cur := r.URL.Query().Get("cursor"); cur != "" {
|
||||||
|
bm, err := unpackBookmark(cur)
|
||||||
|
if err != nil || bm.Scope != scope {
|
||||||
|
return 0, nil, fmt.Errorf("invalid cursor")
|
||||||
|
}
|
||||||
|
return limit, bm, nil
|
||||||
|
}
|
||||||
|
return limit, nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func packBookmark(b *store.Bookmark) string {
|
||||||
|
raw := fmt.Sprintf("%s|%s|%s", b.Scope, b.CreatedAt.UTC().Format(time.RFC3339Nano), b.ID.String())
|
||||||
|
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||||
|
}
|
||||||
|
|
||||||
|
func unpackBookmark(encoded string) (*store.Bookmark, error) {
|
||||||
|
data, err := base64.RawURLEncoding.DecodeString(encoded)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
parts := strings.SplitN(string(data), "|", 3)
|
||||||
|
if len(parts) != 3 {
|
||||||
|
return nil, fmt.Errorf("bad bookmark")
|
||||||
|
}
|
||||||
|
ts, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
id, err := uuid.Parse(parts[2])
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &store.Bookmark{Scope: parts[0], CreatedAt: ts.UTC(), ID: id}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func tsRFC3339(t time.Time) string {
|
||||||
|
return t.UTC().Format("2006-01-02T15:04:05.000Z")
|
||||||
|
}
|
||||||
|
|
||||||
|
func userWire(u *store.User) map[string]any {
|
||||||
|
return map[string]any{
|
||||||
|
"id": u.ID.String(),
|
||||||
|
"username": u.Username,
|
||||||
|
"display_name": u.DisplayName,
|
||||||
|
"created_at": tsRFC3339(u.CreatedAt),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func chatWire(c *store.Chat) map[string]any {
|
||||||
|
members := make([]string, len(c.MemberIDs))
|
||||||
|
for i, id := range c.MemberIDs {
|
||||||
|
members[i] = id.String()
|
||||||
|
}
|
||||||
|
return map[string]any{
|
||||||
|
"id": c.ID.String(),
|
||||||
|
"title": c.Title,
|
||||||
|
"member_ids": members,
|
||||||
|
"created_at": tsRFC3339(c.CreatedAt),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func messageWire(m *store.Message) map[string]any {
|
||||||
|
return map[string]any{
|
||||||
|
"id": m.ID.String(),
|
||||||
|
"chat_id": m.ChatID.String(),
|
||||||
|
"sender_id": m.SenderID.String(),
|
||||||
|
"text": m.Text,
|
||||||
|
"created_at": tsRFC3339(m.CreatedAt),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func pageWire(items []map[string]any, next *store.Bookmark) map[string]any {
|
||||||
|
var cursor any
|
||||||
|
if next != nil {
|
||||||
|
cursor = packBookmark(next)
|
||||||
|
}
|
||||||
|
return map[string]any{"items": items, "next_cursor": cursor}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) writeJSON(w http.ResponseWriter, status int, v any) {
|
||||||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
w.WriteHeader(status)
|
||||||
|
_ = json.NewEncoder(w).Encode(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) writeErr(w http.ResponseWriter, r *http.Request, status int, code, message string) {
|
||||||
|
rid := reqID(r)
|
||||||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
w.WriteHeader(status)
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||||
|
"error": map[string]any{
|
||||||
|
"code": code,
|
||||||
|
"message": message,
|
||||||
|
"request_id": rid,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func displayNameOK(name string) bool {
|
||||||
|
name = strings.TrimSpace(name)
|
||||||
|
if name == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return utf8.RuneCountInString(name) <= 100
|
||||||
|
}
|
||||||
|
|
||||||
|
func titleOK(title string) bool {
|
||||||
|
title = strings.TrimSpace(title)
|
||||||
|
if title == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return utf8.RuneCountInString(title) <= 100
|
||||||
|
}
|
||||||
@@ -0,0 +1,270 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"mtusi2026lab1/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Service — HTTP-обработчики поверх in-memory store.
|
||||||
|
type Service struct {
|
||||||
|
DB *store.MemoryDB
|
||||||
|
ready atomic.Bool
|
||||||
|
draining atomic.Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(db *store.MemoryDB) *Service {
|
||||||
|
s := &Service{DB: db}
|
||||||
|
s.ready.Store(true)
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) SetReady(ok bool) { s.ready.Store(ok) }
|
||||||
|
|
||||||
|
func (s *Service) BeginDrain() {
|
||||||
|
s.draining.Store(true)
|
||||||
|
s.ready.Store(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) Routes() http.Handler {
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("GET /health/live", s.live)
|
||||||
|
mux.HandleFunc("GET /health/ready", s.readyProbe)
|
||||||
|
mux.HandleFunc("POST /api/v1/users", s.registerUser)
|
||||||
|
mux.HandleFunc("GET /api/v1/users/me", s.requireUser(s.whoAmI))
|
||||||
|
mux.HandleFunc("POST /api/v1/chats", s.requireUser(s.openChat))
|
||||||
|
mux.HandleFunc("GET /api/v1/chats", s.requireUser(s.listChats))
|
||||||
|
mux.HandleFunc("GET /api/v1/chats/{chat_id}", s.requireUser(s.fetchChat))
|
||||||
|
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", s.requireUser(s.postMessage))
|
||||||
|
mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", s.requireUser(s.listMessages))
|
||||||
|
return requestIdentity(accessLog(mux))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) live(w http.ResponseWriter, r *http.Request) {
|
||||||
|
s.writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) readyProbe(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if !s.ready.Load() {
|
||||||
|
s.writeErr(w, r, http.StatusServiceUnavailable, "unavailable", "service is shutting down")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) registerUser(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var body struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
DisplayName string `json:"display_name"`
|
||||||
|
}
|
||||||
|
if err := parseJSON(r, &body); err != nil {
|
||||||
|
if err.Error() == "unsupported media type" {
|
||||||
|
s.writeErr(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "unsupported media type")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !usernameOK(body.Username) {
|
||||||
|
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "invalid username")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
display := strings.TrimSpace(body.DisplayName)
|
||||||
|
if !displayNameOK(display) {
|
||||||
|
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "invalid display_name")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
u, err := s.DB.CreateUser(body.Username, display)
|
||||||
|
if err == store.ErrConflict {
|
||||||
|
s.writeErr(w, r, http.StatusConflict, "conflict", "username already taken")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
s.writeErr(w, r, http.StatusInternalServerError, "internal_error", "internal error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.writeJSON(w, http.StatusCreated, userWire(u))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) whoAmI(w http.ResponseWriter, r *http.Request) {
|
||||||
|
u, err := s.DB.GetUser(actorID(r))
|
||||||
|
if err != nil {
|
||||||
|
s.writeErr(w, r, http.StatusUnauthorized, "unauthorized", "authentication required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.writeJSON(w, http.StatusOK, userWire(u))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) openChat(w http.ResponseWriter, r *http.Request) {
|
||||||
|
me := actorID(r)
|
||||||
|
var body struct {
|
||||||
|
Title string `json:"title"`
|
||||||
|
MemberIDs []string `json:"member_ids"`
|
||||||
|
}
|
||||||
|
if err := parseJSON(r, &body); err != nil {
|
||||||
|
if err.Error() == "unsupported media type" {
|
||||||
|
s.writeErr(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "unsupported media type")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !titleOK(body.Title) {
|
||||||
|
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "invalid title")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(body.MemberIDs) < 1 || len(body.MemberIDs) > 100 {
|
||||||
|
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "invalid member_ids")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
seen := make(map[uuid.UUID]struct{}, len(body.MemberIDs))
|
||||||
|
members := make([]uuid.UUID, 0, len(body.MemberIDs))
|
||||||
|
selfIncluded := false
|
||||||
|
for _, raw := range body.MemberIDs {
|
||||||
|
id, err := uuid.Parse(raw)
|
||||||
|
if err != nil {
|
||||||
|
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "invalid member id")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, dup := seen[id]; dup {
|
||||||
|
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "duplicate member id")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
seen[id] = struct{}{}
|
||||||
|
if id == me {
|
||||||
|
selfIncluded = true
|
||||||
|
}
|
||||||
|
members = append(members, id)
|
||||||
|
}
|
||||||
|
if !selfIncluded {
|
||||||
|
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "caller must be a member")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
chat, err := s.DB.CreateChat(strings.TrimSpace(body.Title), members)
|
||||||
|
if err == store.ErrNotFound {
|
||||||
|
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "unknown member")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
s.writeErr(w, r, http.StatusInternalServerError, "internal_error", "internal error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.writeJSON(w, http.StatusCreated, chatWire(chat))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) listChats(w http.ResponseWriter, r *http.Request) {
|
||||||
|
me := actorID(r)
|
||||||
|
limit, after, err := pageParams(r, "chats:"+me.String())
|
||||||
|
if err != nil {
|
||||||
|
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
items, next, err := s.DB.ListChats(me, limit, after)
|
||||||
|
if err == store.ErrInvalidCursor {
|
||||||
|
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "invalid cursor")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
s.writeErr(w, r, http.StatusInternalServerError, "internal_error", "internal error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
wire := make([]map[string]any, len(items))
|
||||||
|
for i, c := range items {
|
||||||
|
wire[i] = chatWire(c)
|
||||||
|
}
|
||||||
|
s.writeJSON(w, http.StatusOK, pageWire(wire, next))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) fetchChat(w http.ResponseWriter, r *http.Request) {
|
||||||
|
me := actorID(r)
|
||||||
|
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||||
|
if err != nil {
|
||||||
|
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
chat, err := s.DB.GetChat(chatID, me)
|
||||||
|
if err == store.ErrNotFound {
|
||||||
|
s.writeErr(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
s.writeErr(w, r, http.StatusInternalServerError, "internal_error", "internal error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.writeJSON(w, http.StatusOK, chatWire(chat))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) postMessage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
me := actorID(r)
|
||||||
|
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||||
|
if err != nil {
|
||||||
|
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var body struct {
|
||||||
|
Text string `json:"text"`
|
||||||
|
}
|
||||||
|
if err := parseJSON(r, &body); err != nil {
|
||||||
|
if err.Error() == "unsupported media type" {
|
||||||
|
s.writeErr(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "unsupported media type")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !nonBlankRunes(body.Text) {
|
||||||
|
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "invalid text")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if utf8.RuneCountInString(body.Text) > 4000 {
|
||||||
|
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "invalid text")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
msg, err := s.DB.CreateMessage(chatID, me, body.Text)
|
||||||
|
if err == store.ErrNotFound {
|
||||||
|
s.writeErr(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
s.writeErr(w, r, http.StatusInternalServerError, "internal_error", "internal error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.writeJSON(w, http.StatusCreated, messageWire(msg))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) listMessages(w http.ResponseWriter, r *http.Request) {
|
||||||
|
me := actorID(r)
|
||||||
|
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||||
|
if err != nil {
|
||||||
|
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
limit, after, err := pageParams(r, "chat:"+chatID.String())
|
||||||
|
if err != nil {
|
||||||
|
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
items, next, err := s.DB.ListMessages(chatID, me, limit, after)
|
||||||
|
if err == store.ErrNotFound {
|
||||||
|
s.writeErr(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err == store.ErrInvalidCursor {
|
||||||
|
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "invalid cursor")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
s.writeErr(w, r, http.StatusInternalServerError, "internal_error", "internal error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
wire := make([]map[string]any, len(items))
|
||||||
|
for i, m := range items {
|
||||||
|
wire[i] = messageWire(m)
|
||||||
|
}
|
||||||
|
s.writeJSON(w, http.StatusOK, pageWire(wire, next))
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ctxKey int
|
||||||
|
|
||||||
|
const (
|
||||||
|
ctxUserID ctxKey = iota
|
||||||
|
ctxReqID
|
||||||
|
)
|
||||||
|
|
||||||
|
type responseTap struct {
|
||||||
|
http.ResponseWriter
|
||||||
|
status int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *responseTap) WriteHeader(code int) {
|
||||||
|
t.status = code
|
||||||
|
t.ResponseWriter.WriteHeader(code)
|
||||||
|
}
|
||||||
|
|
||||||
|
func requestIdentity(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
rid := strings.TrimSpace(r.Header.Get("X-Request-Id"))
|
||||||
|
if rid == "" {
|
||||||
|
rid = uuid.NewString()
|
||||||
|
}
|
||||||
|
w.Header().Set("X-Request-Id", rid)
|
||||||
|
ctx := context.WithValue(r.Context(), ctxReqID, rid)
|
||||||
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func accessLog(next http.Handler) http.Handler {
|
||||||
|
quiet := strings.EqualFold(os.Getenv("APP_ACCESS_LOG"), "0") ||
|
||||||
|
strings.EqualFold(os.Getenv("APP_ACCESS_LOG"), "false")
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
start := time.Now()
|
||||||
|
tap := &responseTap{ResponseWriter: w, status: http.StatusOK}
|
||||||
|
next.ServeHTTP(tap, r)
|
||||||
|
if quiet && strings.HasPrefix(r.URL.Path, "/api/") && tap.status < 400 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(r.URL.Path, "/health/") && tap.status == 200 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rid := tap.Header().Get("X-Request-Id")
|
||||||
|
if rid == "" {
|
||||||
|
rid, _ = r.Context().Value(ctxReqID).(string)
|
||||||
|
}
|
||||||
|
log.Printf("http method=%s path=%s status=%d request_id=%s ms=%d",
|
||||||
|
r.Method, r.URL.Path, tap.status, rid, time.Since(start).Milliseconds())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) requireUser(next http.HandlerFunc) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
raw := strings.TrimSpace(r.Header.Get("X-User-Id"))
|
||||||
|
if raw == "" {
|
||||||
|
s.writeErr(w, r, http.StatusUnauthorized, "unauthorized", "authentication required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id, err := uuid.Parse(raw)
|
||||||
|
if err != nil || !s.DB.UserExists(id) {
|
||||||
|
s.writeErr(w, r, http.StatusUnauthorized, "unauthorized", "authentication required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next(w, r.WithContext(context.WithValue(r.Context(), ctxUserID, id)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func actorID(r *http.Request) uuid.UUID {
|
||||||
|
v, _ := r.Context().Value(ctxUserID).(uuid.UUID)
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
|
||||||
|
func reqID(r *http.Request) string {
|
||||||
|
if v, ok := r.Context().Value(ctxReqID).(string); ok && v != "" {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
return uuid.NewString()
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
Host string
|
||||||
|
Port int
|
||||||
|
Env string
|
||||||
|
}
|
||||||
|
|
||||||
|
func Load() (Config, error) {
|
||||||
|
cfg := Config{
|
||||||
|
Host: getenv("APP_HOST", "0.0.0.0"),
|
||||||
|
Env: getenv("APP_ENV", "lab"),
|
||||||
|
}
|
||||||
|
portStr := getenv("APP_PORT", "8080")
|
||||||
|
port, err := strconv.Atoi(portStr)
|
||||||
|
if err != nil || port < 1 || port > 65535 {
|
||||||
|
return cfg, fmt.Errorf("invalid APP_PORT: %q", portStr)
|
||||||
|
}
|
||||||
|
cfg.Port = port
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Config) Addr() string {
|
||||||
|
return fmt.Sprintf("%s:%d", c.Host, c.Port)
|
||||||
|
}
|
||||||
|
|
||||||
|
func getenv(key, fallback string) string {
|
||||||
|
if v := os.Getenv(key); v != "" {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"sort"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrNotFound = errors.New("not found")
|
||||||
|
ErrConflict = errors.New("conflict")
|
||||||
|
ErrInvalidCursor = errors.New("invalid cursor")
|
||||||
|
)
|
||||||
|
|
||||||
|
type chatRoom struct {
|
||||||
|
meta Chat
|
||||||
|
messages []*Message
|
||||||
|
}
|
||||||
|
|
||||||
|
// MemoryDB — потокобезопасное хранилище в RAM одного процесса.
|
||||||
|
type MemoryDB struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
users map[uuid.UUID]*User
|
||||||
|
byName map[string]uuid.UUID
|
||||||
|
rooms map[uuid.UUID]*chatRoom
|
||||||
|
}
|
||||||
|
|
||||||
|
func New() *MemoryDB {
|
||||||
|
return &MemoryDB{
|
||||||
|
users: make(map[uuid.UUID]*User),
|
||||||
|
byName: make(map[string]uuid.UUID),
|
||||||
|
rooms: make(map[uuid.UUID]*chatRoom),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *MemoryDB) CreateUser(username, displayName string) (*User, error) {
|
||||||
|
db.mu.Lock()
|
||||||
|
defer db.mu.Unlock()
|
||||||
|
if _, taken := db.byName[username]; taken {
|
||||||
|
return nil, ErrConflict
|
||||||
|
}
|
||||||
|
u := &User{
|
||||||
|
ID: uuid.New(),
|
||||||
|
Username: username,
|
||||||
|
DisplayName: displayName,
|
||||||
|
CreatedAt: time.Now().UTC().Truncate(time.Millisecond),
|
||||||
|
}
|
||||||
|
db.users[u.ID] = u
|
||||||
|
db.byName[username] = u.ID
|
||||||
|
return copyUser(u), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *MemoryDB) GetUser(id uuid.UUID) (*User, error) {
|
||||||
|
db.mu.RLock()
|
||||||
|
defer db.mu.RUnlock()
|
||||||
|
u, ok := db.users[id]
|
||||||
|
if !ok {
|
||||||
|
return nil, ErrNotFound
|
||||||
|
}
|
||||||
|
return copyUser(u), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *MemoryDB) UserExists(id uuid.UUID) bool {
|
||||||
|
db.mu.RLock()
|
||||||
|
defer db.mu.RUnlock()
|
||||||
|
_, ok := db.users[id]
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *MemoryDB) CreateChat(title string, members []uuid.UUID) (*Chat, error) {
|
||||||
|
db.mu.Lock()
|
||||||
|
defer db.mu.Unlock()
|
||||||
|
for _, id := range members {
|
||||||
|
if _, ok := db.users[id]; !ok {
|
||||||
|
return nil, ErrNotFound
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c := Chat{
|
||||||
|
ID: uuid.New(),
|
||||||
|
Title: title,
|
||||||
|
MemberIDs: append([]uuid.UUID(nil), members...),
|
||||||
|
CreatedAt: time.Now().UTC().Truncate(time.Millisecond),
|
||||||
|
}
|
||||||
|
db.rooms[c.ID] = &chatRoom{meta: c}
|
||||||
|
return copyChat(&c), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *MemoryDB) GetChat(chatID, viewer uuid.UUID) (*Chat, error) {
|
||||||
|
db.mu.RLock()
|
||||||
|
defer db.mu.RUnlock()
|
||||||
|
room, ok := db.rooms[chatID]
|
||||||
|
if !ok || !memberOf(&room.meta, viewer) {
|
||||||
|
return nil, ErrNotFound
|
||||||
|
}
|
||||||
|
return copyChat(&room.meta), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *MemoryDB) ListChats(viewer uuid.UUID, limit int, after *Bookmark) ([]*Chat, *Bookmark, error) {
|
||||||
|
if after != nil && after.Scope != chatListScope(viewer) {
|
||||||
|
return nil, nil, ErrInvalidCursor
|
||||||
|
}
|
||||||
|
db.mu.RLock()
|
||||||
|
defer db.mu.RUnlock()
|
||||||
|
var mine []*Chat
|
||||||
|
for _, room := range db.rooms {
|
||||||
|
if memberOf(&room.meta, viewer) {
|
||||||
|
mine = append(mine, copyChat(&room.meta))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Slice(mine, func(i, j int) bool {
|
||||||
|
if !mine[i].CreatedAt.Equal(mine[j].CreatedAt) {
|
||||||
|
return mine[i].CreatedAt.Before(mine[j].CreatedAt)
|
||||||
|
}
|
||||||
|
return uuidOrder(mine[i].ID, mine[j].ID)
|
||||||
|
})
|
||||||
|
return paginateChats(mine, limit, after, viewer)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *MemoryDB) CreateMessage(chatID, sender uuid.UUID, text string) (*Message, error) {
|
||||||
|
db.mu.Lock()
|
||||||
|
defer db.mu.Unlock()
|
||||||
|
room, ok := db.rooms[chatID]
|
||||||
|
if !ok || !memberOf(&room.meta, sender) {
|
||||||
|
return nil, ErrNotFound
|
||||||
|
}
|
||||||
|
m := &Message{
|
||||||
|
ID: uuid.New(),
|
||||||
|
ChatID: chatID,
|
||||||
|
SenderID: sender,
|
||||||
|
Text: text,
|
||||||
|
CreatedAt: time.Now().UTC().Truncate(time.Millisecond),
|
||||||
|
}
|
||||||
|
room.messages = append(room.messages, m)
|
||||||
|
return copyMessage(m), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *MemoryDB) ListMessages(chatID, viewer uuid.UUID, limit int, after *Bookmark) ([]*Message, *Bookmark, error) {
|
||||||
|
if after != nil && after.Scope != messageListScope(chatID) {
|
||||||
|
return nil, nil, ErrInvalidCursor
|
||||||
|
}
|
||||||
|
db.mu.RLock()
|
||||||
|
defer db.mu.RUnlock()
|
||||||
|
room, ok := db.rooms[chatID]
|
||||||
|
if !ok || !memberOf(&room.meta, viewer) {
|
||||||
|
return nil, nil, ErrNotFound
|
||||||
|
}
|
||||||
|
items := make([]*Message, len(room.messages))
|
||||||
|
for i, m := range room.messages {
|
||||||
|
items[i] = copyMessage(m)
|
||||||
|
}
|
||||||
|
sort.SliceStable(items, func(i, j int) bool {
|
||||||
|
if !items[i].CreatedAt.Equal(items[j].CreatedAt) {
|
||||||
|
return items[i].CreatedAt.Before(items[j].CreatedAt)
|
||||||
|
}
|
||||||
|
return uuidOrder(items[i].ID, items[j].ID)
|
||||||
|
})
|
||||||
|
return paginateMessages(items, limit, after, chatID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func paginateChats(all []*Chat, limit int, after *Bookmark, viewer uuid.UUID) ([]*Chat, *Bookmark, error) {
|
||||||
|
start := findStart(all, after, func(c *Chat) (time.Time, uuid.UUID) {
|
||||||
|
return c.CreatedAt, c.ID
|
||||||
|
})
|
||||||
|
end := start + limit
|
||||||
|
if end > len(all) {
|
||||||
|
end = len(all)
|
||||||
|
}
|
||||||
|
page := all[start:end]
|
||||||
|
var next *Bookmark
|
||||||
|
if end < len(all) && len(page) > 0 {
|
||||||
|
last := page[len(page)-1]
|
||||||
|
next = &Bookmark{Scope: chatListScope(viewer), CreatedAt: last.CreatedAt, ID: last.ID}
|
||||||
|
}
|
||||||
|
out := make([]*Chat, len(page))
|
||||||
|
for i, c := range page {
|
||||||
|
out[i] = c
|
||||||
|
}
|
||||||
|
return out, next, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func paginateMessages(all []*Message, limit int, after *Bookmark, chatID uuid.UUID) ([]*Message, *Bookmark, error) {
|
||||||
|
start := findStart(all, after, func(m *Message) (time.Time, uuid.UUID) {
|
||||||
|
return m.CreatedAt, m.ID
|
||||||
|
})
|
||||||
|
end := start + limit
|
||||||
|
if end > len(all) {
|
||||||
|
end = len(all)
|
||||||
|
}
|
||||||
|
page := all[start:end]
|
||||||
|
var next *Bookmark
|
||||||
|
if end < len(all) && len(page) > 0 {
|
||||||
|
last := page[len(page)-1]
|
||||||
|
next = &Bookmark{Scope: messageListScope(chatID), CreatedAt: last.CreatedAt, ID: last.ID}
|
||||||
|
}
|
||||||
|
out := make([]*Message, len(page))
|
||||||
|
for i, m := range page {
|
||||||
|
out[i] = m
|
||||||
|
}
|
||||||
|
return out, next, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func findStart[T any](rows []T, after *Bookmark, pick func(T) (time.Time, uuid.UUID)) int {
|
||||||
|
if after == nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
for i, row := range rows {
|
||||||
|
ts, id := pick(row)
|
||||||
|
if ts.After(after.CreatedAt) || (ts.Equal(after.CreatedAt) && uuidOrder(after.ID, id)) {
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return len(rows)
|
||||||
|
}
|
||||||
|
|
||||||
|
func chatListScope(user uuid.UUID) string { return "chats:" + user.String() }
|
||||||
|
func messageListScope(chat uuid.UUID) string { return "chat:" + chat.String() }
|
||||||
|
|
||||||
|
func memberOf(c *Chat, user uuid.UUID) bool {
|
||||||
|
for _, id := range c.MemberIDs {
|
||||||
|
if id == user {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func uuidOrder(a, b uuid.UUID) bool {
|
||||||
|
for i := 0; i < 16; i++ {
|
||||||
|
if a[i] != b[i] {
|
||||||
|
return a[i] < b[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyUser(u *User) *User {
|
||||||
|
cp := *u
|
||||||
|
return &cp
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyChat(c *Chat) *Chat {
|
||||||
|
cp := *c
|
||||||
|
cp.MemberIDs = append([]uuid.UUID(nil), c.MemberIDs...)
|
||||||
|
return &cp
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyMessage(m *Message) *Message {
|
||||||
|
cp := *m
|
||||||
|
return &cp
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
type User struct {
|
||||||
|
ID uuid.UUID
|
||||||
|
Username string
|
||||||
|
DisplayName string
|
||||||
|
CreatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
type Chat struct {
|
||||||
|
ID uuid.UUID
|
||||||
|
Title string
|
||||||
|
MemberIDs []uuid.UUID
|
||||||
|
CreatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
type Message struct {
|
||||||
|
ID uuid.UUID
|
||||||
|
ChatID uuid.UUID
|
||||||
|
SenderID uuid.UUID
|
||||||
|
Text string
|
||||||
|
CreatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bookmark — позиция keyset-пагинации (created_at, id) в рамках scope.
|
||||||
|
type Bookmark struct {
|
||||||
|
Scope string
|
||||||
|
CreatedAt time.Time
|
||||||
|
ID uuid.UUID
|
||||||
|
}
|
||||||
Executable
+6
@@ -0,0 +1,6 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Параллельная отправка 100 сообщений (10×10) через go test; BASE_URL не требуется.
|
||||||
|
set -euo pipefail
|
||||||
|
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||||
|
cd "$ROOT"
|
||||||
|
exec go test ./student-tests/ -run TestConcurrentHundredMessages -v -count=1 -timeout 120s
|
||||||
@@ -0,0 +1,262 @@
|
|||||||
|
package studenttests
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"mtusi2026lab1/internal/api"
|
||||||
|
"mtusi2026lab1/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
func testAPI(t *testing.T) *httptest.Server {
|
||||||
|
t.Helper()
|
||||||
|
_ = os.Setenv("APP_ACCESS_LOG", "0")
|
||||||
|
return httptest.NewServer(api.New(store.New()).Routes())
|
||||||
|
}
|
||||||
|
|
||||||
|
func post(t *testing.T, c *http.Client, url string, body any, hdr map[string]string) (int, map[string]any, http.Header) {
|
||||||
|
t.Helper()
|
||||||
|
var raw []byte
|
||||||
|
if body != nil {
|
||||||
|
var err error
|
||||||
|
raw, err = json.Marshal(body)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(raw))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
for k, v := range hdr {
|
||||||
|
req.Header.Set(k, v)
|
||||||
|
}
|
||||||
|
resp, err := c.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
data, _ := io.ReadAll(resp.Body)
|
||||||
|
var out map[string]any
|
||||||
|
_ = json.Unmarshal(data, &out)
|
||||||
|
return resp.StatusCode, out, resp.Header
|
||||||
|
}
|
||||||
|
|
||||||
|
func get(t *testing.T, c *http.Client, url string, hdr map[string]string) (int, map[string]any, http.Header) {
|
||||||
|
t.Helper()
|
||||||
|
req, err := http.NewRequest(http.MethodGet, url, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for k, v := range hdr {
|
||||||
|
req.Header.Set(k, v)
|
||||||
|
}
|
||||||
|
resp, err := c.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
data, _ := io.ReadAll(resp.Body)
|
||||||
|
var out map[string]any
|
||||||
|
_ = json.Unmarshal(data, &out)
|
||||||
|
return resp.StatusCode, out, resp.Header
|
||||||
|
}
|
||||||
|
|
||||||
|
func register(t *testing.T, c *http.Client, base, username string) map[string]any {
|
||||||
|
t.Helper()
|
||||||
|
st, body, _ := post(t, c, base+"/api/v1/users", map[string]any{
|
||||||
|
"username": username, "display_name": "User " + username,
|
||||||
|
}, nil)
|
||||||
|
if st != 201 {
|
||||||
|
t.Fatalf("register %q: %d %#v", username, st, body)
|
||||||
|
}
|
||||||
|
return body
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMalformedJSON(t *testing.T) {
|
||||||
|
srv := testAPI(t)
|
||||||
|
defer srv.Close()
|
||||||
|
req, _ := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/users", strings.NewReader("{broken"))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
resp, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
if resp.StatusCode != 400 {
|
||||||
|
t.Fatalf("want 400, got %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
if resp.Header.Get("X-Request-Id") == "" {
|
||||||
|
t.Fatal("missing X-Request-Id")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDuplicateUsername(t *testing.T) {
|
||||||
|
srv := testAPI(t)
|
||||||
|
defer srv.Close()
|
||||||
|
c := srv.Client()
|
||||||
|
register(t, c, srv.URL, "dup_u01")
|
||||||
|
st, _, _ := post(t, c, srv.URL+"/api/v1/users", map[string]any{
|
||||||
|
"username": "dup_u01", "display_name": "again",
|
||||||
|
}, nil)
|
||||||
|
if st != 409 {
|
||||||
|
t.Fatalf("want 409, got %d", st)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEmptyMessage(t *testing.T) {
|
||||||
|
srv := testAPI(t)
|
||||||
|
defer srv.Close()
|
||||||
|
c := srv.Client()
|
||||||
|
u := register(t, c, srv.URL, "empty_u")
|
||||||
|
uid := u["id"].(string)
|
||||||
|
st, chat, _ := post(t, c, srv.URL+"/api/v1/chats", map[string]any{
|
||||||
|
"title": "solo", "member_ids": []string{uid},
|
||||||
|
}, map[string]string{"X-User-Id": uid})
|
||||||
|
if st != 201 {
|
||||||
|
t.Fatalf("chat: %d", st)
|
||||||
|
}
|
||||||
|
chatID := chat["id"].(string)
|
||||||
|
st, _, _ = post(t, c, srv.URL+"/api/v1/chats/"+chatID+"/messages",
|
||||||
|
map[string]any{"text": " "}, map[string]string{"X-User-Id": uid})
|
||||||
|
if st != 400 {
|
||||||
|
t.Fatalf("want 400, got %d", st)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestForeignChat(t *testing.T) {
|
||||||
|
srv := testAPI(t)
|
||||||
|
defer srv.Close()
|
||||||
|
c := srv.Client()
|
||||||
|
a := register(t, c, srv.URL, "alice_f")
|
||||||
|
e := register(t, c, srv.URL, "eve_f")
|
||||||
|
aid := a["id"].(string)
|
||||||
|
eid := e["id"].(string)
|
||||||
|
st, chat, _ := post(t, c, srv.URL+"/api/v1/chats", map[string]any{
|
||||||
|
"title": "secret", "member_ids": []string{aid},
|
||||||
|
}, map[string]string{"X-User-Id": aid})
|
||||||
|
if st != 201 {
|
||||||
|
t.Fatal(st)
|
||||||
|
}
|
||||||
|
st, _, _ = get(t, c, srv.URL+"/api/v1/chats/"+chat["id"].(string), map[string]string{"X-User-Id": eid})
|
||||||
|
if st != 404 {
|
||||||
|
t.Fatalf("want 404, got %d", st)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPaginationPages(t *testing.T) {
|
||||||
|
srv := testAPI(t)
|
||||||
|
defer srv.Close()
|
||||||
|
c := srv.Client()
|
||||||
|
u := register(t, c, srv.URL, "page_u")
|
||||||
|
uid := u["id"].(string)
|
||||||
|
st, chat, _ := post(t, c, srv.URL+"/api/v1/chats", map[string]any{
|
||||||
|
"title": "p", "member_ids": []string{uid},
|
||||||
|
}, map[string]string{"X-User-Id": uid})
|
||||||
|
if st != 201 {
|
||||||
|
t.Fatal(st)
|
||||||
|
}
|
||||||
|
chatID := chat["id"].(string)
|
||||||
|
for i := 0; i < 3; i++ {
|
||||||
|
st, _, _ = post(t, c, srv.URL+"/api/v1/chats/"+chatID+"/messages",
|
||||||
|
map[string]any{"text": fmt.Sprintf("msg-%d", i)}, map[string]string{"X-User-Id": uid})
|
||||||
|
if st != 201 {
|
||||||
|
t.Fatalf("msg %d: %d", i, st)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
st, page1, _ := get(t, c, srv.URL+"/api/v1/chats/"+chatID+"/messages?limit=2", map[string]string{"X-User-Id": uid})
|
||||||
|
if st != 200 {
|
||||||
|
t.Fatal(st)
|
||||||
|
}
|
||||||
|
items1 := page1["items"].([]any)
|
||||||
|
if len(items1) != 2 || page1["next_cursor"] == nil {
|
||||||
|
t.Fatalf("page1: %#v", page1)
|
||||||
|
}
|
||||||
|
cursor := page1["next_cursor"].(string)
|
||||||
|
st, page2, _ := get(t, c, srv.URL+"/api/v1/chats/"+chatID+"/messages?limit=2&cursor="+cursor,
|
||||||
|
map[string]string{"X-User-Id": uid})
|
||||||
|
if st != 200 {
|
||||||
|
t.Fatal(st)
|
||||||
|
}
|
||||||
|
items2 := page2["items"].([]any)
|
||||||
|
if len(items2) != 1 || page2["next_cursor"] != nil {
|
||||||
|
t.Fatalf("page2: %#v", page2)
|
||||||
|
}
|
||||||
|
seen := map[string]struct{}{}
|
||||||
|
for _, page := range [][]any{items1, items2} {
|
||||||
|
for _, it := range page {
|
||||||
|
id := it.(map[string]any)["id"].(string)
|
||||||
|
if _, dup := seen[id]; dup {
|
||||||
|
t.Fatalf("duplicate %s", id)
|
||||||
|
}
|
||||||
|
seen[id] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(seen) != 3 {
|
||||||
|
t.Fatalf("want 3 ids, got %d", len(seen))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConcurrentHundredMessages(t *testing.T) {
|
||||||
|
srv := testAPI(t)
|
||||||
|
defer srv.Close()
|
||||||
|
c := srv.Client()
|
||||||
|
users := make([]map[string]any, 10)
|
||||||
|
ids := make([]string, 10)
|
||||||
|
for i := 0; i < 10; i++ {
|
||||||
|
users[i] = register(t, c, srv.URL, fmt.Sprintf("race_%02d", i))
|
||||||
|
ids[i] = users[i]["id"].(string)
|
||||||
|
}
|
||||||
|
st, chat, _ := post(t, c, srv.URL+"/api/v1/chats", map[string]any{
|
||||||
|
"title": "race", "member_ids": ids,
|
||||||
|
}, map[string]string{"X-User-Id": ids[0]})
|
||||||
|
if st != 201 {
|
||||||
|
t.Fatal(st)
|
||||||
|
}
|
||||||
|
chatID := chat["id"].(string)
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
msgIDs := make(chan string, 100)
|
||||||
|
errs := make(chan error, 100)
|
||||||
|
start := time.Now()
|
||||||
|
for i := 0; i < 10; i++ {
|
||||||
|
uid := ids[i]
|
||||||
|
for j := 0; j < 10; j++ {
|
||||||
|
wg.Add(1)
|
||||||
|
go func(user string, n int) {
|
||||||
|
defer wg.Done()
|
||||||
|
st, body, _ := post(t, c, srv.URL+"/api/v1/chats/"+chatID+"/messages",
|
||||||
|
map[string]any{"text": fmt.Sprintf("c-%s-%d", user[:8], n)},
|
||||||
|
map[string]string{"X-User-Id": user})
|
||||||
|
if st != 201 {
|
||||||
|
errs <- fmt.Errorf("status=%d", st)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
msgIDs <- body["id"].(string)
|
||||||
|
}(uid, j)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
close(msgIDs)
|
||||||
|
close(errs)
|
||||||
|
for err := range errs {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
uniq := map[string]struct{}{}
|
||||||
|
for id := range msgIDs {
|
||||||
|
uniq[id] = struct{}{}
|
||||||
|
}
|
||||||
|
t.Logf("elapsed=%s unique=%d", time.Since(start), len(uniq))
|
||||||
|
if len(uniq) != 100 {
|
||||||
|
t.Fatalf("want 100 unique messages, got %d", len(uniq))
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user