Implement lab 3 level 4 failover and idempotency

This commit is contained in:
2026-10-29 23:35:04 +03:00
parent 0ab3a341aa
commit a2cb1ad2ae
338 changed files with 37821 additions and 22 deletions
+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),
}
}
+92
View File
@@ -0,0 +1,92 @@
package handler
import (
"context"
"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
}
func NewHealthHandler(pool *pgxpool.Pool, redisClient *redis.Client) *HealthHandler {
return &HealthHandler{pool: pool, redisClient: redisClient}
}
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.WriteError(
w,
http.StatusServiceUnavailable,
httputils.ErrorDetails{
Message: "unavailable",
Code: "unavailable",
RequestID: 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.WriteError(
w,
http.StatusServiceUnavailable,
httputils.ErrorDetails{
Message: "unavailable",
Code: "unavailable",
RequestID: 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)
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,33 @@
package handler
import (
"highload/internal/model"
"highload/internal/transport/http/httputils"
)
type messageCreateRequest struct {
Text string `json:"text"`
}
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"`
}
type messageGetResponse struct {
Items []messageResponse `json:"items"`
NextCursor *string `json:"next_cursor"`
}
func convertMessageModelToResponse(message *model.Message) *messageResponse {
return &messageResponse{
ID: message.ID,
ChatID: message.ChatID,
SenderID: message.SenderID,
Text: message.Text,
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),
}
}