forked from mtusi2026/mtusi2026lab7
на оценку 4
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
)
|
||||
|
||||
type AttachmentVariantResponse struct {
|
||||
Name string `json:"name"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
|
||||
type AttachmentResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Status domain.AttachmentStatus `json:"status"`
|
||||
Variants []AttachmentVariantResponse `json:"variants"`
|
||||
ErrorCode *string `json:"error_code"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func AttachmentFromDomain(attachment domain.Attachment) AttachmentResponse {
|
||||
variants := make([]AttachmentVariantResponse, 0, len(attachment.Variants))
|
||||
for _, variant := range attachment.Variants {
|
||||
variants = append(variants, AttachmentVariantResponse{
|
||||
Name: variant.Name,
|
||||
ContentType: variant.ContentType,
|
||||
SizeBytes: variant.SizeBytes,
|
||||
Width: variant.Width,
|
||||
Height: variant.Height,
|
||||
SHA256: variant.SHA256,
|
||||
})
|
||||
}
|
||||
return AttachmentResponse{
|
||||
ID: attachment.ID,
|
||||
ChatID: attachment.ChatID,
|
||||
OwnerID: attachment.OwnerID,
|
||||
Filename: attachment.Filename,
|
||||
ContentType: attachment.ContentType,
|
||||
SizeBytes: attachment.SizeBytes,
|
||||
SHA256: attachment.SHA256,
|
||||
Status: attachment.Status,
|
||||
Variants: variants,
|
||||
ErrorCode: attachment.ErrorCode,
|
||||
CreatedAt: attachment.CreatedAt,
|
||||
UpdatedAt: attachment.UpdatedAt,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
)
|
||||
|
||||
type CreateChatRequest struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
type ChatResponse struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type ChatPageResponse struct {
|
||||
Items []ChatResponse `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func ChatFromDomain(chat domain.Chat) ChatResponse {
|
||||
return ChatResponse{
|
||||
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: chat.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func ChatPageFromDomain(page domain.ChatPage) ChatPageResponse {
|
||||
items := make([]ChatResponse, len(page.Items))
|
||||
for index, chat := range page.Items {
|
||||
items[index] = ChatFromDomain(chat)
|
||||
}
|
||||
return ChatPageResponse{Items: items, NextCursor: page.NextCursor}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
)
|
||||
|
||||
type CreateMessageRequest struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
type MessageResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type MessagePageResponse struct {
|
||||
Items []MessageResponse `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func MessageFromDomain(message domain.Message) MessageResponse {
|
||||
attachmentIDs := append([]string(nil), message.AttachmentIDs...)
|
||||
if attachmentIDs == nil {
|
||||
attachmentIDs = make([]string, 0)
|
||||
}
|
||||
|
||||
return MessageResponse{
|
||||
ID: message.ID, ChatID: message.ChatID, SenderID: message.SenderID,
|
||||
Text: message.Text, AttachmentIDs: attachmentIDs, CreatedAt: message.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func MessagePageFromDomain(page domain.MessagePage) MessagePageResponse {
|
||||
items := make([]MessageResponse, len(page.Items))
|
||||
for index, message := range page.Items {
|
||||
items[index] = MessageFromDomain(message)
|
||||
}
|
||||
return MessagePageResponse{Items: items, NextCursor: page.NextCursor}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
)
|
||||
|
||||
type SessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
User UserResponse `json:"user"`
|
||||
}
|
||||
|
||||
func SessionFromDomain(session domain.Session) SessionResponse {
|
||||
return SessionResponse{
|
||||
Token: session.Token, TokenType: session.TokenType, ExpiresAt: session.ExpiresAt,
|
||||
User: UserFromDomain(session.User),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
)
|
||||
|
||||
type CreateUserRequest struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type UserResponse struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func UserFromDomain(user domain.User) UserResponse {
|
||||
return UserResponse{
|
||||
ID: user.ID, Username: user.Username, DisplayName: user.DisplayName, CreatedAt: user.CreatedAt,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
func (h *Handler) CreateChat(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
|
||||
var request dto.CreateChatRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeDecodeJSONError(w, requestID, err)
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := h.service.CreateChat(r.Context(), application.CreateChatCommand{
|
||||
ActorID: currentUser.ID, Title: request.Title, MemberIDs: request.MemberIDs,
|
||||
})
|
||||
if errors.Is(err, application.ErrInvalidInput) {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": "), requestID)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"one or more members do not exist", requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
response.WriteJSON(w, http.StatusCreated, dto.ChatFromDomain(chat), requestID)
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
parsedChatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"invalid chat_id uuid", requestID)
|
||||
return
|
||||
}
|
||||
chatID := parsedChatID.String()
|
||||
|
||||
idempotencyKey := r.Header.Get("Idempotency-Key")
|
||||
if !idempotencyKeyPattern.MatchString(idempotencyKey) {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"Idempotency-Key must match [A-Za-z0-9._:-]{1,128}", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
var request dto.CreateMessageRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeDecodeJSONError(w, requestID, err)
|
||||
return
|
||||
}
|
||||
message, err := h.service.SendMessage(r.Context(), application.SendMessageCommand{
|
||||
ActorID: currentUser.ID,
|
||||
ChatID: chatID,
|
||||
Text: request.Text,
|
||||
AttachmentIDs: request.AttachmentIDs,
|
||||
Method: http.MethodPost,
|
||||
CanonicalPath: "/api/v1/chats/" + chatID + "/messages",
|
||||
IdempotencyKey: idempotencyKey,
|
||||
})
|
||||
if errors.Is(err, application.ErrIdempotencyConflict) {
|
||||
response.WriteError(w, http.StatusConflict, response.CodeConflict,
|
||||
"Idempotency-Key is already used for another request", requestID)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, application.ErrAttachmentNotReady) {
|
||||
response.WriteError(w, http.StatusConflict, response.CodeConflict,
|
||||
"attachment is not ready", requestID)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, application.ErrInvalidInput) {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": "), requestID)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
response.WriteJSON(w, http.StatusCreated, dto.MessageFromDomain(message), requestID)
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
func (h *Handler) DeleteCurrentSession(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
tokenHash := middleware.GetCurrentSessionTokenHash(r.Context())
|
||||
if err := h.service.DeleteSession(r.Context(), tokenHash); err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
h.clearSessionCookie(w)
|
||||
response.WriteJSON(w, http.StatusNoContent, nil, requestID)
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func (h *Handler) GetAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
attachmentID, ok := parseAttachmentID(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
attachment, err := h.service.GetAttachment(r.Context(), attachmentID, currentUser.ID)
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound,
|
||||
"attachment not found", requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
response.WriteJSON(w, http.StatusOK, dto.AttachmentFromDomain(attachment), requestID)
|
||||
}
|
||||
|
||||
func (h *Handler) DownloadAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
attachmentID, ok := parseAttachmentID(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
download, err := h.service.DownloadAttachment(
|
||||
r.Context(), attachmentID, currentUser.ID, r.URL.Query().Get("variant"),
|
||||
)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound,
|
||||
"attachment or variant not found", requestID)
|
||||
return
|
||||
case errors.Is(err, application.ErrAttachmentNotReady):
|
||||
response.WriteError(w, http.StatusConflict, response.CodeConflict,
|
||||
"attachment is not ready", requestID)
|
||||
return
|
||||
case errors.Is(err, application.ErrStorageUnavailable):
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"object storage is temporarily unavailable", requestID)
|
||||
return
|
||||
case err != nil:
|
||||
response.WriteError(w, http.StatusInternalServerError, response.CodeInternalError,
|
||||
"unexpected internal error", requestID)
|
||||
return
|
||||
}
|
||||
defer download.Body.Close()
|
||||
|
||||
w.Header().Set("Content-Type", download.ContentType)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(download.SizeBytes, 10))
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Content-Disposition", mime.FormatMediaType(
|
||||
"attachment", map[string]string{"filename": download.Filename},
|
||||
))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = io.Copy(w, download.Body)
|
||||
}
|
||||
|
||||
func parseAttachmentID(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
requestID string,
|
||||
) (string, bool) {
|
||||
parsedID, err := uuid.Parse(r.PathValue("attachment_id"))
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"invalid attachment_id uuid", requestID)
|
||||
return "", false
|
||||
}
|
||||
return parsedID.String(), true
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
chatID := r.PathValue("chat_id")
|
||||
if _, err := uuid.Parse(chatID); err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"invalid chat_id uuid", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := h.service.GetChat(r.Context(), currentUser.ID, chatID)
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
response.WriteJSON(w, http.StatusOK, dto.ChatFromDomain(chat), requestID)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
func (h *Handler) GetMe(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
response.WriteJSON(w, http.StatusOK, dto.UserFromDomain(currentUser), requestID)
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
const maxJSONBodyBytes = 1 << 20
|
||||
|
||||
var (
|
||||
errUnsupportedMediaType = errors.New("unsupported media type")
|
||||
errJSONBodyTooLarge = errors.New("JSON body exceeds 1 MiB")
|
||||
)
|
||||
|
||||
type ReadinessChecker interface {
|
||||
Ping(ctx context.Context) error
|
||||
}
|
||||
|
||||
type LoginRateLimiter interface {
|
||||
AllowLoginAttempt(context.Context, [32]byte, time.Time, time.Duration, int) (bool, time.Duration, error)
|
||||
ResetLoginAttempts(context.Context, [32]byte) error
|
||||
}
|
||||
|
||||
type Option func(*Handler)
|
||||
|
||||
type Handler struct {
|
||||
service *application.Service
|
||||
readinessChecker ReadinessChecker
|
||||
readinessTimeout time.Duration
|
||||
sessionCookieSecure bool
|
||||
loginRateLimiter LoginRateLimiter
|
||||
loginRateLimit int
|
||||
loginRateWindow time.Duration
|
||||
}
|
||||
|
||||
func NewHandler(
|
||||
service *application.Service,
|
||||
options ...Option,
|
||||
) *Handler {
|
||||
handler := &Handler{
|
||||
service: service,
|
||||
readinessTimeout: 2 * time.Second,
|
||||
loginRateLimit: 5,
|
||||
loginRateWindow: time.Minute,
|
||||
}
|
||||
|
||||
for _, option := range options {
|
||||
option(handler)
|
||||
}
|
||||
|
||||
return handler
|
||||
}
|
||||
|
||||
func WithLoginRateLimit(
|
||||
limiter LoginRateLimiter,
|
||||
limit int,
|
||||
window time.Duration,
|
||||
) Option {
|
||||
return func(handler *Handler) {
|
||||
handler.loginRateLimiter = limiter
|
||||
handler.loginRateLimit = limit
|
||||
handler.loginRateWindow = window
|
||||
}
|
||||
}
|
||||
|
||||
func WithReadiness(
|
||||
checker ReadinessChecker,
|
||||
timeout time.Duration,
|
||||
) Option {
|
||||
return func(handler *Handler) {
|
||||
handler.readinessChecker = checker
|
||||
handler.readinessTimeout = timeout
|
||||
}
|
||||
}
|
||||
|
||||
func WithSessionCookieSecure(secure bool) Option {
|
||||
return func(handler *Handler) {
|
||||
handler.sessionCookieSecure = secure
|
||||
}
|
||||
}
|
||||
|
||||
func decodeJSON(r *http.Request, destination any) error {
|
||||
mediaType, parameters, err := mime.ParseMediaType(
|
||||
r.Header.Get("Content-Type"),
|
||||
)
|
||||
if err != nil || mediaType != "application/json" {
|
||||
return errUnsupportedMediaType
|
||||
}
|
||||
if charset, exists := parameters["charset"]; exists &&
|
||||
!strings.EqualFold(charset, "utf-8") {
|
||||
return errUnsupportedMediaType
|
||||
}
|
||||
|
||||
if r.Body == nil {
|
||||
return errors.New("request body is empty")
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
payload, err := io.ReadAll(io.LimitReader(
|
||||
r.Body,
|
||||
maxJSONBodyBytes+1,
|
||||
))
|
||||
if err != nil {
|
||||
return errors.New("read request body")
|
||||
}
|
||||
if len(payload) > maxJSONBodyBytes {
|
||||
return errJSONBodyTooLarge
|
||||
}
|
||||
if !utf8.Valid(payload) {
|
||||
return errors.New("request body must be valid UTF-8")
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(bytes.NewReader(payload))
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
if err := decoder.Decode(destination); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var extra json.RawMessage
|
||||
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return errors.New("extra data after JSON")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeDecodeJSONError(
|
||||
w http.ResponseWriter,
|
||||
requestID string,
|
||||
err error,
|
||||
) {
|
||||
switch {
|
||||
case errors.Is(err, errUnsupportedMediaType):
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusUnsupportedMediaType,
|
||||
response.CodeUnsupportedMediaType,
|
||||
"Content-Type must be application/json",
|
||||
requestID,
|
||||
)
|
||||
case errors.Is(err, errJSONBodyTooLarge):
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusRequestEntityTooLarge,
|
||||
response.CodePayloadTooLarge,
|
||||
err.Error(),
|
||||
requestID,
|
||||
)
|
||||
default:
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
"malformed or invalid JSON: "+err.Error(),
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDecodeJSONRejectsBodyAboveOneMiB(t *testing.T) {
|
||||
request := httptest.NewRequest(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
strings.NewReader(strings.Repeat(" ", maxJSONBodyBytes+1)),
|
||||
)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
var destination map[string]any
|
||||
err := decodeJSON(request, &destination)
|
||||
if !errors.Is(err, errJSONBodyTooLarge) {
|
||||
t.Fatalf("expected errJSONBodyTooLarge, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
// HealthLive проверяет только то, что HTTP-процесс работает.
|
||||
func (h *Handler) HealthLive(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusOK,
|
||||
map[string]string{"status": "ok"},
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
|
||||
// HealthReady проверяет зависимости, без которых API не может обслуживать трафик.
|
||||
func (h *Handler) HealthReady(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
// Этот вариант сохраняет работоспособность изолированных unit-тестов,
|
||||
// в которых PostgreSQL намеренно не создаётся.
|
||||
if h.readinessChecker == nil {
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusOK,
|
||||
map[string]string{"status": "ok"},
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(
|
||||
r.Context(),
|
||||
h.readinessTimeout,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
if err := h.readinessChecker.Ping(ctx); err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is not ready",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusOK,
|
||||
map[string]string{"status": "ok"},
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
limit, cursor, ok := parsePagination(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
page, err := h.service.ListChats(r.Context(), currentUser.ID, limit, cursor)
|
||||
if errors.Is(err, application.ErrInvalidCursor) {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid cursor", requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
response.WriteJSON(w, http.StatusOK, dto.ChatPageFromDomain(page), requestID)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func (h *Handler) GetMessages(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
chatID := r.PathValue("chat_id")
|
||||
if _, err := uuid.Parse(chatID); err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"invalid chat_id uuid", requestID)
|
||||
return
|
||||
}
|
||||
limit, cursor, ok := parsePagination(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
page, err := h.service.ListMessages(r.Context(), currentUser.ID, chatID, limit, cursor)
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", requestID)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, application.ErrInvalidCursor) {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid cursor", requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
response.WriteJSON(w, http.StatusOK, dto.MessagePageFromDomain(page), requestID)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
func parsePagination(w http.ResponseWriter, r *http.Request, requestID string) (int, string, bool) {
|
||||
query := r.URL.Query()
|
||||
limit := 50
|
||||
if query.Has("limit") {
|
||||
parsed, err := strconv.Atoi(query.Get("limit"))
|
||||
if err != nil || parsed < 1 || parsed > 100 {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"limit must be an integer between 1 and 100", requestID)
|
||||
return 0, "", false
|
||||
}
|
||||
limit = parsed
|
||||
}
|
||||
cursor := query.Get("cursor")
|
||||
if query.Has("cursor") && cursor == "" {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"cursor must not be empty", requestID)
|
||||
return 0, "", false
|
||||
}
|
||||
return limit, cursor, true
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
const sessionCookieName = "mtusi_session"
|
||||
|
||||
func (h *Handler) setSessionCookie(
|
||||
w http.ResponseWriter,
|
||||
token string,
|
||||
expiresAt time.Time,
|
||||
) {
|
||||
maxAge := int(time.Until(expiresAt).Seconds())
|
||||
if maxAge < 1 {
|
||||
maxAge = 1
|
||||
}
|
||||
|
||||
h.writeSessionCookie(w, token, expiresAt, maxAge)
|
||||
}
|
||||
|
||||
func (h *Handler) clearSessionCookie(w http.ResponseWriter) {
|
||||
h.writeSessionCookie(w, "", time.Unix(1, 0).UTC(), -1)
|
||||
}
|
||||
|
||||
func (h *Handler) writeSessionCookie(
|
||||
w http.ResponseWriter,
|
||||
value string,
|
||||
expiresAt time.Time,
|
||||
maxAge int,
|
||||
) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: sessionCookieName, Value: value, Path: "/",
|
||||
Expires: expiresAt, MaxAge: maxAge,
|
||||
HttpOnly: true, Secure: h.sessionCookieSecure,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestSessionCookieIsHardened(t *testing.T) {
|
||||
handler := &Handler{sessionCookieSecure: true}
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
handler.setSessionCookie(
|
||||
recorder,
|
||||
"secret-token",
|
||||
time.Now().Add(time.Hour),
|
||||
)
|
||||
|
||||
cookies := recorder.Result().Cookies()
|
||||
if len(cookies) != 1 {
|
||||
t.Fatalf("cookie count = %d, want 1", len(cookies))
|
||||
}
|
||||
|
||||
cookie := cookies[0]
|
||||
if cookie.Name != sessionCookieName || cookie.Value != "secret-token" {
|
||||
t.Fatalf("unexpected cookie: %#v", cookie)
|
||||
}
|
||||
if cookie.Path != "/" || cookie.Domain != "" {
|
||||
t.Fatalf("cookie scope = path %q domain %q", cookie.Path, cookie.Domain)
|
||||
}
|
||||
if !cookie.HttpOnly || !cookie.Secure {
|
||||
t.Fatalf("cookie flags: HttpOnly=%v Secure=%v", cookie.HttpOnly, cookie.Secure)
|
||||
}
|
||||
if cookie.SameSite != http.SameSiteStrictMode {
|
||||
t.Fatalf("SameSite = %v, want Strict", cookie.SameSite)
|
||||
}
|
||||
if cookie.MaxAge < 1 {
|
||||
t.Fatalf("MaxAge = %d, want positive", cookie.MaxAge)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClearSessionCookieExpiresIt(t *testing.T) {
|
||||
handler := &Handler{}
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
handler.clearSessionCookie(recorder)
|
||||
|
||||
cookies := recorder.Result().Cookies()
|
||||
if len(cookies) != 1 {
|
||||
t.Fatalf("cookie count = %d, want 1", len(cookies))
|
||||
}
|
||||
|
||||
cookie := cookies[0]
|
||||
if cookie.Value != "" || cookie.MaxAge != -1 {
|
||||
t.Fatalf("clear cookie = value %q MaxAge %d", cookie.Value, cookie.MaxAge)
|
||||
}
|
||||
if !cookie.Expires.Before(time.Now()) {
|
||||
t.Fatalf("clear cookie expiry %v is not in the past", cookie.Expires)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
const basicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
|
||||
func (h *Handler) CreateSession(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok || username == "" ||
|
||||
!utf8.ValidString(username) || !utf8.ValidString(password) {
|
||||
writeBasicUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
identifierHash := sha256.Sum256([]byte(strings.ToLower(username)))
|
||||
if h.loginRateLimiter != nil {
|
||||
allowed, retryAfter, err := h.loginRateLimiter.AllowLoginAttempt(
|
||||
r.Context(), identifierHash, time.Now().UTC(), h.loginRateWindow, h.loginRateLimit,
|
||||
)
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
if !allowed {
|
||||
seconds := int(math.Ceil(retryAfter.Seconds()))
|
||||
if seconds < 1 {
|
||||
seconds = 1
|
||||
}
|
||||
w.Header().Set("Retry-After", strconv.Itoa(seconds))
|
||||
response.WriteError(w, http.StatusTooManyRequests, response.CodeRateLimited,
|
||||
"too many login attempts", requestID)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
session, err := h.service.CreateSession(r.Context(), application.CreateSessionCommand{
|
||||
Username: username,
|
||||
Password: password,
|
||||
})
|
||||
if errors.Is(err, application.ErrCredentialState) {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusInternalServerError,
|
||||
response.CodeInternalError,
|
||||
"service is temporarily unavailable",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, application.ErrInvalidCredentials) {
|
||||
writeBasicUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
if h.loginRateLimiter != nil {
|
||||
if err = h.loginRateLimiter.ResetLoginAttempts(r.Context(), identifierHash); err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
h.setSessionCookie(w, session.Token, session.ExpiresAt)
|
||||
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusCreated,
|
||||
dto.SessionFromDomain(session),
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
func writeBasicUnauthorized(
|
||||
w http.ResponseWriter,
|
||||
requestID string,
|
||||
) {
|
||||
w.Header().Set("WWW-Authenticate", basicChallenge)
|
||||
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusUnauthorized,
|
||||
response.CodeUnauthorized,
|
||||
"invalid username or password",
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func (h *Handler) UploadAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
|
||||
parsedChatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"invalid chat_id uuid", requestID)
|
||||
return
|
||||
}
|
||||
filename := r.URL.Query().Get("filename")
|
||||
if filename == "" {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"filename query parameter is required", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
contentType, parameters, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil || len(parameters) != 0 ||
|
||||
(contentType != "image/png" && contentType != "image/jpeg") {
|
||||
response.WriteError(w, http.StatusUnsupportedMediaType,
|
||||
response.CodeUnsupportedMediaType,
|
||||
"Content-Type must be image/png or image/jpeg", requestID)
|
||||
return
|
||||
}
|
||||
if r.ContentLength > domain.MaxAttachmentSizeBytes {
|
||||
response.WriteError(w, http.StatusRequestEntityTooLarge,
|
||||
response.CodePayloadTooLarge,
|
||||
"attachment exceeds 10 MiB", requestID)
|
||||
return
|
||||
}
|
||||
if r.Body == nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"attachment body is required", requestID)
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
attachment, err := h.service.UploadAttachment(
|
||||
r.Context(),
|
||||
application.UploadAttachmentCommand{
|
||||
ActorID: currentUser.ID,
|
||||
ChatID: parsedChatID.String(),
|
||||
Filename: filename,
|
||||
DeclaredContentType: contentType,
|
||||
Body: r.Body,
|
||||
},
|
||||
)
|
||||
switch {
|
||||
case errors.Is(err, application.ErrPayloadTooLarge):
|
||||
response.WriteError(w, http.StatusRequestEntityTooLarge,
|
||||
response.CodePayloadTooLarge,
|
||||
"attachment exceeds 10 MiB or 40 million pixels", requestID)
|
||||
return
|
||||
case errors.Is(err, application.ErrUnsupportedMediaType), errors.Is(err, application.ErrInvalidImage):
|
||||
response.WriteError(w, http.StatusUnsupportedMediaType,
|
||||
response.CodeUnsupportedMediaType,
|
||||
"body is not a valid PNG/JPEG matching the declared Content-Type", requestID)
|
||||
return
|
||||
case errors.Is(err, application.ErrInvalidInput):
|
||||
message := strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": ")
|
||||
response.WriteError(w, http.StatusBadRequest,
|
||||
response.CodeInvalidRequest, message, requestID)
|
||||
return
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
response.WriteError(w, http.StatusNotFound,
|
||||
response.CodeNotFound, "chat not found", requestID)
|
||||
return
|
||||
case errors.Is(err, application.ErrStorageUnavailable):
|
||||
response.WriteError(w, http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable, "object storage is temporarily unavailable", requestID)
|
||||
return
|
||||
case err != nil:
|
||||
response.WriteError(w, http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable, "service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(w, http.StatusAccepted, dto.AttachmentFromDomain(attachment), requestID)
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
func (h *Handler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
var request dto.CreateUserRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeDecodeJSONError(w, requestID, err)
|
||||
return
|
||||
}
|
||||
|
||||
createdUser, err := h.service.CreateUser(r.Context(), application.CreateUserCommand{
|
||||
Username: request.Username, DisplayName: request.DisplayName, Password: request.Password,
|
||||
})
|
||||
if errors.Is(err, application.ErrInvalidInput) {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": "),
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if errors.Is(err, domain.ErrConflict) {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusConflict,
|
||||
response.CodeConflict,
|
||||
"username already exists",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusCreated,
|
||||
dto.UserFromDomain(createdUser),
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
const bearerChallenge = `Bearer realm="messenger"`
|
||||
|
||||
const (
|
||||
UserContextKey contextKey = "current_user"
|
||||
sessionTokenHashKey contextKey = "session_token_hash"
|
||||
)
|
||||
|
||||
type SessionAuthenticator interface {
|
||||
Authenticate(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) (domain.User, []byte, error)
|
||||
}
|
||||
|
||||
func RequireAuth(
|
||||
authenticator SessionAuthenticator,
|
||||
next http.HandlerFunc,
|
||||
) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := GetRequestID(r.Context())
|
||||
|
||||
token, ok := bearerToken(r.Header.Get("Authorization"))
|
||||
if !ok {
|
||||
writeBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
user, tokenHash, err := authenticator.Authenticate(
|
||||
r.Context(),
|
||||
token,
|
||||
)
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
writeBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(
|
||||
r.Context(),
|
||||
UserContextKey,
|
||||
user,
|
||||
)
|
||||
ctx = context.WithValue(
|
||||
ctx,
|
||||
sessionTokenHashKey,
|
||||
tokenHash,
|
||||
)
|
||||
|
||||
next(w, r.WithContext(ctx))
|
||||
}
|
||||
}
|
||||
|
||||
func GetCurrentUser(ctx context.Context) domain.User {
|
||||
user, _ := ctx.Value(UserContextKey).(domain.User)
|
||||
return user
|
||||
}
|
||||
|
||||
func GetCurrentSessionTokenHash(ctx context.Context) []byte {
|
||||
tokenHash, _ := ctx.Value(sessionTokenHashKey).([]byte)
|
||||
|
||||
result := make([]byte, len(tokenHash))
|
||||
copy(result, tokenHash)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func bearerToken(authorization string) (string, bool) {
|
||||
parts := strings.Fields(authorization)
|
||||
|
||||
if len(parts) != 2 ||
|
||||
!strings.EqualFold(parts[0], "Bearer") ||
|
||||
parts[1] == "" {
|
||||
return "", false
|
||||
}
|
||||
|
||||
return parts[1], true
|
||||
}
|
||||
|
||||
func writeBearerUnauthorized(
|
||||
w http.ResponseWriter,
|
||||
requestID string,
|
||||
) {
|
||||
w.Header().Set("WWW-Authenticate", bearerChallenge)
|
||||
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusUnauthorized,
|
||||
response.CodeUnauthorized,
|
||||
"invalid or expired bearer token",
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
// AvailabilityGate lets a process reject new work before its HTTP listener is
|
||||
// closed. Existing requests are still drained by http.Server.Shutdown.
|
||||
type AvailabilityGate struct {
|
||||
accepting atomic.Bool
|
||||
}
|
||||
|
||||
func NewAvailabilityGate() *AvailabilityGate {
|
||||
gate := &AvailabilityGate{}
|
||||
gate.accepting.Store(true)
|
||||
|
||||
return gate
|
||||
}
|
||||
|
||||
func (g *AvailabilityGate) BeginDrain() {
|
||||
g.accepting.Store(false)
|
||||
}
|
||||
|
||||
func (g *AvailabilityGate) IsAccepting() bool {
|
||||
return g.accepting.Load()
|
||||
}
|
||||
|
||||
func (g *AvailabilityGate) Middleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Liveness deliberately stays available while the process drains. The
|
||||
// readiness endpoint and all business traffic receive 503 immediately.
|
||||
if g.IsAccepting() || r.URL.Path == "/health/live" {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is draining",
|
||||
GetRequestID(r.Context()),
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAvailabilityGateRejectsNewWorkWhileKeepingLiveness(t *testing.T) {
|
||||
gate := NewAvailabilityGate()
|
||||
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
handler := RequestID(gate.Middleware(next))
|
||||
|
||||
before := httptest.NewRecorder()
|
||||
handler.ServeHTTP(before, httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil))
|
||||
if before.Code != http.StatusNoContent {
|
||||
t.Fatalf("before drain status = %d, want %d", before.Code, http.StatusNoContent)
|
||||
}
|
||||
|
||||
gate.BeginDrain()
|
||||
|
||||
draining := httptest.NewRecorder()
|
||||
handler.ServeHTTP(draining, httptest.NewRequest(http.MethodGet, "/health/ready", nil))
|
||||
if draining.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("ready while draining status = %d, want %d", draining.Code, http.StatusServiceUnavailable)
|
||||
}
|
||||
if draining.Header().Get("X-Request-Id") == "" {
|
||||
t.Fatal("draining response is missing X-Request-Id")
|
||||
}
|
||||
|
||||
live := httptest.NewRecorder()
|
||||
handler.ServeHTTP(live, httptest.NewRequest(http.MethodGet, "/health/live", nil))
|
||||
if live.Code != http.StatusNoContent {
|
||||
t.Fatalf("live while draining status = %d, want %d", live.Code, http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
const InstanceIDHeader = "X-Instance-Id"
|
||||
|
||||
// InstanceID identifies the process that actually produced the response.
|
||||
// It must wrap recovery and routing so even errors, health checks and 404/405
|
||||
// responses carry the same stable process identifier.
|
||||
func InstanceID(instanceID string, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set(InstanceIDHeader, instanceID)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestInstanceIDOnSuccessfulAndNotFoundResponses(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /ok", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
handler := InstanceID("api-01", mux)
|
||||
|
||||
for _, test := range []struct {
|
||||
path string
|
||||
wantStatus int
|
||||
}{
|
||||
{path: "/ok", wantStatus: http.StatusNoContent},
|
||||
{path: "/missing", wantStatus: http.StatusNotFound},
|
||||
} {
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, test.path, nil))
|
||||
|
||||
if recorder.Code != test.wantStatus {
|
||||
t.Fatalf("%s: got status %d, want %d", test.path, recorder.Code, test.wantStatus)
|
||||
}
|
||||
if got := recorder.Header().Get(InstanceIDHeader); got != "api-01" {
|
||||
t.Fatalf("%s: got instance ID %q, want api-01", test.path, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstanceIDSurvivesRecoveredPanic(t *testing.T) {
|
||||
panicking := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
|
||||
panic("test panic")
|
||||
})
|
||||
handler := InstanceID("api-panic", Recovery(panicking))
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/panic", nil))
|
||||
|
||||
if recorder.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("got status %d, want 500", recorder.Code)
|
||||
}
|
||||
if got := recorder.Header().Get(InstanceIDHeader); got != "api-panic" {
|
||||
t.Fatalf("got instance ID %q, want api-panic", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
apptelemetry "mtusi2026lab7/internal/telemetry"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
type responseWriterInterceptor struct {
|
||||
http.ResponseWriter
|
||||
statusCode int
|
||||
}
|
||||
|
||||
func (w *responseWriterInterceptor) WriteHeader(code int) {
|
||||
w.statusCode = code
|
||||
w.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func Observability(runtime *apptelemetry.Runtime, next http.Handler) (http.Handler, error) {
|
||||
requests, err := runtime.Meter.Int64Counter(
|
||||
"messenger.http.server.requests",
|
||||
metric.WithDescription("Number of completed HTTP requests"),
|
||||
metric.WithUnit("{request}"),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create HTTP request counter: %w", err)
|
||||
}
|
||||
duration, err := runtime.Meter.Float64Histogram(
|
||||
"messenger.http.server.duration",
|
||||
metric.WithDescription("HTTP server request duration"),
|
||||
metric.WithUnit("s"),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create HTTP duration histogram: %w", err)
|
||||
}
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasPrefix(r.URL.Path, "/health/") {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
start := time.Now()
|
||||
parent := otel.GetTextMapPropagator().Extract(
|
||||
r.Context(),
|
||||
propagation.HeaderCarrier(r.Header),
|
||||
)
|
||||
ctx, span := runtime.Tracer.Start(
|
||||
parent,
|
||||
r.Method+" HTTP request",
|
||||
trace.WithSpanKind(trace.SpanKindServer),
|
||||
trace.WithAttributes(attribute.String("http.request.method", r.Method)),
|
||||
)
|
||||
defer span.End()
|
||||
interceptor := &responseWriterInterceptor{
|
||||
ResponseWriter: w,
|
||||
statusCode: http.StatusOK,
|
||||
}
|
||||
observedRequest := r.WithContext(ctx)
|
||||
next.ServeHTTP(interceptor, observedRequest)
|
||||
|
||||
route := observedRequest.Pattern
|
||||
if route == "" {
|
||||
route = "unmatched"
|
||||
}
|
||||
statusClass := strconv.Itoa(interceptor.statusCode/100) + "xx"
|
||||
elapsed := time.Since(start)
|
||||
labels := metric.WithAttributes(
|
||||
attribute.String("method", r.Method),
|
||||
attribute.String("route", route),
|
||||
attribute.String("status_class", statusClass),
|
||||
)
|
||||
requests.Add(ctx, 1, labels)
|
||||
duration.Record(ctx, elapsed.Seconds(), labels)
|
||||
|
||||
span.SetName(r.Method + " " + route)
|
||||
span.SetAttributes(
|
||||
attribute.String("http.route", route),
|
||||
attribute.Int("http.response.status_code", interceptor.statusCode),
|
||||
)
|
||||
if interceptor.statusCode >= http.StatusInternalServerError {
|
||||
span.SetStatus(codes.Error, "server error")
|
||||
} else {
|
||||
span.SetStatus(codes.Ok, "")
|
||||
}
|
||||
|
||||
runtime.Logger.Info(ctx, "http_request_completed", apptelemetry.Fields{
|
||||
"method": r.Method,
|
||||
"route": route,
|
||||
"status_code": interceptor.statusCode,
|
||||
"status_class": statusClass,
|
||||
"duration_ms": float64(elapsed.Microseconds()) / 1000,
|
||||
"request_id": GetRequestID(ctx),
|
||||
})
|
||||
}), nil
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
// Recovery перехватывает панику и возвращает клиенту валидный JSON 500
|
||||
func Recovery(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
reqID := GetRequestID(r.Context())
|
||||
//из контракта: не раскрывать stack trace и внутренности
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusInternalServerError,
|
||||
response.CodeInternalError,
|
||||
"internal server error",
|
||||
reqID,
|
||||
)
|
||||
}
|
||||
}()
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const RequestIDKey contextKey = "request_id"
|
||||
|
||||
// RequestID извлекает или генерирует X-Request-Id и кладет его в контекст и заголовок ответа
|
||||
func RequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := r.Header.Get("X-Request-Id")
|
||||
if reqID == "" {
|
||||
reqID = uuid.NewString()
|
||||
}
|
||||
|
||||
w.Header().Set("X-Request-Id", reqID)
|
||||
|
||||
ctx := context.WithValue(r.Context(), RequestIDKey, reqID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
// GetRequestID достает ID запроса из контекста
|
||||
func GetRequestID(ctx context.Context) string {
|
||||
if val, ok := ctx.Value(RequestIDKey).(string); ok {
|
||||
return val
|
||||
}
|
||||
return uuid.NewString()
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package response
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// коды ошибок по контракту
|
||||
const (
|
||||
CodeInvalidRequest = "invalid_request"
|
||||
CodePayloadTooLarge = "payload_too_large"
|
||||
CodeUnsupportedMediaType = "unsupported_media_type"
|
||||
CodeUnauthorized = "unauthorized"
|
||||
CodeNotFound = "not_found"
|
||||
CodeConflict = "conflict"
|
||||
CodeRateLimited = "rate_limited"
|
||||
CodeUnavailable = "unavailable"
|
||||
CodeInternalError = "internal_error"
|
||||
)
|
||||
|
||||
type ErrorPayload struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
// ErrorResponse — строгое тело ответа при любой ошибке
|
||||
type ErrorResponse struct {
|
||||
Error ErrorPayload `json:"error"`
|
||||
}
|
||||
|
||||
// WriteJSON отправляет любой успешный ответ с правильными заголовками
|
||||
func WriteJSON(w http.ResponseWriter, statusCode int, data any, requestID string) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
if requestID != "" {
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
}
|
||||
|
||||
w.WriteHeader(statusCode)
|
||||
|
||||
if data != nil {
|
||||
_ = json.NewEncoder(w).Encode(data)
|
||||
}
|
||||
}
|
||||
|
||||
// WriteError формирует стандартизированную ошибку с совпадением request_id в теле и заголовке
|
||||
func WriteError(w http.ResponseWriter, statusCode int, code string, message string, requestID string) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
if requestID != "" {
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
}
|
||||
|
||||
w.WriteHeader(statusCode)
|
||||
|
||||
resp := ErrorResponse{
|
||||
Error: ErrorPayload{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: requestID,
|
||||
},
|
||||
}
|
||||
|
||||
_ = json.NewEncoder(w).Encode(resp)
|
||||
}
|
||||
Reference in New Issue
Block a user