Files
mtusi2026lab4/internal/api/messages.go
T

214 lines
6.8 KiB
Go

package api
import (
"bytes"
"crypto/sha256"
"encoding/json"
"errors"
"net/http"
"unicode/utf8"
"mtusi.ru/messenger-lab4/internal/cursor"
"mtusi.ru/messenger-lab4/internal/store"
"mtusi.ru/messenger-lab4/internal/uuid"
)
const maxMessageAttachments = 10
type createMessageRequest struct {
Text *string `json:"text"`
AttachmentIDs json.RawMessage `json:"attachment_ids"`
}
// messageHash is the canonical semantic body used for idempotency. A missing
// attachment_ids is normalised to [], exactly as the contract requires, and
// JSON object key order never affects the hash. Array order is preserved: the
// response also preserves it.
type messageHashBody struct {
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}
func (a *App) createMessage(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
if problem != nil {
a.writeError(w, r, problem)
return
}
// The key is validated before the body, but after authentication and path
// validation: a malformed/missing key is always 400, while an outsider
// still cannot learn anything by replaying someone else's key.
idempotencyKey, problem := idempotencyKey(r)
if problem != nil {
a.writeError(w, r, problem)
return
}
// Resource access is checked before the body is decoded so a foreign chat
// always looks like a missing chat, independent of the submitted payload.
member, err := a.store.IsChatMember(r.Context(), chatID, actor.user.ID)
if err != nil {
if errors.Is(err, store.ErrUnavailable) {
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
}
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
if !member {
a.writeError(w, r, statusNotFound)
return
}
var request createMessageRequest
if problem := a.decodeJSON(r, &request, "text", "attachment_ids"); problem != nil {
a.writeError(w, r, problem)
return
}
if request.Text == nil {
a.writeError(w, r, invalidRequest("text is required"))
return
}
attachmentIDs, problem := parseAttachmentIDs(request.AttachmentIDs)
if problem != nil {
a.writeError(w, r, problem)
return
}
if utf8.RuneCountInString(*request.Text) > 4000 {
a.writeError(w, r, invalidRequest("text must contain at most 4000 Unicode code points"))
return
}
if isBlank(*request.Text) && len(attachmentIDs) == 0 {
a.writeError(w, r, invalidRequest("text must not be blank without attachments"))
return
}
canonical, err := json.Marshal(messageHashBody{Text: *request.Text, AttachmentIDs: attachmentIDs})
if err != nil {
a.writeError(w, r, statusInternal)
return
}
hash := sha256.Sum256(canonical)
message, replayed, err := a.store.CreateMessageIdempotent(
r.Context(), chatID, actor.user.ID, http.MethodPost, messagePath(chatID),
idempotencyKey, hash[:], *request.Text, attachmentIDs,
)
switch {
case errors.Is(err, store.ErrIdempotencyConflict):
a.conflictMessages.Add(1)
a.writeError(w, r, statusConflict)
return
case errors.Is(err, store.ErrAttachmentNotReady):
a.writeError(w, r, conflict("attachment is not ready"))
return
case errors.Is(err, store.ErrNotFound):
a.writeError(w, r, statusNotFound)
return
case errors.Is(err, store.ErrUnavailable):
a.log.Error("create message failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
case err != nil:
a.log.Error("create message failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
if replayed {
a.replayedMessages.Add(1)
} else {
a.createdMessages.Add(1)
}
a.writeJSON(w, r, http.StatusCreated, message)
}
// parseAttachmentIDs accepts an absent field as [], rejects null and every
// wrong JSON type, and enforces the UUID / uniqueness / count rules before any
// database access.
func parseAttachmentIDs(raw json.RawMessage) ([]string, *apiError) {
if len(bytes.TrimSpace(raw)) == 0 {
return []string{}, nil
}
if bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {
return nil, invalidRequest("attachment_ids must be an array, not null")
}
var values []string
if err := json.Unmarshal(raw, &values); err != nil {
return nil, invalidRequest("attachment_ids must be an array of UUID strings")
}
if len(values) > maxMessageAttachments {
return nil, invalidRequest("attachment_ids must contain at most 10 items")
}
result := make([]string, 0, len(values))
seen := make(map[string]struct{}, len(values))
for _, value := range values {
id, ok := uuid.Normalize(value)
if !ok {
return nil, invalidRequest("every attachment_ids entry must be a UUID")
}
if _, duplicate := seen[id]; duplicate {
return nil, invalidRequest("attachment_ids must not contain duplicates")
}
seen[id] = struct{}{}
result = append(result, id)
}
return result, nil
}
func messagePath(chatID string) string {
return "/api/v1/chats/" + chatID + "/messages"
}
func (a *App) listMessages(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
if problem != nil {
a.writeError(w, r, problem)
return
}
// A foreign/nonexistent chat is always 404, even if the query itself is
// malformed; this avoids making object existence observable.
member, err := a.store.IsChatMember(r.Context(), chatID, actor.user.ID)
if err != nil {
if errors.Is(err, store.ErrUnavailable) {
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
}
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
if !member {
a.writeError(w, r, statusNotFound)
return
}
limit, rawCursor, problem := a.pageParams(r)
if problem != nil {
a.writeError(w, r, problem)
return
}
var position *cursor.Cursor
if rawCursor != "" {
decoded, err := cursor.Decode(rawCursor, cursor.ScopeMessages, chatID)
if err != nil {
a.writeError(w, r, invalidRequest("cursor is invalid for this chat"))
return
}
position = &decoded
}
page, err := a.store.Messages(r.Context(), chatID, position, limit)
if err != nil {
if errors.Is(err, store.ErrUnavailable) {
a.log.Error("list messages failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
}
a.log.Error("list messages failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
a.writeJSON(w, r, http.StatusOK, page)
}