refactor: isolate attachment lifecycle
This commit is contained in:
@@ -0,0 +1,302 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
|
||||
)
|
||||
|
||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
func (s *Server) live(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodGet {
|
||||
return methodNotAllowed(w, http.MethodGet)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) readiness(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodGet {
|
||||
return methodNotAllowed(w, http.MethodGet)
|
||||
}
|
||||
if !s.ready.Load() {
|
||||
return unavailable()
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
if err := s.database.Ping(ctx); err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
if err := s.sessions.Ping(ctx); err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
if err := s.objects.Ping(ctx); err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) users(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodPost {
|
||||
return methodNotAllowed(w, http.MethodPost)
|
||||
}
|
||||
var input struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := readJSON(w, r, &input); err != nil {
|
||||
return err
|
||||
}
|
||||
if !usernamePattern.MatchString(input.Username) || !validText(input.DisplayName, 100) || !validPassword(input.Password) {
|
||||
return invalidRequest()
|
||||
}
|
||||
passwordHash, err := s.passwords.Hash(input.Password)
|
||||
if err != nil {
|
||||
return internalError()
|
||||
}
|
||||
user, err := s.userRepository.CreateUser(r.Context(), input.Username, input.DisplayName, passwordHash)
|
||||
if errors.Is(err, model.ErrConflict) {
|
||||
return &apiError{http.StatusConflict, errorCodeConflict, "username already exists"}
|
||||
}
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, user)
|
||||
return nil
|
||||
}
|
||||
|
||||
func validPassword(value string) bool {
|
||||
length := utf8.RuneCountInString(value)
|
||||
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && length >= 12 && length <= 128
|
||||
}
|
||||
|
||||
func (s *Server) me(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodGet {
|
||||
return methodNotAllowed(w, http.MethodGet)
|
||||
}
|
||||
user, _, err := s.authenticate(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
writeJSON(w, http.StatusOK, user)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) chats(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodPost && r.Method != http.MethodGet {
|
||||
return methodNotAllowed(w, http.MethodGet+", "+http.MethodPost)
|
||||
}
|
||||
user, _, authErr := s.authenticate(r)
|
||||
if authErr != nil {
|
||||
return authErr
|
||||
}
|
||||
if r.Method == http.MethodGet {
|
||||
return s.listChats(w, r, user)
|
||||
}
|
||||
var input struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
if err := readJSON(w, r, &input); err != nil {
|
||||
return err
|
||||
}
|
||||
if !validText(input.Title, 100) || len(input.MemberIDs) < 1 || len(input.MemberIDs) > 100 {
|
||||
return invalidRequest()
|
||||
}
|
||||
members := make(map[string]struct{}, len(input.MemberIDs))
|
||||
for i, memberID := range input.MemberIDs {
|
||||
canonical, valid := canonicalID(memberID)
|
||||
if !valid {
|
||||
return invalidRequest()
|
||||
}
|
||||
if _, duplicate := members[canonical]; duplicate {
|
||||
return invalidRequest()
|
||||
}
|
||||
members[canonical] = struct{}{}
|
||||
input.MemberIDs[i] = canonical
|
||||
}
|
||||
if _, included := members[user.ID]; !included {
|
||||
return invalidRequest()
|
||||
}
|
||||
chat, err := s.chatRepository.CreateChat(r.Context(), input.Title, input.MemberIDs, user.ID)
|
||||
if errors.Is(err, model.ErrInvalidMembers) {
|
||||
return invalidRequest()
|
||||
}
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, chat)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) listChats(w http.ResponseWriter, r *http.Request, user User) *apiError {
|
||||
limit, cursor, err := pageParams(r, "chat", user.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
items, hasNext, listErr := s.chatRepository.ListChats(r.Context(), user.ID, cursorPosition(cursor), limit)
|
||||
if errors.Is(listErr, model.ErrInvalidCursor) {
|
||||
return invalidRequest()
|
||||
}
|
||||
if listErr != nil {
|
||||
return unavailable()
|
||||
}
|
||||
if items == nil {
|
||||
items = []Chat{}
|
||||
}
|
||||
var next *string
|
||||
if hasNext {
|
||||
last := items[len(items)-1]
|
||||
value := encodeCursor("chat", user.ID, last.CreatedAt, last.ID)
|
||||
next = &value
|
||||
}
|
||||
writeJSON(w, http.StatusOK, struct {
|
||||
Items []Chat `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}{items, next})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) chat(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodGet {
|
||||
return methodNotAllowed(w, http.MethodGet)
|
||||
}
|
||||
user, _, authErr := s.authenticate(r)
|
||||
if authErr != nil {
|
||||
return authErr
|
||||
}
|
||||
chatID, valid := canonicalID(strings.Split(r.URL.Path, "/")[4])
|
||||
if !valid {
|
||||
return invalidRequest()
|
||||
}
|
||||
chat, err := s.chatRepository.ChatForUser(r.Context(), chatID, user.ID)
|
||||
if errors.Is(err, model.ErrNotFound) {
|
||||
return notFound()
|
||||
}
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
writeJSON(w, http.StatusOK, chat)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) messages(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodPost && r.Method != http.MethodGet {
|
||||
return methodNotAllowed(w, http.MethodGet+", "+http.MethodPost)
|
||||
}
|
||||
user, _, authErr := s.authenticate(r)
|
||||
if authErr != nil {
|
||||
return authErr
|
||||
}
|
||||
chatID, valid := canonicalID(strings.Split(r.URL.Path, "/")[4])
|
||||
if !valid {
|
||||
return invalidRequest()
|
||||
}
|
||||
if r.Method == http.MethodGet {
|
||||
return s.listMessages(w, r, user, chatID)
|
||||
}
|
||||
key, valid := idempotencyKey(r)
|
||||
if !valid {
|
||||
return invalidRequest()
|
||||
}
|
||||
var input struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
if err := readJSON(w, r, &input); err != nil {
|
||||
return err
|
||||
}
|
||||
if !validMessage(input.Text, input.AttachmentIDs) || !canonicalAttachmentIDs(input.AttachmentIDs) {
|
||||
return invalidRequest()
|
||||
}
|
||||
message, replay, err := s.messageRepository.CreateMessage(
|
||||
r.Context(), chatID, user.ID, input.Text, input.AttachmentIDs, key, s.idempotencyTTL,
|
||||
)
|
||||
if errors.Is(err, model.ErrNotFound) {
|
||||
return notFound()
|
||||
}
|
||||
if errors.Is(err, model.ErrIdempotencyConflict) {
|
||||
return &apiError{http.StatusConflict, errorCodeConflict, "idempotency key conflicts with previous request"}
|
||||
}
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
if replay {
|
||||
s.metrics.replays.Inc()
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, message)
|
||||
return nil
|
||||
}
|
||||
|
||||
func validMessage(text string, attachmentIDs []string) bool {
|
||||
if !utf8.ValidString(text) || utf8.RuneCountInString(text) > 4000 {
|
||||
return false
|
||||
}
|
||||
return len(attachmentIDs) > 0 || strings.TrimSpace(text) != ""
|
||||
}
|
||||
|
||||
func canonicalAttachmentIDs(attachmentIDs []string) bool {
|
||||
if len(attachmentIDs) > 10 {
|
||||
return false
|
||||
}
|
||||
seen := make(map[string]struct{}, len(attachmentIDs))
|
||||
for index, attachmentID := range attachmentIDs {
|
||||
canonical, valid := canonicalID(attachmentID)
|
||||
if !valid {
|
||||
return false
|
||||
}
|
||||
if _, duplicate := seen[canonical]; duplicate {
|
||||
return false
|
||||
}
|
||||
seen[canonical] = struct{}{}
|
||||
attachmentIDs[index] = canonical
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) listMessages(w http.ResponseWriter, r *http.Request, user User, chatID string) *apiError {
|
||||
limit, cursor, err := pageParams(r, "message", chatID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
items, hasNext, listErr := s.messageRepository.ListMessages(r.Context(), chatID, user.ID, cursorPosition(cursor), limit)
|
||||
if errors.Is(listErr, model.ErrNotFound) {
|
||||
return notFound()
|
||||
}
|
||||
if errors.Is(listErr, model.ErrInvalidCursor) {
|
||||
return invalidRequest()
|
||||
}
|
||||
if listErr != nil {
|
||||
return unavailable()
|
||||
}
|
||||
if items == nil {
|
||||
items = []Message{}
|
||||
}
|
||||
var next *string
|
||||
if hasNext {
|
||||
last := items[len(items)-1]
|
||||
value := encodeCursor("message", chatID, last.CreatedAt, last.ID)
|
||||
next = &value
|
||||
}
|
||||
writeJSON(w, http.StatusOK, struct {
|
||||
Items []Message `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}{items, next})
|
||||
return nil
|
||||
}
|
||||
|
||||
func cursorPosition(cursor *pageCursor) *model.Position {
|
||||
if cursor == nil {
|
||||
return nil
|
||||
}
|
||||
return &model.Position{CreatedAt: cursor.Time, ID: cursor.ID}
|
||||
}
|
||||
Reference in New Issue
Block a user