forked from mtusi2026/mtusi2026lab3
work 3
This commit is contained in:
@@ -0,0 +1,601 @@
|
||||
// loadgen — closed-loop генератор нагрузки для экспериментов с репликами.
|
||||
//
|
||||
// Смесь чтения истории и записи сообщений. Неподтверждённая запись повторяется с тем же
|
||||
// Idempotency-Key, как у настоящего клиента. После прогона вся история сверяется с
|
||||
// подтверждёнными сообщениями. Closed-loop занижает задержки при перегрузке (coordinated
|
||||
// omission), поэтому результат показывает пропускную способность, а не задержку при заданной
|
||||
// интенсивности. Токены и пароли не печатает.
|
||||
//
|
||||
// Запуск из корня проекта при поднятом стенде:
|
||||
//
|
||||
// docker compose --env-file .env --profile bench run --rm -T loadgen -duration 20s -concurrency 16
|
||||
//
|
||||
// Этапы: подготовка данных, прогрев, замер, сверка истории, запись результата.
|
||||
// Код выхода ненулевой, если сверка нашла потери или дубли либо не смогла прочитать историю.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
mathrand "math/rand/v2"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"slices"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// options — параметры запуска из флагов командной строки.
|
||||
type options struct {
|
||||
baseURL string
|
||||
duration time.Duration
|
||||
warmup time.Duration
|
||||
concurrency int
|
||||
writeShare float64
|
||||
chats int
|
||||
seed int
|
||||
timeout time.Duration
|
||||
label string
|
||||
out string
|
||||
}
|
||||
|
||||
// actor — один клиент API: токен его сессии и его чат. Токен хранится только в памяти.
|
||||
type actor struct {
|
||||
token string
|
||||
chatID string
|
||||
}
|
||||
|
||||
// confirmed — запись, на которую сервер ответил 201. После замера она обязана быть в истории:
|
||||
// chat — индекс чата, id — ID сообщения, text — уникальный текст для поиска дублей.
|
||||
type confirmed struct {
|
||||
chat int
|
||||
id string
|
||||
text string
|
||||
}
|
||||
|
||||
// workerStats заполняется одной горутиной, поэтому без блокировок.
|
||||
// Поля: задержки успешных чтений и записей; ошибки по видам (код ответа или net);
|
||||
// записи, подтверждённые после повтора; запросы по репликам; успехи и ошибки по секундам;
|
||||
// время каждой ошибки; подтверждённые записи.
|
||||
type workerStats struct {
|
||||
reads, writes []time.Duration
|
||||
errors map[string]int
|
||||
retried int
|
||||
instances map[string]int
|
||||
secOK, secErr map[int]int
|
||||
errTimes []time.Duration
|
||||
confirmed []confirmed
|
||||
}
|
||||
|
||||
// main разбирает флаги и запускает прогон. Значения по умолчанию рассчитаны на запуск в сети Docker.
|
||||
func main() {
|
||||
var o options
|
||||
flag.StringVar(&o.baseURL, "base-url", "http://lb:8080", "адрес балансировщика")
|
||||
flag.DurationVar(&o.duration, "duration", 30*time.Second, "длительность замера")
|
||||
flag.DurationVar(&o.warmup, "warmup", 5*time.Second, "прогрев, не входит в замер")
|
||||
flag.IntVar(&o.concurrency, "concurrency", 16, "число клиентов closed-loop")
|
||||
flag.Float64Var(&o.writeShare, "write-share", 0.2, "доля записей")
|
||||
flag.IntVar(&o.chats, "chats", 8, "число пар пользователь+чат")
|
||||
flag.IntVar(&o.seed, "seed", 100, "начальных сообщений на чат")
|
||||
flag.DurationVar(&o.timeout, "timeout", 5*time.Second, "таймаут запроса")
|
||||
flag.StringVar(&o.label, "label", "", "метка прогона")
|
||||
flag.StringVar(&o.out, "out", "", "файл для JSON-результата")
|
||||
flag.Parse()
|
||||
|
||||
if err := run(o); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "loadgen:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// run выполняет прогон целиком и возвращает ошибку, если проверка истории не пройдена.
|
||||
func run(o options) error {
|
||||
// Один общий клиент на всех. Запас простаивающих соединений нужен, чтобы клиенты повторно
|
||||
// использовали их: иначе замер включал бы постоянную установку новых соединений.
|
||||
client := &http.Client{
|
||||
Timeout: o.timeout,
|
||||
Transport: &http.Transport{
|
||||
MaxIdleConns: o.concurrency * 2,
|
||||
MaxIdleConnsPerHost: o.concurrency * 2,
|
||||
IdleConnTimeout: 30 * time.Second,
|
||||
},
|
||||
}
|
||||
// Подготовка до начала отсчёта: в замер не входит.
|
||||
actors, err := setup(client, o)
|
||||
if err != nil {
|
||||
return fmt.Errorf("setup: %w", err)
|
||||
}
|
||||
|
||||
// Границы замера. Клиенты работают и в прогреве, но запросы до measureFrom не учитываются.
|
||||
start := time.Now()
|
||||
measureFrom := start.Add(o.warmup)
|
||||
end := measureFrom.Add(o.duration)
|
||||
// Скрипты отказов ждут эту строку, чтобы привязать действия ко времени замера.
|
||||
go func() {
|
||||
time.Sleep(o.warmup)
|
||||
fmt.Printf("measure_start unix=%d\n", time.Now().Unix())
|
||||
}()
|
||||
|
||||
// У каждого клиента своя статистика и своя горутина. Общие данные появляются только после wg.Wait.
|
||||
stats := make([]*workerStats, o.concurrency)
|
||||
var wg sync.WaitGroup
|
||||
for i := range o.concurrency {
|
||||
stats[i] = newWorkerStats()
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
work(client, o, i, actors, measureFrom, end, stats[i])
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// Сверка идёт уже после нагрузки, поэтому на RPS она не влияет.
|
||||
res := summarize(o, stats)
|
||||
res.Verify = verify(client, o, actors, stats)
|
||||
if err := writeResult(o, res); err != nil {
|
||||
return err
|
||||
}
|
||||
// Результат записан и при неудаче: так можно разобрать, что именно пошло не так.
|
||||
if res.Verify.Error != "" || res.Verify.Lost > 0 || res.Verify.DuplicateIDs > 0 || res.Verify.DuplicateTexts > 0 {
|
||||
return fmt.Errorf("проверка истории не пройдена: %+v", res.Verify)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// newWorkerStats создаёт пустую статистику клиента.
|
||||
func newWorkerStats() *workerStats {
|
||||
return &workerStats{
|
||||
errors: map[string]int{},
|
||||
instances: map[string]int{},
|
||||
secOK: map[int]int{},
|
||||
secErr: map[int]int{},
|
||||
}
|
||||
}
|
||||
|
||||
// work — цикл одного клиента до конца замера (closed-loop): следующий запрос уходит только
|
||||
// после ответа на предыдущий. Клиенты равномерно распределены по чатам.
|
||||
func work(client *http.Client, o options, worker int, actors []actor, from, end time.Time, st *workerStats) {
|
||||
chat := worker % len(actors)
|
||||
a := actors[chat]
|
||||
path := "/api/v1/chats/" + a.chatID + "/messages"
|
||||
// Свой генератор у каждого клиента: общий потребовал бы блокировки.
|
||||
rng := mathrand.New(mathrand.NewPCG(uint64(worker), uint64(time.Now().UnixNano())))
|
||||
|
||||
// observe учитывает результат одного запроса и возвращает true, если он успешен. В замер
|
||||
// входит только запрос, начатый после прогрева и завершившийся до конца замера. lat — куда
|
||||
// записать задержку успешного запроса, want — ожидаемый код ответа.
|
||||
observe := func(began time.Time, status int, instance string, err error, want int, lat *[]time.Duration) bool {
|
||||
now := time.Now()
|
||||
measured := !began.Before(from) && now.Before(end)
|
||||
// Номер секунды замера: из него строится посекундная шкала.
|
||||
sec := int(now.Sub(from) / time.Second)
|
||||
if err == nil && status == want {
|
||||
if measured {
|
||||
*lat = append(*lat, now.Sub(began))
|
||||
st.instances[instance]++
|
||||
st.secOK[sec]++
|
||||
}
|
||||
return true
|
||||
}
|
||||
if measured {
|
||||
// net — ответа не было вообще (обрыв, таймаут), иначе вид ошибки — код ответа.
|
||||
kind := "net"
|
||||
if err == nil {
|
||||
kind = strconv.Itoa(status)
|
||||
}
|
||||
st.errors[kind]++
|
||||
st.secErr[sec]++
|
||||
st.errTimes = append(st.errTimes, now.Sub(from))
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
for seq := 0; time.Now().Before(end); seq++ {
|
||||
// Чтение первой страницы истории. После ошибки короткая пауза, чтобы не долбить сервер в цикле.
|
||||
if rng.Float64() >= o.writeShare {
|
||||
began := time.Now()
|
||||
status, inst, _, err := do(client, o, http.MethodGet, path+"?limit=50", a.token, "", nil)
|
||||
if !observe(began, status, inst, err, http.StatusOK, &st.reads) {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
continue
|
||||
}
|
||||
// Запись: новый ключ идемпотентности и уникальный текст, по которому видны дубли.
|
||||
key := randomHex(16)
|
||||
text := fmt.Sprintf("w-%d-%d-%s", worker, seq, key[:8])
|
||||
// Неопределённый результат повторяется с исходным ключом и телом.
|
||||
// Цикл повторов. При обрыве клиент не знает, записал ли сервер сообщение, поэтому повторяет
|
||||
// с теми же ключом и текстом: сервер должен вернуть то же сообщение, а не создать новое.
|
||||
for attempt := 0; time.Now().Before(end); attempt++ {
|
||||
began := time.Now()
|
||||
status, inst, body, err := do(client, o, http.MethodPost, path, a.token, key, map[string]string{"text": text})
|
||||
if observe(began, status, inst, err, http.StatusCreated, &st.writes) {
|
||||
var m struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if json.Unmarshal(body, &m) == nil {
|
||||
st.confirmed = append(st.confirmed, confirmed{chat: chat, id: m.ID, text: text})
|
||||
}
|
||||
// Запись подтвердилась только с повтора: это видно в результате.
|
||||
if attempt > 0 {
|
||||
st.retried++
|
||||
}
|
||||
break
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// do выполняет один HTTP-запрос с таймаутом и возвращает код, реплику из X-Instance-Id, тело
|
||||
// и ошибку сети. payload кодируется в JSON; пустые token и key не добавляют заголовки.
|
||||
func do(client *http.Client, o options, method, path, token, key string, payload any) (int, string, []byte, error) {
|
||||
var body io.Reader
|
||||
if payload != nil {
|
||||
b, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return 0, "", nil, err
|
||||
}
|
||||
body = bytes.NewReader(b)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), o.timeout)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, method, o.baseURL+path, body)
|
||||
if err != nil {
|
||||
return 0, "", nil, err
|
||||
}
|
||||
if payload != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
if key != "" {
|
||||
req.Header.Set("Idempotency-Key", key)
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return 0, "", nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
// Тело читается полностью: иначе соединение нельзя использовать повторно.
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return 0, "", nil, err
|
||||
}
|
||||
return resp.StatusCode, resp.Header.Get("X-Instance-Id"), data, nil
|
||||
}
|
||||
|
||||
// setup параллельно создаёт пользователей и чаты для всех участников нагрузки.
|
||||
func setup(client *http.Client, o options) ([]actor, error) {
|
||||
actors := make([]actor, o.chats)
|
||||
errs := make([]error, o.chats)
|
||||
var wg sync.WaitGroup
|
||||
for i := range o.chats {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
actors[i], errs[i] = setupActor(client, o)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
for _, err := range errs {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return actors, nil
|
||||
}
|
||||
|
||||
// setupActor создаёт одного участника: пользователь, вход, чат и начальные сообщения.
|
||||
// Имена и пароли случайные и нигде не печатаются.
|
||||
func setupActor(client *http.Client, o options) (actor, error) {
|
||||
username, password := "lg_"+randomHex(8), "T3st-"+randomHex(16)
|
||||
status, _, body, err := do(client, o, http.MethodPost, "/api/v1/users", "", "",
|
||||
map[string]string{"username": username, "display_name": "Load", "password": password})
|
||||
if err != nil || status != http.StatusCreated {
|
||||
return actor{}, fmt.Errorf("create user: status %d: %v", status, err)
|
||||
}
|
||||
var user struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &user); err != nil {
|
||||
return actor{}, err
|
||||
}
|
||||
|
||||
// Вход выполняется через Basic: пользователь получает токен сессии.
|
||||
req, err := http.NewRequest(http.MethodPost, o.baseURL+"/api/v1/auth/sessions", nil)
|
||||
if err != nil {
|
||||
return actor{}, err
|
||||
}
|
||||
req.SetBasicAuth(username, password)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return actor{}, fmt.Errorf("login: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var session struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
return actor{}, fmt.Errorf("login: status %d", resp.StatusCode)
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&session); err != nil {
|
||||
return actor{}, err
|
||||
}
|
||||
|
||||
status, _, body, err = do(client, o, http.MethodPost, "/api/v1/chats", session.Token, "",
|
||||
map[string]any{"title": "Load", "member_ids": []string{user.ID}})
|
||||
if err != nil || status != http.StatusCreated {
|
||||
return actor{}, fmt.Errorf("create chat: status %d: %v", status, err)
|
||||
}
|
||||
var chat struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &chat); err != nil {
|
||||
return actor{}, err
|
||||
}
|
||||
|
||||
// Начальные сообщения, чтобы чтение первой страницы возвращало полноценный ответ.
|
||||
for i := range o.seed {
|
||||
status, _, _, err := do(client, o, http.MethodPost, "/api/v1/chats/"+chat.ID+"/messages", session.Token,
|
||||
randomHex(16), map[string]string{"text": fmt.Sprintf("seed-%d", i)})
|
||||
if err != nil || status != http.StatusCreated {
|
||||
return actor{}, fmt.Errorf("seed: status %d: %v", status, err)
|
||||
}
|
||||
}
|
||||
return actor{token: session.Token, chatID: chat.ID}, nil
|
||||
}
|
||||
|
||||
// verifyResult — итог сверки истории с подтверждёнными записями.
|
||||
type verifyResult struct {
|
||||
Confirmed int `json:"confirmed"`
|
||||
Lost int `json:"lost"`
|
||||
DuplicateIDs int `json:"duplicate_ids"`
|
||||
DuplicateTexts int `json:"duplicate_texts"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// verify читает всю историю каждого чата и сверяет её с подтверждёнными записями.
|
||||
// Потеря — подтверждённого ID нет в истории. Дубль — ID или текст встретился дважды.
|
||||
func verify(client *http.Client, o options, actors []actor, stats []*workerStats) verifyResult {
|
||||
var res verifyResult
|
||||
// Какие ID должны быть в каждом чате.
|
||||
wanted := make([]map[string]bool, len(actors))
|
||||
for i := range wanted {
|
||||
wanted[i] = map[string]bool{}
|
||||
}
|
||||
for _, st := range stats {
|
||||
for _, c := range st.confirmed {
|
||||
wanted[c.chat][c.id] = true
|
||||
res.Confirmed++
|
||||
}
|
||||
}
|
||||
// История читается постранично по курсору, с запасом на временные ошибки.
|
||||
for chat, a := range actors {
|
||||
ids, texts := map[string]bool{}, map[string]bool{}
|
||||
cursor := ""
|
||||
for {
|
||||
q := "?limit=100"
|
||||
if cursor != "" {
|
||||
q += "&cursor=" + url.QueryEscape(cursor)
|
||||
}
|
||||
status, _, body, err := getWithRetry(client, o, "/api/v1/chats/"+a.chatID+"/messages"+q, a.token)
|
||||
if err != nil || status != http.StatusOK {
|
||||
res.Error = fmt.Sprintf("read history: status %d: %v", status, err)
|
||||
return res
|
||||
}
|
||||
var page struct {
|
||||
Items []struct {
|
||||
ID string `json:"id"`
|
||||
Text string `json:"text"`
|
||||
} `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &page); err != nil {
|
||||
res.Error = "decode history: " + err.Error()
|
||||
return res
|
||||
}
|
||||
for _, m := range page.Items {
|
||||
if ids[m.ID] {
|
||||
res.DuplicateIDs++
|
||||
}
|
||||
ids[m.ID] = true
|
||||
if texts[m.Text] {
|
||||
res.DuplicateTexts++
|
||||
}
|
||||
texts[m.Text] = true
|
||||
}
|
||||
if page.NextCursor == nil {
|
||||
break
|
||||
}
|
||||
cursor = *page.NextCursor
|
||||
}
|
||||
// Всё, что было подтверждено, должно найтись.
|
||||
for id := range wanted[chat] {
|
||||
if !ids[id] {
|
||||
res.Lost++
|
||||
}
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// getWithRetry повторяет чтение до 5 раз: сразу после отказа реплики сверка не должна падать
|
||||
// из-за временной ошибки.
|
||||
func getWithRetry(client *http.Client, o options, path, token string) (int, string, []byte, error) {
|
||||
var (
|
||||
status int
|
||||
inst string
|
||||
body []byte
|
||||
err error
|
||||
)
|
||||
for range 5 {
|
||||
status, inst, body, err = do(client, o, http.MethodGet, path, token, "", nil)
|
||||
if err == nil && status == http.StatusOK {
|
||||
break
|
||||
}
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
return status, inst, body, err
|
||||
}
|
||||
|
||||
// latency — задержки успешных запросов одного вида, в миллисекундах.
|
||||
type latency struct {
|
||||
Count int `json:"count"`
|
||||
P50 float64 `json:"p50_ms"`
|
||||
P95 float64 `json:"p95_ms"`
|
||||
P99 float64 `json:"p99_ms"`
|
||||
}
|
||||
|
||||
// incident — эпизод ошибок: начало, длительность и количество.
|
||||
type incident struct {
|
||||
StartS float64 `json:"start_s"`
|
||||
DurationS float64 `json:"duration_s"`
|
||||
Errors int `json:"errors"`
|
||||
}
|
||||
|
||||
// second — одна секунда шкалы: успехи и ошибки.
|
||||
type second struct {
|
||||
T int `json:"t"`
|
||||
OK int `json:"ok"`
|
||||
Err int `json:"err"`
|
||||
}
|
||||
|
||||
// result — итог прогона. Он записывается в JSON и разбирается скриптами сводок.
|
||||
type result struct {
|
||||
Label string `json:"label"`
|
||||
Concurrency int `json:"concurrency"`
|
||||
WriteShare float64 `json:"write_share"`
|
||||
Chats int `json:"chats"`
|
||||
Seed int `json:"seed_per_chat"`
|
||||
DurationS float64 `json:"duration_s"`
|
||||
WarmupS float64 `json:"warmup_s"`
|
||||
RPS float64 `json:"successful_rps"`
|
||||
ReadRPS float64 `json:"read_rps"`
|
||||
WriteRPS float64 `json:"write_rps"`
|
||||
ErrorShare float64 `json:"error_share"`
|
||||
Errors map[string]int `json:"errors"`
|
||||
RetriedWrites int `json:"writes_confirmed_after_retry"`
|
||||
Read latency `json:"read"`
|
||||
Write latency `json:"write"`
|
||||
Instances map[string]int `json:"requests_per_instance"`
|
||||
Incidents []incident `json:"error_incidents"`
|
||||
SecondsNoOK int `json:"seconds_without_success"`
|
||||
Verify verifyResult `json:"verify"`
|
||||
Timeline []second `json:"timeline,omitempty"`
|
||||
}
|
||||
|
||||
// summarize объединяет статистику всех клиентов и считает показатели замера.
|
||||
func summarize(o options, stats []*workerStats) result {
|
||||
res := result{
|
||||
Label: o.label, Concurrency: o.concurrency, WriteShare: o.writeShare, Chats: o.chats, Seed: o.seed,
|
||||
DurationS: o.duration.Seconds(), WarmupS: o.warmup.Seconds(),
|
||||
Errors: map[string]int{}, Instances: map[string]int{},
|
||||
}
|
||||
var reads, writes, errTimes []time.Duration
|
||||
secOK, secErr := map[int]int{}, map[int]int{}
|
||||
for _, st := range stats {
|
||||
reads = append(reads, st.reads...)
|
||||
writes = append(writes, st.writes...)
|
||||
errTimes = append(errTimes, st.errTimes...)
|
||||
res.RetriedWrites += st.retried
|
||||
for k, v := range st.errors {
|
||||
res.Errors[k] += v
|
||||
}
|
||||
for k, v := range st.instances {
|
||||
res.Instances[k] += v
|
||||
}
|
||||
for k, v := range st.secOK {
|
||||
secOK[k] += v
|
||||
}
|
||||
for k, v := range st.secErr {
|
||||
secErr[k] += v
|
||||
}
|
||||
}
|
||||
res.Read, res.Write = percentiles(reads), percentiles(writes)
|
||||
secs := o.duration.Seconds()
|
||||
// RPS учитывает только успешные запросы.
|
||||
res.ReadRPS = float64(len(reads)) / secs
|
||||
res.WriteRPS = float64(len(writes)) / secs
|
||||
res.RPS = res.ReadRPS + res.WriteRPS
|
||||
if total := len(reads) + len(writes) + len(errTimes); total > 0 {
|
||||
res.ErrorShare = float64(len(errTimes)) / float64(total)
|
||||
}
|
||||
res.Incidents = incidents(errTimes, time.Second)
|
||||
// Шкала за все секунды, включая пустые: секунда без успехов — признак полной недоступности.
|
||||
for t := range int(secs) {
|
||||
res.Timeline = append(res.Timeline, second{T: t, OK: secOK[t], Err: secErr[t]})
|
||||
if secOK[t] == 0 {
|
||||
res.SecondsNoOK++
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// percentiles считает p50, p95, p99 по отсортированным задержкам. Метод ближайшего ранга:
|
||||
// значение берётся из данных, без интерполяции.
|
||||
func percentiles(d []time.Duration) latency {
|
||||
if len(d) == 0 {
|
||||
return latency{}
|
||||
}
|
||||
slices.Sort(d)
|
||||
at := func(p float64) float64 {
|
||||
i := min(int(float64(len(d))*p), len(d)-1)
|
||||
return float64(d[i].Microseconds()) / 1000
|
||||
}
|
||||
return latency{Count: len(d), P50: at(0.50), P95: at(0.95), P99: at(0.99)}
|
||||
}
|
||||
|
||||
// incidents объединяет ошибки с разрывом меньше gap в один эпизод.
|
||||
func incidents(times []time.Duration, gap time.Duration) []incident {
|
||||
times = slices.Clone(times)
|
||||
slices.Sort(times)
|
||||
out := []incident{}
|
||||
for i, t := range times {
|
||||
if i == 0 || t-times[i-1] >= gap {
|
||||
out = append(out, incident{StartS: t.Seconds()})
|
||||
}
|
||||
last := &out[len(out)-1]
|
||||
last.Errors++
|
||||
last.DurationS = t.Seconds() - last.StartS
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// writeResult пишет полный JSON в файл, а краткую версию без шкалы печатает на экран.
|
||||
func writeResult(o options, res result) error {
|
||||
full, err := json.MarshalIndent(res, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if o.out != "" {
|
||||
if err := os.WriteFile(o.out, append(full, '\n'), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
res.Timeline = nil
|
||||
brief, err := json.Marshal(res)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(string(brief))
|
||||
return nil
|
||||
}
|
||||
|
||||
// randomHex возвращает n случайных байт в hex. Без случайности нет смысла продолжать, поэтому panic.
|
||||
func randomHex(n int) string {
|
||||
b := make([]byte, n)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestIncidentsGroupsByGap(t *testing.T) {
|
||||
got := incidents([]time.Duration{
|
||||
5 * time.Second,
|
||||
1 * time.Second,
|
||||
1500 * time.Millisecond,
|
||||
}, time.Second)
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("incidents = %+v, want 2", got)
|
||||
}
|
||||
if got[0].Errors != 2 || got[0].DurationS != 0.5 || got[1].Errors != 1 || got[1].DurationS != 0 {
|
||||
t.Errorf("incidents = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPercentiles(t *testing.T) {
|
||||
d := make([]time.Duration, 100)
|
||||
for i := range d {
|
||||
d[i] = time.Duration(100-i) * time.Millisecond
|
||||
}
|
||||
got := percentiles(d)
|
||||
if got.Count != 100 || got.P50 != 51 || got.P95 != 96 || got.P99 != 100 {
|
||||
t.Errorf("percentiles = %+v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
// messenger — сервер API мессенджера, один процесс одной реплики. Своего состояния у реплики нет:
|
||||
// данные лежат в PostgreSQL, сессии в Valkey, поэтому реплик может быть несколько.
|
||||
//
|
||||
// Здесь только сборка: загрузка настроек, подключения, создание сервисов, запуск HTTP-сервера и
|
||||
// штатное завершение по SIGTERM. Логика находится в internal.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/signal"
|
||||
"runtime"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
httpapi "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/cache"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/logging"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/password"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store/db"
|
||||
)
|
||||
|
||||
// main запускает сервер и завершается после сигнала остановки. При ошибке запуска код выхода 1.
|
||||
// os.Exit не выполняет defer, поэтому перед ним подключение к БД закрывается явно.
|
||||
func main() {
|
||||
// Настройки из окружения. Логгера ещё нет, поэтому ошибка идёт прямо в stderr.
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
logger, err := logging.New(cfg.Logger.Level, cfg.Env, cfg.Version)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
slog.SetDefault(logger)
|
||||
|
||||
// Пул подключений к PostgreSQL. Без БД реплика работать не может и завершается: Docker её перезапустит.
|
||||
pool, err := db.Connect(context.Background(), cfg.Database)
|
||||
if err != nil {
|
||||
logger.Error("database connect failed", slog.Any("err", err))
|
||||
os.Exit(1)
|
||||
}
|
||||
// Хранилище с таймаутом запросов на все обращения к БД.
|
||||
storage := db.New(pool, time.Duration(cfg.Database.QueryTimeoutMs)*time.Millisecond)
|
||||
defer storage.Close()
|
||||
|
||||
// Общее хранилище сессий в Valkey: токен, выданный одной репликой, принимают все остальные.
|
||||
sessClient, err := session.Connect(context.Background(), cfg.Cache)
|
||||
if err != nil {
|
||||
logger.Error("session store connect failed", slog.Any("err", err))
|
||||
storage.Close()
|
||||
os.Exit(1)
|
||||
}
|
||||
defer sessClient.Close()
|
||||
sessions := session.NewValkey(sessClient)
|
||||
|
||||
// Хеширование паролей. Оно тяжёлое, поэтому одновременных вычислений не больше числа ядер и не больше 4.
|
||||
hasher := password.NewHasher(password.Default, min(runtime.GOMAXPROCS(0), 4))
|
||||
|
||||
auth, err := service.NewAuth(storage, sessions, hasher, time.Duration(cfg.Session.TTLSeconds)*time.Second)
|
||||
if err != nil {
|
||||
logger.Error("auth init failed", slog.Any("err", err))
|
||||
storage.Close()
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// История сообщений по умолчанию читается прямо из БД. Кэш подключается, только если он включён,
|
||||
// и заменяет собой источник: остальной код разницы не видит.
|
||||
var messages store.MessageStore = storage
|
||||
if cfg.HistoryCache.Mode != cache.ModeOff {
|
||||
hcClient, err := cache.Connect(cfg.HistoryCache)
|
||||
if err != nil {
|
||||
logger.Error("history cache config failed", slog.Any("err", err))
|
||||
storage.Close()
|
||||
os.Exit(1)
|
||||
}
|
||||
defer hcClient.Close()
|
||||
hc := cache.New(storage.Messages, hcClient, cache.Options{
|
||||
Mode: cfg.HistoryCache.Mode,
|
||||
Outbox: storage.Messages,
|
||||
PageTTL: time.Duration(cfg.HistoryCache.PageTTLSeconds) * time.Second,
|
||||
FillDelay: time.Duration(cfg.HistoryCache.FillDelayMs) * time.Millisecond,
|
||||
Logger: logger,
|
||||
})
|
||||
defer hc.Close()
|
||||
messages = hc
|
||||
}
|
||||
logger.Info("history cache", slog.String("mode", cfg.HistoryCache.Mode))
|
||||
|
||||
// Сборка HTTP-сервера из готовых зависимостей.
|
||||
srv := httpapi.NewServer(httpapi.Deps{
|
||||
Config: cfg,
|
||||
Logger: logger,
|
||||
Store: storage,
|
||||
Auth: auth,
|
||||
Users: service.NewUsers(storage, hasher),
|
||||
Chats: service.NewChats(storage),
|
||||
Messages: service.NewMessages(messages),
|
||||
// Readiness: реплика готова, только если доступны и БД, и Valkey. Иначе LB выведет её из
|
||||
// работы. Схему БД эта проверка не проверяет.
|
||||
Ready: func(ctx context.Context) error {
|
||||
if err := storage.Ping(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return sessions.Ping(ctx)
|
||||
},
|
||||
})
|
||||
|
||||
// ctx отменяется при SIGTERM (docker stop) или Ctrl+C: это начало штатного завершения.
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
// Фоновая очистка старых ключей идемпотентности. Останавливается вместе с ctx.
|
||||
go purgeIdempotencyKeys(ctx, storage, time.Duration(cfg.Idempotency.TTLSeconds)*time.Second, logger)
|
||||
|
||||
// Сервер блокирует поток до остановки, поэтому запускается отдельно. Буфер 1 не даёт горутине
|
||||
// зависнуть на отправке, если её уже никто не ждёт.
|
||||
startErr := make(chan error, 1)
|
||||
go func() {
|
||||
startErr <- srv.Start()
|
||||
}()
|
||||
|
||||
// Ждём первое из двух событий: сервер сам завершился или пришёл сигнал остановки.
|
||||
select {
|
||||
case err := <-startErr:
|
||||
if err != nil {
|
||||
logger.Error("server failed to start", slog.Any("err", err))
|
||||
storage.Close()
|
||||
os.Exit(1)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
logger.Info("shutdown signal received")
|
||||
// Drain: readiness начинает отвечать 503, но запросы ещё обслуживаются. За это время LB
|
||||
// выводит реплику, поэтому новые запросы перестают приходить до закрытия порта.
|
||||
srv.Drain(time.Duration(cfg.HTTP.ShutdownDrainMs) * time.Millisecond)
|
||||
}
|
||||
|
||||
// Предел на завершение открытых запросов. Он должен быть меньше stop_grace_period в compose.yaml,
|
||||
// иначе Docker пришлёт SIGKILL раньше.
|
||||
shutdownCtx, cancel := context.WithTimeout(
|
||||
context.Background(),
|
||||
time.Duration(cfg.HTTP.ShutdownTimeoutMs)*time.Millisecond,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
// Закрыть порт и дождаться открытых запросов. Если не успели за предел, это ошибка завершения.
|
||||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||
logger.Error("shutdown failed", slog.Any("err", err))
|
||||
storage.Close()
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Эта строка в логе подтверждает штатное завершение: её ищет failure-detection.py.
|
||||
logger.Info("server stopped cleanly")
|
||||
}
|
||||
|
||||
// Как часто удалять устаревшие ключи идемпотентности.
|
||||
const idempotencyPurgeInterval = time.Hour
|
||||
|
||||
// purgeIdempotencyKeys удаляет ключи старше ttl: сразу при запуске и затем по таймеру. Ошибка не
|
||||
// опасна: очистка просто повторится позже. Удаление работает на каждой реплике, это безопасно,
|
||||
// потому что удалять будет нечего после первой из них.
|
||||
func purgeIdempotencyKeys(ctx context.Context, storage *db.DB, ttl time.Duration, logger *slog.Logger) {
|
||||
t := time.NewTicker(idempotencyPurgeInterval)
|
||||
defer t.Stop()
|
||||
for {
|
||||
if n, err := storage.PurgeIdempotencyKeys(ctx, ttl); err != nil {
|
||||
// Ошибка из-за остановки сервера ожидаема: просто выходим.
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
logger.Warn("idempotency keys purge failed", slog.Any("err", err))
|
||||
} else if n > 0 {
|
||||
logger.Info("idempotency keys purged", slog.Int64("count", n))
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
// Package e2e — проверки против запущенного стенда через балансировщик.
|
||||
//
|
||||
// Запуск: E2E_BASE_URL=http://localhost:8080 go test -count=1 -v ./e2e/
|
||||
// Без E2E_BASE_URL тесты пропускаются, поэтому обычный go test ./... стенд не требует.
|
||||
// Создаёт только синтетические данные, токены и пароли не печатает.
|
||||
package e2e
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
rounds = 20
|
||||
workers = 16
|
||||
)
|
||||
|
||||
type client struct {
|
||||
t *testing.T
|
||||
base string
|
||||
http *http.Client
|
||||
token string
|
||||
}
|
||||
|
||||
type result struct {
|
||||
status int
|
||||
instance string
|
||||
body []byte
|
||||
}
|
||||
|
||||
func randomHex(n int) string {
|
||||
b := make([]byte, n)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
// do не вызывает t.Fatal: он работает и из горутин.
|
||||
func (c *client) do(method, path string, headers map[string]string, payload any) (result, error) {
|
||||
var body io.Reader
|
||||
if payload != nil {
|
||||
b, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return result{}, err
|
||||
}
|
||||
body = bytes.NewReader(b)
|
||||
}
|
||||
req, err := http.NewRequest(method, c.base+path, body)
|
||||
if err != nil {
|
||||
return result{}, err
|
||||
}
|
||||
if payload != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if c.token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+c.token)
|
||||
}
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return result{}, fmt.Errorf("%s %s: %w", method, strings.Split(path, "?")[0], err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return result{}, err
|
||||
}
|
||||
return result{status: resp.StatusCode, instance: resp.Header.Get("X-Instance-Id"), body: data}, nil
|
||||
}
|
||||
|
||||
func (c *client) mustDo(method, path string, want int, payload any, out any) {
|
||||
c.t.Helper()
|
||||
res, err := c.do(method, path, nil, payload)
|
||||
if err != nil {
|
||||
c.t.Fatal(err)
|
||||
}
|
||||
if res.status != want {
|
||||
c.t.Fatalf("%s %s: status = %d, want %d", method, strings.Split(path, "?")[0], res.status, want)
|
||||
}
|
||||
if out != nil {
|
||||
if err := json.Unmarshal(res.body, out); err != nil {
|
||||
c.t.Fatalf("%s %s: decode: %v", method, path, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// bootstrap создаёт пользователя с сессией и чат с ним.
|
||||
func bootstrap(t *testing.T, base string) (*client, string) {
|
||||
t.Helper()
|
||||
c := &client{t: t, base: strings.TrimRight(base, "/"), http: &http.Client{Timeout: 10 * time.Second}}
|
||||
|
||||
username, password := "lb_"+randomHex(8), "T3st-"+randomHex(16)
|
||||
var user struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
c.mustDo(http.MethodPost, "/api/v1/users", http.StatusCreated, map[string]string{
|
||||
"username": username, "display_name": "LB test", "password": password,
|
||||
}, &user)
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, c.base+"/api/v1/auth/sessions", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.SetBasicAuth(username, password)
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("login: status = %d", resp.StatusCode)
|
||||
}
|
||||
var session struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&session); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.token = session.Token
|
||||
|
||||
var chat struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
c.mustDo(http.MethodPost, "/api/v1/chats", http.StatusCreated, map[string]any{
|
||||
"title": "LB test", "member_ids": []string{user.ID},
|
||||
}, &chat)
|
||||
return c, chat.ID
|
||||
}
|
||||
|
||||
// Одинаковый Idempotency-Key одновременно через разные реплики создаёт ровно одно сообщение.
|
||||
func TestLBSameKeyConcurrentlyThroughReplicas(t *testing.T) {
|
||||
base := os.Getenv("E2E_BASE_URL")
|
||||
if base == "" {
|
||||
t.Skip("E2E_BASE_URL не задан")
|
||||
}
|
||||
c, chatID := bootstrap(t, base)
|
||||
path := "/api/v1/chats/" + chatID + "/messages"
|
||||
|
||||
perInstance := map[string]int{}
|
||||
var created []string
|
||||
for round := range rounds {
|
||||
key, text := randomHex(16), fmt.Sprintf("гонка %d", round)
|
||||
results := make([]result, workers)
|
||||
errs := make([]error, workers)
|
||||
start := make(chan struct{})
|
||||
var wg sync.WaitGroup
|
||||
for i := range workers {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
results[i], errs[i] = c.do(http.MethodPost, path,
|
||||
map[string]string{"Idempotency-Key": key}, map[string]string{"text": text})
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
|
||||
instances := map[string]bool{}
|
||||
for i := range workers {
|
||||
if errs[i] != nil {
|
||||
t.Fatalf("round %d: %v", round, errs[i])
|
||||
}
|
||||
if results[i].status != http.StatusCreated {
|
||||
t.Fatalf("round %d: status = %d, want 201", round, results[i].status)
|
||||
}
|
||||
if !bytes.Equal(results[i].body, results[0].body) {
|
||||
t.Fatalf("round %d: реплики вернули разные сообщения", round)
|
||||
}
|
||||
instances[results[i].instance] = true
|
||||
perInstance[results[i].instance]++
|
||||
}
|
||||
if len(instances) < 2 {
|
||||
t.Fatalf("round %d обслужила одна реплика: проверьте LB", round)
|
||||
}
|
||||
var msg struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal(results[0].body, &msg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
created = append(created, msg.ID)
|
||||
}
|
||||
|
||||
var history []string
|
||||
for cursor := ""; ; {
|
||||
q := "?limit=100"
|
||||
if cursor != "" {
|
||||
q += "&cursor=" + url.QueryEscape(cursor)
|
||||
}
|
||||
var page struct {
|
||||
Items []struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
c.mustDo(http.MethodGet, path+q, http.StatusOK, nil, &page)
|
||||
for _, m := range page.Items {
|
||||
history = append(history, m.ID)
|
||||
}
|
||||
if page.NextCursor == nil {
|
||||
break
|
||||
}
|
||||
cursor = *page.NextCursor
|
||||
}
|
||||
slices.Sort(created)
|
||||
slices.Sort(history)
|
||||
if !slices.Equal(created, history) {
|
||||
t.Fatalf("история отличается от подтверждённого: %d сообщений, ожидалось %d", len(history), len(created))
|
||||
}
|
||||
t.Logf("раундов: %d, запросов в раунде: %d, запросов по репликам: %v, сообщений в истории: %d",
|
||||
rounds, workers, perInstance, len(history))
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
module gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl
|
||||
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgx/v5 v5.7.6
|
||||
github.com/labstack/echo/v4 v4.16.2
|
||||
github.com/redis/go-redis/v9 v9.7.3
|
||||
golang.org/x/crypto v0.57.0
|
||||
golang.org/x/sync v0.23.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/labstack/gommon v0.5.0 // indirect
|
||||
github.com/mattn/go-colorable v0.1.15 // indirect
|
||||
github.com/mattn/go-isatty v0.0.22 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasttemplate v1.2.2 // indirect
|
||||
golang.org/x/net v0.60.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
)
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
|
||||
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.7.6 h1:rWQc5FwZSPX58r1OQmkuaNicxdmExaEz5A2DO2hUuTk=
|
||||
github.com/jackc/pgx/v5 v5.7.6/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/labstack/echo/v4 v4.16.2 h1:WFPVqfogOZGH4dTr1UCIB1sqjFIQ/k7vIk5ByL6oWjY=
|
||||
github.com/labstack/echo/v4 v4.16.2/go.mod h1:V/EQaTVHYJH92QhbQe7kFQ4mjgcjxLQQUQtAN87zZdw=
|
||||
github.com/labstack/gommon v0.5.0 h1:6VSQ2NOzsnEJ5W6+84E0RbcaDDmgB6NIAzWCczTEe6c=
|
||||
github.com/labstack/gommon v0.5.0/go.mod h1:Rzlg7HHy1maLfzBYGg9NZcVuz1sA68HHhLjhcEllYE0=
|
||||
github.com/mattn/go-colorable v0.1.15 h1:+u9SLTRGnXv73cEsnsmoZBom+dMU88B2M0aDcWy0/jY=
|
||||
github.com/mattn/go-colorable v0.1.15/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
|
||||
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/redis/go-redis/v9 v9.7.3 h1:YpPyAayJV+XErNsatSElgRZZVCwXX9QzkKYNvO7x0wM=
|
||||
github.com/redis/go-redis/v9 v9.7.3/go.mod h1:bGUrSggJ9X9GUmZpZNEOQKaANxSGgOEBRltRTZHSvrA=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
|
||||
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU=
|
||||
golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,115 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
|
||||
)
|
||||
|
||||
func TestAccess_ForeignChat(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
_, _, eve, chat := bootstrap(r)
|
||||
base := "/api/v1/chats/" + chat.ID
|
||||
|
||||
cases := []struct {
|
||||
method, path string
|
||||
body any
|
||||
}{
|
||||
{http.MethodGet, base, nil},
|
||||
{http.MethodGet, base + "/messages?limit=10", nil},
|
||||
{http.MethodPost, base + "/messages", dto.CreateMessageRequest{Text: "вторжение"}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
var resp *http.Response
|
||||
if tc.body == nil {
|
||||
resp = r.do(tc.method, tc.path, eve.ID, nil, nil)
|
||||
} else {
|
||||
resp = r.doJSON(tc.method, tc.path, eve.ID, tc.body)
|
||||
}
|
||||
if resp.StatusCode != http.StatusNotFound {
|
||||
data, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
t.Fatalf("%s %s expected 404, got %d; body=%s", tc.method, tc.path, resp.StatusCode, string(data))
|
||||
}
|
||||
e := readError(t, resp)
|
||||
if e.Error.Code != CodeNotFound {
|
||||
t.Fatalf("%s %s expected code %q, got %q", tc.method, tc.path, CodeNotFound, e.Error.Code)
|
||||
}
|
||||
}
|
||||
|
||||
resp := r.do(http.MethodGet, "/api/v1/chats?limit=100", eve.ID, nil, nil)
|
||||
expectStatus(t, resp, http.StatusOK)
|
||||
var page dto.ChatsPageResponse
|
||||
readJSON(t, resp, &page)
|
||||
for _, item := range page.Items {
|
||||
if item.ID == chat.ID {
|
||||
t.Fatalf("чат утёк в список чужого пользователя")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccess_AuthBeforeContentType(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
resp := r.do(http.MethodPost, "/api/v1/chats", "",
|
||||
map[string]string{"Content-Type": "text/plain"}, strings.NewReader("x"))
|
||||
expectStatus(t, resp, http.StatusUnauthorized)
|
||||
resp.Body.Close()
|
||||
|
||||
resp = r.do(http.MethodPost, "/api/v1/nope", "", nil, strings.NewReader("x"))
|
||||
expectStatus(t, resp, http.StatusNotFound)
|
||||
if resp.Header.Get("X-Request-Id") == "" {
|
||||
t.Fatal("404 without X-Request-Id")
|
||||
}
|
||||
resp.Body.Close()
|
||||
}
|
||||
|
||||
func TestAccess_RouterErrors(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
alice, _, _, chat := bootstrap(r)
|
||||
chatPath := "/api/v1/chats/" + chat.ID
|
||||
|
||||
cases := []struct {
|
||||
method, path, actor string
|
||||
status int
|
||||
code, message string
|
||||
}{
|
||||
{http.MethodGet, "/nope", "", http.StatusNotFound, CodeNotFound, "Object not found"},
|
||||
{http.MethodGet, "/health/live/", "", http.StatusNotFound, CodeNotFound, "Object not found"},
|
||||
{http.MethodGet, "/api/v1/nope", alice.ID, http.StatusNotFound, CodeNotFound, "Object not found"},
|
||||
{http.MethodPost, "/health/live", "", http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"},
|
||||
{http.MethodGet, "/api/v1/users", "", http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"},
|
||||
{http.MethodPost, "/api/v1/users/me", "", http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"},
|
||||
{http.MethodDelete, "/api/v1/users/me", alice.ID, http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"},
|
||||
{http.MethodDelete, "/api/v1/chats", alice.ID, http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"},
|
||||
{http.MethodPut, chatPath, alice.ID, http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"},
|
||||
{http.MethodPatch, chatPath + "/messages", alice.ID, http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
var body io.Reader
|
||||
headers := map[string]string{}
|
||||
if tc.method == http.MethodPost || tc.method == http.MethodPut || tc.method == http.MethodPatch {
|
||||
body = bytes.NewReader([]byte(`{}`))
|
||||
headers["Content-Type"] = "application/json"
|
||||
}
|
||||
resp := r.do(tc.method, tc.path, tc.actor, headers, body)
|
||||
if resp.StatusCode != tc.status {
|
||||
data, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
t.Fatalf("%s %s: expected %d, got %d; body=%s", tc.method, tc.path, tc.status, resp.StatusCode, string(data))
|
||||
}
|
||||
if tc.status == http.StatusMethodNotAllowed && resp.Header.Get("Allow") == "" {
|
||||
t.Fatalf("%s %s: 405 без заголовка Allow", tc.method, tc.path)
|
||||
}
|
||||
e := readError(t, resp)
|
||||
if e.Error.Code != tc.code || e.Error.Message != tc.message {
|
||||
t.Fatalf("%s %s: expected %q/%q, got %q/%q", tc.method, tc.path, tc.code, tc.message, e.Error.Code, e.Error.Message)
|
||||
}
|
||||
if e.Error.RequestID == "" || e.Error.RequestID != resp.Header.Get("X-Request-Id") {
|
||||
t.Fatalf("%s %s: request_id %q не совпадает с заголовком %q", tc.method, tc.path, e.Error.RequestID, resp.Header.Get("X-Request-Id"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
type authHandler struct {
|
||||
auth service.AuthService
|
||||
}
|
||||
|
||||
func (h *authHandler) createSession(c echo.Context) error {
|
||||
if c.Request().ContentLength > 0 {
|
||||
return WriteError(c, &validate.Error{Field: "body", Reason: "must be empty, credentials go in Authorization: Basic"})
|
||||
}
|
||||
username, password, ok := parseBasic(c.Request().Header.Get(echo.HeaderAuthorization))
|
||||
if !ok {
|
||||
return middleware.Unauthorized(c, middleware.BasicChallenge, "Invalid credentials")
|
||||
}
|
||||
|
||||
s, err := h.auth.Login(c.Request().Context(), username, password)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrUnauthorized) {
|
||||
return middleware.Unauthorized(c, middleware.BasicChallenge, "Invalid credentials")
|
||||
}
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusCreated, dto.SessionResponse{
|
||||
Token: s.Token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: dto.NewTimestamp(s.ExpiresAt),
|
||||
User: toUserResponse(s.User),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *authHandler) revokeSession(c echo.Context) error {
|
||||
tok := c.Get(middleware.AuthTokenKey).(string)
|
||||
if err := h.auth.Logout(c.Request().Context(), tok); err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.NoContent(http.StatusNoContent)
|
||||
}
|
||||
|
||||
|
||||
func parseBasic(header string) (username, password string, ok bool) {
|
||||
scheme, encoded, found := strings.Cut(header, " ")
|
||||
if !found || !strings.EqualFold(scheme, "Basic") {
|
||||
return "", "", false
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(encoded))
|
||||
if err != nil || !utf8.Valid(raw) {
|
||||
return "", "", false
|
||||
}
|
||||
username, password, found = strings.Cut(string(raw), ":")
|
||||
if !found || username == "" || password == "" {
|
||||
return "", "", false
|
||||
}
|
||||
return username, password, true
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session"
|
||||
)
|
||||
|
||||
const (
|
||||
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
bearerChallenge = `Bearer realm="messenger"`
|
||||
)
|
||||
|
||||
func expectUnauthorized(t *testing.T, resp *http.Response, challenge string) {
|
||||
t.Helper()
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusUnauthorized {
|
||||
data, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("expected 401, got %d; body=%s", resp.StatusCode, string(data))
|
||||
}
|
||||
if got := resp.Header.Get("WWW-Authenticate"); got != challenge {
|
||||
t.Fatalf("WWW-Authenticate = %q, want %q", got, challenge)
|
||||
}
|
||||
e := readError(t, resp)
|
||||
if e.Error.Code != CodeUnauthorized || e.Error.RequestID == "" {
|
||||
t.Fatalf("unexpected error body: %+v", e)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *testRig) withHeaders(method, path string, headers map[string]string) *http.Response {
|
||||
r.t.Helper()
|
||||
return r.do(method, path, "", headers, nil)
|
||||
}
|
||||
|
||||
func TestAuth_LoginReturnsSession(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
alice := r.createUser("login_"+randomSuffix(), "Алиса")
|
||||
|
||||
before := time.Now()
|
||||
s := r.login(alice.Username, testPassword)
|
||||
if s.TokenType != "Bearer" || len(s.Token) < 32 {
|
||||
t.Fatalf("bad session: type=%q len(token)=%d", s.TokenType, len(s.Token))
|
||||
}
|
||||
if s.User.ID != alice.ID || s.User.Username != alice.Username {
|
||||
t.Fatalf("session user = %+v, want %s", s.User, alice.ID)
|
||||
}
|
||||
if strings.Contains(s.Token, alice.ID) || strings.Contains(s.Token, alice.Username) {
|
||||
t.Fatal("token is derived from user identity")
|
||||
}
|
||||
if !s.ExpiresAt.After(before.Add(59*time.Minute)) || s.ExpiresAt.After(before.Add(61*time.Minute)) {
|
||||
t.Fatalf("expires_at = %s, want ~now+1h", s.ExpiresAt)
|
||||
}
|
||||
|
||||
if again := r.login(alice.Username, testPassword); again.Token == s.Token {
|
||||
t.Fatal("second login returned the same token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuth_LoginRejectsBadCredentialsUniformly(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
alice := r.createUser("bad_"+randomSuffix(), "Алиса")
|
||||
|
||||
expectUnauthorized(t, r.basicLogin(alice.Username, "wrong-password-123"), basicChallenge)
|
||||
expectUnauthorized(t, r.basicLogin("nobody_"+randomSuffix(), testPassword), basicChallenge)
|
||||
|
||||
b64 := func(s string) string { return base64.StdEncoding.EncodeToString([]byte(s)) }
|
||||
for _, h := range []string{
|
||||
"",
|
||||
"Bearer " + b64(alice.Username+":"+testPassword),
|
||||
"Basic not-base64!!!",
|
||||
"Basic " + b64(alice.Username),
|
||||
"Basic " + b64(alice.Username+":"),
|
||||
"Basic " + b64(":"+testPassword),
|
||||
"Basic " + b64(alice.Username+":\xff\xfe"),
|
||||
} {
|
||||
headers := map[string]string{}
|
||||
if h != "" {
|
||||
headers["Authorization"] = h
|
||||
}
|
||||
expectUnauthorized(t, r.withHeaders(http.MethodPost, "/api/v1/auth/sessions", headers), basicChallenge)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuth_PasswordWithColonAndUnicode(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
username := "colon_" + randomSuffix()
|
||||
pw := "пароль:с:двоеточиями🙂"
|
||||
resp := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{
|
||||
Username: username, DisplayName: "Двоеточие", Password: pw,
|
||||
})
|
||||
expectStatus(t, resp, http.StatusCreated)
|
||||
resp.Body.Close()
|
||||
|
||||
r.login(username, pw)
|
||||
expectUnauthorized(t, r.basicLogin(username, "пароль"), basicChallenge)
|
||||
}
|
||||
|
||||
func TestAuth_LoginRejectsBody(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
alice := r.createUser("body_"+randomSuffix(), "Алиса")
|
||||
req, _ := http.NewRequest(http.MethodPost, r.server.URL+"/api/v1/auth/sessions",
|
||||
strings.NewReader(`{"username":"`+alice.Username+`"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.SetBasicAuth(alice.Username, testPassword)
|
||||
resp, err := r.client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expectStatus(t, resp, http.StatusBadRequest)
|
||||
resp.Body.Close()
|
||||
}
|
||||
|
||||
func TestAuth_BearerRequired(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
alice, _, eve, _ := bootstrap(r)
|
||||
|
||||
expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me", nil), bearerChallenge)
|
||||
expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me",
|
||||
map[string]string{"X-User-Id": alice.ID}), bearerChallenge)
|
||||
basic := base64.StdEncoding.EncodeToString([]byte(alice.Username + ":" + testPassword))
|
||||
expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me",
|
||||
map[string]string{"Authorization": "Basic " + basic}), bearerChallenge)
|
||||
expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me",
|
||||
map[string]string{"Authorization": "Bearer " + strings.Repeat("A", 43)}), bearerChallenge)
|
||||
expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me",
|
||||
map[string]string{"Authorization": "Bearer " + alice.ID}), bearerChallenge)
|
||||
|
||||
resp := r.do(http.MethodGet, "/api/v1/users/me", alice.ID, map[string]string{"X-User-Id": eve.ID}, nil)
|
||||
expectStatus(t, resp, http.StatusOK)
|
||||
var me dto.UserResponse
|
||||
readJSON(t, resp, &me)
|
||||
if me.ID != alice.ID {
|
||||
t.Fatalf("X-User-Id overrode bearer identity: got %s", me.ID)
|
||||
}
|
||||
|
||||
tok := r.tokens[alice.ID]
|
||||
resp = r.withHeaders(http.MethodGet, "/api/v1/users/me", map[string]string{"Authorization": "bearer " + tok})
|
||||
expectStatus(t, resp, http.StatusOK)
|
||||
resp.Body.Close()
|
||||
}
|
||||
|
||||
func TestAuth_Logout(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
alice := r.createUser("logout_"+randomSuffix(), "Алиса")
|
||||
other := r.login(alice.Username, testPassword)
|
||||
|
||||
resp := r.do(http.MethodDelete, "/api/v1/auth/sessions/current", alice.ID, nil, nil)
|
||||
expectStatus(t, resp, http.StatusNoContent)
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if len(body) != 0 {
|
||||
t.Fatalf("204 with body %q", body)
|
||||
}
|
||||
|
||||
expectUnauthorized(t, r.do(http.MethodGet, "/api/v1/users/me", alice.ID, nil, nil), bearerChallenge)
|
||||
expectUnauthorized(t, r.do(http.MethodDelete, "/api/v1/auth/sessions/current", alice.ID, nil, nil), bearerChallenge)
|
||||
|
||||
resp = r.withHeaders(http.MethodGet, "/api/v1/users/me", map[string]string{"Authorization": "Bearer " + other.Token})
|
||||
expectStatus(t, resp, http.StatusOK)
|
||||
resp.Body.Close()
|
||||
}
|
||||
|
||||
func TestAuth_SessionExpires(t *testing.T) {
|
||||
r := newRig(t, defaultTestLimits, session.NewMemory(), 2*time.Second)
|
||||
alice := r.createUser("ttl_"+randomSuffix(), "Алиса")
|
||||
|
||||
resp := r.do(http.MethodGet, "/api/v1/users/me", alice.ID, nil, nil)
|
||||
expectStatus(t, resp, http.StatusOK)
|
||||
resp.Body.Close()
|
||||
|
||||
time.Sleep(2100 * time.Millisecond)
|
||||
expectUnauthorized(t, r.do(http.MethodGet, "/api/v1/users/me", alice.ID, nil, nil), bearerChallenge)
|
||||
}
|
||||
|
||||
type brokenSessions struct {
|
||||
*session.Memory
|
||||
down bool
|
||||
}
|
||||
|
||||
func (b *brokenSessions) Get(ctx context.Context, h []byte) (session.Session, error) {
|
||||
if b.down {
|
||||
return session.Session{}, domain.ErrUnavailable
|
||||
}
|
||||
return b.Memory.Get(ctx, h)
|
||||
}
|
||||
|
||||
func (b *brokenSessions) Save(ctx context.Context, h []byte, s session.Session) error {
|
||||
if b.down {
|
||||
return domain.ErrUnavailable
|
||||
}
|
||||
return b.Memory.Save(ctx, h, s)
|
||||
}
|
||||
|
||||
func TestAuth_SessionStoreDownIs503NotAnonymous(t *testing.T) {
|
||||
store := &brokenSessions{Memory: session.NewMemory()}
|
||||
r := newRig(t, defaultTestLimits, store, time.Hour)
|
||||
alice := r.createUser("down_"+randomSuffix(), "Алиса")
|
||||
store.down = true
|
||||
|
||||
resp := r.do(http.MethodGet, "/api/v1/users/me", alice.ID, nil, nil)
|
||||
expectStatus(t, resp, http.StatusServiceUnavailable)
|
||||
if e := readError(t, resp); e.Error.Code != CodeUnavailable {
|
||||
t.Fatalf("code = %q, want %q", e.Error.Code, CodeUnavailable)
|
||||
}
|
||||
|
||||
resp = r.basicLogin(alice.Username, testPassword)
|
||||
expectStatus(t, resp, http.StatusServiceUnavailable)
|
||||
resp.Body.Close()
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
type chatsHandler struct {
|
||||
chats service.ChatsService
|
||||
}
|
||||
|
||||
func (h *chatsHandler) create(c echo.Context) error {
|
||||
callerID := c.Get(middleware.AuthUserIDKey).(string)
|
||||
var req dto.CreateChatRequest
|
||||
if err := decodeJSON(c.Request().Body, &req); err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
|
||||
chat, err := h.chats.Create(c.Request().Context(), callerID, req.Title, req.MemberIDs)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusCreated, toChatResponse(chat))
|
||||
}
|
||||
|
||||
func (h *chatsHandler) get(c echo.Context) error {
|
||||
callerID := c.Get(middleware.AuthUserIDKey).(string)
|
||||
chatID := c.Param("chat_id")
|
||||
|
||||
chat, err := h.chats.Get(c.Request().Context(), callerID, chatID)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, toChatResponse(chat))
|
||||
}
|
||||
|
||||
func (h *chatsHandler) list(c echo.Context) error {
|
||||
callerID := c.Get(middleware.AuthUserIDKey).(string)
|
||||
limit, cursor, err := parsePageParams(c)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
|
||||
page, err := h.chats.List(c.Request().Context(), callerID, cursor, limit)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, toChatsPage(page))
|
||||
}
|
||||
|
||||
func toChatResponse(ch domain.Chat) dto.ChatResponse {
|
||||
members := make([]string, len(ch.MemberIDs))
|
||||
copy(members, ch.MemberIDs)
|
||||
return dto.ChatResponse{
|
||||
ID: ch.ID,
|
||||
Title: ch.Title,
|
||||
MemberIDs: members,
|
||||
CreatedAt: dto.NewTimestamp(ch.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func toChatsPage(p domain.Page[domain.Chat]) dto.ChatsPageResponse {
|
||||
items := make([]dto.ChatResponse, 0, len(p.Items))
|
||||
for _, ch := range p.Items {
|
||||
items = append(items, toChatResponse(ch))
|
||||
}
|
||||
var next *string
|
||||
if p.NextCursor != "" {
|
||||
s := p.NextCursor
|
||||
next = &s
|
||||
}
|
||||
return dto.ChatsPageResponse{Items: items, NextCursor: next}
|
||||
}
|
||||
|
||||
func parsePageParams(c echo.Context) (int, string, error) {
|
||||
q := c.QueryParams()
|
||||
|
||||
limit := validate.LimitDefault
|
||||
if vals, ok := q["limit"]; ok {
|
||||
n, err := strconv.Atoi(vals[0])
|
||||
if err != nil {
|
||||
return 0, "", &validate.Error{Field: "limit", Reason: "must be an integer"}
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
|
||||
cursor := ""
|
||||
if vals, ok := q["cursor"]; ok {
|
||||
if vals[0] == "" {
|
||||
return 0, "", &validate.Error{Field: "cursor", Reason: "must not be empty"}
|
||||
}
|
||||
cursor = vals[0]
|
||||
}
|
||||
return limit, cursor, nil
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestConcurrency_100MessagesFrom10Clients(t *testing.T) {
|
||||
const clients = 10
|
||||
const perClient = 10
|
||||
const total = clients * perClient
|
||||
|
||||
r := newTestRig(t)
|
||||
users := make([]testUser, clients)
|
||||
memberIDs := make([]string, clients)
|
||||
for i := range users {
|
||||
users[i] = r.createUser(fmt.Sprintf("race_%02d_%s", i, randomSuffix()), fmt.Sprintf("Клиент %d", i))
|
||||
memberIDs[i] = users[i].ID
|
||||
}
|
||||
chat := r.createChat(users[0], "Гонка", memberIDs...)
|
||||
|
||||
type result struct {
|
||||
id, text string
|
||||
err error
|
||||
}
|
||||
results := make(chan result, total)
|
||||
start := make(chan struct{})
|
||||
var wg sync.WaitGroup
|
||||
for i, actor := range users {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
for j := 0; j < perClient; j++ {
|
||||
text := fmt.Sprintf("race-c%02d-m%02d", i, j)
|
||||
status, msg, body := r.sendRaw(actor, chat.ID, mustJSON(map[string]string{"text": text}))
|
||||
if status != http.StatusCreated {
|
||||
results <- result{err: fmt.Errorf("%s: status %d: %s", text, status, body)}
|
||||
continue
|
||||
}
|
||||
results <- result{id: msg.ID, text: msg.Text}
|
||||
}
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
close(results)
|
||||
|
||||
sentIDs := make(map[string]string, total)
|
||||
for res := range results {
|
||||
if res.err != nil {
|
||||
t.Fatal(res.err)
|
||||
}
|
||||
if _, dup := sentIDs[res.id]; dup {
|
||||
t.Fatalf("сервер выдал один id %s двум сообщениям", res.id)
|
||||
}
|
||||
sentIDs[res.id] = res.text
|
||||
}
|
||||
if len(sentIDs) != total {
|
||||
t.Fatalf("подтверждено %d сообщений, ожидалось %d", len(sentIDs), total)
|
||||
}
|
||||
|
||||
history, _ := r.listMessages(users[0], chat.ID, 100)
|
||||
if len(history) != total {
|
||||
t.Fatalf("в истории %d сообщений, ожидалось ровно %d", len(history), total)
|
||||
}
|
||||
seen := make(map[string]struct{}, total)
|
||||
for i, m := range history {
|
||||
if _, dup := seen[m.ID]; dup {
|
||||
t.Fatalf("id %s встречается в истории дважды", m.ID)
|
||||
}
|
||||
seen[m.ID] = struct{}{}
|
||||
if text, ok := sentIDs[m.ID]; !ok || text != m.Text {
|
||||
t.Fatalf("сообщение %s (%q) в истории не совпадает с подтверждённым", m.ID, m.Text)
|
||||
}
|
||||
if i > 0 && !history[i-1].CreatedAt.Before(m.CreatedAt.Time) {
|
||||
t.Fatalf("порядок (created_at) нарушен на индексе %d", i)
|
||||
}
|
||||
}
|
||||
t.Logf("%d клиентов × %d сообщений = %d уникальных сообщений в истории, 0 дубликатов",
|
||||
clients, perClient, total)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package dto
|
||||
|
||||
type CreateChatRequest struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
type ChatResponse struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
}
|
||||
|
||||
type ChatsPageResponse struct {
|
||||
Items []ChatResponse `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package dto
|
||||
|
||||
type CreateMessageRequest struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
type MessageResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
}
|
||||
|
||||
type MessagesPageResponse struct {
|
||||
Items []MessageResponse `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package dto
|
||||
|
||||
import "time"
|
||||
|
||||
const timestampLayout = "2006-01-02T15:04:05.000000Z"
|
||||
|
||||
// Timestamp сериализуется в UTC всегда с 6 цифрами дробной части. Стандартный формат
|
||||
// time.Time отбрасывает нули в конце (…17.95188Z): это корректный RFC 3339, но такое значение
|
||||
// не разбирает datetime.fromisoformat в Python 3.9–3.10, на которых идут публичные тесты.
|
||||
type Timestamp struct {
|
||||
time.Time
|
||||
}
|
||||
|
||||
func NewTimestamp(t time.Time) Timestamp {
|
||||
return Timestamp{Time: t}
|
||||
}
|
||||
|
||||
func (t Timestamp) MarshalJSON() ([]byte, error) {
|
||||
return []byte(`"` + t.UTC().Format(timestampLayout) + `"`), nil
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTimestampAlwaysHasSixFractionalDigits(t *testing.T) {
|
||||
moscow := time.FixedZone("MSK", 3*60*60)
|
||||
cases := []struct {
|
||||
name string
|
||||
in time.Time
|
||||
want string
|
||||
}{
|
||||
{"нули в конце", time.Date(2026, 11, 4, 9, 47, 17, 951880000, time.UTC), `"2026-11-04T09:47:17.951880Z"`},
|
||||
{"без дробной части", time.Date(2026, 11, 4, 9, 47, 17, 0, time.UTC), `"2026-11-04T09:47:17.000000Z"`},
|
||||
{"шесть цифр", time.Date(2026, 11, 4, 9, 47, 17, 123456000, time.UTC), `"2026-11-04T09:47:17.123456Z"`},
|
||||
{"наносекунды отбрасываются", time.Date(2026, 11, 4, 9, 47, 17, 123456789, time.UTC), `"2026-11-04T09:47:17.123456Z"`},
|
||||
{"приводится к UTC", time.Date(2026, 11, 4, 12, 47, 17, 500000000, moscow), `"2026-11-04T09:47:17.500000Z"`},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
got, err := json.Marshal(NewTimestamp(c.in))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(got) != c.want {
|
||||
t.Fatalf("got %s, want %s", got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimestampRoundTrip(t *testing.T) {
|
||||
want := time.Date(2026, 11, 4, 9, 47, 17, 951880000, time.UTC)
|
||||
data, err := json.Marshal(MessageResponse{CreatedAt: NewTimestamp(want)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var got MessageResponse
|
||||
if err := json.Unmarshal(data, &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !got.CreatedAt.Equal(want) {
|
||||
t.Fatalf("got %s, want %s", got.CreatedAt, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package dto
|
||||
|
||||
type CreateUserRequest struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type UserResponse struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
}
|
||||
|
||||
type SessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt Timestamp `json:"expires_at"`
|
||||
User UserResponse `json:"user"`
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
const (
|
||||
CodeInvalidRequest = "invalid_request"
|
||||
CodeUnauthorized = "unauthorized"
|
||||
CodeNotFound = "not_found"
|
||||
CodeConflict = "conflict"
|
||||
CodePayloadTooLarge = "payload_too_large"
|
||||
CodeUnsupportedMedia = "unsupported_media_type"
|
||||
CodeRateLimited = "rate_limited"
|
||||
CodeUnavailable = "unavailable"
|
||||
CodeInternalError = "internal_error"
|
||||
)
|
||||
|
||||
type errorBody struct {
|
||||
Error errorPayload `json:"error"`
|
||||
}
|
||||
|
||||
type errorPayload struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
var (
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
ErrUnsupportedMedia = errors.New("unsupported media type")
|
||||
)
|
||||
|
||||
func Classify(err error) (status int, code, message string) {
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrIdempotencyConflict):
|
||||
return http.StatusConflict, CodeConflict, "Idempotency-Key was already used with a different request"
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return http.StatusNotFound, CodeNotFound, "Object not found"
|
||||
case errors.Is(err, domain.ErrConflict):
|
||||
return http.StatusConflict, CodeConflict, "Resource already exists"
|
||||
case errors.Is(err, domain.ErrInvalidArgument):
|
||||
return http.StatusBadRequest, CodeInvalidRequest, "Invalid request arguments"
|
||||
case errors.Is(err, domain.ErrUnavailable):
|
||||
return http.StatusServiceUnavailable, CodeUnavailable, "Service temporarily unavailable"
|
||||
case errors.Is(err, domain.ErrPayloadTooLarge):
|
||||
return http.StatusRequestEntityTooLarge, CodePayloadTooLarge, "Request body too large"
|
||||
case errors.Is(err, domain.ErrRateLimited):
|
||||
return http.StatusTooManyRequests, CodeRateLimited, "Too many concurrent requests"
|
||||
case errors.Is(err, ErrUnauthorized), errors.Is(err, domain.ErrUnauthorized):
|
||||
return http.StatusUnauthorized, CodeUnauthorized, "Identification required"
|
||||
case errors.Is(err, ErrUnsupportedMedia):
|
||||
return http.StatusUnsupportedMediaType, CodeUnsupportedMedia, "Expected Content-Type: application/json"
|
||||
}
|
||||
|
||||
var vErr *validate.Error
|
||||
if errors.As(err, &vErr) {
|
||||
return http.StatusBadRequest, CodeInvalidRequest, vErr.Error()
|
||||
}
|
||||
|
||||
return http.StatusInternalServerError, CodeInternalError, "Internal server error"
|
||||
}
|
||||
|
||||
func WriteError(c echo.Context, err error) error {
|
||||
status, code, msg := Classify(err)
|
||||
if status == http.StatusTooManyRequests {
|
||||
c.Response().Header().Set("Retry-After", "1")
|
||||
}
|
||||
return c.JSON(status, errorBody{
|
||||
Error: errorPayload{
|
||||
Code: code,
|
||||
Message: msg,
|
||||
RequestID: c.Response().Header().Get(echo.HeaderXRequestID),
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
type healthResponse struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
func healthLive(c echo.Context) error {
|
||||
return c.JSON(http.StatusOK, healthResponse{Status: "ok"})
|
||||
}
|
||||
|
||||
func healthReady(isReady func() bool) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
if !isReady() {
|
||||
return echo.NewHTTPError(http.StatusServiceUnavailable, "Service unavailable")
|
||||
}
|
||||
return c.JSON(http.StatusOK, healthResponse{Status: "ok"})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/password"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
)
|
||||
|
||||
type testRig struct {
|
||||
t *testing.T
|
||||
server *httptest.Server
|
||||
srv *Server
|
||||
memory *store.Memory
|
||||
sessions session.Store
|
||||
client *http.Client
|
||||
|
||||
mu sync.Mutex
|
||||
tokens map[string]string
|
||||
}
|
||||
|
||||
func newTestRig(t *testing.T) *testRig {
|
||||
return newTestRigWithLimits(t, config.Limits{
|
||||
MaxBodyBytes: 1 << 20,
|
||||
MaxInFlight: 256,
|
||||
MaxMessagesGlobal: 100000,
|
||||
MaxHeapBytes: 1 << 40,
|
||||
})
|
||||
}
|
||||
|
||||
func newTestRigWithLimits(t *testing.T, limits config.Limits) *testRig {
|
||||
t.Helper()
|
||||
return newRig(t, limits, session.NewMemory(), time.Hour)
|
||||
}
|
||||
|
||||
const testInstanceID = "test-instance"
|
||||
|
||||
var defaultTestLimits = config.Limits{
|
||||
MaxBodyBytes: 1 << 20,
|
||||
MaxInFlight: 256,
|
||||
MaxMessagesGlobal: 100000,
|
||||
MaxHeapBytes: 1 << 40,
|
||||
}
|
||||
|
||||
func newRig(t *testing.T, limits config.Limits, sessions session.Store, ttl time.Duration) *testRig {
|
||||
t.Helper()
|
||||
cfg := &config.Config{
|
||||
Env: "test",
|
||||
Version: "test",
|
||||
InstanceID: testInstanceID,
|
||||
HTTP: config.HTTP{
|
||||
Addr: "127.0.0.1:0",
|
||||
ReadTimeoutMs: 10000,
|
||||
WriteTimeoutMs: 10000,
|
||||
IdleTimeoutMs: 60000,
|
||||
ShutdownTimeoutMs: 1000,
|
||||
},
|
||||
Limits: limits,
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
memory := store.NewWithLimit(limits.MaxMessagesGlobal)
|
||||
hasher := password.NewHasher(testHashParams, 8)
|
||||
auth, err := service.NewAuth(memory, sessions, hasher, ttl)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := NewServer(Deps{
|
||||
Config: cfg,
|
||||
Logger: logger,
|
||||
Store: memory,
|
||||
Auth: auth,
|
||||
Users: service.NewUsers(memory, hasher),
|
||||
Chats: service.NewChats(memory),
|
||||
Messages: service.NewMessages(memory),
|
||||
})
|
||||
ts := httptest.NewServer(srv.e)
|
||||
t.Cleanup(ts.Close)
|
||||
return &testRig{
|
||||
t: t,
|
||||
server: ts,
|
||||
srv: srv,
|
||||
memory: memory,
|
||||
sessions: sessions,
|
||||
client: &http.Client{Timeout: 10 * time.Second},
|
||||
tokens: make(map[string]string),
|
||||
}
|
||||
}
|
||||
|
||||
type testUser struct {
|
||||
ID string
|
||||
Username string
|
||||
DisplayName string
|
||||
}
|
||||
|
||||
type errorResp struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
func (r *testRig) do(method, path string, actorID string, headers map[string]string, body io.Reader) *http.Response {
|
||||
r.t.Helper()
|
||||
req, err := http.NewRequest(method, r.server.URL+path, body)
|
||||
if err != nil {
|
||||
r.t.Fatalf("new request %s %s: %v", method, path, err)
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
r.setAuth(req, actorID)
|
||||
if method == http.MethodPost && strings.HasSuffix(path, "/messages") {
|
||||
req.Header.Set("Idempotency-Key", uuid.NewString())
|
||||
}
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
resp, err := r.client.Do(req)
|
||||
if err != nil {
|
||||
r.t.Fatalf("do %s %s: %v", method, path, err)
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
func (r *testRig) doJSON(method, path string, actorID string, payload any) *http.Response {
|
||||
r.t.Helper()
|
||||
var body io.Reader
|
||||
if payload != nil {
|
||||
body = bytes.NewReader(mustJSON(payload))
|
||||
}
|
||||
return r.do(method, path, actorID, map[string]string{"Content-Type": "application/json"}, body)
|
||||
}
|
||||
|
||||
func readJSON(t *testing.T, resp *http.Response, dst any) {
|
||||
t.Helper()
|
||||
defer resp.Body.Close()
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read body: %v", err)
|
||||
}
|
||||
if len(data) == 0 {
|
||||
return
|
||||
}
|
||||
if err := json.Unmarshal(data, dst); err != nil {
|
||||
t.Fatalf("decode body (%s): %v", string(data), err)
|
||||
}
|
||||
}
|
||||
|
||||
func readError(t *testing.T, resp *http.Response) errorResp {
|
||||
t.Helper()
|
||||
var e errorResp
|
||||
readJSON(t, resp, &e)
|
||||
return e
|
||||
}
|
||||
|
||||
func expectStatus(t *testing.T, resp *http.Response, want int) {
|
||||
t.Helper()
|
||||
if resp.StatusCode != want {
|
||||
data, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
t.Fatalf("expected status %d, got %d; body=%s", want, resp.StatusCode, string(data))
|
||||
}
|
||||
}
|
||||
|
||||
const testPassword = "test-password-123"
|
||||
|
||||
var testHashParams = password.Params{MemoryKiB: 64, Iterations: 1, Parallelism: 1, SaltLen: 16, KeyLen: 32}
|
||||
|
||||
func (r *testRig) createUser(username, displayName string) testUser {
|
||||
r.t.Helper()
|
||||
resp := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
Password: testPassword,
|
||||
})
|
||||
expectStatus(r.t, resp, http.StatusCreated)
|
||||
var u dto.UserResponse
|
||||
readJSON(r.t, resp, &u)
|
||||
s := r.login(username, testPassword)
|
||||
r.mu.Lock()
|
||||
r.tokens[u.ID] = s.Token
|
||||
r.mu.Unlock()
|
||||
return testUser{ID: u.ID, Username: u.Username, DisplayName: u.DisplayName}
|
||||
}
|
||||
|
||||
// login входит по Basic и возвращает сессию; ожидает 201.
|
||||
func (r *testRig) login(username, pw string) dto.SessionResponse {
|
||||
r.t.Helper()
|
||||
resp := r.basicLogin(username, pw)
|
||||
expectStatus(r.t, resp, http.StatusCreated)
|
||||
var s dto.SessionResponse
|
||||
readJSON(r.t, resp, &s)
|
||||
return s
|
||||
}
|
||||
|
||||
func (r *testRig) basicLogin(username, pw string) *http.Response {
|
||||
r.t.Helper()
|
||||
req, _ := http.NewRequest(http.MethodPost, r.server.URL+"/api/v1/auth/sessions", nil)
|
||||
req.SetBasicAuth(username, pw)
|
||||
resp, err := r.client.Do(req)
|
||||
if err != nil {
|
||||
r.t.Fatalf("login: %v", err)
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
func (r *testRig) setAuth(req *http.Request, actorID string) {
|
||||
if actorID == "" {
|
||||
return
|
||||
}
|
||||
r.mu.Lock()
|
||||
tok, ok := r.tokens[strings.ToLower(actorID)]
|
||||
r.mu.Unlock()
|
||||
if !ok {
|
||||
tok = "unknown-" + actorID
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+tok)
|
||||
}
|
||||
|
||||
func (r *testRig) createChat(owner testUser, title string, members ...string) dto.ChatResponse {
|
||||
r.t.Helper()
|
||||
resp := r.doJSON(http.MethodPost, "/api/v1/chats", owner.ID, dto.CreateChatRequest{
|
||||
Title: title,
|
||||
MemberIDs: members,
|
||||
})
|
||||
expectStatus(r.t, resp, http.StatusCreated)
|
||||
var ch dto.ChatResponse
|
||||
readJSON(r.t, resp, &ch)
|
||||
return ch
|
||||
}
|
||||
|
||||
func (r *testRig) sendMessage(actor testUser, chatID, text string) (*http.Response, dto.MessageResponse) {
|
||||
r.t.Helper()
|
||||
resp := r.doJSON(http.MethodPost, "/api/v1/chats/"+chatID+"/messages", actor.ID, dto.CreateMessageRequest{Text: text})
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
return resp, dto.MessageResponse{}
|
||||
}
|
||||
var m dto.MessageResponse
|
||||
readJSON(r.t, resp, &m)
|
||||
return resp, m
|
||||
}
|
||||
|
||||
func (r *testRig) sendRaw(actor testUser, chatID string, body []byte) (int, dto.MessageResponse, []byte) {
|
||||
r.t.Helper()
|
||||
resp := r.do(http.MethodPost, "/api/v1/chats/"+chatID+"/messages", actor.ID,
|
||||
map[string]string{"Content-Type": "application/json"}, bytes.NewReader(body))
|
||||
defer resp.Body.Close()
|
||||
data, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
return resp.StatusCode, dto.MessageResponse{}, data
|
||||
}
|
||||
var m dto.MessageResponse
|
||||
if err := json.Unmarshal(data, &m); err != nil {
|
||||
r.t.Fatalf("decode message: %v", err)
|
||||
}
|
||||
return resp.StatusCode, m, data
|
||||
}
|
||||
|
||||
func (r *testRig) send(actor testUser, chatID, text string) (int, dto.MessageResponse) {
|
||||
r.t.Helper()
|
||||
status, msg, _ := r.sendRaw(actor, chatID, mustJSON(dto.CreateMessageRequest{Text: text}))
|
||||
return status, msg
|
||||
}
|
||||
|
||||
func (r *testRig) listMessages(actor testUser, chatID string, pageSize int) ([]dto.MessageResponse, int) {
|
||||
r.t.Helper()
|
||||
collected := []dto.MessageResponse{}
|
||||
cursor := ""
|
||||
for pages := 1; ; pages++ {
|
||||
q := fmt.Sprintf("/api/v1/chats/%s/messages?limit=%d", chatID, pageSize)
|
||||
if cursor != "" {
|
||||
q += "&cursor=" + url.QueryEscape(cursor)
|
||||
}
|
||||
resp := r.do(http.MethodGet, q, actor.ID, nil, nil)
|
||||
expectStatus(r.t, resp, http.StatusOK)
|
||||
var page dto.MessagesPageResponse
|
||||
readJSON(r.t, resp, &page)
|
||||
collected = append(collected, page.Items...)
|
||||
if page.NextCursor == nil {
|
||||
return collected, pages
|
||||
}
|
||||
cursor = *page.NextCursor
|
||||
if pages > 100_000 {
|
||||
r.t.Fatalf("пагинация не сходится: next_cursor не исчезает")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func bootstrap(r *testRig) (alice, bob, eve testUser, chat dto.ChatResponse) {
|
||||
alice = r.createUser("own_alice_"+randomSuffix(), "Алиса")
|
||||
bob = r.createUser("own_bob_"+randomSuffix(), "Боб")
|
||||
eve = r.createUser("own_eve_"+randomSuffix(), "Ева")
|
||||
chat = r.createChat(alice, "Контрактный тест", alice.ID, bob.ID)
|
||||
return
|
||||
}
|
||||
|
||||
var suffixMu sync.Mutex
|
||||
var suffixSeq int
|
||||
|
||||
func randomSuffix() string {
|
||||
suffixMu.Lock()
|
||||
defer suffixMu.Unlock()
|
||||
suffixSeq++
|
||||
return fmt.Sprintf("%09d_%d", time.Now().UnixNano()%1_000_000_000, suffixSeq)
|
||||
}
|
||||
|
||||
func mustJSON(v any) []byte {
|
||||
data, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func extractErrorCode(t *testing.T, data []byte) string {
|
||||
t.Helper()
|
||||
var e errorResp
|
||||
if err := json.Unmarshal(data, &e); err != nil {
|
||||
t.Fatalf("decode error body: %v; raw=%s", err, string(data))
|
||||
}
|
||||
return e.Error.Code
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func (r *testRig) postKeyed(actorID, chatID, key, body string) (int, []byte) {
|
||||
r.t.Helper()
|
||||
resp := r.do(http.MethodPost, "/api/v1/chats/"+chatID+"/messages", actorID,
|
||||
map[string]string{"Content-Type": "application/json", "Idempotency-Key": key},
|
||||
bytes.NewReader([]byte(body)))
|
||||
defer resp.Body.Close()
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
r.t.Fatal(err)
|
||||
}
|
||||
return resp.StatusCode, data
|
||||
}
|
||||
|
||||
func TestIdempotency_ReplayReturnsSameBody(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
alice := r.createUser("alice_"+randomSuffix(), "Alice")
|
||||
chat := r.createChat(alice, "replay", alice.ID)
|
||||
key := uuid.NewString()
|
||||
|
||||
code, first := r.postKeyed(alice.ID, chat.ID, key, `{"text":"привет"}`)
|
||||
if code != http.StatusCreated {
|
||||
t.Fatalf("first: status = %d, body = %s", code, first)
|
||||
}
|
||||
// Иное форматирование JSON — тот же запрос.
|
||||
code, replay := r.postKeyed(alice.ID, chat.ID, key, "{ \"text\" : \"привет\" }")
|
||||
if code != http.StatusCreated {
|
||||
t.Fatalf("replay: status = %d, body = %s", code, replay)
|
||||
}
|
||||
if !bytes.Equal(first, replay) {
|
||||
t.Errorf("replay differs:\n%s\n%s", first, replay)
|
||||
}
|
||||
if items, _ := r.listMessages(alice, chat.ID, 100); len(items) != 1 {
|
||||
t.Errorf("messages = %d, want 1", len(items))
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdempotency_DifferentBodyConflicts(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
alice := r.createUser("alice_"+randomSuffix(), "Alice")
|
||||
chat := r.createChat(alice, "conflict", alice.ID)
|
||||
key := uuid.NewString()
|
||||
|
||||
if code, body := r.postKeyed(alice.ID, chat.ID, key, `{"text":"раз"}`); code != http.StatusCreated {
|
||||
t.Fatalf("first: status = %d, body = %s", code, body)
|
||||
}
|
||||
if code, body := r.postKeyed(alice.ID, chat.ID, key, `{"text":"два"}`); code != http.StatusConflict {
|
||||
t.Fatalf("conflict: status = %d, body = %s", code, body)
|
||||
}
|
||||
if items, _ := r.listMessages(alice, chat.ID, 100); len(items) != 1 {
|
||||
t.Errorf("messages = %d, want 1", len(items))
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdempotency_ScopeAndAccess(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
alice := r.createUser("alice_"+randomSuffix(), "Alice")
|
||||
bob := r.createUser("bob_"+randomSuffix(), "Bob")
|
||||
eve := r.createUser("eve_"+randomSuffix(), "Eve")
|
||||
chat := r.createChat(alice, "shared", alice.ID, bob.ID)
|
||||
other := r.createChat(alice, "other", alice.ID)
|
||||
key := uuid.NewString()
|
||||
|
||||
if code, body := r.postKeyed(alice.ID, chat.ID, key, `{"text":"от alice"}`); code != http.StatusCreated {
|
||||
t.Fatalf("alice: status = %d, body = %s", code, body)
|
||||
}
|
||||
if code, body := r.postKeyed(bob.ID, chat.ID, key, `{"text":"от bob"}`); code != http.StatusCreated {
|
||||
t.Fatalf("bob: status = %d, body = %s", code, body)
|
||||
}
|
||||
if code, body := r.postKeyed(alice.ID, other.ID, key, `{"text":"другой чат"}`); code != http.StatusCreated {
|
||||
t.Fatalf("other chat: status = %d, body = %s", code, body)
|
||||
}
|
||||
if code, body := r.postKeyed(eve.ID, chat.ID, key, `{"text":"от alice"}`); code != http.StatusNotFound {
|
||||
t.Fatalf("stranger: status = %d, body = %s", code, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdempotency_ConcurrentCreatesOne(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
alice := r.createUser("alice_"+randomSuffix(), "Alice")
|
||||
chat := r.createChat(alice, "race", alice.ID)
|
||||
key := uuid.NewString()
|
||||
|
||||
const workers = 20
|
||||
bodies := make([][]byte, workers)
|
||||
codes := make([]int, workers)
|
||||
var wg sync.WaitGroup
|
||||
for i := range workers {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
codes[i], bodies[i] = r.postKeyed(alice.ID, chat.ID, key, `{"text":"гонка"}`)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
for i := range workers {
|
||||
if codes[i] != http.StatusCreated {
|
||||
t.Fatalf("worker %d: status = %d, body = %s", i, codes[i], bodies[i])
|
||||
}
|
||||
if !bytes.Equal(bodies[i], bodies[0]) {
|
||||
t.Errorf("worker %d: body differs", i)
|
||||
}
|
||||
}
|
||||
if items, _ := r.listMessages(alice, chat.ID, 100); len(items) != 1 {
|
||||
t.Errorf("messages = %d, want 1", len(items))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestInstanceID_OnEveryResponse(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
cases := []struct {
|
||||
name, method, path string
|
||||
want int
|
||||
}{
|
||||
{"live", http.MethodGet, "/health/live", http.StatusOK},
|
||||
{"ready", http.MethodGet, "/health/ready", http.StatusOK},
|
||||
{"unauthorized", http.MethodGet, "/api/v1/users/me", http.StatusUnauthorized},
|
||||
{"unknown route", http.MethodGet, "/api/v1/nope", http.StatusNotFound},
|
||||
{"wrong method", http.MethodPatch, "/api/v1/users", http.StatusMethodNotAllowed},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
resp := r.do(tc.method, tc.path, "", nil, nil)
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != tc.want {
|
||||
t.Fatalf("status = %d, want %d", resp.StatusCode, tc.want)
|
||||
}
|
||||
if got := resp.Header.Get("X-Instance-Id"); got != testInstanceID {
|
||||
t.Errorf("X-Instance-Id = %q, want %q", got, testInstanceID)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdempotencyKey_Validation(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
alice := r.createUser("alice_key", "Alice")
|
||||
chat := r.createChat(alice, "keys", alice.ID)
|
||||
url := r.server.URL + "/api/v1/chats/" + chat.ID + "/messages"
|
||||
|
||||
post := func(setKey func(http.Header)) int {
|
||||
t.Helper()
|
||||
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader([]byte(`{"text":"hi"}`)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
r.setAuth(req, alice.ID)
|
||||
setKey(req.Header)
|
||||
resp, err := r.client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
return resp.StatusCode
|
||||
}
|
||||
withKey := func(key string) func(http.Header) {
|
||||
return func(h http.Header) { h.Set("Idempotency-Key", key) }
|
||||
}
|
||||
|
||||
if got := post(func(http.Header) {}); got != http.StatusBadRequest {
|
||||
t.Errorf("missing key: status = %d, want 400", got)
|
||||
}
|
||||
for name, key := range map[string]string{
|
||||
"empty": "",
|
||||
"too long": strings.Repeat("a", 129),
|
||||
"space": "a b",
|
||||
"unicode": "ключ",
|
||||
"slash": "a/b",
|
||||
} {
|
||||
if got := post(withKey(key)); got != http.StatusBadRequest {
|
||||
t.Errorf("%s: status = %d, want 400", name, got)
|
||||
}
|
||||
}
|
||||
for name, key := range map[string]string{
|
||||
"all allowed chars": "aZ09._:-",
|
||||
"max length": strings.Repeat("a", 128),
|
||||
"uuid": uuid.NewString(),
|
||||
} {
|
||||
if got := post(withKey(key)); got != http.StatusCreated {
|
||||
t.Errorf("%s: status = %d, want 201", name, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDrain_NotReadyButStillServing(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
status := func(path string) int {
|
||||
t.Helper()
|
||||
resp := r.do(http.MethodGet, path, "", nil, nil)
|
||||
defer resp.Body.Close()
|
||||
return resp.StatusCode
|
||||
}
|
||||
if got := status("/health/ready"); got != http.StatusOK {
|
||||
t.Fatalf("ready before drain = %d", got)
|
||||
}
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
r.srv.Drain(500 * time.Millisecond)
|
||||
}()
|
||||
deadline := time.Now().Add(400 * time.Millisecond)
|
||||
for status("/health/ready") != http.StatusServiceUnavailable {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("readiness did not become 503 during drain")
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
if got := status("/health/live"); got != http.StatusOK {
|
||||
t.Errorf("live during drain = %d, want 200", got)
|
||||
}
|
||||
if got := status("/api/v1/users/me"); got != http.StatusUnauthorized {
|
||||
t.Errorf("API during drain = %d, want 401: запросы должны обслуживаться", got)
|
||||
}
|
||||
<-done
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session"
|
||||
)
|
||||
|
||||
func TestLimits_PayloadTooLarge(t *testing.T) {
|
||||
r := newTestRigWithLimits(t, config.Limits{
|
||||
MaxBodyBytes: 256,
|
||||
MaxInFlight: 16,
|
||||
MaxMessagesGlobal: 100,
|
||||
MaxHeapBytes: 1 << 40,
|
||||
})
|
||||
alice := r.createUser("a_"+randomSuffix(), "Алиса")
|
||||
bob := r.createUser("b_"+randomSuffix(), "Боб")
|
||||
chat := r.createChat(alice, "Деградация", alice.ID, bob.ID)
|
||||
|
||||
ok, _, _ := r.sendRaw(alice, chat.ID, mustJSON(dto.CreateMessageRequest{Text: "ok"}))
|
||||
if ok != http.StatusCreated {
|
||||
t.Fatalf("baseline send expected 201, got %d", ok)
|
||||
}
|
||||
stored := r.memory.MessagesTotal()
|
||||
if stored != 1 {
|
||||
t.Fatalf("baseline total expected 1, got %d", stored)
|
||||
}
|
||||
|
||||
big := strings.Repeat("x", 512)
|
||||
status, _, body := r.sendRaw(alice, chat.ID, mustJSON(dto.CreateMessageRequest{Text: big}))
|
||||
if status != http.StatusRequestEntityTooLarge {
|
||||
t.Fatalf("expected 413 by content-length, got %d body=%s", status, string(body))
|
||||
}
|
||||
code := extractErrorCode(t, body)
|
||||
if code != CodePayloadTooLarge {
|
||||
t.Fatalf("expected code %q, got %q", CodePayloadTooLarge, code)
|
||||
}
|
||||
|
||||
if got := r.memory.MessagesTotal(); got != stored {
|
||||
t.Fatalf("после 413 store изменился: было %d, стало %d", stored, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimits_PayloadBoundaries(t *testing.T) {
|
||||
const limit = 256
|
||||
r := newTestRigWithLimits(t, config.Limits{
|
||||
MaxBodyBytes: limit,
|
||||
MaxInFlight: 16,
|
||||
MaxMessagesGlobal: 100,
|
||||
MaxHeapBytes: 1 << 40,
|
||||
})
|
||||
alice := r.createUser("a_"+randomSuffix(), "Алиса")
|
||||
bob := r.createUser("b_"+randomSuffix(), "Боб")
|
||||
chat := r.createChat(alice, "Деградация", alice.ID, bob.ID)
|
||||
|
||||
exact := []byte(`{"text":"` + strings.Repeat("x", limit-len(`{"text":""}`)) + `"}`)
|
||||
if len(exact) != limit {
|
||||
t.Fatalf("test bug: body is %d bytes, want %d", len(exact), limit)
|
||||
}
|
||||
|
||||
post := func(body io.Reader) (int, []byte) {
|
||||
req, _ := http.NewRequest(http.MethodPost,
|
||||
r.server.URL+"/api/v1/chats/"+chat.ID+"/messages", body)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Idempotency-Key", uuid.NewString())
|
||||
r.setAuth(req, alice.ID)
|
||||
resp, err := r.client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("send: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
data, _ := io.ReadAll(resp.Body)
|
||||
return resp.StatusCode, data
|
||||
}
|
||||
chunked := func(b []byte) io.Reader { return io.MultiReader(bytes.NewReader(b)) }
|
||||
|
||||
if status, body := post(bytes.NewReader(exact)); status != http.StatusCreated {
|
||||
t.Fatalf("body ровно %d байт с Content-Length: expected 201, got %d body=%s", limit, status, body)
|
||||
}
|
||||
if status, body := post(chunked(exact)); status != http.StatusCreated {
|
||||
t.Fatalf("body ровно %d байт без Content-Length: expected 201, got %d body=%s", limit, status, body)
|
||||
}
|
||||
stored := r.memory.MessagesTotal()
|
||||
|
||||
over := []byte(`{"text":"` + strings.Repeat("x", limit) + `"}`)
|
||||
status, body := post(chunked(over))
|
||||
if status != http.StatusRequestEntityTooLarge {
|
||||
t.Fatalf("body %d байт без Content-Length: expected 413, got %d body=%s", len(over), status, body)
|
||||
}
|
||||
if code := extractErrorCode(t, body); code != CodePayloadTooLarge {
|
||||
t.Fatalf("expected code %q, got %q", CodePayloadTooLarge, code)
|
||||
}
|
||||
if got := r.memory.MessagesTotal(); got != stored {
|
||||
t.Fatalf("после 413 store изменился: было %d, стало %d", stored, got)
|
||||
}
|
||||
}
|
||||
|
||||
type slowSessions struct {
|
||||
*session.Memory
|
||||
delay atomic.Int64
|
||||
}
|
||||
|
||||
func (s *slowSessions) Get(ctx context.Context, h []byte) (session.Session, error) {
|
||||
time.Sleep(time.Duration(s.delay.Load()))
|
||||
return s.Memory.Get(ctx, h)
|
||||
}
|
||||
|
||||
func TestLimits_RateLimited(t *testing.T) {
|
||||
sessions := &slowSessions{Memory: session.NewMemory()}
|
||||
r := newRig(t, config.Limits{
|
||||
MaxBodyBytes: 1 << 16,
|
||||
MaxInFlight: 2,
|
||||
MaxMessagesGlobal: 10000,
|
||||
MaxHeapBytes: 1 << 40,
|
||||
}, sessions, time.Hour)
|
||||
alice := r.createUser("c_"+randomSuffix(), "Алиса")
|
||||
bob := r.createUser("d_"+randomSuffix(), "Боб")
|
||||
chat := r.createChat(alice, "Деградация", alice.ID, bob.ID)
|
||||
sessions.delay.Store(int64(20 * time.Millisecond))
|
||||
|
||||
const total = 50
|
||||
var (
|
||||
ok atomic.Int32
|
||||
throttled atomic.Int32
|
||||
errs atomic.Int32
|
||||
wg sync.WaitGroup
|
||||
)
|
||||
wg.Add(total)
|
||||
start := make(chan struct{})
|
||||
for i := 0; i < total; i++ {
|
||||
i := i
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
body, _ := json.Marshal(dto.CreateMessageRequest{Text: fmt.Sprintf("flood-%d", i)})
|
||||
req, _ := http.NewRequest(http.MethodPost,
|
||||
r.server.URL+"/api/v1/chats/"+chat.ID+"/messages",
|
||||
bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Idempotency-Key", uuid.NewString())
|
||||
r.setAuth(req, alice.ID)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
errs.Add(1)
|
||||
return
|
||||
}
|
||||
switch resp.StatusCode {
|
||||
case http.StatusCreated:
|
||||
ok.Add(1)
|
||||
case http.StatusTooManyRequests:
|
||||
throttled.Add(1)
|
||||
if resp.Header.Get("Retry-After") != "1" {
|
||||
errs.Add(1)
|
||||
}
|
||||
default:
|
||||
errs.Add(1)
|
||||
}
|
||||
resp.Body.Close()
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
sessions.delay.Store(0)
|
||||
|
||||
if errs.Load() != 0 {
|
||||
t.Fatalf("неожиданные ошибки/статусы под нагрузкой: %d", errs.Load())
|
||||
}
|
||||
if throttled.Load() == 0 {
|
||||
t.Fatalf("ожидался хотя бы один 429 при maxInFlight=2 и %d параллельных запросах", total)
|
||||
}
|
||||
if ok.Load() == 0 {
|
||||
t.Fatalf("ни одного 201 — лимит не пропускает валидный трафик")
|
||||
}
|
||||
if int(ok.Load()+throttled.Load()) != total {
|
||||
t.Fatalf("ok=%d throttled=%d не покрывают total=%d", ok.Load(), throttled.Load(), total)
|
||||
}
|
||||
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
status, _ := r.send(alice, chat.ID, "после-пика "+randomSuffix())
|
||||
if status == http.StatusCreated {
|
||||
break
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
status, _ := r.send(alice, chat.ID, "после-пика-2 "+randomSuffix())
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("после отступления нагрузки сервис не восстановился: %d", status)
|
||||
}
|
||||
|
||||
collected, _ := r.listMessages(alice, chat.ID, 100)
|
||||
if int32(len(collected)) < ok.Load() {
|
||||
t.Fatalf("часть подтверждённых сообщений потеряна: подтверждено %d, в истории %d",
|
||||
ok.Load(), len(collected))
|
||||
}
|
||||
t.Logf("ok=%d throttled=%d errors=%d; history=%d", ok.Load(), throttled.Load(), errs.Load(), len(collected))
|
||||
}
|
||||
|
||||
func TestLimits_MessageQuota(t *testing.T) {
|
||||
const quota = 10
|
||||
r := newTestRigWithLimits(t, config.Limits{
|
||||
MaxBodyBytes: 1 << 16,
|
||||
MaxInFlight: 16,
|
||||
MaxMessagesGlobal: quota,
|
||||
MaxHeapBytes: 1 << 40,
|
||||
})
|
||||
alice := r.createUser("e_"+randomSuffix(), "Алиса")
|
||||
bob := r.createUser("f_"+randomSuffix(), "Боб")
|
||||
chat := r.createChat(alice, "Деградация", alice.ID, bob.ID)
|
||||
|
||||
var saved []string
|
||||
for i := 0; i < quota; i++ {
|
||||
status, msg := r.send(alice, chat.ID, fmt.Sprintf("saved-%02d", i))
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("send %d: expected 201, got %d", i, status)
|
||||
}
|
||||
saved = append(saved, msg.ID)
|
||||
}
|
||||
|
||||
status, _, body := r.sendRaw(alice, chat.ID, mustJSON(dto.CreateMessageRequest{Text: "overflow"}))
|
||||
if status != http.StatusServiceUnavailable {
|
||||
t.Fatalf("expected 503 after quota exhausted, got %d body=%s", status, string(body))
|
||||
}
|
||||
if code := extractErrorCode(t, body); code != CodeUnavailable {
|
||||
t.Fatalf("expected code %q, got %q", CodeUnavailable, code)
|
||||
}
|
||||
|
||||
collected, _ := r.listMessages(alice, chat.ID, 100)
|
||||
if len(collected) != quota {
|
||||
t.Fatalf("после 503 история чата %d, ожидалось %d", len(collected), quota)
|
||||
}
|
||||
gotIDs := make(map[string]struct{}, len(collected))
|
||||
for _, m := range collected {
|
||||
gotIDs[m.ID] = struct{}{}
|
||||
}
|
||||
for _, id := range saved {
|
||||
if _, ok := gotIDs[id]; !ok {
|
||||
t.Fatalf("подтверждённое сообщение %s исчезло из истории", id)
|
||||
}
|
||||
}
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
s, _, _ := r.sendRaw(alice, chat.ID, mustJSON(dto.CreateMessageRequest{Text: "still-over"}))
|
||||
if s != http.StatusServiceUnavailable {
|
||||
t.Fatalf("повторный 503 ожидался, получен %d", s)
|
||||
}
|
||||
}
|
||||
|
||||
req, _ := http.NewRequest(http.MethodGet, r.server.URL+"/health/live", nil)
|
||||
resp, err := r.client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("health/live: %v", err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("health/live под перегрузкой: ожидали 200, получили %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimits_NoSilentLoss(t *testing.T) {
|
||||
const quota = 20
|
||||
r := newTestRigWithLimits(t, config.Limits{
|
||||
MaxBodyBytes: 1 << 16,
|
||||
MaxInFlight: 8,
|
||||
MaxMessagesGlobal: quota,
|
||||
MaxHeapBytes: 1 << 40,
|
||||
})
|
||||
alice := r.createUser("g_"+randomSuffix(), "Алиса")
|
||||
bob := r.createUser("h_"+randomSuffix(), "Боб")
|
||||
chat := r.createChat(alice, "Деградация", alice.ID, bob.ID)
|
||||
|
||||
const attempts = quota * 3
|
||||
acked := make([]string, 0, quota)
|
||||
codes := make(map[int]int)
|
||||
for i := 0; i < attempts; i++ {
|
||||
status, msg, _ := r.sendRaw(alice, chat.ID, mustJSON(dto.CreateMessageRequest{Text: fmt.Sprintf("loss-%03d", i)}))
|
||||
codes[status]++
|
||||
if status == http.StatusCreated {
|
||||
acked = append(acked, msg.ID)
|
||||
}
|
||||
}
|
||||
if len(acked) != quota {
|
||||
t.Fatalf("ожидалось ровно %d подтверждённых записей, получено %d; codes=%v", quota, len(acked), codes)
|
||||
}
|
||||
if codes[http.StatusServiceUnavailable] == 0 {
|
||||
t.Fatalf("ни одного 503 — лимит не сработал")
|
||||
}
|
||||
|
||||
collected, _ := r.listMessages(alice, chat.ID, 100)
|
||||
gotIDs := make(map[string]struct{}, len(collected))
|
||||
for _, m := range collected {
|
||||
gotIDs[m.ID] = struct{}{}
|
||||
}
|
||||
for _, id := range acked {
|
||||
if _, ok := gotIDs[id]; !ok {
|
||||
t.Fatalf("подтверждённое сообщение %s исчезло из истории — незаметная потеря данных", id)
|
||||
}
|
||||
}
|
||||
if len(collected) != len(acked) {
|
||||
t.Fatalf("история чата содержит %d сообщений, подтверждено %d — скрытое отличие",
|
||||
len(collected), len(acked))
|
||||
}
|
||||
t.Logf("codes=%v acked=%d history=%d", codes, len(acked), len(collected))
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
|
||||
)
|
||||
|
||||
const headerIdempotencyKey = "Idempotency-Key"
|
||||
|
||||
type messagesHandler struct {
|
||||
messages service.MessagesService
|
||||
}
|
||||
|
||||
func (h *messagesHandler) send(c echo.Context) error {
|
||||
callerID := c.Get(middleware.AuthUserIDKey).(string)
|
||||
chatID := c.Param("chat_id")
|
||||
|
||||
var req dto.CreateMessageRequest
|
||||
if err := decodeJSON(c.Request().Body, &req); err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
|
||||
msg, err := h.messages.Send(c.Request().Context(), callerID, chatID, c.Request().Header.Get(headerIdempotencyKey), req.Text)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusCreated, toMessageResponse(msg))
|
||||
}
|
||||
|
||||
func (h *messagesHandler) list(c echo.Context) error {
|
||||
callerID := c.Get(middleware.AuthUserIDKey).(string)
|
||||
chatID := c.Param("chat_id")
|
||||
|
||||
limit, cursor, err := parsePageParams(c)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
|
||||
page, err := h.messages.List(c.Request().Context(), callerID, chatID, cursor, limit)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, toMessagesPage(page))
|
||||
}
|
||||
|
||||
func toMessageResponse(m domain.Message) dto.MessageResponse {
|
||||
return dto.MessageResponse{
|
||||
ID: m.ID,
|
||||
ChatID: m.ChatID,
|
||||
SenderID: m.AuthorID,
|
||||
Text: m.Text,
|
||||
CreatedAt: dto.NewTimestamp(m.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func toMessagesPage(p domain.Page[domain.Message]) dto.MessagesPageResponse {
|
||||
items := make([]dto.MessageResponse, 0, len(p.Items))
|
||||
for _, m := range p.Items {
|
||||
items = append(items, toMessageResponse(m))
|
||||
}
|
||||
var next *string
|
||||
if p.NextCursor != "" {
|
||||
s := p.NextCursor
|
||||
next = &s
|
||||
}
|
||||
return dto.MessagesPageResponse{Items: items, NextCursor: next}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
const AuthTokenKey = "auth_token"
|
||||
|
||||
const (
|
||||
BearerChallenge = `Bearer realm="messenger"`
|
||||
BasicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
)
|
||||
|
||||
type Authenticator interface {
|
||||
Authenticate(ctx context.Context, token string) (userID string, err error)
|
||||
}
|
||||
|
||||
|
||||
func Bearer(auth Authenticator) echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
tok, ok := BearerToken(c.Request().Header.Get(echo.HeaderAuthorization))
|
||||
if !ok {
|
||||
return unauthorized(c, BearerChallenge, "Bearer token required")
|
||||
}
|
||||
userID, err := auth.Authenticate(c.Request().Context(), tok)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrUnauthorized) {
|
||||
return unauthorized(c, BearerChallenge, "Invalid or expired session")
|
||||
}
|
||||
return err
|
||||
}
|
||||
c.Set(AuthUserIDKey, userID)
|
||||
c.Set(AuthTokenKey, tok)
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BearerToken(header string) (string, bool) {
|
||||
scheme, tok, found := strings.Cut(header, " ")
|
||||
if !found || !strings.EqualFold(scheme, "Bearer") {
|
||||
return "", false
|
||||
}
|
||||
tok = strings.TrimSpace(tok)
|
||||
return tok, tok != ""
|
||||
}
|
||||
|
||||
func unauthorized(c echo.Context, challenge, msg string) error {
|
||||
c.Response().Header().Set(echo.HeaderWWWAuthenticate, challenge)
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, msg)
|
||||
}
|
||||
|
||||
func Unauthorized(c echo.Context, challenge, msg string) error {
|
||||
return unauthorized(c, challenge, msg)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"mime"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
func ContentType() echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
if !methodHasBody(c.Request().Method) {
|
||||
return next(c)
|
||||
}
|
||||
if !isApplicationJSON(c.Request().Header.Get(echo.HeaderContentType)) {
|
||||
return echo.NewHTTPError(http.StatusUnsupportedMediaType, "Expected Content-Type: application/json")
|
||||
}
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func methodHasBody(method string) bool {
|
||||
switch method {
|
||||
case http.MethodPost, http.MethodPut, http.MethodPatch:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isApplicationJSON(ct string) bool {
|
||||
if ct == "" {
|
||||
return false
|
||||
}
|
||||
mediatype, _, err := mime.ParseMediaType(ct)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return strings.EqualFold(mediatype, "application/json")
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package middleware
|
||||
|
||||
import "github.com/labstack/echo/v4"
|
||||
|
||||
const HeaderInstanceID = "X-Instance-Id"
|
||||
|
||||
func InstanceID(id string) echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
c.Response().Header().Set(HeaderInstanceID, id)
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"io"
|
||||
"runtime"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
func BodyLimit(maxBytes int64) echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
if !methodHasBody(c.Request().Method) {
|
||||
return next(c)
|
||||
}
|
||||
if cl := c.Request().ContentLength; cl > maxBytes {
|
||||
return domain.ErrPayloadTooLarge
|
||||
}
|
||||
c.Request().Body = &limitedBody{
|
||||
raw: c.Request().Body,
|
||||
maxLeft: maxBytes,
|
||||
}
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type limitedBody struct {
|
||||
raw io.ReadCloser
|
||||
maxLeft int64
|
||||
}
|
||||
|
||||
func (b *limitedBody) Read(p []byte) (int, error) {
|
||||
if int64(len(p)) > b.maxLeft+1 {
|
||||
p = p[:b.maxLeft+1]
|
||||
}
|
||||
n, err := b.raw.Read(p)
|
||||
b.maxLeft -= int64(n)
|
||||
if b.maxLeft < 0 {
|
||||
return n, domain.ErrPayloadTooLarge
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (b *limitedBody) Close() error {
|
||||
return b.raw.Close()
|
||||
}
|
||||
|
||||
func InFlight(maxInFlight int) echo.MiddlewareFunc {
|
||||
sem := make(chan struct{}, maxInFlight)
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
if isHealthPath(c.Request().URL.Path) {
|
||||
return next(c)
|
||||
}
|
||||
select {
|
||||
case sem <- struct{}{}:
|
||||
defer func() { <-sem }()
|
||||
return next(c)
|
||||
default:
|
||||
return domain.ErrRateLimited
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func MemoryGuard(maxHeapBytes uint64, poll time.Duration) echo.MiddlewareFunc {
|
||||
var sample atomic.Uint64
|
||||
|
||||
readOnce := func() {
|
||||
var m runtime.MemStats
|
||||
runtime.ReadMemStats(&m)
|
||||
if m.HeapInuse > maxHeapBytes {
|
||||
runtime.GC()
|
||||
runtime.ReadMemStats(&m)
|
||||
}
|
||||
sample.Store(m.HeapInuse)
|
||||
}
|
||||
readOnce()
|
||||
|
||||
if poll > 0 {
|
||||
go func() {
|
||||
t := time.NewTicker(poll)
|
||||
defer t.Stop()
|
||||
for range t.C {
|
||||
readOnce()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
if !methodHasBody(c.Request().Method) || isHealthPath(c.Request().URL.Path) {
|
||||
return next(c)
|
||||
}
|
||||
if sample.Load() > maxHeapBytes {
|
||||
return domain.ErrUnavailable
|
||||
}
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func isHealthPath(path string) bool {
|
||||
return path == "/health/live" || path == "/health/ready"
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
const AuthUserIDKey = "caller_id"
|
||||
|
||||
func Logger(logger *slog.Logger) echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
start := time.Now()
|
||||
if err := next(c); err != nil {
|
||||
c.Error(err)
|
||||
}
|
||||
status := c.Response().Status
|
||||
|
||||
rid, _ := c.Get(RequestIDKey).(string)
|
||||
uid, _ := c.Get(AuthUserIDKey).(string)
|
||||
|
||||
attrs := []slog.Attr{
|
||||
slog.String("request_id", rid),
|
||||
slog.String("method", c.Request().Method),
|
||||
slog.String("path", c.Request().URL.Path),
|
||||
slog.Int("status", status),
|
||||
slog.Int64("duration_ms", time.Since(start).Milliseconds()),
|
||||
slog.String("remote_ip", c.RealIP()),
|
||||
}
|
||||
if uid != "" {
|
||||
attrs = append(attrs, slog.String("user_id", uid))
|
||||
}
|
||||
|
||||
level := slog.LevelInfo
|
||||
switch {
|
||||
case status >= 500:
|
||||
level = slog.LevelError
|
||||
case status >= 400:
|
||||
level = slog.LevelWarn
|
||||
}
|
||||
logger.LogAttrs(c.Request().Context(), level, "http request", attrs...)
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
func Recover(logger *slog.Logger) echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) (err error) {
|
||||
defer func() {
|
||||
r := recover()
|
||||
if r == nil {
|
||||
return
|
||||
}
|
||||
rid, _ := c.Get(RequestIDKey).(string)
|
||||
logger.Error("panic recovered",
|
||||
slog.String("request_id", rid),
|
||||
slog.String("method", c.Request().Method),
|
||||
slog.String("path", c.Request().URL.Path),
|
||||
slog.Any("panic", r),
|
||||
slog.String("stack", string(debug.Stack())),
|
||||
)
|
||||
err = echo.NewHTTPError(http.StatusInternalServerError, "Internal server error")
|
||||
}()
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
const RequestIDKey = "request_id"
|
||||
|
||||
func RequestID() echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
rid := c.Request().Header.Get(echo.HeaderXRequestID)
|
||||
if rid == "" {
|
||||
rid = uuid.NewString()
|
||||
}
|
||||
c.Response().Header().Set(echo.HeaderXRequestID, rid)
|
||||
c.Set(RequestIDKey, rid)
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPagination_MultiPageWalk(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
alice, bob, _, chat := bootstrap(r)
|
||||
|
||||
const total = 7
|
||||
var sentIDs []string
|
||||
for i := 0; i < total; i++ {
|
||||
actor := alice
|
||||
if i%2 == 1 {
|
||||
actor = bob
|
||||
}
|
||||
_, msg := r.sendMessage(actor, chat.ID, fmt.Sprintf("page-%02d", i))
|
||||
if msg.ID == "" {
|
||||
t.Fatalf("send message %d failed", i)
|
||||
}
|
||||
sentIDs = append(sentIDs, msg.ID)
|
||||
}
|
||||
|
||||
history, pages := r.listMessages(alice, chat.ID, 3)
|
||||
if pages != 3 {
|
||||
t.Fatalf("ожидалось 3 страницы (3+3+1), получено %d", pages)
|
||||
}
|
||||
if len(history) != total {
|
||||
t.Fatalf("собрано %d сообщений, ожидалось %d", len(history), total)
|
||||
}
|
||||
for i, m := range history {
|
||||
if m.ID != sentIDs[i] {
|
||||
t.Fatalf("позиция %d: ожидался %s, получен %s (повтор, пропуск или нарушен порядок)", i, sentIDs[i], m.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPagination_ExactPageAndEmptyChat(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
alice, _, _, chat := bootstrap(r)
|
||||
|
||||
history, pages := r.listMessages(alice, chat.ID, 5)
|
||||
if len(history) != 0 || pages != 1 {
|
||||
t.Fatalf("пустой чат: items=%d pages=%d", len(history), pages)
|
||||
}
|
||||
|
||||
for i := 0; i < 4; i++ {
|
||||
r.send(alice, chat.ID, fmt.Sprintf("m%d", i))
|
||||
}
|
||||
if _, pages := r.listMessages(alice, chat.ID, 4); pages != 1 {
|
||||
t.Fatalf("4 сообщения при limit=4: ожидалась 1 страница, получено %d", pages)
|
||||
}
|
||||
if _, pages := r.listMessages(alice, chat.ID, 2); pages != 2 {
|
||||
t.Fatalf("4 сообщения при limit=2: ожидалось 2 страницы, получено %d", pages)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPagination_CursorBoundToChat(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
alice, bob, _, chat := bootstrap(r)
|
||||
other := r.createChat(alice, "Другой", alice.ID, bob.ID)
|
||||
for i := 0; i < 3; i++ {
|
||||
r.send(alice, chat.ID, fmt.Sprintf("m%d", i))
|
||||
}
|
||||
|
||||
resp := r.do(http.MethodGet, "/api/v1/chats/"+chat.ID+"/messages?limit=1", alice.ID, nil, nil)
|
||||
expectStatus(t, resp, http.StatusOK)
|
||||
var page struct {
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
readJSON(t, resp, &page)
|
||||
if page.NextCursor == nil {
|
||||
t.Fatal("ожидался next_cursor")
|
||||
}
|
||||
|
||||
for _, path := range []string{
|
||||
"/api/v1/chats/" + other.ID + "/messages?cursor=" + url.QueryEscape(*page.NextCursor),
|
||||
"/api/v1/chats?cursor=" + url.QueryEscape(*page.NextCursor),
|
||||
"/api/v1/chats/" + chat.ID + "/messages?cursor=not-a-cursor",
|
||||
} {
|
||||
resp := r.do(http.MethodGet, path, alice.ID, nil, nil)
|
||||
expectStatus(t, resp, http.StatusBadRequest)
|
||||
resp.Body.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func TestPagination_IncompleteCursor(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
alice, _, _, chat := bootstrap(r)
|
||||
r.send(alice, chat.ID, "m0")
|
||||
|
||||
enc := func(s string) string { return base64.RawURLEncoding.EncodeToString([]byte(s)) }
|
||||
msgScope := `"s":"chat:` + chat.ID + `"`
|
||||
chatsScope := `"s":"chats:` + alice.ID + `"`
|
||||
ts := `"t":"2026-01-01T00:00:00Z"`
|
||||
id := `"i":"` + chat.ID + `"`
|
||||
|
||||
cases := map[string]string{
|
||||
"только scope": enc(`{` + msgScope + `}`),
|
||||
"без i": enc(`{` + ts + `,` + msgScope + `}`),
|
||||
"без t": enc(`{` + id + `,` + msgScope + `}`),
|
||||
"i не UUID": enc(`{` + ts + `,"i":"zzz",` + msgScope + `}`),
|
||||
"нулевое t": enc(`{"t":"0001-01-01T00:00:00Z",` + id + `,` + msgScope + `}`),
|
||||
"лишнее поле": enc(`{` + ts + `,` + id + `,` + msgScope + `,"x":1}`),
|
||||
"данные после объекта": enc(`{` + ts + `,` + id + `,` + msgScope + `}}`),
|
||||
"base64 с паддингом": base64.URLEncoding.EncodeToString([]byte(`{` + ts + `,` + id + `,` + msgScope + `}`)),
|
||||
"пустой объект": enc(`{}`),
|
||||
"null": enc(`null`),
|
||||
}
|
||||
for name, cur := range cases {
|
||||
resp := r.do(http.MethodGet, "/api/v1/chats/"+chat.ID+"/messages?cursor="+url.QueryEscape(cur), alice.ID, nil, nil)
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Errorf("messages, %s: ожидался 400, получен %d", name, resp.StatusCode)
|
||||
}
|
||||
resp.Body.Close()
|
||||
}
|
||||
|
||||
resp := r.do(http.MethodGet, "/api/v1/chats?cursor="+url.QueryEscape(enc(`{`+chatsScope+`}`)), alice.ID, nil, nil)
|
||||
expectStatus(t, resp, http.StatusBadRequest)
|
||||
resp.Body.Close()
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
|
||||
)
|
||||
|
||||
func registerRoutes(e *echo.Echo, d Deps, isReady func() bool) {
|
||||
e.GET("/health/live", healthLive)
|
||||
e.GET("/health/ready", healthReady(isReady))
|
||||
|
||||
usersH := &usersHandler{users: d.Users}
|
||||
chatsH := &chatsHandler{chats: d.Chats}
|
||||
messagesH := &messagesHandler{messages: d.Messages}
|
||||
authH := &authHandler{auth: d.Auth}
|
||||
|
||||
auth := middleware.Bearer(d.Auth)
|
||||
|
||||
jsonBody := middleware.ContentType()
|
||||
|
||||
v1 := e.Group("/api/v1")
|
||||
v1.POST("/users", usersH.create, jsonBody)
|
||||
v1.POST("/auth/sessions", authH.createSession)
|
||||
v1.DELETE("/auth/sessions/current", authH.revokeSession, auth)
|
||||
v1.GET("/users/me", usersH.me, auth)
|
||||
v1.POST("/chats", chatsH.create, auth, jsonBody)
|
||||
v1.GET("/chats", chatsH.list, auth)
|
||||
v1.GET("/chats/:chat_id", chatsH.get, auth)
|
||||
v1.POST("/chats/:chat_id/messages", messagesH.send, auth, jsonBody)
|
||||
v1.GET("/chats/:chat_id/messages", messagesH.list, auth)
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
nethttp "net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
)
|
||||
|
||||
type Deps struct {
|
||||
Config *config.Config
|
||||
Logger *slog.Logger
|
||||
Store store.Store
|
||||
Auth service.AuthService
|
||||
Users service.UsersService
|
||||
Chats service.ChatsService
|
||||
Messages service.MessagesService
|
||||
|
||||
Ready func(ctx context.Context) error
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
e *echo.Echo
|
||||
cfg config.HTTP
|
||||
logger *slog.Logger
|
||||
shutting atomic.Bool
|
||||
ready func(ctx context.Context) error
|
||||
}
|
||||
|
||||
func NewServer(d Deps) *Server {
|
||||
s := &Server{
|
||||
e: echo.New(),
|
||||
cfg: d.Config.HTTP,
|
||||
logger: d.Logger,
|
||||
ready: d.Ready,
|
||||
}
|
||||
|
||||
s.e.HideBanner = true
|
||||
s.e.HidePort = true
|
||||
s.e.HTTPErrorHandler = s.httpErrorHandler
|
||||
|
||||
s.e.Server.ReadTimeout = time.Duration(s.cfg.ReadTimeoutMs) * time.Millisecond
|
||||
s.e.Server.WriteTimeout = time.Duration(s.cfg.WriteTimeoutMs) * time.Millisecond
|
||||
s.e.Server.IdleTimeout = time.Duration(s.cfg.IdleTimeoutMs) * time.Millisecond
|
||||
|
||||
s.e.Use(middleware.InstanceID(d.Config.InstanceID))
|
||||
s.e.Use(middleware.Recover(d.Logger))
|
||||
s.e.Use(middleware.RequestID())
|
||||
s.e.Use(middleware.Logger(d.Logger))
|
||||
s.e.Use(middleware.InFlight(d.Config.Limits.MaxInFlight))
|
||||
s.e.Use(middleware.BodyLimit(d.Config.Limits.MaxBodyBytes))
|
||||
s.e.Use(middleware.MemoryGuard(d.Config.Limits.MaxHeapBytes, 100*time.Millisecond))
|
||||
|
||||
registerRoutes(s.e, d, s.IsReady)
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Server) Start() error {
|
||||
s.logger.Info("http server starting", slog.String("addr", s.cfg.Addr))
|
||||
err := s.e.Start(s.cfg.Addr)
|
||||
if errors.Is(err, nethttp.ErrServerClosed) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Drain переводит readiness в 503 и ждёт d, продолжая обслуживать запросы: за это время
|
||||
// балансировщик выводит реплику, и новые запросы не попадают на закрытый listener.
|
||||
func (s *Server) Drain(d time.Duration) {
|
||||
s.shutting.Store(true)
|
||||
s.logger.Info("http server draining", slog.Duration("for", d))
|
||||
time.Sleep(d)
|
||||
}
|
||||
|
||||
func (s *Server) Shutdown(ctx context.Context) error {
|
||||
s.shutting.Store(true)
|
||||
s.logger.Info("http server shutting down")
|
||||
return s.e.Shutdown(ctx)
|
||||
}
|
||||
|
||||
func (s *Server) IsReady() bool {
|
||||
if s.shutting.Load() {
|
||||
return false
|
||||
}
|
||||
if s.ready == nil {
|
||||
return true
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), readyTimeout)
|
||||
defer cancel()
|
||||
return s.ready(ctx) == nil
|
||||
}
|
||||
|
||||
const readyTimeout = time.Second
|
||||
|
||||
func (s *Server) Handler() nethttp.Handler {
|
||||
return s.e
|
||||
}
|
||||
|
||||
func (s *Server) httpErrorHandler(err error, c echo.Context) {
|
||||
if c.Response().Committed {
|
||||
return
|
||||
}
|
||||
|
||||
var httpErr *echo.HTTPError
|
||||
if errors.As(err, &httpErr) {
|
||||
code := codeFromStatus(httpErr.Code)
|
||||
msg, _ := httpErr.Message.(string)
|
||||
if msg == "" || msg == nethttp.StatusText(httpErr.Code) {
|
||||
msg = messageFor(httpErr.Code, code)
|
||||
}
|
||||
_ = c.JSON(httpErr.Code, errorBody{
|
||||
Error: errorPayload{
|
||||
Code: code,
|
||||
Message: msg,
|
||||
RequestID: c.Response().Header().Get(echo.HeaderXRequestID),
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
_ = WriteError(c, err)
|
||||
}
|
||||
|
||||
var codesByStatus = map[int]string{
|
||||
nethttp.StatusBadRequest: CodeInvalidRequest,
|
||||
nethttp.StatusUnauthorized: CodeUnauthorized,
|
||||
nethttp.StatusNotFound: CodeNotFound,
|
||||
nethttp.StatusMethodNotAllowed: CodeInvalidRequest,
|
||||
nethttp.StatusConflict: CodeConflict,
|
||||
nethttp.StatusRequestEntityTooLarge: CodePayloadTooLarge,
|
||||
nethttp.StatusUnsupportedMediaType: CodeUnsupportedMedia,
|
||||
nethttp.StatusTooManyRequests: CodeRateLimited,
|
||||
nethttp.StatusServiceUnavailable: CodeUnavailable,
|
||||
}
|
||||
|
||||
func codeFromStatus(status int) string {
|
||||
if c, ok := codesByStatus[status]; ok {
|
||||
return c
|
||||
}
|
||||
return CodeInternalError
|
||||
}
|
||||
|
||||
var messagesByStatus = map[int]string{
|
||||
nethttp.StatusMethodNotAllowed: "Method not allowed",
|
||||
}
|
||||
|
||||
func messageFor(status int, code string) string {
|
||||
if m, ok := messagesByStatus[status]; ok {
|
||||
return m
|
||||
}
|
||||
return defaultMessages[code]
|
||||
}
|
||||
|
||||
var defaultMessages = map[string]string{
|
||||
CodeInvalidRequest: "Invalid request",
|
||||
CodeUnauthorized: "Identification required",
|
||||
CodeNotFound: "Object not found",
|
||||
CodeConflict: "Conflict",
|
||||
CodePayloadTooLarge: "Request body too large",
|
||||
CodeUnsupportedMedia: "Unsupported Content-Type",
|
||||
CodeRateLimited: "Too many requests",
|
||||
CodeUnavailable: "Service unavailable",
|
||||
CodeInternalError: "Internal server error",
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
type usersHandler struct {
|
||||
users service.UsersService
|
||||
}
|
||||
|
||||
func (h *usersHandler) create(c echo.Context) error {
|
||||
var req dto.CreateUserRequest
|
||||
if err := decodeJSON(c.Request().Body, &req); err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
|
||||
user, err := h.users.Register(c.Request().Context(), req.Username, req.DisplayName, req.Password)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusCreated, toUserResponse(user))
|
||||
}
|
||||
|
||||
func (h *usersHandler) me(c echo.Context) error {
|
||||
callerID := c.Get(middleware.AuthUserIDKey).(string)
|
||||
user, err := h.users.Me(c.Request().Context(), callerID)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, toUserResponse(user))
|
||||
}
|
||||
|
||||
func toUserResponse(u domain.User) dto.UserResponse {
|
||||
return dto.UserResponse{
|
||||
ID: u.ID,
|
||||
Username: u.Username,
|
||||
DisplayName: u.DisplayName,
|
||||
CreatedAt: dto.NewTimestamp(u.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func decodeJSON(body io.Reader, dst any) error {
|
||||
data, err := io.ReadAll(body)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrPayloadTooLarge) {
|
||||
return err
|
||||
}
|
||||
return &validate.Error{Field: "body", Reason: "cannot read body"}
|
||||
}
|
||||
if !utf8.Valid(data) {
|
||||
return &validate.Error{Field: "body", Reason: "invalid UTF-8"}
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(data))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
return &validate.Error{Field: "body", Reason: jsonErrorReason(err)}
|
||||
}
|
||||
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
|
||||
return &validate.Error{Field: "body", Reason: "unexpected data after JSON object"}
|
||||
}
|
||||
return checkExactKeys(data, dst)
|
||||
}
|
||||
|
||||
func checkExactKeys(data []byte, dst any) error {
|
||||
var obj map[string]json.RawMessage
|
||||
if err := json.Unmarshal(data, &obj); err != nil {
|
||||
return nil
|
||||
}
|
||||
allowed := make(map[string]struct{})
|
||||
t := reflect.TypeOf(dst).Elem()
|
||||
for i := 0; i < t.NumField(); i++ {
|
||||
name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",")
|
||||
allowed[name] = struct{}{}
|
||||
}
|
||||
for key := range obj {
|
||||
if _, ok := allowed[key]; !ok {
|
||||
return &validate.Error{Field: "body", Reason: fmt.Sprintf("unknown field %q", key)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func jsonErrorReason(err error) string {
|
||||
if errors.Is(err, io.EOF) {
|
||||
return "empty body"
|
||||
}
|
||||
var typeErr *json.UnmarshalTypeError
|
||||
if errors.As(err, &typeErr) {
|
||||
if typeErr.Field == "" {
|
||||
return "expected a JSON object"
|
||||
}
|
||||
return fmt.Sprintf("field %q: invalid type", typeErr.Field)
|
||||
}
|
||||
if name, ok := strings.CutPrefix(err.Error(), "json: unknown field "); ok {
|
||||
return "unknown field " + name
|
||||
}
|
||||
return "invalid JSON"
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
|
||||
)
|
||||
|
||||
func TestValidation_InvalidJSON(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
alice, _, _, chat := bootstrap(r)
|
||||
path := "/api/v1/chats/" + chat.ID + "/messages"
|
||||
|
||||
bad := [][]byte{
|
||||
[]byte(`{"text":`),
|
||||
[]byte(`not json at all`),
|
||||
[]byte(`{"text": 123,}`),
|
||||
[]byte(``),
|
||||
[]byte(`{"text": "ok"}{"text":"bonus"}`),
|
||||
[]byte(`{"text": "ok"}}`),
|
||||
[]byte(`{"text": "ok"}]`),
|
||||
[]byte(`{"text": "ok"} }`),
|
||||
[]byte(`{"text": "ok"} x`),
|
||||
[]byte("{\"text\":\"\xff\xfe bad utf8\"}"),
|
||||
}
|
||||
for _, payload := range bad {
|
||||
resp := r.do(http.MethodPost, path, alice.ID,
|
||||
map[string]string{"Content-Type": "application/json"},
|
||||
bytes.NewReader(payload))
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
data, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
t.Fatalf("payload %q: expected 400, got %d; body=%s", payload, resp.StatusCode, string(data))
|
||||
}
|
||||
e := readError(t, resp)
|
||||
if e.Error.Code != CodeInvalidRequest {
|
||||
t.Fatalf("payload %q: expected code %q, got %q", payload, CodeInvalidRequest, e.Error.Code)
|
||||
}
|
||||
if e.Error.RequestID == "" {
|
||||
t.Fatalf("payload %q: missing request_id in body", payload)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidation_InvalidUTF8(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
alice, bob, _, _ := bootstrap(r)
|
||||
|
||||
cases := []struct {
|
||||
path, actor string
|
||||
payload []byte
|
||||
}{
|
||||
{"/api/v1/users", "", []byte("{\"username\":\"u_" + randomSuffix()[:8] + "\",\"display_name\":\"\xc3\x28\"}")},
|
||||
{"/api/v1/chats", alice.ID, []byte("{\"title\":\"\xe2\x82\",\"member_ids\":[\"" + alice.ID + "\",\"" + bob.ID + "\"]}")},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
resp := r.do(http.MethodPost, tc.path, tc.actor,
|
||||
map[string]string{"Content-Type": "application/json"},
|
||||
bytes.NewReader(tc.payload))
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
data, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
t.Fatalf("%s %q: expected 400, got %d; body=%s", tc.path, tc.payload, resp.StatusCode, string(data))
|
||||
}
|
||||
e := readError(t, resp)
|
||||
if e.Error.Code != CodeInvalidRequest {
|
||||
t.Fatalf("%s: expected code %q, got %q", tc.path, CodeInvalidRequest, e.Error.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidation_JSONKeysAreCaseSensitive(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
resp := r.do(http.MethodPost, "/api/v1/users", "",
|
||||
map[string]string{"Content-Type": "application/json"},
|
||||
strings.NewReader(`{"USERNAME":"case_bob","Display_Name":"B"}`))
|
||||
expectStatus(t, resp, http.StatusBadRequest)
|
||||
resp.Body.Close()
|
||||
}
|
||||
|
||||
func TestValidation_ErrorMessages(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
alice, bob, _, chat := bootstrap(r)
|
||||
msgs := "/api/v1/chats/" + chat.ID + "/messages"
|
||||
|
||||
cases := []struct {
|
||||
method, path, actor, body, message string
|
||||
}{
|
||||
{http.MethodPost, "/api/v1/users", "", `{"username":"ab","display_name":"x"}`,
|
||||
"username: must match [a-z0-9_]{3,32}"},
|
||||
{http.MethodPost, "/api/v1/users", "", `{"username":"abc_` + randomSuffix()[:6] + `","display_name":" "}`,
|
||||
"display_name: must not be empty or whitespace only"},
|
||||
{http.MethodPost, "/api/v1/users", "", `{"username":123,"display_name":"x"}`,
|
||||
`body: field "username": invalid type`},
|
||||
{http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x","password":"p"}`,
|
||||
"password: length must be in [12, 128] code points"},
|
||||
{http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x"}`,
|
||||
"password: must not be empty or whitespace only"},
|
||||
{http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x","password":"` + strings.Repeat("я", 129) + `"}`,
|
||||
"password: length must be in [12, 128] code points"},
|
||||
{http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x","password":"long-enough-pw","password_hash":"h"}`,
|
||||
`body: unknown field "password_hash"`},
|
||||
{http.MethodPost, "/api/v1/users", "", `{"username":`, "body: invalid JSON"},
|
||||
{http.MethodPost, "/api/v1/users", "", ``, "body: empty body"},
|
||||
{http.MethodPost, "/api/v1/users", "", `[]`, "body: expected a JSON object"},
|
||||
{http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x"} {}`, "body: unexpected data after JSON object"},
|
||||
{http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x"}}`, "body: unexpected data after JSON object"},
|
||||
{http.MethodPost, "/api/v1/users", "", "{\"username\":\"abc\",\"display_name\":\"\xff\"}",
|
||||
"body: invalid UTF-8"},
|
||||
{http.MethodPost, "/api/v1/chats", alice.ID, `{"title":"t","member_ids":["` + bob.ID + `"]}`,
|
||||
"member_ids: must contain caller"},
|
||||
{http.MethodPost, "/api/v1/chats", alice.ID, `{"title":"t","member_ids":["` + alice.ID + `","x"]}`,
|
||||
"member_ids[1]: must be a valid UUID"},
|
||||
{http.MethodPost, msgs, alice.ID, `{"text":" "}`, "text: must not be empty or whitespace only"},
|
||||
{http.MethodGet, msgs + "?limit=abc", alice.ID, "", "limit: must be an integer"},
|
||||
{http.MethodGet, msgs + "?limit=0", alice.ID, "", "limit: must be in [1, 100]"},
|
||||
{http.MethodGet, msgs + "?limit=", alice.ID, "", "limit: must be an integer"},
|
||||
{http.MethodGet, msgs + "?cursor=", alice.ID, "", "cursor: must not be empty"},
|
||||
{http.MethodGet, msgs + "?limit=10&cursor=", alice.ID, "", "cursor: must not be empty"},
|
||||
{http.MethodGet, "/api/v1/chats?limit=", alice.ID, "", "limit: must be an integer"},
|
||||
{http.MethodGet, "/api/v1/chats?cursor=", alice.ID, "", "cursor: must not be empty"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
headers := map[string]string{}
|
||||
var body io.Reader
|
||||
if tc.method == http.MethodPost {
|
||||
headers["Content-Type"] = "application/json"
|
||||
body = bytes.NewReader([]byte(tc.body))
|
||||
}
|
||||
resp := r.do(tc.method, tc.path, tc.actor, headers, body)
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
data, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
t.Fatalf("%s %s %q: expected 400, got %d; body=%s", tc.method, tc.path, tc.body, resp.StatusCode, string(data))
|
||||
}
|
||||
e := readError(t, resp)
|
||||
if e.Error.Message != tc.message {
|
||||
t.Fatalf("%s %s %q:\n want %q\n got %q", tc.method, tc.path, tc.body, tc.message, e.Error.Message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidation_EmptyMessage(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
alice, _, _, chat := bootstrap(r)
|
||||
path := "/api/v1/chats/" + chat.ID + "/messages"
|
||||
|
||||
for _, text := range []string{"", " ", "\n\t "} {
|
||||
resp := r.doJSON(http.MethodPost, path, alice.ID, dto.CreateMessageRequest{Text: text})
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
data, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
t.Fatalf("text %q: expected 400, got %d; body=%s", text, resp.StatusCode, string(data))
|
||||
}
|
||||
e := readError(t, resp)
|
||||
if e.Error.Code != CodeInvalidRequest {
|
||||
t.Fatalf("text %q: expected code %q, got %q", text, CodeInvalidRequest, e.Error.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidation_DuplicateUsername(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
username := "own_dup_" + randomSuffix()
|
||||
|
||||
first := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{
|
||||
Username: username,
|
||||
DisplayName: "Первый",
|
||||
Password: testPassword,
|
||||
})
|
||||
expectStatus(t, first, http.StatusCreated)
|
||||
first.Body.Close()
|
||||
|
||||
second := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{
|
||||
Username: username,
|
||||
DisplayName: "Второй",
|
||||
Password: testPassword,
|
||||
})
|
||||
if second.StatusCode != http.StatusConflict {
|
||||
data, _ := io.ReadAll(second.Body)
|
||||
second.Body.Close()
|
||||
t.Fatalf("second POST same username: expected 409, got %d; body=%s", second.StatusCode, string(data))
|
||||
}
|
||||
e := readError(t, second)
|
||||
if e.Error.Code != CodeConflict {
|
||||
t.Fatalf("expected code %q, got %q", CodeConflict, e.Error.Code)
|
||||
}
|
||||
|
||||
third := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{
|
||||
Username: username,
|
||||
DisplayName: "Первый",
|
||||
Password: testPassword,
|
||||
})
|
||||
if third.StatusCode != http.StatusConflict {
|
||||
data, _ := io.ReadAll(third.Body)
|
||||
third.Body.Close()
|
||||
t.Fatalf("third POST same username/display_name: expected 409, got %d; body=%s", third.StatusCode, string(data))
|
||||
}
|
||||
third.Body.Close()
|
||||
}
|
||||
|
||||
func TestValidation_UUIDForms(t *testing.T) {
|
||||
r := newTestRig(t)
|
||||
alice, bob, _, chat := bootstrap(r)
|
||||
upper := strings.ToUpper(alice.ID)
|
||||
|
||||
resp := r.do(http.MethodGet, "/api/v1/users/me", upper, nil, nil)
|
||||
expectStatus(t, resp, http.StatusOK)
|
||||
resp.Body.Close()
|
||||
resp = r.do(http.MethodGet, "/api/v1/chats/"+strings.ToUpper(chat.ID), alice.ID, nil, nil)
|
||||
expectStatus(t, resp, http.StatusOK)
|
||||
resp.Body.Close()
|
||||
|
||||
resp = r.do(http.MethodGet, "/api/v1/users/me", "{"+alice.ID+"}", nil, nil)
|
||||
expectStatus(t, resp, http.StatusUnauthorized)
|
||||
resp.Body.Close()
|
||||
resp = r.do(http.MethodGet, "/api/v1/chats/"+strings.ReplaceAll(chat.ID, "-", ""), alice.ID, nil, nil)
|
||||
expectStatus(t, resp, http.StatusBadRequest)
|
||||
resp.Body.Close()
|
||||
|
||||
resp = r.doJSON(http.MethodPost, "/api/v1/chats", alice.ID, map[string]any{
|
||||
"title": "dup", "member_ids": []string{alice.ID, upper, bob.ID},
|
||||
})
|
||||
expectStatus(t, resp, http.StatusBadRequest)
|
||||
resp.Body.Close()
|
||||
}
|
||||
Vendored
+478
@@ -0,0 +1,478 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"golang.org/x/sync/singleflight"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
ModeOff = "off"
|
||||
ModeNaive = "naive"
|
||||
ModeSafe = "safe"
|
||||
)
|
||||
|
||||
type Source interface {
|
||||
store.MessageStore
|
||||
IsMember(ctx context.Context, chatID, userID string) (bool, error)
|
||||
HistoryPage(ctx context.Context, chatID, cursor string, limit int) (domain.Page[domain.Message], error)
|
||||
}
|
||||
|
||||
// Outbox хранит долг инвалидации в источнике истины, чтобы он пережил
|
||||
// рестарт API. Без него отложенная инвалидация живёт только в памяти.
|
||||
type Outbox interface {
|
||||
AddPendingInvalidation(ctx context.Context, chatID string) (int64, error)
|
||||
PendingInvalidations(ctx context.Context) (map[string]int64, error)
|
||||
ResolvePendingInvalidation(ctx context.Context, chatID string, gen int64) error
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
Mode string
|
||||
Outbox Outbox
|
||||
PageTTL time.Duration
|
||||
LockTTL time.Duration
|
||||
FillDelay time.Duration
|
||||
Logger *slog.Logger
|
||||
}
|
||||
|
||||
var _ store.MessageStore = (*Messages)(nil)
|
||||
|
||||
// pendingEntry — несброшенная версия чата. seq меняется при каждом новом
|
||||
// сбое: повтор снимает запись, только если seq не изменился с его снимка.
|
||||
// gen — поколение строки в Outbox (0 — не записана).
|
||||
type pendingEntry struct {
|
||||
seq uint64
|
||||
gen int64
|
||||
}
|
||||
|
||||
type Messages struct {
|
||||
src Source
|
||||
rdb *redis.Client
|
||||
opt Options
|
||||
group singleflight.Group
|
||||
log *slog.Logger
|
||||
|
||||
downUntil atomic.Int64
|
||||
// loaded: долг инвалидации из Outbox прочитан. До этого любой чат может
|
||||
// иметь устаревшую версию, поэтому все чтения идут мимо кэша.
|
||||
loaded atomic.Bool
|
||||
|
||||
mu sync.Mutex
|
||||
pending map[string]pendingEntry
|
||||
seq uint64
|
||||
stop chan struct{}
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
const (
|
||||
memberTTL = 24 * time.Hour
|
||||
versionTTL = 24 * time.Hour
|
||||
breakerPause = time.Second
|
||||
retryInterval = 200 * time.Millisecond
|
||||
pollInterval = 5 * time.Millisecond
|
||||
defaultPageTTL = 30 * time.Second
|
||||
defaultLockTTL = 500 * time.Millisecond
|
||||
)
|
||||
|
||||
func New(src Source, rdb *redis.Client, opt Options) *Messages {
|
||||
if opt.PageTTL <= 0 {
|
||||
opt.PageTTL = defaultPageTTL
|
||||
}
|
||||
if opt.LockTTL <= 0 {
|
||||
opt.LockTTL = defaultLockTTL
|
||||
}
|
||||
if opt.Logger == nil {
|
||||
opt.Logger = slog.Default()
|
||||
}
|
||||
m := &Messages{
|
||||
src: src,
|
||||
rdb: rdb,
|
||||
opt: opt,
|
||||
log: opt.Logger,
|
||||
pending: make(map[string]pendingEntry),
|
||||
stop: make(chan struct{}),
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
m.loaded.Store(opt.Outbox == nil || opt.Mode != ModeSafe)
|
||||
go m.retryLoop()
|
||||
return m
|
||||
}
|
||||
|
||||
func Connect(cfg config.HistoryCache) (*redis.Client, error) {
|
||||
url := cfg.URL
|
||||
if cfg.URLFile != "" {
|
||||
b, err := os.ReadFile(cfg.URLFile)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cache: read HISTORY_CACHE_URL_FILE: %w", err)
|
||||
}
|
||||
url = strings.TrimSpace(string(b))
|
||||
}
|
||||
if url == "" {
|
||||
return nil, errors.New("cache: HISTORY_CACHE_URL_FILE or HISTORY_CACHE_URL is required unless HISTORY_CACHE=off")
|
||||
}
|
||||
opts, err := redis.ParseURL(url)
|
||||
if err != nil {
|
||||
return nil, errors.New("cache: invalid HISTORY_CACHE_URL")
|
||||
}
|
||||
timeout := time.Duration(cfg.TimeoutMs) * time.Millisecond
|
||||
opts.PoolSize = cfg.PoolSize
|
||||
opts.DialTimeout = timeout
|
||||
opts.ReadTimeout = timeout
|
||||
opts.WriteTimeout = timeout
|
||||
opts.PoolTimeout = timeout
|
||||
opts.MaxRetries = -1 // без повторов: промах кэша дешевле ожидания
|
||||
return redis.NewClient(opts), nil
|
||||
}
|
||||
|
||||
func (m *Messages) Close() {
|
||||
close(m.stop)
|
||||
<-m.done
|
||||
}
|
||||
|
||||
func (m *Messages) AddMessage(ctx context.Context, callerID, chatID, idempotencyKey, text string) (domain.Message, error) {
|
||||
msg, err := m.src.AddMessage(ctx, callerID, chatID, idempotencyKey, text)
|
||||
if err != nil {
|
||||
return msg, err
|
||||
}
|
||||
// Инвалидация нужна и при повторе: реплика, выполнившая COMMIT, могла упасть до
|
||||
// сброса кэша, и тогда ответ 201 на повтор — первое подтверждение этого сообщения.
|
||||
ictx := context.WithoutCancel(ctx)
|
||||
switch m.opt.Mode {
|
||||
case ModeNaive:
|
||||
m.naiveInvalidate(ictx, chatID)
|
||||
case ModeSafe:
|
||||
if err := m.rdb.Del(ictx, verKey(chatID)).Err(); err != nil {
|
||||
m.markDown(err)
|
||||
m.addPending(ictx, chatID)
|
||||
}
|
||||
}
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
func (m *Messages) ListMessages(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) {
|
||||
if m.opt.Mode == ModeOff || m.bypass(chatID) {
|
||||
return m.src.ListMessages(ctx, callerID, chatID, cursor, limit)
|
||||
}
|
||||
if err := m.checkMember(ctx, chatID, callerID); err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
if m.opt.Mode == ModeNaive {
|
||||
return m.naiveList(ctx, chatID, cursor, limit)
|
||||
}
|
||||
return m.safeList(ctx, chatID, cursor, limit)
|
||||
}
|
||||
|
||||
func (m *Messages) checkMember(ctx context.Context, chatID, userID string) error {
|
||||
key := "hc:member:" + chatID + ":" + userID
|
||||
if !m.isDown() {
|
||||
v, err := m.rdb.Get(ctx, key).Result()
|
||||
if err == nil && v == "1" {
|
||||
return nil
|
||||
}
|
||||
m.markDown(err)
|
||||
}
|
||||
ok, err := m.src.IsMember(ctx, chatID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
// Отрицательный ответ не кэшируем.
|
||||
return domain.ErrNotFound
|
||||
}
|
||||
if !m.isDown() {
|
||||
m.markDown(m.rdb.Set(ctx, key, "1", memberTTL).Err())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Messages) naiveList(ctx context.Context, chatID, cursor string, limit int) (domain.Page[domain.Message], error) {
|
||||
key := pageKey("hc:naive:"+chatID, cursor, limit)
|
||||
if page, ok := m.getPage(ctx, key); ok {
|
||||
return page, nil
|
||||
}
|
||||
page, err := m.src.HistoryPage(ctx, chatID, cursor, limit)
|
||||
if err != nil {
|
||||
return page, err
|
||||
}
|
||||
m.sleepFill(ctx)
|
||||
if b, err := encodePage(page); err == nil {
|
||||
setKey := "hc:naive:keys:" + chatID
|
||||
_, err := m.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
|
||||
p.Set(ctx, key, b, m.opt.PageTTL)
|
||||
p.SAdd(ctx, setKey, key)
|
||||
p.Expire(ctx, setKey, m.opt.PageTTL)
|
||||
return nil
|
||||
})
|
||||
m.markDown(err)
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (m *Messages) naiveInvalidate(ctx context.Context, chatID string) {
|
||||
setKey := "hc:naive:keys:" + chatID
|
||||
keys, err := m.rdb.SMembers(ctx, setKey).Result()
|
||||
if err != nil {
|
||||
m.markDown(err)
|
||||
return
|
||||
}
|
||||
m.markDown(m.rdb.Del(ctx, append(keys, setKey)...).Err())
|
||||
}
|
||||
|
||||
func (m *Messages) safeList(ctx context.Context, chatID, cursor string, limit int) (domain.Page[domain.Message], error) {
|
||||
ver, err := m.version(ctx, chatID)
|
||||
if err != nil {
|
||||
m.markDown(err)
|
||||
return m.src.HistoryPage(ctx, chatID, cursor, limit)
|
||||
}
|
||||
key := pageKey("hc:page:"+chatID+":"+ver, cursor, limit)
|
||||
if page, ok := m.getPage(ctx, key); ok {
|
||||
return page, nil
|
||||
}
|
||||
v, err, _ := m.group.Do(key, func() (any, error) {
|
||||
return m.fill(context.WithoutCancel(ctx), key, chatID, cursor, limit)
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
return v.(domain.Page[domain.Message]), nil
|
||||
}
|
||||
|
||||
func (m *Messages) version(ctx context.Context, chatID string) (string, error) {
|
||||
key := verKey(chatID)
|
||||
v, err := m.rdb.Get(ctx, key).Result()
|
||||
if err == nil {
|
||||
return v, nil
|
||||
}
|
||||
if !errors.Is(err, redis.Nil) {
|
||||
return "", err
|
||||
}
|
||||
fresh := randomVersion()
|
||||
old, err := m.rdb.SetArgs(ctx, key, fresh, redis.SetArgs{Mode: "NX", Get: true, TTL: versionTTL}).Result()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return fresh, nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return old, nil
|
||||
}
|
||||
|
||||
var unlockScript = redis.NewScript(`
|
||||
if redis.call("GET", KEYS[1]) == ARGV[1] then return redis.call("DEL", KEYS[1]) end
|
||||
return 0`)
|
||||
|
||||
func (m *Messages) fill(ctx context.Context, key, chatID, cursor string, limit int) (domain.Page[domain.Message], error) {
|
||||
lockKey := "hc:lock:" + key
|
||||
token := randomVersion()
|
||||
locked, err := m.rdb.SetNX(ctx, lockKey, token, m.opt.LockTTL).Result()
|
||||
if err != nil {
|
||||
m.markDown(err)
|
||||
return m.src.HistoryPage(ctx, chatID, cursor, limit)
|
||||
}
|
||||
if !locked {
|
||||
deadline := time.Now().Add(m.opt.LockTTL)
|
||||
for time.Now().Before(deadline) {
|
||||
time.Sleep(pollInterval)
|
||||
if page, ok := m.getPage(ctx, key); ok {
|
||||
return page, nil
|
||||
}
|
||||
}
|
||||
return m.src.HistoryPage(ctx, chatID, cursor, limit)
|
||||
}
|
||||
defer unlockScript.Run(ctx, m.rdb, []string{lockKey}, token)
|
||||
|
||||
page, err := m.src.HistoryPage(ctx, chatID, cursor, limit)
|
||||
if err != nil {
|
||||
return page, err
|
||||
}
|
||||
m.sleepFill(ctx)
|
||||
if b, err := encodePage(page); err == nil {
|
||||
m.markDown(m.rdb.Set(ctx, key, b, m.opt.PageTTL).Err())
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// addPending вызывается до ответа 201: после него чат читается мимо кэша,
|
||||
// пока версия не будет сброшена, в том числе после рестарта API.
|
||||
func (m *Messages) addPending(ctx context.Context, chatID string) {
|
||||
m.markPending(chatID, 0)
|
||||
if m.opt.Outbox == nil {
|
||||
m.log.Warn("history cache invalidation deferred", slog.String("chat_id", chatID))
|
||||
return
|
||||
}
|
||||
gen, err := m.opt.Outbox.AddPendingInvalidation(ctx, chatID)
|
||||
if err != nil {
|
||||
m.log.Error("history cache invalidation deferred in memory only, lost on restart",
|
||||
slog.String("chat_id", chatID), slog.Any("err", err))
|
||||
return
|
||||
}
|
||||
m.markPending(chatID, gen)
|
||||
m.log.Warn("history cache invalidation deferred",
|
||||
slog.String("chat_id", chatID), slog.Int64("gen", gen))
|
||||
}
|
||||
|
||||
// markPending всегда выдаёт новый seq, чтобы повтор, начатый раньше, не снял
|
||||
// запись. gen не уменьшается.
|
||||
func (m *Messages) markPending(chatID string, gen int64) {
|
||||
m.mu.Lock()
|
||||
m.seq++
|
||||
e := m.pending[chatID]
|
||||
e.seq = m.seq
|
||||
e.gen = max(e.gen, gen)
|
||||
m.pending[chatID] = e
|
||||
m.mu.Unlock()
|
||||
}
|
||||
|
||||
func (m *Messages) bypass(chatID string) bool {
|
||||
if m.isDown() || !m.loaded.Load() {
|
||||
return true
|
||||
}
|
||||
m.mu.Lock()
|
||||
_, ok := m.pending[chatID]
|
||||
m.mu.Unlock()
|
||||
return ok
|
||||
}
|
||||
|
||||
func (m *Messages) loadPending() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
rows, err := m.opt.Outbox.PendingInvalidations(ctx)
|
||||
if err != nil {
|
||||
m.log.Warn("history cache: pending invalidations not loaded, bypassing", slog.Any("err", err))
|
||||
return
|
||||
}
|
||||
for id, gen := range rows {
|
||||
m.markPending(id, gen)
|
||||
}
|
||||
m.loaded.Store(true)
|
||||
if len(rows) > 0 {
|
||||
m.log.Info("history cache: pending invalidations loaded", slog.Int("chats", len(rows)))
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Messages) retryLoop() {
|
||||
defer close(m.done)
|
||||
t := time.NewTicker(retryInterval)
|
||||
defer t.Stop()
|
||||
for {
|
||||
if !m.loaded.Load() {
|
||||
m.loadPending()
|
||||
}
|
||||
m.retryPending()
|
||||
select {
|
||||
case <-m.stop:
|
||||
return
|
||||
case <-t.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Messages) retryPending() {
|
||||
m.mu.Lock()
|
||||
chats := make(map[string]pendingEntry, len(m.pending))
|
||||
for id, e := range m.pending {
|
||||
chats[id] = e
|
||||
}
|
||||
m.mu.Unlock()
|
||||
for id, e := range chats {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
err := m.rdb.Del(ctx, verKey(id)).Err()
|
||||
if err == nil && e.gen > 0 {
|
||||
err = m.opt.Outbox.ResolvePendingInvalidation(ctx, id, e.gen)
|
||||
}
|
||||
cancel()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
m.resolved(id, e)
|
||||
}
|
||||
}
|
||||
|
||||
// resolved снимает запись, если после снимка e не было нового сбоя.
|
||||
func (m *Messages) resolved(chatID string, e pendingEntry) {
|
||||
m.mu.Lock()
|
||||
if m.pending[chatID].seq == e.seq {
|
||||
delete(m.pending, chatID)
|
||||
}
|
||||
m.mu.Unlock()
|
||||
}
|
||||
|
||||
func (m *Messages) isDown() bool {
|
||||
return time.Now().UnixNano() < m.downUntil.Load()
|
||||
}
|
||||
|
||||
func (m *Messages) markDown(err error) {
|
||||
if err == nil || errors.Is(err, redis.Nil) {
|
||||
return
|
||||
}
|
||||
if !m.isDown() {
|
||||
m.log.Warn("history cache unavailable, bypassing", slog.Any("err", err))
|
||||
}
|
||||
m.downUntil.Store(time.Now().Add(breakerPause).UnixNano())
|
||||
}
|
||||
|
||||
func (m *Messages) getPage(ctx context.Context, key string) (domain.Page[domain.Message], bool) {
|
||||
b, err := m.rdb.Get(ctx, key).Bytes()
|
||||
if err != nil {
|
||||
m.markDown(err)
|
||||
return domain.Page[domain.Message]{}, false
|
||||
}
|
||||
page, err := decodePage(b)
|
||||
return page, err == nil
|
||||
}
|
||||
|
||||
func (m *Messages) sleepFill(ctx context.Context) {
|
||||
if m.opt.FillDelay <= 0 {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-time.After(m.opt.FillDelay):
|
||||
case <-ctx.Done():
|
||||
}
|
||||
}
|
||||
|
||||
func verKey(chatID string) string { return "hc:ver:" + chatID }
|
||||
|
||||
func pageKey(prefix, cursor string, limit int) string {
|
||||
return prefix + ":" + strconv.Itoa(limit) + ":" + cursor
|
||||
}
|
||||
|
||||
func randomVersion() string {
|
||||
var b [8]byte
|
||||
_, _ = rand.Read(b[:])
|
||||
return hex.EncodeToString(b[:])
|
||||
}
|
||||
|
||||
type cachedPage struct {
|
||||
Items []domain.Message `json:"items"`
|
||||
NextCursor string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func encodePage(p domain.Page[domain.Message]) ([]byte, error) {
|
||||
return json.Marshal(cachedPage{Items: p.Items, NextCursor: p.NextCursor})
|
||||
}
|
||||
|
||||
func decodePage(b []byte) (domain.Page[domain.Message], error) {
|
||||
var c cachedPage
|
||||
if err := json.Unmarshal(b, &c); err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
return domain.Page[domain.Message]{Items: c.Items, NextCursor: c.NextCursor}, nil
|
||||
}
|
||||
Vendored
+208
@@ -0,0 +1,208 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
const member = "alice"
|
||||
|
||||
type fakeSource struct {
|
||||
mu sync.Mutex
|
||||
msgs []domain.Message
|
||||
queryDelay time.Duration
|
||||
pageCalls atomic.Int64
|
||||
}
|
||||
|
||||
func (f *fakeSource) AddMessage(_ context.Context, callerID, chatID, _, text string) (domain.Message, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
m := domain.Message{
|
||||
ID: fmt.Sprintf("m%04d", len(f.msgs)),
|
||||
ChatID: chatID,
|
||||
AuthorID: callerID,
|
||||
Text: text,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
f.msgs = append(f.msgs, m)
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (f *fakeSource) IsMember(_ context.Context, _, userID string) (bool, error) {
|
||||
return userID == member, nil
|
||||
}
|
||||
|
||||
func (f *fakeSource) HistoryPage(context.Context, string, string, int) (domain.Page[domain.Message], error) {
|
||||
f.pageCalls.Add(1)
|
||||
f.mu.Lock()
|
||||
snapshot := append([]domain.Message(nil), f.msgs...)
|
||||
f.mu.Unlock()
|
||||
time.Sleep(f.queryDelay)
|
||||
return domain.Page[domain.Message]{Items: snapshot}, nil
|
||||
}
|
||||
|
||||
func (f *fakeSource) ListMessages(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) {
|
||||
if ok, _ := f.IsMember(ctx, chatID, callerID); !ok {
|
||||
return domain.Page[domain.Message]{}, domain.ErrNotFound
|
||||
}
|
||||
return f.HistoryPage(ctx, chatID, cursor, limit)
|
||||
}
|
||||
|
||||
func newCache(t *testing.T, c *redis.Client, mode string, src *fakeSource, fillDelay time.Duration) *Messages {
|
||||
t.Helper()
|
||||
m := New(src, c, Options{
|
||||
Mode: mode,
|
||||
PageTTL: time.Minute,
|
||||
FillDelay: fillDelay,
|
||||
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||
})
|
||||
t.Cleanup(m.Close)
|
||||
return m
|
||||
}
|
||||
|
||||
func contains(p domain.Page[domain.Message], id string) bool {
|
||||
for _, m := range p.Items {
|
||||
if m.ID == id {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TestCacheDown_Bypass(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
dead := redis.NewClient(&redis.Options{
|
||||
Addr: "127.0.0.1:1", DialTimeout: 50 * time.Millisecond, MaxRetries: -1,
|
||||
})
|
||||
t.Cleanup(func() { dead.Close() })
|
||||
src := &fakeSource{}
|
||||
h := newCache(t, dead, ModeSafe, src, 0)
|
||||
|
||||
msg, err := h.AddMessage(ctx, member, "chat-down", randomVersion(), "при упавшем кэше")
|
||||
if err != nil {
|
||||
t.Fatalf("запись при упавшем кэше: %v", err)
|
||||
}
|
||||
page, err := h.ListMessages(ctx, member, "chat-down", "", 50)
|
||||
if err != nil || !contains(page, msg.ID) {
|
||||
t.Fatalf("чтение при упавшем кэше: err=%v", err)
|
||||
}
|
||||
if !h.bypass("chat-down") {
|
||||
t.Fatal("чат с несброшенной версией должен читаться мимо кэша")
|
||||
}
|
||||
if _, err := h.ListMessages(ctx, "mallory", "chat-down", "", 50); !errors.Is(err, domain.ErrNotFound) {
|
||||
t.Fatalf("обход кэша не должен пропускать постороннего: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
type fakeOutbox struct {
|
||||
mu sync.Mutex
|
||||
rows map[string]int64
|
||||
seq int64 // как cache_invalidations_gen_seq: gen не повторяется
|
||||
loadErr error
|
||||
}
|
||||
|
||||
func (f *fakeOutbox) AddPendingInvalidation(_ context.Context, chatID string) (int64, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.seq++
|
||||
f.rows[chatID] = f.seq
|
||||
return f.seq, nil
|
||||
}
|
||||
|
||||
func (f *fakeOutbox) PendingInvalidations(context.Context) (map[string]int64, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.loadErr != nil {
|
||||
return nil, f.loadErr
|
||||
}
|
||||
out := make(map[string]int64, len(f.rows))
|
||||
for k, v := range f.rows {
|
||||
out[k] = v
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (f *fakeOutbox) ResolvePendingInvalidation(_ context.Context, chatID string, gen int64) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.rows[chatID] == gen {
|
||||
delete(f.rows, chatID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeOutbox) len() int {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return len(f.rows)
|
||||
}
|
||||
|
||||
func TestBypassUntilOutboxLoaded(t *testing.T) {
|
||||
outbox := &fakeOutbox{rows: map[string]int64{}, loadErr: errors.New("db down")}
|
||||
h := New(&fakeSource{}, redis.NewClient(&redis.Options{Addr: "127.0.0.1:1"}), Options{
|
||||
Mode: ModeSafe,
|
||||
Outbox: outbox,
|
||||
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||
})
|
||||
defer h.Close()
|
||||
time.Sleep(3 * retryInterval)
|
||||
if !h.bypass("any") {
|
||||
t.Fatal("пока долг из Outbox не прочитан, кэш не должен отдавать страницы")
|
||||
}
|
||||
outbox.mu.Lock()
|
||||
outbox.loadErr = nil
|
||||
outbox.mu.Unlock()
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for h.bypass("any") {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("после загрузки Outbox чтение через кэш не включилось")
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// Повтор сбросил версию и снял строку Outbox, но до того, как он снял запись
|
||||
// из памяти, новая запись снова не смогла сбросить версию. Запись в памяти и
|
||||
// строка Outbox должны остаться, иначе ответ 201 придёт при устаревшем кэше.
|
||||
func TestRetryDoesNotDropNewerFailure(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
outbox := &fakeOutbox{rows: map[string]int64{}}
|
||||
h := New(&fakeSource{}, redis.NewClient(&redis.Options{Addr: "127.0.0.1:1"}), Options{
|
||||
Mode: ModeSafe,
|
||||
Outbox: outbox,
|
||||
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||
})
|
||||
h.Close() // повтор ведём вручную
|
||||
h.loaded.Store(true)
|
||||
chat := "chat-retry-race"
|
||||
|
||||
h.addPending(ctx, chat)
|
||||
snap := h.pending[chat] // снимок повтора; DEL версии прошёл
|
||||
if err := outbox.ResolvePendingInvalidation(ctx, chat, snap.gen); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.addPending(ctx, chat) // новый сбой DEL до ответа 201
|
||||
h.resolved(chat, snap)
|
||||
|
||||
if !h.bypass(chat) {
|
||||
t.Fatal("повтор снял запись о более новом сбое")
|
||||
}
|
||||
if rows, _ := outbox.PendingInvalidations(ctx); rows[chat] <= snap.gen {
|
||||
t.Fatalf("строка Outbox: gen=%d, ожидался новый gen > %d", rows[chat], snap.gen)
|
||||
}
|
||||
h.resolved(chat, h.pending[chat])
|
||||
if h.bypass(chat) {
|
||||
t.Fatal("актуальный повтор должен снять запись")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var instanceIDPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
type Config struct {
|
||||
Env string
|
||||
Version string
|
||||
InstanceID string
|
||||
|
||||
HTTP HTTP
|
||||
Logger Logger
|
||||
Limits Limits
|
||||
Database Database
|
||||
Cache Cache
|
||||
Session Session
|
||||
|
||||
Idempotency Idempotency
|
||||
HistoryCache HistoryCache
|
||||
}
|
||||
|
||||
func Load() (*Config, error) {
|
||||
cfg := defaults()
|
||||
if err := cfg.applyEnv(os.LookupEnv); err != nil {
|
||||
return nil, fmt.Errorf("config: env: %w", err)
|
||||
}
|
||||
if cfg.InstanceID == "" {
|
||||
cfg.InstanceID = defaultInstanceID()
|
||||
}
|
||||
if err := cfg.validate(); err != nil {
|
||||
return nil, fmt.Errorf("config: validate: %w", err)
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func defaults() *Config {
|
||||
return &Config{
|
||||
Env: "lab",
|
||||
Version: "dev",
|
||||
HTTP: HTTP{
|
||||
Addr: "0.0.0.0:8080",
|
||||
ReadTimeoutMs: 10000,
|
||||
WriteTimeoutMs: 10000,
|
||||
IdleTimeoutMs: 60000,
|
||||
ShutdownTimeoutMs: 10000,
|
||||
ShutdownDrainMs: 3000,
|
||||
},
|
||||
Logger: Logger{Level: "info"},
|
||||
Limits: Limits{
|
||||
MaxBodyBytes: 64 * 1024,
|
||||
MaxInFlight: 64,
|
||||
MaxMessagesGlobal: 100000,
|
||||
MaxHeapBytes: 256 * 1024 * 1024,
|
||||
},
|
||||
Database: Database{
|
||||
MaxConns: 10,
|
||||
ConnectTimeoutMs: 5000,
|
||||
QueryTimeoutMs: 3000,
|
||||
},
|
||||
Cache: Cache{
|
||||
PoolSize: 20,
|
||||
TimeoutMs: 1000,
|
||||
},
|
||||
Session: Session{Store: "valkey", TTLSeconds: 3600},
|
||||
Idempotency: Idempotency{TTLSeconds: MinIdempotencyTTLSeconds},
|
||||
HistoryCache: HistoryCache{
|
||||
Mode: "off",
|
||||
PageTTLSeconds: 30,
|
||||
TimeoutMs: 200,
|
||||
PoolSize: 20,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// defaultInstanceID — hostname: в Docker это короткий ID контейнера, поэтому ответ
|
||||
// можно сопоставить с конкретным контейнером. Значение неизменно на всю жизнь процесса.
|
||||
func defaultInstanceID() string {
|
||||
if h, err := os.Hostname(); err == nil && instanceIDPattern.MatchString(h) {
|
||||
return h
|
||||
}
|
||||
return uuid.NewString()
|
||||
}
|
||||
|
||||
func (c *Config) validate() error {
|
||||
if !instanceIDPattern.MatchString(c.InstanceID) {
|
||||
return fmt.Errorf("APP_INSTANCE_ID must match %s", instanceIDPattern)
|
||||
}
|
||||
if strings.TrimSpace(c.Env) == "" {
|
||||
return errors.New("env is required")
|
||||
}
|
||||
if strings.TrimSpace(c.Version) == "" {
|
||||
return errors.New("version is required")
|
||||
}
|
||||
if strings.TrimSpace(c.HTTP.Addr) == "" {
|
||||
return errors.New("http.addr is required")
|
||||
}
|
||||
if c.HTTP.ShutdownTimeoutMs <= 0 || c.HTTP.ShutdownTimeoutMs > 10000 {
|
||||
return fmt.Errorf("APP_SHUTDOWN_TIMEOUT_MS must be in (0, 10000], got %d", c.HTTP.ShutdownTimeoutMs)
|
||||
}
|
||||
if c.HTTP.ShutdownDrainMs < 0 || c.HTTP.ShutdownDrainMs > 10000 {
|
||||
return fmt.Errorf("APP_SHUTDOWN_DRAIN_MS must be in [0, 10000], got %d", c.HTTP.ShutdownDrainMs)
|
||||
}
|
||||
if c.HTTP.ReadTimeoutMs <= 0 {
|
||||
return fmt.Errorf("APP_READ_TIMEOUT_MS must be > 0, got %d", c.HTTP.ReadTimeoutMs)
|
||||
}
|
||||
if c.HTTP.WriteTimeoutMs <= 0 {
|
||||
return fmt.Errorf("APP_WRITE_TIMEOUT_MS must be > 0, got %d", c.HTTP.WriteTimeoutMs)
|
||||
}
|
||||
if c.HTTP.IdleTimeoutMs <= 0 {
|
||||
return fmt.Errorf("APP_IDLE_TIMEOUT_MS must be > 0, got %d", c.HTTP.IdleTimeoutMs)
|
||||
}
|
||||
|
||||
if c.Limits.MaxBodyBytes <= 0 {
|
||||
return fmt.Errorf("APP_MAX_BODY_BYTES must be > 0, got %d", c.Limits.MaxBodyBytes)
|
||||
}
|
||||
if c.Limits.MaxInFlight <= 0 {
|
||||
return fmt.Errorf("APP_MAX_INFLIGHT must be > 0, got %d", c.Limits.MaxInFlight)
|
||||
}
|
||||
if c.Limits.MaxMessagesGlobal <= 0 {
|
||||
return fmt.Errorf("APP_MAX_MESSAGES must be > 0, got %d", c.Limits.MaxMessagesGlobal)
|
||||
}
|
||||
if c.Limits.MaxHeapBytes == 0 {
|
||||
return errors.New("APP_MAX_HEAP_BYTES must be > 0")
|
||||
}
|
||||
|
||||
if c.Database.MaxConns <= 0 {
|
||||
return fmt.Errorf("DB_MAX_CONNS must be > 0, got %d", c.Database.MaxConns)
|
||||
}
|
||||
if c.Database.ConnectTimeoutMs <= 0 {
|
||||
return fmt.Errorf("DB_CONNECT_TIMEOUT_MS must be > 0, got %d", c.Database.ConnectTimeoutMs)
|
||||
}
|
||||
if c.Database.QueryTimeoutMs <= 0 {
|
||||
return fmt.Errorf("DB_QUERY_TIMEOUT_MS must be > 0, got %d", c.Database.QueryTimeoutMs)
|
||||
}
|
||||
if c.Cache.PoolSize <= 0 {
|
||||
return fmt.Errorf("CACHE_POOL_SIZE must be > 0, got %d", c.Cache.PoolSize)
|
||||
}
|
||||
if c.Cache.TimeoutMs <= 0 {
|
||||
return fmt.Errorf("CACHE_TIMEOUT_MS must be > 0, got %d", c.Cache.TimeoutMs)
|
||||
}
|
||||
switch c.HistoryCache.Mode {
|
||||
case "off", "naive", "safe":
|
||||
default:
|
||||
return fmt.Errorf("HISTORY_CACHE must be off|naive|safe, got %q", c.HistoryCache.Mode)
|
||||
}
|
||||
if c.HistoryCache.PageTTLSeconds <= 0 {
|
||||
return fmt.Errorf("HISTORY_CACHE_TTL_SECONDS must be > 0, got %d", c.HistoryCache.PageTTLSeconds)
|
||||
}
|
||||
if c.HistoryCache.TimeoutMs <= 0 || c.HistoryCache.PoolSize <= 0 {
|
||||
return errors.New("HISTORY_CACHE_TIMEOUT_MS and HISTORY_CACHE_POOL_SIZE must be > 0")
|
||||
}
|
||||
if c.HistoryCache.FillDelayMs < 0 || c.HistoryCache.FillDelayMs > 1000 {
|
||||
return fmt.Errorf("HISTORY_CACHE_FILL_DELAY_MS must be in [0, 1000], got %d", c.HistoryCache.FillDelayMs)
|
||||
}
|
||||
// Реализовано одно хранилище сессий; иное значение — ошибка конфигурации, а не тихий выбор.
|
||||
if c.Session.Store != "valkey" {
|
||||
return fmt.Errorf("SESSION_STORE must be valkey (the only implemented session store), got %q", c.Session.Store)
|
||||
}
|
||||
if c.Idempotency.TTLSeconds < MinIdempotencyTTLSeconds {
|
||||
return fmt.Errorf("IDEMPOTENCY_TTL_SECONDS must be >= %d, got %d", MinIdempotencyTTLSeconds, c.Idempotency.TTLSeconds)
|
||||
}
|
||||
if c.Session.TTLSeconds <= 0 {
|
||||
return fmt.Errorf("SESSION_TTL_SECONDS must be > 0, got %d", c.Session.TTLSeconds)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package config
|
||||
|
||||
type Database struct {
|
||||
URLFile string
|
||||
URL string
|
||||
MaxConns int32
|
||||
ConnectTimeoutMs int
|
||||
QueryTimeoutMs int
|
||||
// EnableBitmapScan: по умолчанию выключено. Для чата, которого ещё нет в статистике,
|
||||
// планировщик может ожидать почти пустой результат и выбрать чтение всего чата с сортировкой.
|
||||
// Это гипотеза: замеров, подтверждающих выигрыш, в evidence нет. Флаг нужен для сравнения.
|
||||
EnableBitmapScan bool
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func (c *Config) applyEnv(lookup func(string) (string, bool)) error {
|
||||
get := func(key string) (string, bool) {
|
||||
v, ok := lookup(key)
|
||||
v = strings.TrimSpace(v)
|
||||
return v, ok && v != ""
|
||||
}
|
||||
|
||||
if v, ok := get("APP_ENV"); ok {
|
||||
c.Env = v
|
||||
}
|
||||
if v, ok := get("APP_VERSION"); ok {
|
||||
c.Version = v
|
||||
}
|
||||
if v, ok := get("APP_INSTANCE_ID"); ok {
|
||||
c.InstanceID = v
|
||||
}
|
||||
if v, ok := get("APP_LOG_LEVEL"); ok {
|
||||
c.Logger.Level = v
|
||||
}
|
||||
if v, ok := get("DATABASE_URL_FILE"); ok {
|
||||
c.Database.URLFile = v
|
||||
}
|
||||
if v, ok := get("DATABASE_URL"); ok {
|
||||
c.Database.URL = v
|
||||
}
|
||||
if v, ok := get("CACHE_URL_FILE"); ok {
|
||||
c.Cache.URLFile = v
|
||||
}
|
||||
if v, ok := get("CACHE_URL"); ok {
|
||||
c.Cache.URL = v
|
||||
}
|
||||
if v, ok := get("SESSION_STORE"); ok {
|
||||
c.Session.Store = strings.ToLower(v)
|
||||
}
|
||||
if v, ok := get("HISTORY_CACHE"); ok {
|
||||
c.HistoryCache.Mode = strings.ToLower(v)
|
||||
}
|
||||
if v, ok := get("HISTORY_CACHE_URL_FILE"); ok {
|
||||
c.HistoryCache.URLFile = v
|
||||
}
|
||||
if v, ok := get("HISTORY_CACHE_URL"); ok {
|
||||
c.HistoryCache.URL = v
|
||||
}
|
||||
|
||||
host, port, err := net.SplitHostPort(c.HTTP.Addr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("default addr %q: %w", c.HTTP.Addr, err)
|
||||
}
|
||||
if v, ok := get("APP_HOST"); ok {
|
||||
host = v
|
||||
}
|
||||
if v, ok := get("APP_PORT"); ok {
|
||||
port = v
|
||||
}
|
||||
if n, err := strconv.Atoi(port); err != nil || n < 1 || n > 65535 {
|
||||
return fmt.Errorf("APP_PORT must be in [1, 65535], got %q", port)
|
||||
}
|
||||
c.HTTP.Addr = net.JoinHostPort(host, port)
|
||||
|
||||
ints := []struct {
|
||||
key string
|
||||
dst *int
|
||||
}{
|
||||
{"APP_READ_TIMEOUT_MS", &c.HTTP.ReadTimeoutMs},
|
||||
{"APP_WRITE_TIMEOUT_MS", &c.HTTP.WriteTimeoutMs},
|
||||
{"APP_IDLE_TIMEOUT_MS", &c.HTTP.IdleTimeoutMs},
|
||||
{"APP_SHUTDOWN_TIMEOUT_MS", &c.HTTP.ShutdownTimeoutMs},
|
||||
{"APP_SHUTDOWN_DRAIN_MS", &c.HTTP.ShutdownDrainMs},
|
||||
{"APP_MAX_INFLIGHT", &c.Limits.MaxInFlight},
|
||||
{"APP_MAX_MESSAGES", &c.Limits.MaxMessagesGlobal},
|
||||
{"DB_CONNECT_TIMEOUT_MS", &c.Database.ConnectTimeoutMs},
|
||||
{"DB_QUERY_TIMEOUT_MS", &c.Database.QueryTimeoutMs},
|
||||
{"CACHE_POOL_SIZE", &c.Cache.PoolSize},
|
||||
{"CACHE_TIMEOUT_MS", &c.Cache.TimeoutMs},
|
||||
{"SESSION_TTL_SECONDS", &c.Session.TTLSeconds},
|
||||
{"IDEMPOTENCY_TTL_SECONDS", &c.Idempotency.TTLSeconds},
|
||||
{"HISTORY_CACHE_TTL_SECONDS", &c.HistoryCache.PageTTLSeconds},
|
||||
{"HISTORY_CACHE_TIMEOUT_MS", &c.HistoryCache.TimeoutMs},
|
||||
{"HISTORY_CACHE_POOL_SIZE", &c.HistoryCache.PoolSize},
|
||||
{"HISTORY_CACHE_FILL_DELAY_MS", &c.HistoryCache.FillDelayMs},
|
||||
}
|
||||
for _, it := range ints {
|
||||
v, ok := get(it.key)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: not an integer: %q", it.key, v)
|
||||
}
|
||||
*it.dst = n
|
||||
}
|
||||
|
||||
if v, ok := get("APP_MAX_BODY_BYTES"); ok {
|
||||
n, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("APP_MAX_BODY_BYTES: not an integer: %q", v)
|
||||
}
|
||||
c.Limits.MaxBodyBytes = n
|
||||
}
|
||||
if v, ok := get("DB_MAX_CONNS"); ok {
|
||||
n, err := strconv.ParseInt(v, 10, 32)
|
||||
if err != nil {
|
||||
return fmt.Errorf("DB_MAX_CONNS: not an integer: %q", v)
|
||||
}
|
||||
c.Database.MaxConns = int32(n)
|
||||
}
|
||||
if v, ok := get("DB_ENABLE_BITMAPSCAN"); ok {
|
||||
b, err := strconv.ParseBool(v)
|
||||
if err != nil {
|
||||
return fmt.Errorf("DB_ENABLE_BITMAPSCAN: not a boolean: %q", v)
|
||||
}
|
||||
c.Database.EnableBitmapScan = b
|
||||
}
|
||||
if v, ok := get("APP_MAX_HEAP_BYTES"); ok {
|
||||
n, err := strconv.ParseUint(v, 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("APP_MAX_HEAP_BYTES: not a non-negative integer: %q", v)
|
||||
}
|
||||
c.Limits.MaxHeapBytes = n
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package config
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestLoad_Defaults(t *testing.T) {
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.HTTP.Addr != "0.0.0.0:8080" || cfg.Env != "lab" || cfg.Limits.MaxInFlight != 64 {
|
||||
t.Errorf("cfg = %+v", cfg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoad_EnvOverridesDefaults(t *testing.T) {
|
||||
t.Setenv("APP_HOST", "127.0.0.1")
|
||||
t.Setenv("APP_PORT", "9090")
|
||||
t.Setenv("APP_ENV", "docker")
|
||||
t.Setenv("APP_MAX_INFLIGHT", "8")
|
||||
t.Setenv("APP_MAX_BODY_BYTES", "2048")
|
||||
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.HTTP.Addr != "127.0.0.1:9090" {
|
||||
t.Errorf("addr = %q, want 127.0.0.1:9090", cfg.HTTP.Addr)
|
||||
}
|
||||
if cfg.Env != "docker" {
|
||||
t.Errorf("env = %q, want docker", cfg.Env)
|
||||
}
|
||||
if cfg.Limits.MaxInFlight != 8 || cfg.Limits.MaxBodyBytes != 2048 {
|
||||
t.Errorf("limits = %+v", cfg.Limits)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoad_PortOnlyKeepsDefaultHost(t *testing.T) {
|
||||
t.Setenv("APP_PORT", "18080")
|
||||
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.HTTP.Addr != "0.0.0.0:18080" {
|
||||
t.Errorf("addr = %q, want 0.0.0.0:18080", cfg.HTTP.Addr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoad_InstanceID(t *testing.T) {
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.InstanceID == "" {
|
||||
t.Error("default instance id is empty")
|
||||
}
|
||||
|
||||
t.Setenv("APP_INSTANCE_ID", "api-1")
|
||||
cfg, err = Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.InstanceID != "api-1" {
|
||||
t.Errorf("instance id = %q, want api-1", cfg.InstanceID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoad_InvalidEnvFails(t *testing.T) {
|
||||
for key, val := range map[string]string{
|
||||
"APP_PORT": "http",
|
||||
"APP_MAX_INFLIGHT": "many",
|
||||
"APP_MAX_MESSAGES": "0",
|
||||
"APP_SHUTDOWN_TIMEOUT_MS": "30000",
|
||||
"APP_INSTANCE_ID": "bad id",
|
||||
"APP_SHUTDOWN_DRAIN_MS": "-1",
|
||||
"IDEMPOTENCY_TTL_SECONDS": "3600",
|
||||
} {
|
||||
t.Run(key, func(t *testing.T) {
|
||||
t.Setenv(key, val)
|
||||
if _, err := Load(); err == nil {
|
||||
t.Errorf("%s=%q: expected error", key, val)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package config
|
||||
|
||||
type HistoryCache struct {
|
||||
Mode string
|
||||
URLFile string
|
||||
URL string
|
||||
PageTTLSeconds int
|
||||
TimeoutMs int
|
||||
PoolSize int
|
||||
FillDelayMs int
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package config
|
||||
|
||||
type HTTP struct {
|
||||
Addr string
|
||||
ReadTimeoutMs int
|
||||
WriteTimeoutMs int
|
||||
IdleTimeoutMs int
|
||||
ShutdownTimeoutMs int
|
||||
// ShutdownDrainMs — сколько после SIGTERM обслуживать запросы, отвечая на readiness 503,
|
||||
// чтобы балансировщик успел вывести реплику. Должно быть больше времени его обнаружения.
|
||||
ShutdownDrainMs int
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package config
|
||||
|
||||
// MinIdempotencyTTLSeconds — контракт требует хранить результат не менее 24 часов.
|
||||
const MinIdempotencyTTLSeconds = 86400
|
||||
|
||||
type Idempotency struct {
|
||||
TTLSeconds int
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package config
|
||||
|
||||
type Limits struct {
|
||||
MaxBodyBytes int64
|
||||
MaxInFlight int
|
||||
MaxMessagesGlobal int
|
||||
MaxHeapBytes uint64
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package config
|
||||
|
||||
type Logger struct {
|
||||
Level string
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package config
|
||||
|
||||
type Session struct {
|
||||
Store string
|
||||
TTLSeconds int
|
||||
}
|
||||
|
||||
type Cache struct {
|
||||
URLFile string
|
||||
URL string
|
||||
PoolSize int
|
||||
TimeoutMs int
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
type Chat struct {
|
||||
ID string
|
||||
Title string
|
||||
MemberIDs []string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("not found")
|
||||
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
|
||||
ErrConflict = errors.New("conflict")
|
||||
|
||||
// ErrIdempotencyConflict — ключ уже использован с другим телом запроса.
|
||||
ErrIdempotencyConflict = fmt.Errorf("idempotency key reused with different request: %w", ErrConflict)
|
||||
|
||||
ErrInvalidArgument = errors.New("invalid argument")
|
||||
|
||||
ErrUnavailable = errors.New("unavailable")
|
||||
|
||||
ErrPayloadTooLarge = errors.New("payload too large")
|
||||
|
||||
ErrRateLimited = errors.New("rate limited")
|
||||
)
|
||||
@@ -0,0 +1,11 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
type Message struct {
|
||||
ID string
|
||||
ChatID string
|
||||
AuthorID string
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Page[T any] struct {
|
||||
Items []T
|
||||
NextCursor string
|
||||
}
|
||||
|
||||
type Cursor struct {
|
||||
CreatedAt time.Time `json:"t"`
|
||||
ID string `json:"i"`
|
||||
Scope string `json:"s,omitempty"`
|
||||
}
|
||||
|
||||
func (c Cursor) IsZero() bool {
|
||||
return c.ID == "" && c.CreatedAt.IsZero()
|
||||
}
|
||||
|
||||
func (c Cursor) Less(createdAt time.Time, id string) bool {
|
||||
if c.CreatedAt.Before(createdAt) {
|
||||
return true
|
||||
}
|
||||
if c.CreatedAt.After(createdAt) {
|
||||
return false
|
||||
}
|
||||
return c.ID < id
|
||||
}
|
||||
|
||||
func EncodeCursor(c Cursor) string {
|
||||
if c.IsZero() {
|
||||
return ""
|
||||
}
|
||||
b, _ := json.Marshal(c)
|
||||
return base64.RawURLEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
func DecodeCursor(s string) (Cursor, error) {
|
||||
if s == "" {
|
||||
return Cursor{}, nil
|
||||
}
|
||||
raw, err := base64.RawURLEncoding.DecodeString(s)
|
||||
if err != nil {
|
||||
return Cursor{}, ErrInvalidArgument
|
||||
}
|
||||
var c Cursor
|
||||
if err := json.Unmarshal(raw, &c); err != nil {
|
||||
return Cursor{}, ErrInvalidArgument
|
||||
}
|
||||
|
||||
if c.CreatedAt.IsZero() || c.Scope == "" {
|
||||
return Cursor{}, ErrInvalidArgument
|
||||
}
|
||||
if _, err := uuid.Parse(c.ID); err != nil || len(c.ID) != 36 {
|
||||
return Cursor{}, ErrInvalidArgument
|
||||
}
|
||||
if EncodeCursor(c) != s {
|
||||
return Cursor{}, ErrInvalidArgument
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
type Session struct {
|
||||
Token string
|
||||
ExpiresAt time.Time
|
||||
User User
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
type User struct {
|
||||
ID string
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func New(level, env, version string) (*slog.Logger, error) {
|
||||
lvl, err := parseLevel(level)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return build(os.Stdout, lvl, env, version), nil
|
||||
}
|
||||
|
||||
func build(w io.Writer, lvl slog.Level, env, version string) *slog.Logger {
|
||||
handler := slog.NewJSONHandler(w, &slog.HandlerOptions{
|
||||
Level: lvl,
|
||||
ReplaceAttr: forceUTCTime,
|
||||
})
|
||||
return slog.New(handler).With(
|
||||
slog.String("service", "messenger"),
|
||||
slog.String("env", env),
|
||||
slog.String("version", version),
|
||||
)
|
||||
}
|
||||
|
||||
func forceUTCTime(_ []string, a slog.Attr) slog.Attr {
|
||||
if a.Value.Kind() == slog.KindTime {
|
||||
a.Value = slog.TimeValue(a.Value.Time().UTC())
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func parseLevel(s string) (slog.Level, error) {
|
||||
switch strings.ToLower(strings.TrimSpace(s)) {
|
||||
case "", "info":
|
||||
return slog.LevelInfo, nil
|
||||
case "debug":
|
||||
return slog.LevelDebug, nil
|
||||
case "warn", "warning":
|
||||
return slog.LevelWarn, nil
|
||||
case "error":
|
||||
return slog.LevelError, nil
|
||||
default:
|
||||
return 0, fmt.Errorf("logging: unknown level %q (want debug|info|warn|error)", s)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package password
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
type Params struct {
|
||||
MemoryKiB uint32
|
||||
Iterations uint32
|
||||
Parallelism uint8
|
||||
SaltLen uint32
|
||||
KeyLen uint32
|
||||
}
|
||||
|
||||
var Default = Params{
|
||||
MemoryKiB: 19 * 1024,
|
||||
Iterations: 2,
|
||||
Parallelism: 1,
|
||||
SaltLen: 16,
|
||||
KeyLen: 32,
|
||||
}
|
||||
|
||||
var ErrMalformedHash = errors.New("password: malformed hash")
|
||||
|
||||
var b64 = base64.RawStdEncoding
|
||||
|
||||
|
||||
type Hasher struct {
|
||||
params Params
|
||||
slots chan struct{}
|
||||
}
|
||||
|
||||
func NewHasher(p Params, maxConcurrent int) *Hasher {
|
||||
if maxConcurrent <= 0 {
|
||||
maxConcurrent = 1
|
||||
}
|
||||
return &Hasher{params: p, slots: make(chan struct{}, maxConcurrent)}
|
||||
}
|
||||
|
||||
func (h *Hasher) acquire(ctx context.Context) error {
|
||||
select {
|
||||
case h.slots <- struct{}{}:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hasher) release() { <-h.slots }
|
||||
|
||||
// Hash возвращает PHC-строку Argon2id со случайной солью.
|
||||
func (h *Hasher) Hash(ctx context.Context, plain string) (string, error) {
|
||||
salt := make([]byte, h.params.SaltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("password: rand: %w", err)
|
||||
}
|
||||
if err := h.acquire(ctx); err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer h.release()
|
||||
|
||||
p := h.params
|
||||
key := argon2.IDKey([]byte(plain), salt, p.Iterations, p.MemoryKiB, p.Parallelism, p.KeyLen)
|
||||
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version, p.MemoryKiB, p.Iterations, p.Parallelism,
|
||||
b64.EncodeToString(salt), b64.EncodeToString(key)), nil
|
||||
}
|
||||
|
||||
func (h *Hasher) Verify(ctx context.Context, plain, encoded string) (bool, error) {
|
||||
p, salt, want, err := decode(encoded)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := h.acquire(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer h.release()
|
||||
|
||||
got := argon2.IDKey([]byte(plain), salt, p.Iterations, p.MemoryKiB, p.Parallelism, uint32(len(want)))
|
||||
return subtle.ConstantTimeCompare(got, want) == 1, nil
|
||||
}
|
||||
|
||||
func decode(encoded string) (Params, []byte, []byte, error) {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" {
|
||||
return Params{}, nil, nil, ErrMalformedHash
|
||||
}
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version {
|
||||
return Params{}, nil, nil, ErrMalformedHash
|
||||
}
|
||||
var p Params
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.MemoryKiB, &p.Iterations, &p.Parallelism); err != nil {
|
||||
return Params{}, nil, nil, ErrMalformedHash
|
||||
}
|
||||
salt, err := b64.DecodeString(parts[4])
|
||||
if err != nil || len(salt) == 0 {
|
||||
return Params{}, nil, nil, ErrMalformedHash
|
||||
}
|
||||
key, err := b64.DecodeString(parts[5])
|
||||
if err != nil || len(key) == 0 {
|
||||
return Params{}, nil, nil, ErrMalformedHash
|
||||
}
|
||||
return p, salt, key, nil
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package password
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var testParams = Params{MemoryKiB: 64, Iterations: 1, Parallelism: 1, SaltLen: 16, KeyLen: 32}
|
||||
|
||||
func TestHashVerify(t *testing.T) {
|
||||
h := NewHasher(testParams, 2)
|
||||
ctx := context.Background()
|
||||
|
||||
pw := "пароль:с-двоеточием-и-юникодом"
|
||||
encoded, err := h.Hash(ctx, pw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(encoded, "$argon2id$v=19$m=64,t=1,p=1$") {
|
||||
t.Errorf("unexpected format %q", encoded)
|
||||
}
|
||||
if strings.Contains(encoded, pw) {
|
||||
t.Error("hash contains plaintext")
|
||||
}
|
||||
|
||||
ok, err := h.Verify(ctx, pw, encoded)
|
||||
if err != nil || !ok {
|
||||
t.Errorf("Verify(correct) = %v, %v", ok, err)
|
||||
}
|
||||
ok, err = h.Verify(ctx, pw+"x", encoded)
|
||||
if err != nil || ok {
|
||||
t.Errorf("Verify(wrong) = %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHash_RandomSalt(t *testing.T) {
|
||||
h := NewHasher(testParams, 1)
|
||||
a, _ := h.Hash(context.Background(), "same-password-123")
|
||||
b, _ := h.Hash(context.Background(), "same-password-123")
|
||||
if a == b {
|
||||
t.Error("two hashes of the same password are equal: salt is not random")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerify_UsesParamsFromHash(t *testing.T) {
|
||||
old := NewHasher(testParams, 1)
|
||||
encoded, _ := old.Hash(context.Background(), "long-enough-password")
|
||||
|
||||
stronger := testParams
|
||||
stronger.Iterations = 3
|
||||
ok, err := NewHasher(stronger, 1).Verify(context.Background(), "long-enough-password", encoded)
|
||||
if err != nil || !ok {
|
||||
t.Errorf("old hash must verify after params change: %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerify_Malformed(t *testing.T) {
|
||||
h := NewHasher(testParams, 1)
|
||||
for _, s := range []string{"", "!", "$argon2i$v=19$m=64,t=1,p=1$AAAA$AAAA", "$argon2id$v=19$m=64$AAAA$AAAA"} {
|
||||
if _, err := h.Verify(context.Background(), "x", s); !errors.Is(err, ErrMalformedHash) {
|
||||
t.Errorf("Verify(%q) err = %v, want ErrMalformedHash", s, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHash_RespectsContextWhenBusy(t *testing.T) {
|
||||
h := NewHasher(testParams, 1)
|
||||
h.slots <- struct{}{} // единственный слот занят
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := h.Hash(ctx, "long-enough-password"); !errors.Is(err, context.Canceled) {
|
||||
t.Errorf("err = %v, want context.Canceled", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/password"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/token"
|
||||
)
|
||||
|
||||
var (
|
||||
_ AuthService = (*Auth)(nil)
|
||||
)
|
||||
|
||||
type Auth struct {
|
||||
users store.UserStore
|
||||
sessions session.Store
|
||||
hasher *password.Hasher
|
||||
ttl time.Duration
|
||||
now func() time.Time
|
||||
|
||||
dummyHash string
|
||||
}
|
||||
|
||||
func NewAuth(users store.UserStore, sessions session.Store, hasher *password.Hasher, ttl time.Duration) (*Auth, error) {
|
||||
dummy, err := hasher.Hash(context.Background(), "dummy-password-for-timing")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("auth: dummy hash: %w", err)
|
||||
}
|
||||
return &Auth{
|
||||
users: users,
|
||||
sessions: sessions,
|
||||
hasher: hasher,
|
||||
ttl: ttl,
|
||||
now: time.Now,
|
||||
dummyHash: dummy,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a *Auth) Login(ctx context.Context, username, plainPassword string) (domain.Session, error) {
|
||||
user, hash, err := a.users.CredentialsByUsername(ctx, username)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
_, _ = a.hasher.Verify(ctx, plainPassword, a.dummyHash)
|
||||
return domain.Session{}, domain.ErrUnauthorized
|
||||
case err != nil:
|
||||
return domain.Session{}, err
|
||||
}
|
||||
|
||||
ok, err := a.hasher.Verify(ctx, plainPassword, hash)
|
||||
if err != nil {
|
||||
if errors.Is(err, password.ErrMalformedHash) {
|
||||
return domain.Session{}, domain.ErrUnauthorized
|
||||
}
|
||||
return domain.Session{}, err
|
||||
}
|
||||
if !ok {
|
||||
return domain.Session{}, domain.ErrUnauthorized
|
||||
}
|
||||
|
||||
plain, tokenHash, err := token.New()
|
||||
if err != nil {
|
||||
return domain.Session{}, err
|
||||
}
|
||||
expiresAt := a.now().Add(a.ttl).UTC().Truncate(time.Second)
|
||||
if err := a.sessions.Save(ctx, tokenHash, session.Session{UserID: user.ID, ExpiresAt: expiresAt}); err != nil {
|
||||
return domain.Session{}, err
|
||||
}
|
||||
return domain.Session{Token: plain, ExpiresAt: expiresAt, User: user}, nil
|
||||
}
|
||||
|
||||
func (a *Auth) Authenticate(ctx context.Context, plainToken string) (string, error) {
|
||||
tokenHash, err := token.Parse(plainToken)
|
||||
if err != nil {
|
||||
return "", domain.ErrUnauthorized
|
||||
}
|
||||
s, err := a.sessions.Get(ctx, tokenHash)
|
||||
if errors.Is(err, session.ErrNotFound) {
|
||||
return "", domain.ErrUnauthorized
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !a.now().Before(s.ExpiresAt) {
|
||||
return "", domain.ErrUnauthorized
|
||||
}
|
||||
return s.UserID, nil
|
||||
}
|
||||
|
||||
func (a *Auth) Logout(ctx context.Context, plainToken string) error {
|
||||
tokenHash, err := token.Parse(plainToken)
|
||||
if err != nil {
|
||||
return domain.ErrUnauthorized
|
||||
}
|
||||
return a.sessions.Delete(ctx, tokenHash)
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
var (
|
||||
_ ChatsService = (*Chats)(nil)
|
||||
)
|
||||
|
||||
type Chats struct {
|
||||
store store.ChatStore
|
||||
}
|
||||
|
||||
func NewChats(s store.ChatStore) *Chats {
|
||||
return &Chats{store: s}
|
||||
}
|
||||
|
||||
func (c *Chats) Create(ctx context.Context, callerID, title string, memberIDs []string) (domain.Chat, error) {
|
||||
if err := validate.ChatTitle(title); err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
memberIDs, err := validate.MemberIDs(memberIDs, callerID)
|
||||
if err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
return c.store.CreateChat(ctx, callerID, title, memberIDs)
|
||||
}
|
||||
|
||||
func (c *Chats) Get(ctx context.Context, callerID, chatID string) (domain.Chat, error) {
|
||||
chatID, err := validate.CanonicalUUID("chat_id", chatID)
|
||||
if err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
return c.store.ChatByID(ctx, callerID, chatID)
|
||||
}
|
||||
|
||||
func (c *Chats) List(ctx context.Context, callerID, cursor string, limit int) (domain.Page[domain.Chat], error) {
|
||||
if err := validate.Limit(limit); err != nil {
|
||||
return domain.Page[domain.Chat]{}, err
|
||||
}
|
||||
return c.store.ListChats(ctx, callerID, cursor, limit)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
var (
|
||||
_ MessagesService = (*Messages)(nil)
|
||||
)
|
||||
|
||||
type Messages struct {
|
||||
store store.MessageStore
|
||||
}
|
||||
|
||||
func NewMessages(s store.MessageStore) *Messages {
|
||||
return &Messages{store: s}
|
||||
}
|
||||
|
||||
func (m *Messages) Send(ctx context.Context, callerID, chatID, idempotencyKey, text string) (domain.Message, error) {
|
||||
chatID, err := validate.CanonicalUUID("chat_id", chatID)
|
||||
if err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
if err := validate.IdempotencyKey(idempotencyKey); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
if err := validate.MessageText(text); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
return m.store.AddMessage(ctx, callerID, chatID, idempotencyKey, text)
|
||||
}
|
||||
|
||||
func (m *Messages) List(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) {
|
||||
chatID, err := validate.CanonicalUUID("chat_id", chatID)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
if err := validate.Limit(limit); err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
return m.store.ListMessages(ctx, callerID, chatID, cursor, limit)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
type UsersService interface {
|
||||
Register(ctx context.Context, username, displayName, password string) (domain.User, error)
|
||||
Me(ctx context.Context, callerID string) (domain.User, error)
|
||||
}
|
||||
|
||||
type ChatsService interface {
|
||||
Create(ctx context.Context, callerID, title string, memberIDs []string) (domain.Chat, error)
|
||||
Get(ctx context.Context, callerID, chatID string) (domain.Chat, error)
|
||||
List(ctx context.Context, callerID, cursor string, limit int) (domain.Page[domain.Chat], error)
|
||||
}
|
||||
|
||||
type MessagesService interface {
|
||||
Send(ctx context.Context, callerID, chatID, idempotencyKey, text string) (domain.Message, error)
|
||||
List(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error)
|
||||
}
|
||||
|
||||
type AuthService interface {
|
||||
Login(ctx context.Context, username, password string) (domain.Session, error)
|
||||
Authenticate(ctx context.Context, token string) (userID string, err error)
|
||||
Logout(ctx context.Context, token string) error
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/password"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
var (
|
||||
_ UsersService = (*Users)(nil)
|
||||
)
|
||||
|
||||
type Users struct {
|
||||
store store.UserStore
|
||||
hasher *password.Hasher
|
||||
}
|
||||
|
||||
func NewUsers(s store.UserStore, h *password.Hasher) *Users {
|
||||
return &Users{store: s, hasher: h}
|
||||
}
|
||||
|
||||
func (u *Users) Register(ctx context.Context, username, displayName, plainPassword string) (domain.User, error) {
|
||||
if err := validate.Username(username); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
if err := validate.DisplayName(displayName); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
if err := validate.Password(plainPassword); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
hash, err := u.hasher.Hash(ctx, plainPassword)
|
||||
if err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
return u.store.CreateUser(ctx, username, displayName, hash)
|
||||
}
|
||||
|
||||
func (u *Users) Me(ctx context.Context, callerID string) (domain.User, error) {
|
||||
return u.store.UserByID(ctx, callerID)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var _ Store = (*Memory)(nil)
|
||||
|
||||
type Memory struct {
|
||||
mu sync.Mutex
|
||||
sessions map[string]Session
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewMemory() *Memory {
|
||||
return &Memory{sessions: make(map[string]Session), now: time.Now}
|
||||
}
|
||||
|
||||
func (m *Memory) Save(_ context.Context, tokenHash []byte, s Session) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.sessions[string(tokenHash)] = s
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) Get(_ context.Context, tokenHash []byte) (Session, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
s, ok := m.sessions[string(tokenHash)]
|
||||
if !ok {
|
||||
return Session{}, ErrNotFound
|
||||
}
|
||||
if !m.now().Before(s.ExpiresAt) {
|
||||
delete(m.sessions, string(tokenHash))
|
||||
return Session{}, ErrNotFound
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (m *Memory) Delete(_ context.Context, tokenHash []byte) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
delete(m.sessions, string(tokenHash))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) Ping(context.Context) error { return nil }
|
||||
@@ -0,0 +1,21 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Session struct {
|
||||
UserID string `json:"user_id"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
var ErrNotFound = errors.New("session: not found")
|
||||
|
||||
type Store interface {
|
||||
Save(ctx context.Context, tokenHash []byte, s Session) error
|
||||
Get(ctx context.Context, tokenHash []byte) (Session, error)
|
||||
Delete(ctx context.Context, tokenHash []byte) error
|
||||
Ping(ctx context.Context) error
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
var _ Store = (*Valkey)(nil)
|
||||
|
||||
const keyPrefix = "session:"
|
||||
|
||||
type Valkey struct {
|
||||
client *redis.Client
|
||||
}
|
||||
|
||||
func NewValkey(client *redis.Client) *Valkey {
|
||||
return &Valkey{client: client}
|
||||
}
|
||||
|
||||
func Connect(ctx context.Context, cfg config.Cache) (*redis.Client, error) {
|
||||
url, err := urlFrom(cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
opts, err := redis.ParseURL(url)
|
||||
if err != nil {
|
||||
return nil, errors.New("session: invalid CACHE_URL")
|
||||
}
|
||||
timeout := time.Duration(cfg.TimeoutMs) * time.Millisecond
|
||||
opts.PoolSize = cfg.PoolSize
|
||||
opts.DialTimeout = timeout
|
||||
opts.ReadTimeout = timeout
|
||||
opts.WriteTimeout = timeout
|
||||
opts.PoolTimeout = timeout
|
||||
opts.MaxRetries = 1
|
||||
|
||||
client := redis.NewClient(opts)
|
||||
pingCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
if err := client.Ping(pingCtx).Err(); err != nil {
|
||||
_ = client.Close()
|
||||
return nil, fmt.Errorf("session: ping: %w", err)
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func urlFrom(cfg config.Cache) (string, error) {
|
||||
if cfg.URLFile != "" {
|
||||
b, err := os.ReadFile(cfg.URLFile)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("session: read CACHE_URL_FILE: %w", err)
|
||||
}
|
||||
return strings.TrimSpace(string(b)), nil
|
||||
}
|
||||
if cfg.URL != "" {
|
||||
return cfg.URL, nil
|
||||
}
|
||||
return "", errors.New("session: CACHE_URL_FILE or CACHE_URL is required")
|
||||
}
|
||||
|
||||
func key(tokenHash []byte) string {
|
||||
return keyPrefix + hex.EncodeToString(tokenHash)
|
||||
}
|
||||
|
||||
func (v *Valkey) Save(ctx context.Context, tokenHash []byte, s Session) error {
|
||||
val, err := json.Marshal(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// NX: 256-битный токен не совпадёт, но перезаписать чужую сессию нельзя даже теоретически.
|
||||
err = v.client.SetArgs(ctx, key(tokenHash), val, redis.SetArgs{
|
||||
Mode: "NX",
|
||||
ExpireAt: s.ExpiresAt,
|
||||
}).Err()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return fmt.Errorf("session: token collision")
|
||||
}
|
||||
return unavailable(err)
|
||||
}
|
||||
|
||||
func (v *Valkey) Get(ctx context.Context, tokenHash []byte) (Session, error) {
|
||||
val, err := v.client.Get(ctx, key(tokenHash)).Bytes()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return Session{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return Session{}, unavailable(err)
|
||||
}
|
||||
var s Session
|
||||
if err := json.Unmarshal(val, &s); err != nil {
|
||||
return Session{}, fmt.Errorf("session: corrupt value: %w", err)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (v *Valkey) Delete(ctx context.Context, tokenHash []byte) error {
|
||||
return unavailable(v.client.Del(ctx, key(tokenHash)).Err())
|
||||
}
|
||||
|
||||
func (v *Valkey) Ping(ctx context.Context) error {
|
||||
return unavailable(v.client.Ping(ctx).Err())
|
||||
}
|
||||
|
||||
func unavailable(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("%w: session store: %v", domain.ErrUnavailable, err)
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
type Chats struct {
|
||||
conn
|
||||
}
|
||||
|
||||
func (c *Chats) CreateChat(ctx context.Context, callerID, title string, memberIDs []string) (domain.Chat, error) {
|
||||
if strings.TrimSpace(title) == "" {
|
||||
return domain.Chat{}, domain.ErrInvalidArgument
|
||||
}
|
||||
if len(memberIDs) == 0 || len(memberIDs) > 100 {
|
||||
return domain.Chat{}, domain.ErrInvalidArgument
|
||||
}
|
||||
seen := make(map[string]struct{}, len(memberIDs))
|
||||
callerInMembers := false
|
||||
for _, id := range memberIDs {
|
||||
if _, dup := seen[id]; dup {
|
||||
return domain.Chat{}, domain.ErrInvalidArgument
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
if id == callerID {
|
||||
callerInMembers = true
|
||||
}
|
||||
}
|
||||
if !callerInMembers {
|
||||
return domain.Chat{}, domain.ErrInvalidArgument
|
||||
}
|
||||
|
||||
ctx, cancel := c.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
tx, err := c.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return domain.Chat{}, mapErr(err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
chat := domain.Chat{Title: title}
|
||||
err = tx.QueryRow(ctx, `
|
||||
INSERT INTO chats (title)
|
||||
VALUES ($1)
|
||||
RETURNING id::text, created_at`,
|
||||
encodeText(title),
|
||||
).Scan(&chat.ID, &chat.CreatedAt)
|
||||
if err != nil {
|
||||
return domain.Chat{}, mapErr(err)
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO chat_members (chat_id, user_id)
|
||||
SELECT $1, unnest($2::uuid[])`,
|
||||
chat.ID, memberIDs,
|
||||
)
|
||||
if err != nil {
|
||||
return domain.Chat{}, mapErr(err)
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return domain.Chat{}, mapErr(err)
|
||||
}
|
||||
|
||||
chat.MemberIDs = append([]string(nil), memberIDs...)
|
||||
chat.CreatedAt = chat.CreatedAt.UTC()
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (c *Chats) ChatByID(ctx context.Context, callerID, chatID string) (domain.Chat, error) {
|
||||
ctx, cancel := c.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
chat := domain.Chat{}
|
||||
err := c.pool.QueryRow(ctx, `
|
||||
SELECT c.id::text, c.title, c.created_at,
|
||||
(SELECT array_agg(m.user_id::text ORDER BY m.user_id)
|
||||
FROM chat_members m WHERE m.chat_id = c.id)
|
||||
FROM chats c
|
||||
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2
|
||||
WHERE c.id = $1`,
|
||||
chatID, callerID,
|
||||
).Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs)
|
||||
if err != nil {
|
||||
err = mapErr(err)
|
||||
if err == domain.ErrInvalidArgument {
|
||||
return domain.Chat{}, domain.ErrNotFound
|
||||
}
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
chat.Title = decodeText(chat.Title)
|
||||
chat.CreatedAt = chat.CreatedAt.UTC()
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (c *Chats) ListChats(ctx context.Context, callerID, cursor string, limit int) (domain.Page[domain.Chat], error) {
|
||||
if limit <= 0 || limit > 100 {
|
||||
return domain.Page[domain.Chat]{}, domain.ErrInvalidArgument
|
||||
}
|
||||
cur, err := domain.DecodeCursor(cursor)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Chat]{}, err
|
||||
}
|
||||
scope := "chats:" + callerID
|
||||
if cursor != "" && cur.Scope != scope {
|
||||
return domain.Page[domain.Chat]{}, domain.ErrInvalidArgument
|
||||
}
|
||||
afterTime, afterID := cursorArgs(cur)
|
||||
|
||||
ctx, cancel := c.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
rows, err := c.pool.Query(ctx, `
|
||||
SELECT c.id::text, c.title, c.created_at,
|
||||
(SELECT array_agg(m.user_id::text ORDER BY m.user_id)
|
||||
FROM chat_members m WHERE m.chat_id = c.id)
|
||||
FROM chat_members me
|
||||
JOIN chats c ON c.id = me.chat_id
|
||||
WHERE me.user_id = $1
|
||||
AND ($2::timestamptz IS NULL OR (c.created_at, c.id) > ($2, $3::uuid))
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4`,
|
||||
callerID, afterTime, afterID, limit+1,
|
||||
)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Chat]{}, mapErr(err)
|
||||
}
|
||||
out, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (domain.Chat, error) {
|
||||
var ch domain.Chat
|
||||
err := r.Scan(&ch.ID, &ch.Title, &ch.CreatedAt, &ch.MemberIDs)
|
||||
ch.Title = decodeText(ch.Title)
|
||||
ch.CreatedAt = ch.CreatedAt.UTC()
|
||||
return ch, err
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Page[domain.Chat]{}, mapErr(err)
|
||||
}
|
||||
|
||||
page := domain.Page[domain.Chat]{}
|
||||
if len(out) > limit {
|
||||
last := out[limit-1]
|
||||
page.NextCursor = domain.EncodeCursor(domain.Cursor{
|
||||
CreatedAt: last.CreatedAt,
|
||||
ID: last.ID,
|
||||
Scope: scope,
|
||||
})
|
||||
out = out[:limit]
|
||||
}
|
||||
page.Items = out
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func cursorArgs(c domain.Cursor) (*time.Time, *string) {
|
||||
if c.IsZero() {
|
||||
return nil, nil
|
||||
}
|
||||
return &c.CreatedAt, &c.ID
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
)
|
||||
|
||||
var _ store.Store = (*DB)(nil)
|
||||
|
||||
type DB struct {
|
||||
*Users
|
||||
*Chats
|
||||
*Messages
|
||||
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool, queryTimeout time.Duration) *DB {
|
||||
c := conn{pool: pool, timeout: queryTimeout}
|
||||
return &DB{
|
||||
Users: &Users{conn: c},
|
||||
Chats: &Chats{conn: c},
|
||||
Messages: &Messages{conn: c},
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
func Connect(ctx context.Context, cfg config.Database) (*pgxpool.Pool, error) {
|
||||
dsn, err := dsnFrom(cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pcfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, errors.New("db: invalid DSN")
|
||||
}
|
||||
pcfg.MaxConns = cfg.MaxConns
|
||||
pcfg.ConnConfig.ConnectTimeout = time.Duration(cfg.ConnectTimeoutMs) * time.Millisecond
|
||||
if !cfg.EnableBitmapScan {
|
||||
pcfg.ConnConfig.RuntimeParams["enable_bitmapscan"] = "off"
|
||||
}
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, pcfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("db: pool: %w", err)
|
||||
}
|
||||
|
||||
pingCtx, cancel := context.WithTimeout(ctx, pcfg.ConnConfig.ConnectTimeout)
|
||||
defer cancel()
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("db: ping: %w", err)
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
func dsnFrom(cfg config.Database) (string, error) {
|
||||
if cfg.URLFile != "" {
|
||||
b, err := os.ReadFile(cfg.URLFile)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("db: read DATABASE_URL_FILE: %w", err)
|
||||
}
|
||||
return strings.TrimSpace(string(b)), nil
|
||||
}
|
||||
if cfg.URL != "" {
|
||||
return cfg.URL, nil
|
||||
}
|
||||
return "", errors.New("db: DATABASE_URL_FILE or DATABASE_URL is required")
|
||||
}
|
||||
|
||||
func (d *DB) Ping(ctx context.Context) error {
|
||||
return d.pool.Ping(ctx)
|
||||
}
|
||||
|
||||
func (d *DB) Close() {
|
||||
d.pool.Close()
|
||||
}
|
||||
|
||||
type conn struct {
|
||||
pool *pgxpool.Pool
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
func (c conn) withTimeout(parent context.Context) (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(parent, c.timeout)
|
||||
}
|
||||
|
||||
|
||||
const (
|
||||
codeUniqueViolation = "23505"
|
||||
codeForeignKeyViolation = "23503"
|
||||
codeCheckViolation = "23514"
|
||||
codeInvalidTextRepr = "22P02"
|
||||
)
|
||||
|
||||
func mapErr(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.ErrNotFound
|
||||
}
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
switch pgErr.Code {
|
||||
case codeUniqueViolation:
|
||||
return domain.ErrConflict
|
||||
case codeForeignKeyViolation, codeCheckViolation, codeInvalidTextRepr:
|
||||
return domain.ErrInvalidArgument
|
||||
}
|
||||
switch pgErr.Code[:2] {
|
||||
case "08", "53", "57":
|
||||
return fmt.Errorf("%w: db: %s", domain.ErrUnavailable, pgErr.Code)
|
||||
}
|
||||
return fmt.Errorf("db: %s: %w", pgErr.Code, err)
|
||||
}
|
||||
return fmt.Errorf("%w: db: %v", domain.ErrUnavailable, err)
|
||||
}
|
||||
|
||||
func isFKViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == codeForeignKeyViolation
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
func TestMapErr(t *testing.T) {
|
||||
pg := func(code string) error { return &pgconn.PgError{Code: code} }
|
||||
cases := []struct {
|
||||
name string
|
||||
err error
|
||||
want error
|
||||
}{
|
||||
{"no rows", pgx.ErrNoRows, domain.ErrNotFound},
|
||||
{"unique", pg("23505"), domain.ErrConflict},
|
||||
{"fk", pg("23503"), domain.ErrInvalidArgument},
|
||||
{"check", pg("23514"), domain.ErrInvalidArgument},
|
||||
{"bad uuid text", pg("22P02"), domain.ErrInvalidArgument},
|
||||
{"admin shutdown (postgres stop)", pg("57P01"), domain.ErrUnavailable},
|
||||
{"cannot connect now (starting up)", pg("57P03"), domain.ErrUnavailable},
|
||||
{"connection failure", pg("08006"), domain.ErrUnavailable},
|
||||
{"too many connections", pg("53300"), domain.ErrUnavailable},
|
||||
{"timeout", fmt.Errorf("query: %w", context.DeadlineExceeded), domain.ErrUnavailable},
|
||||
{"dial refused", errors.New("dial tcp: connection refused"), domain.ErrUnavailable},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := mapErr(tc.err); !errors.Is(got, tc.want) {
|
||||
t.Errorf("%s: mapErr = %v, want %v", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
|
||||
if got := mapErr(pg("42601")); errors.Is(got, domain.ErrUnavailable) || errors.Is(got, domain.ErrInvalidArgument) {
|
||||
t.Errorf("syntax error mapped to %v", got)
|
||||
}
|
||||
if mapErr(nil) != nil {
|
||||
t.Error("mapErr(nil) != nil")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (m *Messages) AddPendingInvalidation(ctx context.Context, chatID string) (int64, error) {
|
||||
ctx, cancel := m.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var gen int64
|
||||
err := m.pool.QueryRow(ctx, `
|
||||
INSERT INTO cache_invalidations (chat_id) VALUES ($1)
|
||||
ON CONFLICT (chat_id) DO UPDATE
|
||||
SET gen = nextval('cache_invalidations_gen_seq'), updated_at = now()
|
||||
RETURNING gen`,
|
||||
chatID,
|
||||
).Scan(&gen)
|
||||
if err != nil {
|
||||
return 0, mapErr(err)
|
||||
}
|
||||
return gen, nil
|
||||
}
|
||||
|
||||
func (m *Messages) PendingInvalidations(ctx context.Context) (map[string]int64, error) {
|
||||
ctx, cancel := m.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
rows, err := m.pool.Query(ctx, `SELECT chat_id::text, gen FROM cache_invalidations`)
|
||||
if err != nil {
|
||||
return nil, mapErr(err)
|
||||
}
|
||||
out := map[string]int64{}
|
||||
var (
|
||||
id string
|
||||
gen int64
|
||||
)
|
||||
_, err = pgx.ForEachRow(rows, []any{&id, &gen}, func() error {
|
||||
out[id] = gen
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, mapErr(err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
|
||||
func (m *Messages) ResolvePendingInvalidation(ctx context.Context, chatID string, gen int64) error {
|
||||
ctx, cancel := m.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
_, err := m.pool.Exec(ctx,
|
||||
`DELETE FROM cache_invalidations WHERE chat_id = $1 AND gen = $2`,
|
||||
chatID, gen,
|
||||
)
|
||||
return mapErr(err)
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
type Messages struct {
|
||||
conn
|
||||
}
|
||||
|
||||
func (m *Messages) AddMessage(ctx context.Context, callerID, chatID, idempotencyKey, text string) (domain.Message, error) {
|
||||
if strings.TrimSpace(text) == "" {
|
||||
return domain.Message{}, domain.ErrInvalidArgument
|
||||
}
|
||||
|
||||
ctx, cancel := m.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
tx, err := m.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return domain.Message{}, mapErr(err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
msg := domain.Message{ChatID: chatID, AuthorID: callerID, Text: text}
|
||||
err = tx.QueryRow(ctx, `
|
||||
INSERT INTO message_idempotency_keys (user_id, chat_id, key, message_id)
|
||||
VALUES ($1, $2, $3, gen_random_uuid())
|
||||
ON CONFLICT (user_id, chat_id, key) DO NOTHING
|
||||
RETURNING message_id::text`,
|
||||
callerID, chatID, idempotencyKey,
|
||||
).Scan(&msg.ID)
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
return replayMessage(ctx, tx, callerID, chatID, idempotencyKey, text)
|
||||
case isFKViolation(err):
|
||||
return domain.Message{}, domain.ErrNotFound
|
||||
case err != nil:
|
||||
return domain.Message{}, mapErr(err)
|
||||
}
|
||||
|
||||
err = tx.QueryRow(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING created_at`,
|
||||
msg.ID, chatID, callerID, encodeText(text),
|
||||
).Scan(&msg.CreatedAt)
|
||||
if err != nil {
|
||||
return domain.Message{}, mapErr(err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return domain.Message{}, mapErr(err)
|
||||
}
|
||||
msg.CreatedAt = msg.CreatedAt.UTC()
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
func replayMessage(ctx context.Context, tx pgx.Tx, callerID, chatID, idempotencyKey, text string) (domain.Message, error) {
|
||||
msg := domain.Message{ChatID: chatID, AuthorID: callerID}
|
||||
err := tx.QueryRow(ctx, `
|
||||
SELECT m.id::text, m.text, m.created_at
|
||||
FROM message_idempotency_keys k
|
||||
JOIN messages m ON m.id = k.message_id
|
||||
WHERE k.user_id = $1 AND k.chat_id = $2 AND k.key = $3`,
|
||||
callerID, chatID, idempotencyKey,
|
||||
).Scan(&msg.ID, &msg.Text, &msg.CreatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Message{}, domain.ErrUnavailable
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Message{}, mapErr(err)
|
||||
}
|
||||
msg.Text = decodeText(msg.Text)
|
||||
if msg.Text != text {
|
||||
return domain.Message{}, domain.ErrIdempotencyConflict
|
||||
}
|
||||
msg.CreatedAt = msg.CreatedAt.UTC()
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
func (m *Messages) PurgeIdempotencyKeys(ctx context.Context, ttl time.Duration) (int64, error) {
|
||||
ctx, cancel := m.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
tag, err := m.pool.Exec(ctx,
|
||||
`DELETE FROM message_idempotency_keys WHERE created_at < now() - make_interval(secs => $1)`,
|
||||
ttl.Seconds(),
|
||||
)
|
||||
if err != nil {
|
||||
return 0, mapErr(err)
|
||||
}
|
||||
return tag.RowsAffected(), nil
|
||||
}
|
||||
|
||||
func (m *Messages) ListMessages(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) {
|
||||
member, err := m.IsMember(ctx, chatID, callerID)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
if !member {
|
||||
return domain.Page[domain.Message]{}, domain.ErrNotFound
|
||||
}
|
||||
return m.HistoryPage(ctx, chatID, cursor, limit)
|
||||
}
|
||||
|
||||
|
||||
func (m *Messages) IsMember(ctx context.Context, chatID, userID string) (bool, error) {
|
||||
ctx, cancel := m.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var member bool
|
||||
err := m.pool.QueryRow(ctx,
|
||||
`SELECT EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`,
|
||||
chatID, userID,
|
||||
).Scan(&member)
|
||||
if err != nil {
|
||||
return false, mapErr(err)
|
||||
}
|
||||
return member, nil
|
||||
}
|
||||
|
||||
func (m *Messages) HistoryPage(ctx context.Context, chatID, cursor string, limit int) (domain.Page[domain.Message], error) {
|
||||
if limit <= 0 || limit > 100 {
|
||||
return domain.Page[domain.Message]{}, domain.ErrInvalidArgument
|
||||
}
|
||||
cur, err := domain.DecodeCursor(cursor)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
scope := "chat:" + chatID
|
||||
if cursor != "" && cur.Scope != scope {
|
||||
return domain.Page[domain.Message]{}, domain.ErrInvalidArgument
|
||||
}
|
||||
ctx, cancel := m.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var rows pgx.Rows
|
||||
if cur.IsZero() {
|
||||
rows, err = m.pool.Query(ctx, `
|
||||
SELECT m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $2`,
|
||||
chatID, limit+1,
|
||||
)
|
||||
} else {
|
||||
rows, err = m.pool.Query(ctx, `
|
||||
SELECT m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1
|
||||
AND (m.created_at, m.id) > ($2, $3::uuid)
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $4`,
|
||||
chatID, cur.CreatedAt, cur.ID, limit+1,
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, mapErr(err)
|
||||
}
|
||||
out, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (domain.Message, error) {
|
||||
var msg domain.Message
|
||||
err := r.Scan(&msg.ID, &msg.ChatID, &msg.AuthorID, &msg.Text, &msg.CreatedAt)
|
||||
msg.Text = decodeText(msg.Text)
|
||||
msg.CreatedAt = msg.CreatedAt.UTC()
|
||||
return msg, err
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, mapErr(err)
|
||||
}
|
||||
|
||||
page := domain.Page[domain.Message]{}
|
||||
if len(out) > limit {
|
||||
last := out[limit-1]
|
||||
page.NextCursor = domain.EncodeCursor(domain.Cursor{
|
||||
CreatedAt: last.CreatedAt,
|
||||
ID: last.ID,
|
||||
Scope: scope,
|
||||
})
|
||||
out = out[:limit]
|
||||
}
|
||||
page.Items = out
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package db
|
||||
|
||||
import "strings"
|
||||
|
||||
var (
|
||||
textEncoder = strings.NewReplacer(`\`, `\\`, "\x00", `\0`)
|
||||
textDecoder = strings.NewReplacer(`\\`, `\`, `\0`, "\x00")
|
||||
)
|
||||
|
||||
func encodeText(s string) string {
|
||||
if !strings.ContainsAny(s, "\\\x00") {
|
||||
return s
|
||||
}
|
||||
return textEncoder.Replace(s)
|
||||
}
|
||||
|
||||
func decodeText(s string) string {
|
||||
if !strings.Contains(s, `\`) {
|
||||
return s
|
||||
}
|
||||
return textDecoder.Replace(s)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package db
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestTextEscapeRoundTrip(t *testing.T) {
|
||||
cases := []string{"", "plain", "\x00", "a\x00b", `\`, `\0`, `\\0`, "\\\x00", "\x00\\0\x00", "привет\x00мир"}
|
||||
for _, s := range cases {
|
||||
enc := encodeText(s)
|
||||
for i := 0; i < len(enc); i++ {
|
||||
if enc[i] == 0 {
|
||||
t.Fatalf("encodeText(%q) = %q содержит NUL", s, enc)
|
||||
}
|
||||
}
|
||||
if got := decodeText(enc); got != s {
|
||||
t.Fatalf("decodeText(encodeText(%q)) = %q", s, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
type Users struct {
|
||||
conn
|
||||
}
|
||||
|
||||
func (u *Users) CreateUser(ctx context.Context, username, displayName, passwordHash string) (domain.User, error) {
|
||||
if strings.TrimSpace(username) == "" || strings.TrimSpace(displayName) == "" || passwordHash == "" {
|
||||
return domain.User{}, domain.ErrInvalidArgument
|
||||
}
|
||||
|
||||
ctx, cancel := u.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
user := domain.User{Username: username, DisplayName: displayName}
|
||||
err := u.pool.QueryRow(ctx, `
|
||||
INSERT INTO users (username, display_name, password_hash)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING id::text, created_at`,
|
||||
username, encodeText(displayName), passwordHash,
|
||||
).Scan(&user.ID, &user.CreatedAt)
|
||||
if err != nil {
|
||||
return domain.User{}, mapErr(err)
|
||||
}
|
||||
user.CreatedAt = user.CreatedAt.UTC()
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (u *Users) UserByID(ctx context.Context, id string) (domain.User, error) {
|
||||
ctx, cancel := u.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
user := domain.User{}
|
||||
err := u.pool.QueryRow(ctx, `
|
||||
SELECT id::text, username, display_name, created_at
|
||||
FROM users
|
||||
WHERE id = $1`,
|
||||
id,
|
||||
).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
|
||||
if err != nil {
|
||||
err = mapErr(err)
|
||||
if err == domain.ErrInvalidArgument {
|
||||
return domain.User{}, domain.ErrNotFound
|
||||
}
|
||||
return domain.User{}, err
|
||||
}
|
||||
user.DisplayName = decodeText(user.DisplayName)
|
||||
user.CreatedAt = user.CreatedAt.UTC()
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (u *Users) CredentialsByUsername(ctx context.Context, username string) (domain.User, string, error) {
|
||||
ctx, cancel := u.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
user := domain.User{}
|
||||
var hash string
|
||||
err := u.pool.QueryRow(ctx, `
|
||||
SELECT id::text, username, display_name, created_at, password_hash
|
||||
FROM users
|
||||
WHERE username = $1`,
|
||||
encodeText(username),
|
||||
).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &hash)
|
||||
if err != nil {
|
||||
return domain.User{}, "", mapErr(err)
|
||||
}
|
||||
user.DisplayName = decodeText(user.DisplayName)
|
||||
user.CreatedAt = user.CreatedAt.UTC()
|
||||
return user, hash, nil
|
||||
}
|
||||
|
||||
func (u *Users) UsernameExists(ctx context.Context, username string) bool {
|
||||
ctx, cancel := u.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var exists bool
|
||||
err := u.pool.QueryRow(ctx,
|
||||
`SELECT EXISTS (SELECT 1 FROM users WHERE username = $1)`,
|
||||
encodeText(username),
|
||||
).Scan(&exists)
|
||||
return err == nil && exists
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var _ Store = (*Memory)(nil)
|
||||
|
||||
type Memory struct {
|
||||
mu sync.RWMutex
|
||||
|
||||
users map[string]domain.User
|
||||
byName map[string]string
|
||||
hashes map[string]string
|
||||
|
||||
chats map[string]*chatBucket
|
||||
chatOrder []string
|
||||
|
||||
lastTime time.Time
|
||||
|
||||
idempotency map[string]domain.Message
|
||||
|
||||
maxMessages int
|
||||
messagesTotal int
|
||||
}
|
||||
|
||||
type chatBucket struct {
|
||||
chat domain.Chat
|
||||
members map[string]struct{}
|
||||
messages []domain.Message
|
||||
}
|
||||
|
||||
func New() *Memory {
|
||||
return NewWithLimit(0)
|
||||
}
|
||||
|
||||
func NewWithLimit(maxMessages int) *Memory {
|
||||
return &Memory{
|
||||
users: make(map[string]domain.User),
|
||||
byName: make(map[string]string),
|
||||
hashes: make(map[string]string),
|
||||
chats: make(map[string]*chatBucket),
|
||||
idempotency: make(map[string]domain.Message),
|
||||
maxMessages: maxMessages,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Memory) MessagesTotal() int {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
return m.messagesTotal
|
||||
}
|
||||
|
||||
func (m *Memory) now() time.Time {
|
||||
t := time.Now().UTC()
|
||||
if !t.After(m.lastTime) {
|
||||
t = m.lastTime.Add(time.Nanosecond)
|
||||
}
|
||||
m.lastTime = t
|
||||
return t
|
||||
}
|
||||
|
||||
func (m *Memory) CreateUser(_ context.Context, username, displayName, passwordHash string) (domain.User, error) {
|
||||
if strings.TrimSpace(username) == "" || strings.TrimSpace(displayName) == "" {
|
||||
return domain.User{}, domain.ErrInvalidArgument
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
if _, taken := m.byName[username]; taken {
|
||||
return domain.User{}, domain.ErrConflict
|
||||
}
|
||||
|
||||
u := domain.User{
|
||||
ID: uuid.NewString(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: m.now(),
|
||||
}
|
||||
m.users[u.ID] = u
|
||||
m.byName[username] = u.ID
|
||||
m.hashes[u.ID] = passwordHash
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (m *Memory) UserByID(_ context.Context, id string) (domain.User, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
u, ok := m.users[id]
|
||||
if !ok {
|
||||
return domain.User{}, domain.ErrNotFound
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (m *Memory) CredentialsByUsername(_ context.Context, username string) (domain.User, string, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
id, ok := m.byName[username]
|
||||
if !ok {
|
||||
return domain.User{}, "", domain.ErrNotFound
|
||||
}
|
||||
return m.users[id], m.hashes[id], nil
|
||||
}
|
||||
|
||||
func (m *Memory) UsernameExists(_ context.Context, username string) bool {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
_, taken := m.byName[username]
|
||||
return taken
|
||||
}
|
||||
|
||||
func (m *Memory) CreateChat(_ context.Context, callerID, title string, memberIDs []string) (domain.Chat, error) {
|
||||
if strings.TrimSpace(title) == "" {
|
||||
return domain.Chat{}, domain.ErrInvalidArgument
|
||||
}
|
||||
if len(memberIDs) == 0 || len(memberIDs) > 100 {
|
||||
return domain.Chat{}, domain.ErrInvalidArgument
|
||||
}
|
||||
|
||||
seen := make(map[string]struct{}, len(memberIDs))
|
||||
callerInMembers := false
|
||||
for _, id := range memberIDs {
|
||||
if _, dup := seen[id]; dup {
|
||||
return domain.Chat{}, domain.ErrInvalidArgument
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
if id == callerID {
|
||||
callerInMembers = true
|
||||
}
|
||||
}
|
||||
if !callerInMembers {
|
||||
return domain.Chat{}, domain.ErrInvalidArgument
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
for _, id := range memberIDs {
|
||||
if _, ok := m.users[id]; !ok {
|
||||
return domain.Chat{}, domain.ErrInvalidArgument
|
||||
}
|
||||
}
|
||||
|
||||
members := append([]string(nil), memberIDs...)
|
||||
|
||||
chat := domain.Chat{
|
||||
ID: uuid.NewString(),
|
||||
Title: title,
|
||||
MemberIDs: members,
|
||||
CreatedAt: m.now(),
|
||||
}
|
||||
m.chats[chat.ID] = &chatBucket{
|
||||
chat: chat,
|
||||
members: seen,
|
||||
}
|
||||
m.chatOrder = append(m.chatOrder, chat.ID)
|
||||
return cloneChat(chat), nil
|
||||
}
|
||||
|
||||
func (m *Memory) ChatByID(_ context.Context, callerID, chatID string) (domain.Chat, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
b, ok := m.chats[chatID]
|
||||
if !ok {
|
||||
return domain.Chat{}, domain.ErrNotFound
|
||||
}
|
||||
if _, member := b.members[callerID]; !member {
|
||||
return domain.Chat{}, domain.ErrNotFound
|
||||
}
|
||||
return cloneChat(b.chat), nil
|
||||
}
|
||||
|
||||
func (m *Memory) ListChats(_ context.Context, callerID, cursor string, limit int) (domain.Page[domain.Chat], error) {
|
||||
if limit <= 0 || limit > 100 {
|
||||
return domain.Page[domain.Chat]{}, domain.ErrInvalidArgument
|
||||
}
|
||||
c, err := domain.DecodeCursor(cursor)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Chat]{}, err
|
||||
}
|
||||
if cursor != "" && c.Scope != "chats:"+callerID {
|
||||
return domain.Page[domain.Chat]{}, domain.ErrInvalidArgument
|
||||
}
|
||||
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
out := make([]domain.Chat, 0, limit+1)
|
||||
for _, id := range m.chatOrder {
|
||||
b := m.chats[id]
|
||||
if _, member := b.members[callerID]; !member {
|
||||
continue
|
||||
}
|
||||
if !c.Less(b.chat.CreatedAt, b.chat.ID) {
|
||||
continue
|
||||
}
|
||||
out = append(out, cloneChat(b.chat))
|
||||
if len(out) > limit {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
page := domain.Page[domain.Chat]{}
|
||||
if len(out) > limit {
|
||||
last := out[limit-1]
|
||||
page.NextCursor = domain.EncodeCursor(domain.Cursor{
|
||||
CreatedAt: last.CreatedAt,
|
||||
ID: last.ID,
|
||||
Scope: "chats:" + callerID,
|
||||
})
|
||||
out = out[:limit]
|
||||
}
|
||||
page.Items = out
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (m *Memory) AddMessage(_ context.Context, callerID, chatID, idempotencyKey, text string) (domain.Message, error) {
|
||||
if strings.TrimSpace(text) == "" {
|
||||
return domain.Message{}, domain.ErrInvalidArgument
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
b, ok := m.chats[chatID]
|
||||
if !ok {
|
||||
return domain.Message{}, domain.ErrNotFound
|
||||
}
|
||||
if _, member := b.members[callerID]; !member {
|
||||
return domain.Message{}, domain.ErrNotFound
|
||||
}
|
||||
|
||||
idemKey := callerID + "\x00" + chatID + "\x00" + idempotencyKey
|
||||
if prev, ok := m.idempotency[idemKey]; ok {
|
||||
if prev.Text != text {
|
||||
return domain.Message{}, domain.ErrIdempotencyConflict
|
||||
}
|
||||
return prev, nil
|
||||
}
|
||||
|
||||
if m.maxMessages > 0 && m.messagesTotal >= m.maxMessages {
|
||||
return domain.Message{}, domain.ErrUnavailable
|
||||
}
|
||||
|
||||
msg := domain.Message{
|
||||
ID: uuid.NewString(),
|
||||
ChatID: chatID,
|
||||
AuthorID: callerID,
|
||||
Text: text,
|
||||
CreatedAt: m.now(),
|
||||
}
|
||||
b.messages = append(b.messages, msg)
|
||||
m.idempotency[idemKey] = msg
|
||||
m.messagesTotal++
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
func (m *Memory) ListMessages(_ context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) {
|
||||
if limit <= 0 || limit > 100 {
|
||||
return domain.Page[domain.Message]{}, domain.ErrInvalidArgument
|
||||
}
|
||||
c, err := domain.DecodeCursor(cursor)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
|
||||
if cursor != "" && c.Scope != "chat:"+chatID {
|
||||
return domain.Page[domain.Message]{}, domain.ErrInvalidArgument
|
||||
}
|
||||
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
b, ok := m.chats[chatID]
|
||||
if !ok {
|
||||
return domain.Page[domain.Message]{}, domain.ErrNotFound
|
||||
}
|
||||
if _, member := b.members[callerID]; !member {
|
||||
return domain.Page[domain.Message]{}, domain.ErrNotFound
|
||||
}
|
||||
|
||||
start := 0
|
||||
for ; start < len(b.messages); start++ {
|
||||
if c.Less(b.messages[start].CreatedAt, b.messages[start].ID) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
end := start + limit
|
||||
hasMore := end < len(b.messages)
|
||||
if end > len(b.messages) {
|
||||
end = len(b.messages)
|
||||
}
|
||||
|
||||
out := make([]domain.Message, end-start)
|
||||
copy(out, b.messages[start:end])
|
||||
|
||||
page := domain.Page[domain.Message]{Items: out}
|
||||
if hasMore && len(out) > 0 {
|
||||
last := out[len(out)-1]
|
||||
page.NextCursor = domain.EncodeCursor(domain.Cursor{
|
||||
CreatedAt: last.CreatedAt,
|
||||
ID: last.ID,
|
||||
Scope: "chat:" + chatID,
|
||||
})
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func cloneChat(c domain.Chat) domain.Chat {
|
||||
out := c
|
||||
out.MemberIDs = append([]string(nil), c.MemberIDs...)
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
|
||||
type UserStore interface {
|
||||
CreateUser(ctx context.Context, username, displayName, passwordHash string) (domain.User, error)
|
||||
UserByID(ctx context.Context, id string) (domain.User, error)
|
||||
CredentialsByUsername(ctx context.Context, username string) (domain.User, string, error)
|
||||
UsernameExists(ctx context.Context, username string) bool
|
||||
}
|
||||
|
||||
type ChatStore interface {
|
||||
CreateChat(ctx context.Context, callerID, title string, memberIDs []string) (domain.Chat, error)
|
||||
ChatByID(ctx context.Context, callerID, chatID string) (domain.Chat, error)
|
||||
ListChats(ctx context.Context, callerID, cursor string, limit int) (domain.Page[domain.Chat], error)
|
||||
}
|
||||
|
||||
type MessageStore interface {
|
||||
// AddMessage идемпотентен по (callerID, chatID, idempotencyKey): повтор с тем же
|
||||
// text возвращает исходное сообщение, с другим — domain.ErrIdempotencyConflict.
|
||||
AddMessage(ctx context.Context, callerID, chatID, idempotencyKey, text string) (domain.Message, error)
|
||||
ListMessages(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error)
|
||||
}
|
||||
|
||||
type Store interface {
|
||||
UserStore
|
||||
ChatStore
|
||||
MessageStore
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package token
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
const Bytes = 32
|
||||
|
||||
var encoding = base64.RawURLEncoding
|
||||
|
||||
var EncodedLen = encoding.EncodedLen(Bytes)
|
||||
|
||||
var ErrMalformed = errors.New("token: malformed")
|
||||
|
||||
func New() (plain string, hash []byte, err error) {
|
||||
buf := make([]byte, Bytes)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", nil, fmt.Errorf("token: rand: %w", err)
|
||||
}
|
||||
plain = encoding.EncodeToString(buf)
|
||||
return plain, Hash(plain), nil
|
||||
}
|
||||
|
||||
func Hash(plain string) []byte {
|
||||
sum := sha256.Sum256([]byte(plain))
|
||||
return sum[:]
|
||||
}
|
||||
|
||||
|
||||
func Parse(plain string) ([]byte, error) {
|
||||
if len(plain) != EncodedLen {
|
||||
return nil, ErrMalformed
|
||||
}
|
||||
raw, err := encoding.DecodeString(plain)
|
||||
if err != nil || len(raw) != Bytes {
|
||||
return nil, ErrMalformed
|
||||
}
|
||||
return Hash(plain), nil
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package token
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNew_FormatAndHash(t *testing.T) {
|
||||
plain, hash, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(plain) != EncodedLen || len(plain) < 32 {
|
||||
t.Errorf("len(token) = %d, want %d", len(plain), EncodedLen)
|
||||
}
|
||||
if len(hash) != 32 {
|
||||
t.Errorf("len(hash) = %d, want 32", len(hash))
|
||||
}
|
||||
if !bytes.Equal(hash, Hash(plain)) {
|
||||
t.Error("hash from New differs from Hash(token)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNew_Unique(t *testing.T) {
|
||||
seen := make(map[string]struct{}, 1000)
|
||||
for i := 0; i < 1000; i++ {
|
||||
plain, _, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := seen[plain]; ok {
|
||||
t.Fatalf("duplicate token %q", plain)
|
||||
}
|
||||
seen[plain] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParse(t *testing.T) {
|
||||
plain, hash, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := Parse(plain)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, hash) {
|
||||
t.Error("Parse hash differs from New hash")
|
||||
}
|
||||
|
||||
bad := []string{
|
||||
"",
|
||||
"short",
|
||||
plain[:EncodedLen-1],
|
||||
plain + "A",
|
||||
"+" + plain[1:],
|
||||
"00000000-0000-0000-0000-000000000000",
|
||||
}
|
||||
for _, s := range bad {
|
||||
if _, err := Parse(s); !errors.Is(err, ErrMalformed) {
|
||||
t.Errorf("Parse(%q) err = %v, want ErrMalformed", s, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package validate
|
||||
|
||||
import "fmt"
|
||||
|
||||
func ChatTitle(s string) error {
|
||||
if !notOnlyWhitespace(s) {
|
||||
return newError("title", "must not be empty or whitespace only")
|
||||
}
|
||||
if !codePointsBetween(s, ChatTitleMinLen, ChatTitleMaxLen) {
|
||||
return newError("title", fmt.Sprintf("length must be in [%d, %d] code points", ChatTitleMinLen, ChatTitleMaxLen))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func MemberIDs(ids []string, callerID string) ([]string, error) {
|
||||
if len(ids) < MemberIDsMin || len(ids) > MemberIDsMax {
|
||||
return nil, newError("member_ids", fmt.Sprintf("count must be in [%d, %d]", MemberIDsMin, MemberIDsMax))
|
||||
}
|
||||
|
||||
out := make([]string, 0, len(ids))
|
||||
seen := make(map[string]struct{}, len(ids))
|
||||
callerIn := false
|
||||
for i, raw := range ids {
|
||||
id, err := CanonicalUUID(fmt.Sprintf("member_ids[%d]", i), raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, dup := seen[id]; dup {
|
||||
return nil, newError("member_ids", "must not contain duplicates")
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
if id == callerID {
|
||||
callerIn = true
|
||||
}
|
||||
out = append(out, id)
|
||||
}
|
||||
|
||||
if !callerIn {
|
||||
return nil, newError("member_ids", "must contain caller")
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package validate
|
||||
|
||||
import "regexp"
|
||||
|
||||
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
func IdempotencyKey(s string) error {
|
||||
if !idempotencyKeyPattern.MatchString(s) {
|
||||
return newError("Idempotency-Key", "must match [A-Za-z0-9._:-]{1,128}")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package validate
|
||||
|
||||
import "fmt"
|
||||
|
||||
func MessageText(s string) error {
|
||||
if !notOnlyWhitespace(s) {
|
||||
return newError("text", "must not be empty or whitespace only")
|
||||
}
|
||||
if !codePointsBetween(s, MessageTextMinLen, MessageTextMaxLen) {
|
||||
return newError("text", fmt.Sprintf("length must be in [%d, %d] code points", MessageTextMinLen, MessageTextMaxLen))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package validate
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
UsernameMinLen = 3
|
||||
UsernameMaxLen = 32
|
||||
|
||||
DisplayNameMinLen = 1
|
||||
DisplayNameMaxLen = 100
|
||||
|
||||
PasswordMinLen = 12
|
||||
PasswordMaxLen = 128
|
||||
|
||||
ChatTitleMinLen = 1
|
||||
ChatTitleMaxLen = 100
|
||||
|
||||
MessageTextMinLen = 1
|
||||
MessageTextMaxLen = 4000
|
||||
|
||||
MemberIDsMin = 1
|
||||
MemberIDsMax = 100
|
||||
|
||||
LimitMin = 1
|
||||
LimitMax = 100
|
||||
LimitDefault = 50
|
||||
)
|
||||
|
||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
func CanonicalUUID(field, s string) (string, error) {
|
||||
if len(s) != 36 {
|
||||
return "", newError(field, "must be a valid UUID")
|
||||
}
|
||||
u, err := uuid.Parse(s)
|
||||
if err != nil {
|
||||
return "", newError(field, "must be a valid UUID")
|
||||
}
|
||||
return u.String(), nil
|
||||
}
|
||||
|
||||
func Limit(n int) error {
|
||||
if n < LimitMin || n > LimitMax {
|
||||
return newError("limit", fmt.Sprintf("must be in [%d, %d]", LimitMin, LimitMax))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func codePointsBetween(s string, min, max int) bool {
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= min && n <= max
|
||||
}
|
||||
|
||||
func notOnlyWhitespace(s string) bool {
|
||||
return strings.TrimSpace(s) != ""
|
||||
}
|
||||
|
||||
type Error struct {
|
||||
Field string
|
||||
Reason string
|
||||
}
|
||||
|
||||
func (e *Error) Error() string {
|
||||
return e.Field + ": " + e.Reason
|
||||
}
|
||||
|
||||
func (e *Error) Is(target error) bool {
|
||||
_, ok := target.(*Error)
|
||||
return ok
|
||||
}
|
||||
|
||||
func newError(field, reason string) *Error {
|
||||
return &Error{Field: field, Reason: reason}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package validate
|
||||
|
||||
import "fmt"
|
||||
|
||||
func Username(s string) error {
|
||||
if !usernamePattern.MatchString(s) {
|
||||
return newError("username", fmt.Sprintf("must match [a-z0-9_]{%d,%d}", UsernameMinLen, UsernameMaxLen))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func DisplayName(s string) error {
|
||||
if !notOnlyWhitespace(s) {
|
||||
return newError("display_name", "must not be empty or whitespace only")
|
||||
}
|
||||
if !codePointsBetween(s, DisplayNameMinLen, DisplayNameMaxLen) {
|
||||
return newError("display_name", fmt.Sprintf("length must be in [%d, %d] code points", DisplayNameMinLen, DisplayNameMaxLen))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Password(s string) error {
|
||||
if !notOnlyWhitespace(s) {
|
||||
return newError("password", "must not be empty or whitespace only")
|
||||
}
|
||||
if !codePointsBetween(s, PasswordMinLen, PasswordMaxLen) {
|
||||
return newError("password", fmt.Sprintf("length must be in [%d, %d] code points", PasswordMinLen, PasswordMaxLen))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user