Перенос минимума из lab1

This commit is contained in:
2026-10-30 09:21:46 +03:00
parent 65003b6119
commit e70fd2bb61
12 changed files with 1606 additions and 11 deletions
+312
View File
@@ -0,0 +1,312 @@
package api
import (
"net/http"
"strings"
"messenger/internal/store"
)
func (a *API) live(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
func (a *API) ready(w http.ResponseWriter, r *http.Request) {
if a.shutting.Load() {
a.fail(w, r, http.StatusServiceUnavailable, "unavailable", "Сервер останавливается", 1)
return
}
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
func (a *API) route(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
switch {
case path == "/api/v1/users" && r.Method == http.MethodPost:
a.createUser(w, r)
case path == "/api/v1/users/me" && r.Method == http.MethodGet:
a.currentUser(w, r)
case path == "/api/v1/chats" && r.Method == http.MethodPost:
a.createChat(w, r)
case path == "/api/v1/chats" && r.Method == http.MethodGet:
a.listChats(w, r)
default:
chatID, messages, ok := splitChatPath(path)
if !ok {
if knownWrongMethod(path) {
a.fail(w, r, http.StatusMethodNotAllowed, "invalid_request", "Метод не поддерживается", 0)
return
}
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
return
}
switch {
case !messages && r.Method == http.MethodGet:
a.getChat(w, r, chatID)
case messages && r.Method == http.MethodPost:
a.createMessage(w, r, chatID)
case messages && r.Method == http.MethodGet:
a.listMessages(w, r, chatID)
default:
a.fail(w, r, http.StatusMethodNotAllowed, "invalid_request", "Метод не поддерживается", 0)
}
}
}
func knownWrongMethod(path string) bool {
switch path {
case "/api/v1/users", "/api/v1/users/me", "/api/v1/chats":
return true
default:
return false
}
}
func (a *API) createUser(w http.ResponseWriter, r *http.Request) {
var body struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
}
if !a.readJSON(w, r, &body) {
return
}
if !usernameRe.MatchString(body.Username) || !validText(body.DisplayName, 1, 100) {
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректные поля пользователя", 0)
return
}
user, err := a.store.CreateUser(body.Username, body.DisplayName)
if err == store.ErrConflict {
a.fail(w, r, http.StatusConflict, "conflict", "Имя пользователя уже занято", 0)
return
}
if err != nil {
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
return
}
writeJSON(w, http.StatusCreated, asUser(user))
}
func (a *API) currentUser(w http.ResponseWriter, r *http.Request) {
user, ok := a.authenticate(w, r)
if !ok {
return
}
writeJSON(w, http.StatusOK, asUser(user))
}
func (a *API) createChat(w http.ResponseWriter, r *http.Request) {
caller, ok := a.authenticate(w, r)
if !ok {
return
}
var body struct {
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
}
if !a.readJSON(w, r, &body) {
return
}
if !validText(body.Title, 1, 100) || len(body.MemberIDs) < 1 || len(body.MemberIDs) > 100 {
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректные поля чата", 0)
return
}
ids := make([]string, len(body.MemberIDs))
seen := make(map[string]struct{}, len(body.MemberIDs))
callerIn := false
for i, raw := range body.MemberIDs {
id, ok := canonicalUUID(raw)
if !ok {
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
return
}
if _, dup := seen[id]; dup {
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
return
}
seen[id] = struct{}{}
if _, exists := a.store.User(id); !exists {
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
return
}
if id == caller.ID {
callerIn = true
}
ids[i] = id
}
if !callerIn {
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
return
}
chat, err := a.store.CreateChat(body.Title, ids, caller.ID)
switch err {
case nil:
writeJSON(w, http.StatusCreated, asChat(chat))
case store.ErrInvalid:
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
default:
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
}
}
func (a *API) listChats(w http.ResponseWriter, r *http.Request) {
user, ok := a.authenticate(w, r)
if !ok {
return
}
limit, cur, ok := a.pageQuery(w, r, "chats:"+user.ID)
if !ok {
return
}
items, hasMore, err := a.store.ListChats(user.ID, cur, limit)
if err == store.ErrBadCursor {
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
return
}
if err != nil {
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
return
}
out := make([]chatJSON, 0, len(items))
for _, c := range items {
out = append(out, asChat(c))
}
var next *string
if hasMore && len(items) > 0 {
last := items[len(items)-1]
encoded := encodeCursor(cursorPayload{Scope: "chats:" + user.ID, ID: last.ID, At: formatTime(last.CreatedAt)})
next = &encoded
}
writeJSON(w, http.StatusOK, chatPage{Items: out, NextCursor: next})
}
func (a *API) getChat(w http.ResponseWriter, r *http.Request, rawID string) {
user, ok := a.authenticate(w, r)
if !ok {
return
}
id, ok := a.chatID(w, r, rawID)
if !ok {
return
}
chat, err := a.store.ChatFor(id, user.ID)
if err == store.ErrNotFound {
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
return
}
if err != nil {
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
return
}
writeJSON(w, http.StatusOK, asChat(chat))
}
func (a *API) createMessage(w http.ResponseWriter, r *http.Request, rawID string) {
user, ok := a.authenticate(w, r)
if !ok {
return
}
id, ok := a.chatID(w, r, rawID)
if !ok {
return
}
if _, err := a.store.ChatFor(id, user.ID); err == store.ErrNotFound {
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
return
} else if err != nil {
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
return
}
var body struct {
Text string `json:"text"`
}
if !a.readJSON(w, r, &body) {
return
}
if !validText(body.Text, 1, 4000) {
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный текст сообщения", 0)
return
}
msg, err := a.store.AddMessage(id, user.ID, body.Text)
switch err {
case nil:
writeJSON(w, http.StatusCreated, asMessage(msg))
case store.ErrNotFound:
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
default:
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
}
}
func (a *API) listMessages(w http.ResponseWriter, r *http.Request, rawID string) {
user, ok := a.authenticate(w, r)
if !ok {
return
}
id, ok := a.chatID(w, r, rawID)
if !ok {
return
}
if _, err := a.store.ChatFor(id, user.ID); err == store.ErrNotFound {
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
return
} else if err != nil {
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
return
}
limit, cur, ok := a.pageQuery(w, r, "msg:"+id)
if !ok {
return
}
items, hasMore, err := a.store.ListMessages(id, user.ID, cur, limit)
if err == store.ErrBadCursor {
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
return
}
if err == store.ErrNotFound {
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
return
}
if err != nil {
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
return
}
out := make([]messageJSON, 0, len(items))
for _, m := range items {
out = append(out, asMessage(m))
}
var next *string
if hasMore && len(items) > 0 {
last := items[len(items)-1]
encoded := encodeCursor(cursorPayload{Scope: "msg:" + id, ID: last.ID, At: formatTime(last.CreatedAt)})
next = &encoded
}
writeJSON(w, http.StatusOK, messagePage{Items: out, NextCursor: next})
}
func (a *API) chatID(w http.ResponseWriter, r *http.Request, raw string) (string, bool) {
id, ok := canonicalUUID(raw)
if !ok {
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный идентификатор", 0)
return "", false
}
return id, true
}
func splitChatPath(path string) (id string, messages bool, ok bool) {
const prefix = "/api/v1/chats/"
if !strings.HasPrefix(path, prefix) {
return "", false, false
}
rest := strings.TrimPrefix(path, prefix)
if rest == "" || strings.Contains(rest, "/") && !strings.HasSuffix(rest, "/messages") {
return "", false, false
}
if strings.HasSuffix(rest, "/messages") {
id = strings.TrimSuffix(rest, "/messages")
if id == "" || strings.Contains(id, "/") {
return "", false, false
}
return id, true, true
}
return rest, false, true
}
+321
View File
@@ -0,0 +1,321 @@
package api
import (
"bytes"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"encoding/json"
"io"
"net/http"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
"messenger/internal/store"
)
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
var uuidRe = regexp.MustCompile(`(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
var limitRe = regexp.MustCompile(`^[0-9]{1,3}$`)
var requestIDRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,64}$`)
type errorEnvelope struct {
Error errorObject `json:"error"`
}
type errorObject struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
}
type userJSON struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt string `json:"created_at"`
}
type chatJSON struct {
ID string `json:"id"`
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
CreatedAt string `json:"created_at"`
}
type messageJSON struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt string `json:"created_at"`
}
type chatPage struct {
Items []chatJSON `json:"items"`
NextCursor *string `json:"next_cursor"`
}
type messagePage struct {
Items []messageJSON `json:"items"`
NextCursor *string `json:"next_cursor"`
}
type cursorPayload struct {
Scope string `json:"scope"`
ID string `json:"id"`
At string `json:"at"`
}
type statusWriter struct {
http.ResponseWriter
status int
wrote bool
}
func (s *statusWriter) WriteHeader(code int) {
if s.wrote {
return
}
s.status = code
s.wrote = true
s.ResponseWriter.WriteHeader(code)
}
func (s *statusWriter) Write(b []byte) (int, error) {
if !s.wrote {
s.WriteHeader(http.StatusOK)
}
return s.ResponseWriter.Write(b)
}
func (a *API) fail(w http.ResponseWriter, r *http.Request, status int, code, message string, retryAfter int) {
if retryAfter > 0 {
w.Header().Set("Retry-After", strconv.Itoa(retryAfter))
}
writeJSON(w, status, errorEnvelope{Error: errorObject{
Code: code,
Message: message,
RequestID: requestIDFrom(r),
}})
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
_ = enc.Encode(v)
}
func (a *API) readJSON(w http.ResponseWriter, r *http.Request, dst any) bool {
media := ""
if ct := r.Header.Get("Content-Type"); ct != "" {
media = strings.TrimSpace(strings.Split(ct, ";")[0])
}
if !strings.EqualFold(media, "application/json") {
a.fail(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "Нужен Content-Type application/json", 0)
return false
}
body, err := io.ReadAll(r.Body)
if err != nil || !utf8.Valid(body) || !decodeExactJSON(body, dst) {
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный JSON", 0)
return false
}
return true
}
// decodeExactJSON принимает один JSON-объект: точные имена полей, без хвоста и без замены битого UTF-8.
func decodeExactJSON(body []byte, dst any) bool {
dec := json.NewDecoder(bytes.NewReader(body))
var fields map[string]json.RawMessage
if err := dec.Decode(&fields); err != nil || fields == nil {
return false
}
var trailing json.RawMessage
if err := dec.Decode(&trailing); err != io.EOF {
return false
}
allowed, ok := jsonFieldNames(dst)
if !ok {
return false
}
for name := range fields {
if _, ok := allowed[name]; !ok {
return false
}
}
return json.Unmarshal(body, dst) == nil
}
func jsonFieldNames(dst any) (map[string]struct{}, bool) {
t := reflect.TypeOf(dst)
if t == nil || t.Kind() != reflect.Pointer {
return nil, false
}
t = t.Elem()
if t.Kind() != reflect.Struct {
return nil, false
}
names := make(map[string]struct{}, t.NumField())
for i := 0; i < t.NumField(); i++ {
name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",")
if name == "" || name == "-" {
return nil, false
}
names[name] = struct{}{}
}
return names, true
}
func (a *API) authenticate(w http.ResponseWriter, r *http.Request) (store.User, bool) {
raw := strings.TrimSpace(r.Header.Get("X-User-Id"))
id, ok := canonicalUUID(raw)
if !ok {
a.fail(w, r, http.StatusUnauthorized, "unauthorized", "Нет действительной идентификации", 0)
return store.User{}, false
}
user, exists := a.store.User(id)
if !exists {
a.fail(w, r, http.StatusUnauthorized, "unauthorized", "Нет действительной идентификации", 0)
return store.User{}, false
}
return user, true
}
func (a *API) pageQuery(w http.ResponseWriter, r *http.Request, scope string) (int, *store.Cursor, bool) {
q := r.URL.Query()
limit := 50
if q.Has("limit") {
raw := q.Get("limit")
n, err := strconv.Atoi(raw)
if err != nil || !limitRe.MatchString(raw) || n < 1 || n > 100 {
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный limit", 0)
return 0, nil, false
}
limit = n
}
if !q.Has("cursor") {
return limit, nil, true
}
raw := q.Get("cursor")
if raw == "" || len(raw) > 512 {
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
return 0, nil, false
}
payload, err := decodeCursor(raw)
if err != nil || payload.Scope != scope || payload.ID == "" || payload.At == "" {
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
return 0, nil, false
}
at, err := time.Parse("2006-01-02T15:04:05.000000Z", payload.At)
if err != nil {
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
return 0, nil, false
}
id, ok := canonicalUUID(payload.ID)
if !ok {
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
return 0, nil, false
}
return limit, &store.Cursor{ID: id, At: at}, true
}
func asUser(u store.User) userJSON {
return userJSON{
ID: u.ID,
Username: u.Username,
DisplayName: u.DisplayName,
CreatedAt: formatTime(u.CreatedAt),
}
}
func asChat(c store.Chat) chatJSON {
ids := c.MemberIDs
if ids == nil {
ids = []string{}
}
return chatJSON{
ID: c.ID,
Title: c.Title,
MemberIDs: ids,
CreatedAt: formatTime(c.CreatedAt),
}
}
func asMessage(m store.Message) messageJSON {
return messageJSON{
ID: m.ID,
ChatID: m.ChatID,
SenderID: m.SenderID,
Text: m.Text,
CreatedAt: formatTime(m.CreatedAt),
}
}
func formatTime(t time.Time) string {
return t.UTC().Format("2006-01-02T15:04:05.000000Z")
}
func canonicalUUID(s string) (string, bool) {
if !uuidRe.MatchString(s) {
return "", false
}
return strings.ToLower(s), true
}
func validText(s string, min, max int) bool {
if strings.TrimSpace(s) == "" {
return false
}
n := utf8.RuneCountInString(s)
return n >= min && n <= max
}
func requestID(r *http.Request) string {
incoming := strings.TrimSpace(r.Header.Get("X-Request-Id"))
if requestIDRe.MatchString(incoming) {
return incoming
}
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
return strconv.FormatInt(time.Now().UnixNano(), 36)
}
return hex.EncodeToString(b[:])
}
func encodeCursor(p cursorPayload) string {
raw, err := json.Marshal(p)
if err != nil {
return ""
}
return base64.RawURLEncoding.EncodeToString(raw)
}
func decodeCursor(s string) (cursorPayload, error) {
b, err := base64.RawURLEncoding.DecodeString(s)
if err != nil {
b, err = base64.URLEncoding.DecodeString(s)
if err != nil {
return cursorPayload{}, err
}
}
dec := json.NewDecoder(bytes.NewReader(b))
dec.DisallowUnknownFields()
var p cursorPayload
if err := dec.Decode(&p); err != nil {
return cursorPayload{}, err
}
var trailing json.RawMessage
if err := dec.Decode(&trailing); err != io.EOF {
if err == nil {
err = io.ErrUnexpectedEOF
}
return cursorPayload{}, err
}
return p, nil
}
+86
View File
@@ -0,0 +1,86 @@
package api
import (
"context"
"log/slog"
"net/http"
"sync/atomic"
"time"
"messenger/internal/store"
)
type ctxKey struct{}
type API struct {
store *store.Store
log *slog.Logger
shutting atomic.Bool
}
// Создает Api
func New(st *store.Store, log *slog.Logger) *API {
if log == nil {
log = slog.Default()
}
return &API{
store: st,
log: log,
}
}
// BeginShutdown переводит /health/ready в 503 и говорит новым бизнес-запросам
// отказать до закрытия слушателя. Уже принятые обработчики дорабатывают.
func (a *API) BeginShutdown() {
a.shutting.Store(true)
a.log.Info("shutdown started")
}
// Точка входа
func (a *API) ServeHTTP(w http.ResponseWriter, r *http.Request) {
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
start := time.Now()
id := requestID(r)
sw.Header().Set("X-Request-Id", id)
r = r.WithContext(context.WithValue(r.Context(), ctxKey{}, id))
defer func() {
if p := recover(); p != nil {
a.log.Error("panic", "request_id", id)
if !sw.wrote {
a.fail(sw, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
}
}
a.log.Info("request",
"request_id", id,
"method", r.Method,
"path", r.URL.Path,
"status", sw.status,
"duration_ms", time.Since(start).Milliseconds(),
"bytes_in", r.ContentLength,
)
}()
switch {
case r.Method == http.MethodGet && r.URL.Path == "/health/live":
a.live(sw, r)
return
case r.Method == http.MethodGet && r.URL.Path == "/health/ready":
a.ready(sw, r)
return
}
if a.shutting.Load() {
a.fail(sw, r, http.StatusServiceUnavailable, "unavailable", "Сервер останавливается", 1)
return
}
a.route(sw, r)
}
func requestIDFrom(r *http.Request) string {
id, _ := r.Context().Value(ctxKey{}).(string)
if id == "" {
return "unknown"
}
return id
}
+409
View File
@@ -0,0 +1,409 @@
package api
import (
"bytes"
"encoding/base64"
"encoding/json"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
"messenger/internal/store"
)
func newServer(t *testing.T) (*httptest.Server, *API, *bytes.Buffer) {
t.Helper()
var logs bytes.Buffer
st := store.New()
application := New(st, slog.New(slog.NewJSONHandler(&logs, nil)))
srv := httptest.NewServer(application)
t.Cleanup(srv.Close)
return srv, application, &logs
}
func do(t *testing.T, method, url, user string, body any, raw []byte, contentType string) (int, http.Header, []byte) {
t.Helper()
var rdr io.Reader
if raw != nil {
rdr = bytes.NewReader(raw)
} else if body != nil {
b, err := json.Marshal(body)
if err != nil {
t.Fatal(err)
}
rdr = bytes.NewReader(b)
}
req, err := http.NewRequest(method, url, rdr)
if err != nil {
t.Fatal(err)
}
if body != nil || raw != nil {
if contentType == "" {
contentType = "application/json"
}
req.Header.Set("Content-Type", contentType)
}
if user != "" {
req.Header.Set("X-User-Id", user)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if resp.Header.Get("X-Request-Id") == "" {
t.Fatalf("%s %s: missing X-Request-Id", method, url)
}
if resp.StatusCode >= 400 {
var env errorEnvelope
if err := json.Unmarshal(data, &env); err != nil {
t.Fatalf("error json: %v body %s", err, data)
}
if env.Error.RequestID != resp.Header.Get("X-Request-Id") || env.Error.Code == "" || env.Error.Message == "" {
t.Fatalf("bad error envelope: %+v", env)
}
}
return resp.StatusCode, resp.Header, data
}
func createUser(t *testing.T, base, username, display string) userJSON {
t.Helper()
status, _, body := do(t, http.MethodPost, base+"/api/v1/users", "", map[string]string{
"username": username, "display_name": display,
}, nil, "")
if status != http.StatusCreated {
t.Fatalf("create user %s: %d %s", username, status, body)
}
var u userJSON
if err := json.Unmarshal(body, &u); err != nil {
t.Fatal(err)
}
return u
}
func createChat(t *testing.T, base, caller, title string, members ...string) chatJSON {
t.Helper()
status, _, body := do(t, http.MethodPost, base+"/api/v1/chats", caller, map[string]any{
"title": title, "member_ids": members,
}, nil, "")
if status != http.StatusCreated {
t.Fatalf("create chat: %d %s", status, body)
}
var c chatJSON
if err := json.Unmarshal(body, &c); err != nil {
t.Fatal(err)
}
return c
}
func TestInvalidJSONExtraFieldAndTypes(t *testing.T) {
srv, _, _ := newServer(t)
cases := [][]byte{
[]byte(`{`),
[]byte(`{"username":"abc","display_name":"Алиса","extra":1}`),
[]byte(`{"username":1,"display_name":"Алиса"}`),
[]byte(`null`),
}
for _, raw := range cases {
status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/users", "", nil, raw, "application/json")
if status != http.StatusBadRequest || !bytes.Contains(body, []byte(`"invalid_request"`)) {
t.Fatalf("body %s: %d %s", raw, status, body)
}
}
status, _, _ := do(t, http.MethodPost, srv.URL+"/api/v1/users", "", nil, []byte(`{"username":"abc","display_name":"Алиса"}`), "text/plain")
if status != http.StatusUnsupportedMediaType {
t.Fatalf("content type: %d", status)
}
}
func TestStrictJSONNamesUTF8AndCursorTail(t *testing.T) {
srv, _, _ := newServer(t)
bad := [][]byte{
[]byte(`{"username":"bad_json","display_name":"Я"}]`),
[]byte(`{"username":"bad_json","display_name":"Я"}}`),
[]byte(`{"Username":"bad_case","display_name":"Я"}`),
append([]byte(`{"username":"bad_utf","display_name":"`), 0xff, '"', '}'),
}
for _, raw := range bad {
status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/users", "", nil, raw, "application/json")
if status != http.StatusBadRequest {
t.Fatalf("user body %q: %d %s", raw, status, body)
}
}
alice := createUser(t, srv.URL, "alice", "Алиса")
status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/chats", alice.ID, nil, []byte(`{"Title":"чат","member_ids":["`+alice.ID+`"]}`), "application/json")
if status != http.StatusBadRequest {
t.Fatalf("Title: %d %s", status, body)
}
chat := createChat(t, srv.URL, alice.ID, "чат", alice.ID)
status, _, body = do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, nil, []byte(`{"TEXT":"hi"}`), "application/json")
if status != http.StatusBadRequest {
t.Fatalf("TEXT: %d %s", status, body)
}
rawText := append([]byte(`{"text":"`), 0xff, '"', '}')
status, _, body = do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, nil, rawText, "application/json")
if status != http.StatusBadRequest {
t.Fatalf("message utf-8: %d %s", status, body)
}
status, _, body = do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": "one"}, nil, "")
if status != http.StatusCreated {
t.Fatalf("seed: %d %s", status, body)
}
status, _, body = do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": "two"}, nil, "")
if status != http.StatusCreated {
t.Fatalf("seed2: %d %s", status, body)
}
status, _, body = do(t, http.MethodGet, srv.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=1", alice.ID, nil, nil, "")
if status != http.StatusOK {
t.Fatalf("page: %d %s", status, body)
}
var page messagePage
if err := json.Unmarshal(body, &page); err != nil || page.NextCursor == nil {
t.Fatalf("cursor: %v %s", err, body)
}
decoded, err := base64.RawURLEncoding.DecodeString(*page.NextCursor)
if err != nil {
t.Fatal(err)
}
tampered := base64.RawURLEncoding.EncodeToString(append(decoded, []byte("garbage")...))
status, _, body = do(t, http.MethodGet, srv.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=1&cursor="+url.QueryEscape(tampered), alice.ID, nil, nil, "")
if status != http.StatusBadRequest {
t.Fatalf("tampered cursor: %d %s", status, body)
}
status, _, _ = do(t, http.MethodGet, srv.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=1&cursor="+url.QueryEscape(*page.NextCursor), alice.ID, nil, nil, "")
if status != http.StatusOK {
t.Fatalf("valid cursor: %d", status)
}
}
func TestDuplicateUsername(t *testing.T) {
srv, _, _ := newServer(t)
createUser(t, srv.URL, "alice", "Алиса")
status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/users", "", map[string]string{
"username": "alice", "display_name": "Другая",
}, nil, "")
if status != http.StatusConflict || !bytes.Contains(body, []byte(`"conflict"`)) {
t.Fatalf("duplicate: %d %s", status, body)
}
}
func TestEmptyMessageForeignChatAndAuth(t *testing.T) {
srv, _, _ := newServer(t)
alice := createUser(t, srv.URL, "alice", "Алиса")
bob := createUser(t, srv.URL, "bob", "Боб")
eve := createUser(t, srv.URL, "eve", "Ева")
chat := createChat(t, srv.URL, alice.ID, "Контрактный тест", alice.ID, bob.ID)
status, _, _ := do(t, http.MethodGet, srv.URL+"/api/v1/users/me", "", nil, nil, "")
if status != http.StatusUnauthorized {
t.Fatalf("missing header: %d", status)
}
status, _, _ = do(t, http.MethodGet, srv.URL+"/api/v1/users/me", "11111111-1111-4111-8111-111111111111", nil, nil, "")
if status != http.StatusUnauthorized {
t.Fatalf("unknown user: %d", status)
}
meStatus, _, meBody := do(t, http.MethodGet, srv.URL+"/api/v1/users/me", alice.ID, nil, nil, "")
if meStatus != http.StatusOK || !bytes.Contains(meBody, []byte(alice.ID)) {
t.Fatalf("me: %d %s", meStatus, meBody)
}
status, _, _ = do(t, http.MethodGet, srv.URL+"/api/v1/chats/"+chat.ID, eve.ID, nil, nil, "")
if status != http.StatusNotFound {
t.Fatalf("foreign chat: %d", status)
}
status, _, _ = do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", eve.ID, map[string]string{"text": "чужое"}, nil, "")
if status != http.StatusNotFound {
t.Fatalf("foreign post: %d", status)
}
for _, text := range []string{"", " ", "\n\t"} {
status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": text}, nil, "")
if status != http.StatusBadRequest {
t.Fatalf("empty %q: %d %s", text, status, body)
}
}
status, _, _ = do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": "привет", "sender_id": eve.ID}, nil, "")
if status != http.StatusBadRequest {
t.Fatalf("sender_id must be rejected: %d", status)
}
text := "Привет, мир 👋"
status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": text}, nil, "")
if status != http.StatusCreated {
t.Fatalf("unicode: %d %s", status, body)
}
var msg messageJSON
if err := json.Unmarshal(body, &msg); err != nil {
t.Fatal(err)
}
if msg.Text != text || msg.SenderID != alice.ID || msg.ChatID != chat.ID {
t.Fatalf("message mutated: %+v", msg)
}
if !strings.HasSuffix(msg.CreatedAt, "Z") {
t.Fatalf("timestamp: %s", msg.CreatedAt)
}
}
func TestPaginationSeveralPages(t *testing.T) {
srv, _, _ := newServer(t)
alice := createUser(t, srv.URL, "alice", "Алиса")
bob := createUser(t, srv.URL, "bob", "Боб")
chat := createChat(t, srv.URL, alice.ID, "страницы", alice.ID, bob.ID)
other := createChat(t, srv.URL, alice.ID, "другой", alice.ID)
const n = 25
ids := make([]string, 0, n)
for i := 0; i < n; i++ {
sender := alice.ID
if i%2 == 1 {
sender = bob.ID
}
status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", sender, map[string]string{
"text": "сообщение " + strings.Repeat("я", i%3) + string(rune('a'+i%26)),
}, nil, "")
if status != http.StatusCreated {
t.Fatalf("post %d: %d %s", i, status, body)
}
var msg messageJSON
if err := json.Unmarshal(body, &msg); err != nil {
t.Fatal(err)
}
ids = append(ids, msg.ID)
}
var got []string
cursor := ""
pages := 0
for {
pages++
if pages > 10 {
t.Fatal("pagination did not finish")
}
url := srv.URL + "/api/v1/chats/" + chat.ID + "/messages?limit=10"
if cursor != "" {
url += "&cursor=" + cursor
}
status, _, body := do(t, http.MethodGet, url, bob.ID, nil, nil, "")
if status != http.StatusOK {
t.Fatalf("page: %d %s", status, body)
}
var page messagePage
if err := json.Unmarshal(body, &page); err != nil {
t.Fatal(err)
}
if len(page.Items) == 0 || len(page.Items) > 10 {
t.Fatalf("page size %d", len(page.Items))
}
for _, item := range page.Items {
got = append(got, item.ID)
}
if page.NextCursor == nil {
break
}
cursor = *page.NextCursor
}
if pages < 3 {
t.Fatalf("expected several pages, got %d", pages)
}
if strings.Join(got, ",") != strings.Join(ids, ",") {
t.Fatalf("order/duplication mismatch\nwant %v\ngot %v", ids, got)
}
status, _, _ := do(t, http.MethodGet, srv.URL+"/api/v1/chats/"+other.ID+"/messages?limit=10&cursor="+cursor, alice.ID, nil, nil, "")
if status != http.StatusBadRequest {
t.Fatalf("foreign cursor: %d", status)
}
status, _, _ = do(t, http.MethodGet, srv.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=0", alice.ID, nil, nil, "")
if status != http.StatusBadRequest {
t.Fatalf("limit 0: %d", status)
}
}
func TestConcurrentHundredMessages(t *testing.T) {
srv, _, _ := newServer(t)
users := make([]userJSON, 10)
ids := make([]string, 10)
for i := 0; i < 10; i++ {
users[i] = createUser(t, srv.URL, "u"+string(rune('a'+i))+"x", "Участник")
ids[i] = users[i].ID
}
chat := createChat(t, srv.URL, ids[0], "гонка", ids...)
var wg sync.WaitGroup
errCh := make(chan error, 100)
for i := 0; i < 10; i++ {
wg.Add(1)
go func(user string) {
defer wg.Done()
for j := 0; j < 10; j++ {
req, err := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", strings.NewReader(`{"text":"n"}`))
if err != nil {
errCh <- err
return
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-User-Id", user)
resp, err := http.DefaultClient.Do(req)
if err != nil {
errCh <- err
return
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
errCh <- &statusErr{resp.StatusCode, body}
}
}
}(ids[i])
}
wg.Wait()
close(errCh)
for err := range errCh {
t.Fatal(err)
}
seen := map[string]struct{}{}
cursor := ""
for {
url := srv.URL + "/api/v1/chats/" + chat.ID + "/messages?limit=17"
if cursor != "" {
url += "&cursor=" + cursor
}
status, _, body := do(t, http.MethodGet, url, ids[3], nil, nil, "")
if status != http.StatusOK {
t.Fatalf("list: %d %s", status, body)
}
var page messagePage
if err := json.Unmarshal(body, &page); err != nil {
t.Fatal(err)
}
for _, item := range page.Items {
if _, ok := seen[item.ID]; ok {
t.Fatalf("duplicate %s", item.ID)
}
seen[item.ID] = struct{}{}
}
if page.NextCursor == nil {
break
}
cursor = *page.NextCursor
}
if len(seen) != 100 {
t.Fatalf("unique messages = %d, want 100", len(seen))
}
}
type statusErr struct {
code int
body []byte
}
func (e *statusErr) Error() string {
return http.StatusText(e.code) + " " + string(e.body)
}