forked from mtusi2026/mtusi2026lab3
feat: implement lab3 load balancing and idempotency
This commit is contained in:
@@ -0,0 +1,229 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab2/internal/middleware"
|
||||
"mtusi2026lab2/internal/model"
|
||||
"mtusi2026lab2/internal/storage"
|
||||
)
|
||||
|
||||
type ChatHandler struct {
|
||||
store *storage.ChatStore
|
||||
}
|
||||
|
||||
func NewChatHandler(store *storage.ChatStore) *ChatHandler {
|
||||
return &ChatHandler{store: store}
|
||||
}
|
||||
|
||||
type createChatRequest struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []uuid.UUID `json:"member_ids"`
|
||||
}
|
||||
|
||||
type chatPage struct {
|
||||
Items []model.Chat `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func (h *ChatHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
currentUser, ok := middleware.GetCurrentUser(r.Context())
|
||||
if !ok {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
var req createChatRequest
|
||||
if err := decodeOneObject(r, &req); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
title := strings.TrimSpace(req.Title)
|
||||
titleLength := utf8.RuneCountInString(title)
|
||||
|
||||
if titleLength < 1 || titleLength > 100 {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "title must contain from 1 to 100 characters")
|
||||
return
|
||||
}
|
||||
|
||||
if len(req.MemberIDs) < 1 || len(req.MemberIDs) > 100 {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "member_ids must contain from 1 to 100 users")
|
||||
return
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]struct{}, len(req.MemberIDs))
|
||||
currentUserIsMember := false
|
||||
|
||||
for _, memberID := range req.MemberIDs {
|
||||
if _, exists := seen[memberID]; exists {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "member_ids must contain unique users")
|
||||
return
|
||||
}
|
||||
seen[memberID] = struct{}{}
|
||||
|
||||
if memberID == currentUser.ID {
|
||||
currentUserIsMember = true
|
||||
}
|
||||
}
|
||||
|
||||
if !currentUserIsMember {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "current user must be a chat member")
|
||||
return
|
||||
}
|
||||
|
||||
for _, memberID := range req.MemberIDs {
|
||||
exists, err := h.store.ExistsUser(r.Context(), memberID)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
if !exists {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "member does not exist")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
chat := model.Chat{
|
||||
ID: uuid.New(),
|
||||
Title: title,
|
||||
MemberIDs: req.MemberIDs,
|
||||
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
||||
}
|
||||
|
||||
err := h.store.CreateChat(r.Context(), chat)
|
||||
if errors.Is(err, storage.ErrInvalidMember) {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "member does not exist")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, chat)
|
||||
}
|
||||
|
||||
func (h *ChatHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
currentUser, ok := middleware.GetCurrentUser(r.Context())
|
||||
if !ok {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
limit := 50
|
||||
if values, exists := r.URL.Query()["limit"]; exists {
|
||||
if len(values) != 1 {
|
||||
writeError(w, r, 400, "invalid_request", "invalid limit")
|
||||
return
|
||||
}
|
||||
n, err := strconv.Atoi(values[0])
|
||||
if err != nil || n < 1 || n > 100 {
|
||||
writeError(w, r, 400, "invalid_request", "limit must be between 1 and 100")
|
||||
return
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
var cursorTime *time.Time
|
||||
var cursorID *uuid.UUID
|
||||
if values, exists := r.URL.Query()["cursor"]; exists {
|
||||
if len(values) != 1 || values[0] == "" {
|
||||
writeError(w, r, 400, "invalid_request", "invalid cursor")
|
||||
return
|
||||
}
|
||||
t, id, err := decodeChatCursor(values[0], currentUser.ID)
|
||||
if err != nil {
|
||||
writeError(w, r, 400, "invalid_request", "invalid cursor")
|
||||
return
|
||||
}
|
||||
cursorTime = &t
|
||||
cursorID = &id
|
||||
}
|
||||
chats, more, err := h.store.ListChatsPage(r.Context(), currentUser.ID, limit, cursorTime, cursorID)
|
||||
if err != nil {
|
||||
writeError(w, r, 503, "unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
var next *string
|
||||
if more && len(chats) > 0 {
|
||||
c := encodeChatCursor(currentUser.ID, chats[len(chats)-1])
|
||||
next = &c
|
||||
}
|
||||
writeJSON(w, 200, chatPage{Items: chats, NextCursor: next})
|
||||
}
|
||||
|
||||
func (h *ChatHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
currentUser, ok := middleware.GetCurrentUser(r.Context())
|
||||
if !ok {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid chat id")
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := h.store.GetChatForUser(
|
||||
r.Context(), chatID, currentUser.ID,
|
||||
)
|
||||
if errors.Is(err, storage.ErrChatNotFound) {
|
||||
writeError(w, r, http.StatusNotFound,
|
||||
"not_found", "chat not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, chat)
|
||||
}
|
||||
|
||||
func encodeChatCursor(userID uuid.UUID, chat model.Chat) string {
|
||||
value := fmt.Sprintf("%s|%s|%s", userID, chat.CreatedAt.Format(time.RFC3339Nano), chat.ID)
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(value))
|
||||
}
|
||||
func decodeChatCursor(cursor string, userID uuid.UUID) (time.Time, uuid.UUID, error) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return time.Time{}, uuid.Nil, err
|
||||
}
|
||||
parts := strings.Split(string(data), "|")
|
||||
if len(parts) != 3 || parts[0] != userID.String() {
|
||||
return time.Time{}, uuid.Nil, fmt.Errorf("invalid cursor")
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil {
|
||||
return time.Time{}, uuid.Nil, err
|
||||
}
|
||||
id, err := uuid.Parse(parts[2])
|
||||
if err != nil {
|
||||
return time.Time{}, uuid.Nil, err
|
||||
}
|
||||
return t, id, nil
|
||||
}
|
||||
Reference in New Issue
Block a user