Files
mtusi2026lab3/internal/api/messages.go

151 lines
4.7 KiB
Go

package api
import (
"crypto/sha256"
"errors"
"net/http"
"mtusi.ru/messenger-lab3/internal/cursor"
"mtusi.ru/messenger-lab3/internal/store"
)
type createMessageRequest struct {
Text *string `json:"text"`
}
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"); problem != nil {
a.writeError(w, r, problem)
return
}
if request.Text == nil {
a.writeError(w, r, invalidRequest("text is required"))
return
}
if problem := validateMessageText(*request.Text); problem != nil {
a.writeError(w, r, problem)
return
}
// The canonical body for lab3 is {"text": ...}. Hash the decoded text, not
// the raw bytes: insignificant JSON whitespace or escapes must replay the
// same key, while any different text must conflict. attachment_ids is not
// part of the lab3 schema; lab4 will extend this canonical form.
hash := sha256.Sum256([]byte(*request.Text))
message, replayed, err := a.store.CreateMessageIdempotent(
r.Context(), chatID, actor.user.ID, http.MethodPost, messagePath(chatID), idempotencyKey, hash[:], *request.Text,
)
switch {
case errors.Is(err, store.ErrIdempotencyConflict):
a.conflictMessages.Add(1)
a.writeError(w, r, statusConflict)
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)
}
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)
}