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
+142
View File
@@ -0,0 +1,142 @@
package service
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"errors"
"highload/internal/model"
"highload/internal/repository"
"highload/internal/security"
"time"
)
const tokenType = "Bearer"
type AuthService struct {
userRepo repository.UserRepository
sessionRepo repository.SessionRepository
sessionTTL time.Duration
}
func NewAuthService(userRepo repository.UserRepository, sessionRepo repository.SessionRepository, sessionTTL time.Duration) *AuthService {
return &AuthService{
userRepo: userRepo,
sessionRepo: sessionRepo,
sessionTTL: sessionTTL,
}
}
func (s *AuthService) Authenticate(ctx context.Context, username, password string) (*model.User, error) {
userOK := checkUsername(username)
passwordOK := checkPassword(password)
if !userOK || !passwordOK {
return nil, ErrUnauthorized
}
user, err := s.userRepo.GetUserByUsername(ctx, username)
if err != nil {
if errors.Is(err, repository.ErrNotFound) {
return nil, ErrUnauthorized
}
return nil, convertRepoError(err)
}
isVerify, err := security.VerifyPassword(password, user.PasswordHash)
if err != nil {
return nil, ErrServerError
}
if !isVerify {
return nil, ErrUnauthorized
}
return user, nil
}
type CreatedSession struct {
Token string
TokenType string
ExpiresAt time.Time
User *model.User
}
func (s *AuthService) CreateSession(ctx context.Context, username, password string) (*CreatedSession, error) {
user, err := s.Authenticate(ctx, username, password)
if err != nil {
return nil, err
}
if s.sessionTTL <= 0 {
return nil, ErrServerError
}
tokenBytes := make([]byte, 32)
_, err = rand.Read(tokenBytes)
if err != nil {
return nil, ErrServerError
}
token := base64.RawURLEncoding.EncodeToString(tokenBytes)
tokenHash := sha256.Sum256([]byte(token))
session, err := s.sessionRepo.Create(ctx, tokenHash[:], user.ID, s.sessionTTL)
if err != nil {
return nil, convertRepoError(err)
}
createdSession := &CreatedSession{
Token: token,
TokenType: tokenType,
ExpiresAt: session.ExpiresAt,
User: user,
}
return createdSession, nil
}
func (s *AuthService) ValidateSession(ctx context.Context, token string) (string, error) {
if token == "" {
return "", ErrUnauthorized
}
tokenHash := sha256.Sum256([]byte(token))
session, err := s.sessionRepo.GetSessionByTokenHash(ctx, tokenHash[:])
if err != nil {
if errors.Is(err, repository.ErrNotFound) {
return "", ErrUnauthorized
}
return "", convertRepoError(err)
}
if session.RevokedAt != nil {
return "", ErrUnauthorized
}
if !time.Now().Before(session.ExpiresAt) {
return "", ErrUnauthorized
}
return session.UserID, nil
}
func (s *AuthService) RevokeSession(ctx context.Context, token string) error {
tokenHash := sha256.Sum256([]byte(token))
_, err := s.sessionRepo.RevokeSession(ctx, tokenHash[:])
if err != nil {
return convertRepoError(err)
}
return nil
}
+188
View File
@@ -0,0 +1,188 @@
package service
import (
"context"
"errors"
"highload/internal/model"
"highload/internal/repository"
"slices"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
)
type ChatService struct {
repo repository.ChatRepository
userRepo repository.UserRepository
userService *UserService
}
func NewChatService(repo repository.ChatRepository, userRepo repository.UserRepository, userService *UserService) *ChatService {
return &ChatService{repo: repo, userRepo: userRepo, userService: userService}
}
func (s *ChatService) Create(ctx context.Context, title string, memberIDs []string, userID string) (*model.Chat, error) {
trimTitle := strings.TrimSpace(title)
lenTitle := utf8.RuneCountInString(title)
if lenTitle < 1 || lenTitle > 100 {
return nil, ErrInvalidInput
}
if trimTitle == "" {
return nil, ErrInvalidInput
}
if memberIDs == nil || len(memberIDs) == 0 || len(memberIDs) > 100 {
return nil, ErrInvalidInput
}
seen := make(map[string]struct{})
for _, memberID := range memberIDs {
parsedID, err := uuid.Parse(memberID)
if err != nil {
return nil, ErrInvalidInput
}
normalizedID := parsedID.String()
if _, exist := seen[normalizedID]; exist {
return nil, ErrInvalidInput
}
seen[normalizedID] = struct{}{}
_, err = s.userRepo.GetUserByID(ctx, memberID)
if err != nil {
// NOTE: MemberNotFound –> InvalidInput
if errors.Is(err, repository.ErrNotFound) {
return nil, ErrInvalidInput
}
return nil, convertRepoError(err)
}
}
parsedUserID, err := uuid.Parse(userID)
if err != nil {
return nil, ErrServerError
}
normalizedUserID := parsedUserID.String()
_, creatorExists := seen[normalizedUserID]
if !creatorExists {
return nil, ErrInvalidInput
}
chat, err := s.repo.CreateChat(ctx, title, memberIDs)
if err != nil {
return nil, convertRepoError(err)
}
return chat, nil
}
func (s *ChatService) GetChatsByUserID(ctx context.Context, userID string, limit *int, cursor *string) ([]*model.Chat, *string, error) {
actualLimit := 50
if limit != nil {
actualLimit = *limit
}
if actualLimit <= 0 || actualLimit > 100 {
return nil, nil, ErrInvalidInput
}
var chatPosition *repository.ChatPosition
if cursor != nil {
chCursor, err := decodeCursor[chatCursor](*cursor)
if err != nil {
return nil, nil, ErrInvalidInput
}
_, err = uuid.Parse(chCursor.ChatID)
if err != nil {
return nil, nil, ErrInvalidInput
}
if chCursor.CreatedAt.IsZero() {
return nil, nil, ErrInvalidInput
}
_, err = uuid.Parse(chCursor.UserID)
if err != nil {
return nil, nil, ErrInvalidInput
}
if chCursor.UserID != userID {
return nil, nil, ErrInvalidInput
}
chatPosition = &repository.ChatPosition{
CreatedAt: chCursor.CreatedAt,
ID: chCursor.ChatID,
}
}
chats, err := s.repo.GetChatsByUserID(ctx, userID, actualLimit+1, chatPosition)
if err != nil {
return nil, nil, convertRepoError(err)
}
var chCursor *chatCursor
if len(chats) > actualLimit {
chCursor = &chatCursor{
ChatID: chats[actualLimit-1].ID,
UserID: userID,
CreatedAt: chats[actualLimit-1].CreatedAt,
}
cursor, err = encodeCursor[chatCursor](*chCursor)
if err != nil {
return nil, nil, ErrServerError
}
return chats[:actualLimit], cursor, nil
}
return chats, nil, nil
}
func (s *ChatService) GetChatByID(ctx context.Context, chatID, userID string) (*model.Chat, error) {
_, err := uuid.Parse(chatID)
if err != nil {
return nil, ErrInvalidInput
}
chat, err := s.repo.GetChatByID(ctx, chatID)
if err != nil {
return nil, convertRepoError(err)
}
index := slices.Index(chat.MemberIDs, userID)
if index == -1 {
return nil, ErrNotFound
}
return chat, nil
}
type chatCursor struct {
CreatedAt time.Time `json:"created_at"`
ChatID string `json:"chat_id"`
UserID string `json:"user_id"`
}
+42
View File
@@ -0,0 +1,42 @@
package service
import (
"errors"
"fmt"
"highload/internal/repository"
)
var (
ErrInvalidInput = errors.New("invalid input")
ErrAlreadyExists = errors.New("user already exists")
ErrNotFound = errors.New("user not found")
ErrServerError = errors.New("server error")
ErrUnauthorized = errors.New("unauthorized")
ErrServiceUnavailable = errors.New("service unavailable")
ErrConflict = errors.New("data conflict")
)
func convertRepoError(err error) error {
var category error
switch {
case errors.Is(err, repository.ErrNotFound):
category = ErrNotFound
case errors.Is(err, repository.ErrAlreadyExists):
category = ErrAlreadyExists
case errors.Is(err, repository.ErrInvalidInput):
category = ErrInvalidInput
case errors.Is(err, repository.ErrDatabase):
category = ErrServerError
case errors.Is(err, repository.ErrServiceUnavailable):
category = ErrServiceUnavailable
case errors.Is(err, repository.ErrConflict):
category = ErrConflict
default:
return err
}
return fmt.Errorf("%w: %v", category, err)
}
+63
View File
@@ -0,0 +1,63 @@
package service
import (
"encoding/base64"
"encoding/json/v2"
"regexp"
"strings"
"unicode/utf8"
)
func encodeCursor[C any](cursor C) (*string, error) {
data, err := json.Marshal(cursor)
if err != nil {
return nil, err
}
encoded := base64.RawURLEncoding.EncodeToString(data)
return &encoded, nil
}
func decodeCursor[C any](cursor string) (*C, error) {
data, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil {
return nil, ErrInvalidInput
}
var decoded C
err = json.Unmarshal(data, &decoded)
if err != nil {
return nil, ErrInvalidInput
}
return &decoded, nil
}
var usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
func checkUsername(username string) bool {
return usernameRegex.MatchString(username)
}
func checkPassword(password string) bool {
if !utf8.ValidString(password) {
return false
}
if strings.TrimSpace(password) == "" {
return false
}
passwordLength := utf8.RuneCountInString(password)
if passwordLength < 12 || passwordLength > 128 {
return false
}
return true
}
+130
View File
@@ -0,0 +1,130 @@
package service
import (
"context"
"highload/internal/model"
"highload/internal/repository"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
)
type MessageService struct {
repo repository.MessageRepository
userService *UserService
chatService *ChatService
}
func NewMessageService(repo repository.MessageRepository, chatService *ChatService, userService *UserService) *MessageService {
return &MessageService{repo: repo, chatService: chatService, userService: userService}
}
func (s *MessageService) CreateMessage(ctx context.Context, text, chatID, userID, key string) (*model.Message, error) {
_, err := s.chatService.GetChatByID(ctx, chatID, userID)
if err != nil {
return nil, err
}
lenText := utf8.RuneCountInString(text)
if lenText > 4000 || lenText < 1 {
return nil, ErrInvalidInput
}
trimText := strings.TrimSpace(text)
if len(trimText) == 0 {
return nil, ErrInvalidInput
}
message, err := s.repo.CreateMessage(ctx, chatID, userID, text, key)
if err != nil {
return nil, convertRepoError(err)
}
return message, nil
}
func (s *MessageService) GetMessagesByChatID(ctx context.Context, chatID, userID string, limit *int, cursor *string) ([]*model.Message, *string, error) {
actualLimit := 50
if limit != nil {
actualLimit = *limit
}
if actualLimit <= 0 || actualLimit > 100 {
return nil, nil, ErrInvalidInput
}
chat, err := s.chatService.GetChatByID(ctx, chatID, userID)
if err != nil {
return nil, nil, err
}
var messagePosition *repository.MessagePosition
if cursor != nil {
mesCursor, err := decodeCursor[messageCursor](*cursor)
if err != nil {
return nil, nil, ErrInvalidInput
}
if _, err := uuid.Parse(mesCursor.ChatID); err != nil {
return nil, nil, ErrInvalidInput
}
if _, err := uuid.Parse(mesCursor.MessageID); err != nil {
return nil, nil, ErrInvalidInput
}
if mesCursor.CreatedAt.IsZero() {
return nil, nil, ErrInvalidInput
}
if mesCursor.ChatID != chat.ID {
return nil, nil, ErrInvalidInput
}
messagePosition = &repository.MessagePosition{
ID: mesCursor.MessageID,
CreatedAt: mesCursor.CreatedAt,
}
}
messages, err := s.repo.GetMessagesByChatID(ctx, chat.ID, actualLimit+1, messagePosition)
if err != nil {
return nil, nil, convertRepoError(err)
}
if len(messages) > actualLimit {
mesCursor := &messageCursor{
MessageID: messages[actualLimit-1].ID,
ChatID: chat.ID,
CreatedAt: messages[actualLimit-1].CreatedAt,
}
cursor, err = encodeCursor[messageCursor](*mesCursor)
if err != nil {
return nil, nil, ErrServerError
}
return messages[:actualLimit], cursor, nil
}
return messages, nil, nil
}
type messageCursor struct {
MessageID string `json:"message_id"`
ChatID string `json:"chat_id"`
CreatedAt time.Time `json:"created_at"`
}
+70
View File
@@ -0,0 +1,70 @@
package service
import (
"context"
"highload/internal/model"
"highload/internal/repository"
"highload/internal/security"
"strings"
"unicode/utf8"
"github.com/google/uuid"
)
type UserService struct {
repo repository.UserRepository
}
func NewUserService(repo repository.UserRepository) *UserService {
return &UserService{repo}
}
func (s *UserService) CreateUser(ctx context.Context, username, displayName, password string) (*model.User, error) {
userOK := checkUsername(username)
passwordOK := checkPassword(password)
if !userOK || !passwordOK {
return nil, ErrInvalidInput
}
if !utf8.ValidString(displayName) {
return nil, ErrInvalidInput
}
if strings.TrimSpace(displayName) == "" {
return nil, ErrInvalidInput
}
if utf8.RuneCountInString(displayName) > 100 {
return nil, ErrInvalidInput
}
passwordHash, err := security.HashPassword(password)
if err != nil {
return nil, ErrServerError
}
user, err := s.repo.Create(ctx, username, displayName, passwordHash)
if err != nil {
return nil, convertRepoError(err)
}
return user, nil
}
func (s *UserService) GetUser(ctx context.Context, id string) (*model.User, error) {
_, err := uuid.Parse(id)
if err != nil {
return nil, ErrInvalidInput
}
user, err := s.repo.GetUserByID(ctx, id)
if err != nil {
return nil, convertRepoError(err)
}
return user, nil
}