ЛР 5 — асинхронная обработка и версии pipeline

This commit is contained in:
2026-11-16 02:38:13 +03:00
parent 276dbdad8a
commit 1f535f1b5b
163 changed files with 17194 additions and 24 deletions
@@ -0,0 +1,159 @@
package handler
import (
"errors"
"highload/internal/service"
"highload/internal/transport/http/httputils"
"highload/internal/transport/http/middleware"
"io"
"log/slog"
"net/http"
"os"
"time"
)
type AttachmentHandler struct {
attachmentService *service.AttachmentService
uploadSlots chan struct{}
}
func NewAttachmentHandler(attachmentService *service.AttachmentService) *AttachmentHandler {
uploadSlots := make(chan struct{}, 1)
return &AttachmentHandler{attachmentService: attachmentService, uploadSlots: uploadSlots}
}
func (h *AttachmentHandler) CreateAttachment(w http.ResponseWriter, r *http.Request) {
requestID := middleware.RequestIDFromContext(r.Context())
userID := middleware.UserIDFromContext(r.Context())
chatID := r.PathValue("chat_id")
filename := r.URL.Query().Get("filename")
contentType := r.Header.Get("Content-Type")
select {
case h.uploadSlots <- struct{}{}:
defer func() { <-h.uploadSlots }()
case <-time.After(1 * time.Second):
w.Header().Set("Retry-After", "1")
httputils.WriteError(w, http.StatusTooManyRequests, httputils.ErrorDetails{
Code: "rate_limited",
Message: "too many concurrent uploads, try again later",
RequestID: requestID,
})
return
case <-r.Context().Done():
return
}
file, err := os.CreateTemp("", "attachment-*")
if err != nil {
httputils.WriteServiceError(w, err, requestID)
return
}
defer file.Close()
if err := os.Remove(file.Name()); err != nil {
httputils.WriteServiceError(w, err, requestID)
return
}
body := http.MaxBytesReader(w, r.Body, service.MaxAttachmentBytes)
defer body.Close()
size, err := io.Copy(file, uploadBodyReader{body})
var maxErr *http.MaxBytesError
if errors.As(err, &maxErr) {
httputils.WriteError(w, http.StatusRequestEntityTooLarge, httputils.ErrorDetails{
Code: "payload_too_large",
Message: "payload_too_large",
RequestID: requestID,
})
return
}
if err != nil {
var readErr *uploadBodyReadError
if !errors.As(err, &readErr) {
httputils.WriteServiceError(w, err, requestID)
return
}
httputils.WriteError(w, http.StatusBadRequest, httputils.ErrorDetails{
Code: "invalid_request",
Message: "invalid_request",
RequestID: requestID,
})
return
}
attachment, err := h.attachmentService.CreateAttachment(r.Context(), chatID, userID, filename, contentType, file, size)
if err != nil {
httputils.WriteServiceError(w, err, requestID)
return
}
response := convertAttachmentModelToResponse(attachment)
wrErr := httputils.WriteJSON[attachmentResponse](w, http.StatusAccepted, *response)
if wrErr != nil {
slog.Error("failed to write create attachment response", "error", wrErr, "requestID", requestID)
}
}
type uploadBodyReader struct{ io.Reader }
func (r uploadBodyReader) Read(p []byte) (int, error) {
n, err := r.Reader.Read(p)
if err != nil && err != io.EOF {
return n, &uploadBodyReadError{err}
}
return n, err
}
type uploadBodyReadError struct{ cause error }
func (e *uploadBodyReadError) Error() string { return e.cause.Error() }
func (e *uploadBodyReadError) Unwrap() error { return e.cause }
func (h *AttachmentHandler) GetAttachment(w http.ResponseWriter, r *http.Request) {
requestID := middleware.RequestIDFromContext(r.Context())
userID := middleware.UserIDFromContext(r.Context())
attachmentID := r.PathValue("attachment_id")
attachment, err := h.attachmentService.GetAttachment(r.Context(), userID, attachmentID)
if err != nil {
httputils.WriteServiceError(w, err, requestID)
return
}
wrErr := httputils.WriteJSON[attachmentResponse](w, http.StatusOK, *convertAttachmentModelToResponse(attachment))
if wrErr != nil {
slog.Error("failed to write get attachment response", "error", wrErr, "requestID", requestID)
}
}
func (h *AttachmentHandler) GetAttachmentContent(w http.ResponseWriter, r *http.Request) {
requestID := middleware.RequestIDFromContext(r.Context())
userID := middleware.UserIDFromContext(r.Context())
attachmentID := r.PathValue("attachment_id")
variant := r.URL.Query().Get("variant")
contentType, stream, err := h.attachmentService.GetAttachmentContent(r.Context(), userID, attachmentID, variant)
if err != nil {
httputils.WriteServiceError(w, err, requestID)
return
}
defer stream.Close()
w.Header().Set("Content-Type", contentType)
_, err = io.Copy(w, stream)
if err != nil {
slog.Error("failed to copy attachment content to w", "error", err, "request_id", requestID)
}
}
@@ -0,0 +1,54 @@
package handler
import (
"highload/internal/model"
"highload/internal/transport/http/httputils"
)
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 string `json:"status"`
Variants []attachmentVariantResponse `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
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"`
}
func convertAttachmentModelToResponse(attachment *model.Attachment) *attachmentResponse {
variants := make([]attachmentVariantResponse, 0, len(attachment.Variants))
for _, v := range attachment.Variants {
variants = append(variants, attachmentVariantResponse{
Name: v.Name, ContentType: v.ContentType, SizeBytes: v.SizeBytes,
Width: v.Width, Height: v.Height, SHA256: v.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: httputils.FormatTime(attachment.CreatedAt),
UpdatedAt: httputils.FormatTime(attachment.UpdatedAt),
}
}
+94
View File
@@ -0,0 +1,94 @@
package handler
import (
"errors"
"highload/internal/service"
"highload/internal/transport/http/httputils"
"highload/internal/transport/http/middleware"
"io"
"net/http"
)
type AuthHandler struct {
authService *service.AuthService
}
func NewAuthHandler(authService *service.AuthService) *AuthHandler {
return &AuthHandler{authService: authService}
}
func (h *AuthHandler) CreateSession(w http.ResponseWriter, r *http.Request) {
requestID := middleware.RequestIDFromContext(r.Context())
username, password, ok := r.BasicAuth()
if !ok {
httputils.WriteBasicUnauthorized(w, requestID)
return
}
var probe [1]byte
n, err := r.Body.Read(probe[:])
if n > 0 || (err != nil && !errors.Is(err, io.EOF)) {
_ = httputils.WriteError(w, http.StatusBadRequest, httputils.ErrorDetails{
Code: "invalid_request",
Message: "Request body must be empty",
RequestID: requestID,
})
return
}
createdSession, err := h.authService.CreateSession(r.Context(), username, password)
if err != nil {
if errors.Is(err, service.ErrUnauthorized) {
httputils.WriteBasicUnauthorized(w, requestID)
return
}
httputils.WriteServiceError(w, err, requestID)
return
}
response := createSessionResponse{
Token: createdSession.Token,
TokenType: createdSession.TokenType,
ExpiresAt: httputils.FormatTime(createdSession.ExpiresAt),
User: UserResponse{
Username: createdSession.User.Username,
ID: createdSession.User.ID,
DisplayName: createdSession.User.DisplayName,
CreatedAt: httputils.FormatTime(createdSession.User.CreatedAt),
},
}
httputils.WriteJSON[createSessionResponse](w, http.StatusCreated, response)
}
func (h *AuthHandler) DeleteSession(w http.ResponseWriter, r *http.Request) {
requestID := middleware.RequestIDFromContext(r.Context())
token, ok := httputils.ExtractBearerToken(r)
if !ok {
httputils.WriteBearerUnauthorized(w, requestID)
return
}
err := h.authService.RevokeSession(r.Context(), token)
if err != nil {
if errors.Is(err, service.ErrUnauthorized) {
httputils.WriteBearerUnauthorized(w, requestID)
return
}
httputils.WriteServiceError(w, err, requestID)
return
}
w.WriteHeader(http.StatusNoContent)
}
@@ -0,0 +1,15 @@
package handler
type UserResponse struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt string `json:"created_at"`
}
type createSessionResponse struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt string `json:"expires_at"`
User UserResponse `json:"user"`
}
+102
View File
@@ -0,0 +1,102 @@
package handler
import (
"highload/internal/service"
"highload/internal/transport/http/httputils"
"highload/internal/transport/http/middleware"
"net/http"
)
type ChatHandler struct {
chatService *service.ChatService
}
func NewChatHandler(chatService *service.ChatService) *ChatHandler {
return &ChatHandler{chatService: chatService}
}
func (h *ChatHandler) CreateChat(w http.ResponseWriter, r *http.Request) {
requestID := middleware.RequestIDFromContext(r.Context())
userID := middleware.UserIDFromContext(r.Context())
req, code := httputils.Decode[chatCreateRequest](r)
if code != http.StatusOK {
if code == http.StatusUnsupportedMediaType {
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "unsupported_media_type", Message: "Неверный media type", RequestID: requestID})
return
}
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "invalid_request", Message: "Неверный запрос", RequestID: requestID})
return
}
result, err := h.chatService.Create(r.Context(), req.Title, req.MemberIDs, userID)
if err != nil {
httputils.WriteServiceError(w, err, requestID)
return
}
response := chatResponse{
Title: result.Title,
MemberIDs: result.MemberIDs,
ID: result.ID,
CreatedAt: httputils.FormatTime(result.CreatedAt),
}
_ = httputils.WriteJSON[chatResponse](w, http.StatusCreated, response)
}
func (h *ChatHandler) GetChatsByUserID(w http.ResponseWriter, r *http.Request) {
requestID := middleware.RequestIDFromContext(r.Context())
userID := middleware.UserIDFromContext(r.Context())
limit, cursor, ok := httputils.GetLimitAndCursor(r)
if !ok {
httputils.WriteError(w, http.StatusBadRequest, httputils.ErrorDetails{Code: "invalid_request", Message: "Неверный запрос", RequestID: requestID})
return
}
chats, nextCursor, err := h.chatService.GetChatsByUserID(r.Context(), userID, limit, cursor)
if err != nil {
httputils.WriteServiceError(w, err, requestID)
return
}
chatResponses := make([]chatResponse, len(chats))
for index, chat := range chats {
chatResponses[index] = *convertChatModelToResponse(chat)
}
response := chatGetByUserIDResponse{
Items: chatResponses,
NextCursor: nextCursor,
}
_ = httputils.WriteJSON[chatGetByUserIDResponse](w, http.StatusOK, response)
}
func (h *ChatHandler) GetChatByChatID(w http.ResponseWriter, r *http.Request) {
requestID := middleware.RequestIDFromContext(r.Context())
userID := middleware.UserIDFromContext(r.Context())
chatID := r.PathValue("chat_id")
chat, err := h.chatService.GetChatByID(r.Context(), chatID, userID)
if err != nil {
httputils.WriteServiceError(w, err, requestID)
return
}
response := convertChatModelToResponse(chat)
_ = httputils.WriteJSON[chatResponse](w, http.StatusOK, *response)
}
@@ -0,0 +1,32 @@
package handler
import (
"highload/internal/model"
"highload/internal/transport/http/httputils"
)
type chatCreateRequest struct {
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
}
type chatResponse struct {
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
ID string `json:"id"`
CreatedAt string `json:"created_at"`
}
type chatGetByUserIDResponse struct {
Items []chatResponse `json:"items"`
NextCursor *string `json:"next_cursor"`
}
func convertChatModelToResponse(model *model.Chat) *chatResponse {
return &chatResponse{
Title: model.Title,
ID: model.ID,
MemberIDs: model.MemberIDs,
CreatedAt: httputils.FormatTime(model.CreatedAt),
}
}
+86
View File
@@ -0,0 +1,86 @@
package handler
import (
"context"
"highload/internal/storage/s3"
"highload/internal/transport/http/httputils"
"highload/internal/transport/http/middleware"
"log/slog"
"net/http"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
)
type HealthHandler struct {
pool *pgxpool.Pool
redisClient *redis.Client
s3Storage *s3.Storage
}
func NewHealthHandler(pool *pgxpool.Pool, redisClient *redis.Client, s3Storage *s3.Storage) *HealthHandler {
return &HealthHandler{pool: pool, redisClient: redisClient, s3Storage: s3Storage}
}
func (h *HealthHandler) Live(w http.ResponseWriter, r *http.Request) {
response := HealthResponse{Status: "ok"}
err := httputils.WriteJSON[HealthResponse](w, http.StatusOK, response)
if err != nil {
slog.Error("failed to write health response", "error", err)
}
}
func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
requestID := middleware.RequestIDFromContext(r.Context())
if err := h.pool.Ping(ctx); err != nil {
slog.Error("database readiness check failed", "error", err)
if writeErr := httputils.WriteServiceUnavailable(w, requestID); writeErr != nil {
slog.Error("failed to write readiness response", "error", writeErr)
}
return
}
if err := h.redisClient.Ping(ctx).Err(); err != nil {
slog.Error("redis readiness check failed", "error", err)
if writeErr := httputils.WriteServiceUnavailable(w, requestID); writeErr != nil {
slog.Error("failed to write readiness response", "error", writeErr)
}
return
}
if err := h.s3Storage.Check(ctx); err != nil {
slog.Error("s3 storage check failed", "error", err)
if writeErr := httputils.WriteServiceUnavailable(w, requestID); writeErr != nil {
slog.Error("failed to write readiness response", "error", writeErr)
}
return
}
response := HealthResponse{Status: "ok"}
err := httputils.WriteJSON[HealthResponse](w, http.StatusOK, response)
if err != nil {
slog.Error("failed to write health response", "error", err)
}
}
func (h *HealthHandler) NotFoundRoute(w http.ResponseWriter, r *http.Request) {
requestID := middleware.RequestIDFromContext(r.Context())
err := httputils.WriteError(
w,
http.StatusNotFound,
httputils.ErrorDetails{
Code: "not_found",
Message: "Not Found",
RequestID: requestID,
},
)
if err != nil {
slog.Error("failed to write not found response", "error", err)
}
}
@@ -0,0 +1,5 @@
package handler
type HealthResponse struct {
Status string `json:"status"`
}
@@ -0,0 +1,90 @@
package handler
import (
"highload/internal/service"
"highload/internal/transport/http/httputils"
"highload/internal/transport/http/middleware"
"net/http"
)
type MessageHandler struct {
messageService *service.MessageService
}
func NewMessageHandler(messageService *service.MessageService) *MessageHandler {
return &MessageHandler{messageService: messageService}
}
func (h *MessageHandler) CreateMessage(w http.ResponseWriter, r *http.Request) {
requestID := middleware.RequestIDFromContext(r.Context())
userID := middleware.UserIDFromContext(r.Context())
chatID := r.PathValue("chat_id")
req, code := httputils.Decode[messageCreateRequest](r)
if code != http.StatusOK {
if code == http.StatusUnsupportedMediaType {
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "unsupported_media_type", Message: "Неверный media type", RequestID: requestID})
return
}
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "invalid_request", Message: "Неверный запрос", RequestID: requestID})
return
}
key := r.Header.Get("Idempotency-Key")
if ok := httputils.CheckIdempotencyKeyPattern(key); !ok {
httputils.WriteError(w, http.StatusBadRequest, httputils.ErrorDetails{
Code: "invalid_request",
Message: "wrong Idempotency-Key",
RequestID: requestID,
})
return
}
message, err := h.messageService.CreateMessage(r.Context(), req.Text, chatID, userID, key, req.AttachmentIDs)
if err != nil {
httputils.WriteServiceError(w, err, requestID)
return
}
response := convertMessageModelToResponse(message)
_ = httputils.WriteJSON[messageResponse](w, http.StatusCreated, *response)
}
func (h *MessageHandler) GetMessagesByChatID(w http.ResponseWriter, r *http.Request) {
requestID := middleware.RequestIDFromContext(r.Context())
userID := middleware.UserIDFromContext(r.Context())
chatID := r.PathValue("chat_id")
limit, cursor, ok := httputils.GetLimitAndCursor(r)
if !ok {
httputils.WriteError(w, http.StatusBadRequest, httputils.ErrorDetails{Code: "invalid_request", Message: "Неверный запрос", RequestID: requestID})
return
}
messages, nextCursor, err := h.messageService.GetMessagesByChatID(r.Context(), chatID, userID, limit, cursor)
if err != nil {
httputils.WriteServiceError(w, err, requestID)
return
}
messageResponses := make([]messageResponse, len(messages))
for index, message := range messages {
messageResponses[index] = *convertMessageModelToResponse(message)
}
response := messageGetResponse{
Items: messageResponses,
NextCursor: nextCursor,
}
_ = httputils.WriteJSON[messageGetResponse](w, http.StatusOK, response)
}
@@ -0,0 +1,42 @@
package handler
import (
"highload/internal/model"
"highload/internal/transport/http/httputils"
)
type messageCreateRequest 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"`
CreatedAt string `json:"created_at"`
AttachmentIDs []string `json:"attachment_ids"`
}
type messageGetResponse struct {
Items []messageResponse `json:"items"`
NextCursor *string `json:"next_cursor"`
}
func convertMessageModelToResponse(message *model.Message) *messageResponse {
attachmentIDs := message.AttachmentIDs
if attachmentIDs == nil {
attachmentIDs = []string{}
}
return &messageResponse{
ID: message.ID,
ChatID: message.ChatID,
SenderID: message.SenderID,
Text: message.Text,
AttachmentIDs: attachmentIDs,
CreatedAt: httputils.FormatTime(message.CreatedAt),
}
}
+60
View File
@@ -0,0 +1,60 @@
package handler
import (
"highload/internal/service"
"highload/internal/transport/http/httputils"
"highload/internal/transport/http/middleware"
"net/http"
)
type UserHandler struct {
userService *service.UserService
}
func NewUserHandler(service *service.UserService) *UserHandler {
return &UserHandler{userService: service}
}
func (h *UserHandler) CreateUser(w http.ResponseWriter, r *http.Request) {
requestID := middleware.RequestIDFromContext(r.Context())
req, code := httputils.Decode[userCreateRequest](r)
if code != http.StatusOK {
if code == http.StatusUnsupportedMediaType {
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "unsupported_media_type", Message: "Неверный media type", RequestID: requestID})
return
}
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "invalid_request", Message: "Неверный запрос", RequestID: requestID})
return
}
user, err := h.userService.CreateUser(r.Context(), req.Username, req.DisplayName, req.Password)
if err != nil {
httputils.WriteServiceError(w, err, requestID)
return
}
response := convertUserModelToResponse(user)
_ = httputils.WriteJSON[userResponse](w, http.StatusCreated, *response)
}
func (h *UserHandler) GetCurrentUser(w http.ResponseWriter, r *http.Request) {
requestID := middleware.RequestIDFromContext(r.Context())
userID := middleware.UserIDFromContext(r.Context())
user, err := h.userService.GetUser(r.Context(), userID)
if err != nil {
httputils.WriteServiceError(w, err, requestID)
return
}
response := convertUserModelToResponse(user)
_ = httputils.WriteJSON[userResponse](w, http.StatusOK, *response)
}
@@ -0,0 +1,28 @@
package handler
import (
"highload/internal/model"
"highload/internal/transport/http/httputils"
)
type userCreateRequest 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 string `json:"created_at"`
}
func convertUserModelToResponse(user *model.User) *userResponse {
return &userResponse{
ID: user.ID,
Username: user.Username,
DisplayName: user.DisplayName,
CreatedAt: httputils.FormatTime(user.CreatedAt),
}
}