forked from mtusi2026/mtusi2026lab2
feat:lab1-catchup
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"mtusi-messenger/src/domain"
|
||||
)
|
||||
|
||||
// writeError пишет ошибку в формате контракта.
|
||||
func writeError(w http.ResponseWriter, r *http.Request, status int, code, message string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(domain.ErrorBody{
|
||||
Error: domain.ErrorDetail{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: requestIDFrom(r),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// writeJSON пишет успешный JSON-ответ.
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"mtusi-messenger/src/domain"
|
||||
)
|
||||
|
||||
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
// Handler держит хранилище.
|
||||
type Handler struct {
|
||||
Store *domain.Store
|
||||
}
|
||||
|
||||
// --- Health ---
|
||||
|
||||
func (h *Handler) Live(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (h *Handler) Ready(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
// --- Users ---
|
||||
|
||||
type createUserReq struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
}
|
||||
|
||||
func (h *Handler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
var req createUserReq
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "malformed JSON")
|
||||
return
|
||||
}
|
||||
if !usernameRe.MatchString(req.Username) {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid username")
|
||||
return
|
||||
}
|
||||
if len([]rune(req.DisplayName)) < 1 || len([]rune(req.DisplayName)) > 100 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid display_name")
|
||||
return
|
||||
}
|
||||
u, err := h.Store.CreateUser(req.Username, req.DisplayName)
|
||||
if err == domain.ErrConflict {
|
||||
writeError(w, r, http.StatusConflict, "conflict", "username taken")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, u)
|
||||
}
|
||||
|
||||
func (h *Handler) CurrentUser(w http.ResponseWriter, r *http.Request) {
|
||||
userID := r.Header.Get("X-User-Id")
|
||||
if userID == "" {
|
||||
writeError(w, r, http.StatusUnauthorized, "unauthorized", "missing X-User-Id")
|
||||
return
|
||||
}
|
||||
u, err := h.Store.GetUser(userID)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusUnauthorized, "unauthorized", "unknown user")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, u)
|
||||
}
|
||||
|
||||
// --- Chats ---
|
||||
|
||||
type createChatReq struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
func (h *Handler) CreateChat(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := h.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req createChatReq
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "malformed JSON")
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(req.Title) == "" || len([]rune(req.Title)) > 100 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid title")
|
||||
return
|
||||
}
|
||||
if len(req.MemberIDs) < 1 || len(req.MemberIDs) > 100 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid member_ids")
|
||||
return
|
||||
}
|
||||
c, err := h.Store.CreateChat(req.Title, req.MemberIDs, userID)
|
||||
if err == domain.ErrInvalid {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid members")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, c)
|
||||
}
|
||||
|
||||
func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := h.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
chats := h.Store.ListChats(userID)
|
||||
if chats == nil {
|
||||
chats = []domain.Chat{}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, domain.ChatPage{Items: chats, NextCursor: nil})
|
||||
}
|
||||
|
||||
func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := h.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
chatID := r.PathValue("chat_id")
|
||||
c, err := h.Store.GetChat(chatID, userID)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "chat not found")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, c)
|
||||
}
|
||||
|
||||
// --- Messages ---
|
||||
|
||||
type createMessageReq struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := h.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
chatID := r.PathValue("chat_id")
|
||||
if _, err := h.Store.GetChat(chatID, userID); err != nil {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "chat not found")
|
||||
return
|
||||
}
|
||||
var req createMessageReq
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "malformed JSON")
|
||||
return
|
||||
}
|
||||
text := strings.TrimSpace(req.Text)
|
||||
if text == "" {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "empty message")
|
||||
return
|
||||
}
|
||||
if len([]rune(req.Text)) > 4000 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "message too long")
|
||||
return
|
||||
}
|
||||
m, err := h.Store.AddMessage(chatID, userID, req.Text)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "chat not found")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, m)
|
||||
}
|
||||
|
||||
func (h *Handler) ListMessages(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := h.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
chatID := r.PathValue("chat_id")
|
||||
if _, err := h.Store.GetChat(chatID, userID); err != nil {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "chat not found")
|
||||
return
|
||||
}
|
||||
limit := 50
|
||||
if v := r.URL.Query().Get("limit"); v != "" {
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil || n < 1 || n > 100 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid limit")
|
||||
return
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
cursor := r.URL.Query().Get("cursor")
|
||||
items, next, err := h.Store.ListMessages(chatID, limit, cursor)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid cursor")
|
||||
return
|
||||
}
|
||||
if items == nil {
|
||||
items = []domain.Message{}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, domain.MessagePage{Items: items, NextCursor: next})
|
||||
}
|
||||
|
||||
// requireUser проверяет X-User-Id и возвращает ID.
|
||||
func (h *Handler) requireUser(w http.ResponseWriter, r *http.Request) (string, bool) {
|
||||
userID := r.Header.Get("X-User-Id")
|
||||
if userID == "" {
|
||||
writeError(w, r, http.StatusUnauthorized, "unauthorized", "missing X-User-Id")
|
||||
return "", false
|
||||
}
|
||||
if _, err := h.Store.GetUser(userID); err != nil {
|
||||
writeError(w, r, http.StatusUnauthorized, "unauthorized", "unknown user")
|
||||
return "", false
|
||||
}
|
||||
return userID, true
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type ctxKey string
|
||||
|
||||
const requestIDKey ctxKey = "request_id"
|
||||
|
||||
// requestIDFrom достаёт request_id из контекста.
|
||||
func requestIDFrom(r *http.Request) string {
|
||||
if v, ok := r.Context().Value(requestIDKey).(string); ok {
|
||||
return v
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// withRequestID добавляет X-Request-Id во все ответы.
|
||||
func withRequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.Header.Get("X-Request-Id")
|
||||
if id == "" {
|
||||
id = uuid.NewString()
|
||||
}
|
||||
w.Header().Set("X-Request-Id", id)
|
||||
ctx := context.WithValue(r.Context(), requestIDKey, id)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package api
|
||||
|
||||
import "net/http"
|
||||
|
||||
// NewRouter собирает маршруты.
|
||||
func NewRouter(h *Handler) http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /health/live", h.Live)
|
||||
mux.HandleFunc("GET /health/ready", h.Ready)
|
||||
mux.HandleFunc("POST /api/v1/users", h.CreateUser)
|
||||
mux.HandleFunc("GET /api/v1/users/me", h.CurrentUser)
|
||||
mux.HandleFunc("POST /api/v1/chats", h.CreateChat)
|
||||
mux.HandleFunc("GET /api/v1/chats", h.ListChats)
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}", h.GetChat)
|
||||
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", h.CreateMessage)
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", h.ListMessages)
|
||||
return withRequestID(mux)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// Config — конфигурация, приходящая из окружения.
|
||||
type Config struct {
|
||||
Host string
|
||||
Port int
|
||||
Env string
|
||||
}
|
||||
|
||||
// Load читает переменные окружения со значениями по умолчанию.
|
||||
func Load() Config {
|
||||
port := 8080
|
||||
if v := os.Getenv("APP_PORT"); v != "" {
|
||||
if p, err := strconv.Atoi(v); err == nil {
|
||||
port = p
|
||||
}
|
||||
}
|
||||
host := os.Getenv("APP_HOST")
|
||||
if host == "" {
|
||||
host = "0.0.0.0"
|
||||
}
|
||||
env := os.Getenv("APP_ENV")
|
||||
if env == "" {
|
||||
env = "lab"
|
||||
}
|
||||
return Config{Host: host, Port: port, Env: env}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
// User — пользователь системы.
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// Chat — чат с участниками.
|
||||
type Chat struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// Message — сообщение в чате.
|
||||
type Message struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// MessagePage — страница истории сообщений.
|
||||
type MessagePage struct {
|
||||
Items []Message `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
// ChatPage — страница списка чатов.
|
||||
type ChatPage struct {
|
||||
Items []Chat `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
// ErrorBody — тело ошибки в формате контракта.
|
||||
type ErrorBody struct {
|
||||
Error ErrorDetail `json:"error"`
|
||||
}
|
||||
|
||||
// ErrorDetail — детали ошибки.
|
||||
type ErrorDetail struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrInvalid = errors.New("invalid request")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
)
|
||||
|
||||
// Store — in-memory хранилище. Все данные исчезают при перезапуске процесса.
|
||||
type Store struct {
|
||||
mu sync.RWMutex // безопасность при параллельных запросах
|
||||
users map[string]*User
|
||||
byName map[string]*User
|
||||
chats map[string]*Chat
|
||||
messages map[string][]*Message // chat_id -> сообщения
|
||||
idIndex map[string]int // message_id -> позиция в messages[chat_id]
|
||||
}
|
||||
|
||||
// NewStore создаёт пустое хранилище.
|
||||
func NewStore() *Store {
|
||||
return &Store{
|
||||
users: make(map[string]*User),
|
||||
byName: make(map[string]*User),
|
||||
chats: make(map[string]*Chat),
|
||||
messages: make(map[string][]*Message),
|
||||
idIndex: make(map[string]int),
|
||||
}
|
||||
}
|
||||
|
||||
// CreateUser создаёт пользователя. Возвращает ErrConflict при дубликате username.
|
||||
func (s *Store) CreateUser(username, displayName string) (*User, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if _, exists := s.byName[username]; exists {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
u := &User{
|
||||
ID: uuid.NewString(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
s.users[u.ID] = u
|
||||
s.byName[username] = u
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// GetUser возвращает пользователя по ID.
|
||||
func (s *Store) GetUser(id string) (*User, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
u, ok := s.users[id]
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// CreateChat создаёт чат. Проверяет, что все участники существуют и вызывающий входит в список.
|
||||
func (s *Store) CreateChat(title string, memberIDs []string, creatorID string) (*Chat, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
seen := make(map[string]bool, len(memberIDs))
|
||||
for _, id := range memberIDs {
|
||||
if seen[id] {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
seen[id] = true
|
||||
if _, ok := s.users[id]; !ok {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
}
|
||||
if !seen[creatorID] {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
c := &Chat{
|
||||
ID: uuid.NewString(),
|
||||
Title: title,
|
||||
MemberIDs: append([]string(nil), memberIDs...),
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
s.chats[c.ID] = c
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// GetChat возвращает чат, если пользователь — участник.
|
||||
func (s *Store) GetChat(chatID, userID string) (*Chat, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
c, ok := s.chats[chatID]
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
for _, id := range c.MemberIDs {
|
||||
if id == userID {
|
||||
return c, nil
|
||||
}
|
||||
}
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
|
||||
// ListChats возвращает чаты пользователя, отсортированные по (created_at, id).
|
||||
func (s *Store) ListChats(userID string) []Chat {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
result := make([]Chat, 0)
|
||||
for _, c := range s.chats {
|
||||
for _, id := range c.MemberIDs {
|
||||
if id == userID {
|
||||
result = append(result, *c)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Slice(result, func(i, j int) bool {
|
||||
if result[i].CreatedAt.Equal(result[j].CreatedAt) {
|
||||
return result[i].ID < result[j].ID
|
||||
}
|
||||
return result[i].CreatedAt.Before(result[j].CreatedAt)
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
// compareMessages возвращает true, если a < b по (created_at, id).
|
||||
func compareMessages(a, b *Message) bool {
|
||||
if a.CreatedAt.Equal(b.CreatedAt) {
|
||||
return a.ID < b.ID
|
||||
}
|
||||
return a.CreatedAt.Before(b.CreatedAt)
|
||||
}
|
||||
|
||||
// AddMessage добавляет сообщение, поддерживая сортировку вставкой.
|
||||
// Изменение относительно baseline: вместо append + sort при чтении
|
||||
// вставляем в нужную позицию сразу — чтение становится O(limit).
|
||||
func (s *Store) AddMessage(chatID, senderID, text string) (*Message, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if _, ok := s.chats[chatID]; !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
m := &Message{
|
||||
ID: uuid.NewString(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
msgs := s.messages[chatID]
|
||||
idx := sort.Search(len(msgs), func(i int) bool {
|
||||
return !compareMessages(msgs[i], m)
|
||||
})
|
||||
msgs = append(msgs, nil)
|
||||
copy(msgs[idx+1:], msgs[idx:])
|
||||
msgs[idx] = m
|
||||
s.messages[chatID] = msgs
|
||||
// Перестраиваем индексы от позиции вставки до конца.
|
||||
for i := idx; i < len(msgs); i++ {
|
||||
s.idIndex[msgs[i].ID] = i
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// ListMessages возвращает страницу сообщений по курсору.
|
||||
// Изменение относительно baseline: без сортировки — срез уже отсортирован.
|
||||
func (s *Store) ListMessages(chatID string, limit int, cursor string) ([]Message, *string, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
msgs := s.messages[chatID]
|
||||
if len(msgs) == 0 {
|
||||
return []Message{}, nil, nil
|
||||
}
|
||||
start := 0
|
||||
if cursor != "" {
|
||||
pos, ok := s.idIndex[cursor]
|
||||
if !ok || pos >= len(msgs) || msgs[pos].ID != cursor || msgs[pos].ChatID != chatID {
|
||||
return nil, nil, ErrInvalid
|
||||
}
|
||||
start = pos + 1
|
||||
}
|
||||
end := start + limit
|
||||
if end > len(msgs) {
|
||||
end = len(msgs)
|
||||
}
|
||||
items := make([]Message, 0, end-start)
|
||||
for _, m := range msgs[start:end] {
|
||||
items = append(items, *m)
|
||||
}
|
||||
var next *string
|
||||
if end < len(msgs) {
|
||||
last := msgs[end-1].ID
|
||||
next = &last
|
||||
}
|
||||
return items, next, nil
|
||||
}
|
||||
Reference in New Issue
Block a user