ЛР 5 — асинхронная обработка и версии pipeline
This commit is contained in:
@@ -0,0 +1,207 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"highload/internal/fault"
|
||||
"highload/internal/model"
|
||||
"highload/internal/repository"
|
||||
"highload/internal/storage"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const MaxAttachmentBytes = 10 * 1024 * 1024
|
||||
const maxImagePixels = 40_000_000
|
||||
const attachmentObjectPrefix = "attachments/"
|
||||
|
||||
type AttachmentService struct {
|
||||
repo repository.AttachmentRepository
|
||||
chatService *ChatService
|
||||
objects storage.ObjectWriter
|
||||
}
|
||||
|
||||
func NewAttachmentService(repo repository.AttachmentRepository, chatService *ChatService, objects storage.ObjectWriter) *AttachmentService {
|
||||
return &AttachmentService{repo: repo, chatService: chatService, objects: objects}
|
||||
}
|
||||
|
||||
func (s *AttachmentService) CreateAttachment(ctx context.Context, chatID, userID, filename, declaredContentType string, body io.ReadSeeker, size int64) (*model.Attachment, error) {
|
||||
|
||||
chat, err := s.chatService.GetChatByID(ctx, chatID, userID)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
mimeType, err := validateAttachment(filename, declaredContentType, body, size)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
id := uuid.NewString()
|
||||
key := "staging/" + id + "/original"
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sum := sha256.New()
|
||||
n, err := io.Copy(sum, io.LimitReader(body, size+1))
|
||||
if err != nil || n != size {
|
||||
return nil, ErrServerError
|
||||
}
|
||||
if _, err := body.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, ErrServerError
|
||||
}
|
||||
sumString := hex.EncodeToString(sum.Sum(nil))
|
||||
|
||||
var attachment *model.Attachment
|
||||
fn := func(ctx context.Context, tx repository.AttachmentTx) error {
|
||||
err := s.objects.Put(ctx, key, mimeType, body, size)
|
||||
|
||||
if err != nil {
|
||||
return convertStorageError(err)
|
||||
}
|
||||
|
||||
if err := fault.Pause(ctx, "after_staging", id); err != nil {
|
||||
return err
|
||||
}
|
||||
attachment, err = tx.CreateQueued(ctx, id, chat.ID, userID, mimeType, sumString, key, filename, size)
|
||||
return err
|
||||
}
|
||||
|
||||
acquired, err := s.repo.WithObjectKeyLock(ctx, key, fn)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertRepoError(err)
|
||||
}
|
||||
|
||||
if !acquired {
|
||||
return nil, ErrServiceUnavailable
|
||||
}
|
||||
|
||||
return attachment, nil
|
||||
|
||||
}
|
||||
|
||||
func (s *AttachmentService) GetAttachment(ctx context.Context, userID, attachmentID string) (*model.Attachment, error) {
|
||||
_, err := uuid.Parse(attachmentID)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
_, err = uuid.Parse(userID)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
attachment, err := s.repo.GetAttachmentForUser(ctx, userID, attachmentID)
|
||||
if err != nil {
|
||||
return nil, convertRepoError(err)
|
||||
}
|
||||
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *AttachmentService) GetAttachmentContent(ctx context.Context, userID, attachmentID, variant string) (string, io.ReadCloser, error) {
|
||||
attachment, err := s.GetAttachment(ctx, userID, attachmentID)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
if attachment.Status != "ready" {
|
||||
return "", nil, ErrConflict
|
||||
}
|
||||
key, mime := attachment.ObjectKey, attachment.ContentType
|
||||
if variant != "" && variant != "original" {
|
||||
key = ""
|
||||
for _, candidate := range attachment.Variants {
|
||||
if candidate.Name == variant {
|
||||
key, mime = candidate.ObjectKey, candidate.ContentType
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if key == "" {
|
||||
return "", nil, ErrNotFound
|
||||
}
|
||||
contentReader, err := s.objects.Get(ctx, key)
|
||||
if err != nil {
|
||||
return "", nil, convertStorageError(err)
|
||||
}
|
||||
return mime, contentReader, nil
|
||||
}
|
||||
|
||||
func validateAttachment(filename, declaredContentType string, body io.ReadSeeker, size int64) (string, error) {
|
||||
if !utf8.ValidString(filename) || strings.TrimSpace(filename) == "" || utf8.RuneCountInString(filename) > 255 {
|
||||
return "", ErrInvalidInput
|
||||
}
|
||||
|
||||
if strings.ContainsAny(filename, "/\\") || containsControlChars(filename) {
|
||||
return "", ErrInvalidInput
|
||||
}
|
||||
|
||||
if size > MaxAttachmentBytes {
|
||||
return "", ErrPayloadTooLarge
|
||||
}
|
||||
if size <= 0 {
|
||||
return "", ErrUnsupportMediaType
|
||||
}
|
||||
|
||||
if _, err := body.Seek(0, io.SeekStart); err != nil {
|
||||
return "", ErrServerError
|
||||
}
|
||||
imageConfig, format, err := image.DecodeConfig(io.LimitReader(body, size))
|
||||
if err != nil {
|
||||
return "", ErrUnsupportMediaType
|
||||
}
|
||||
|
||||
if imageConfig.Height <= 0 || imageConfig.Width <= 0 {
|
||||
return "", ErrUnsupportMediaType
|
||||
}
|
||||
if imageConfig.Width > maxImagePixels/imageConfig.Height {
|
||||
return "", ErrPayloadTooLarge
|
||||
}
|
||||
|
||||
var mimeType string
|
||||
switch format {
|
||||
case "png":
|
||||
mimeType = "image/png"
|
||||
case "jpeg":
|
||||
mimeType = "image/jpeg"
|
||||
default:
|
||||
return "", ErrUnsupportMediaType
|
||||
|
||||
}
|
||||
if mimeType != declaredContentType {
|
||||
return "", ErrUnsupportMediaType
|
||||
}
|
||||
|
||||
if _, err := body.Seek(0, io.SeekStart); err != nil {
|
||||
return "", ErrServerError
|
||||
}
|
||||
_, _, err = image.Decode(io.LimitReader(body, size))
|
||||
if err != nil {
|
||||
return "", ErrUnsupportMediaType
|
||||
}
|
||||
|
||||
if _, err := body.Seek(0, io.SeekStart); err != nil {
|
||||
return "", ErrServerError
|
||||
}
|
||||
return mimeType, nil
|
||||
}
|
||||
|
||||
func containsControlChars(s string) bool {
|
||||
for _, r := range s {
|
||||
if (r >= 0 && r <= 31) || r == 127 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/repository"
|
||||
"highload/internal/storage"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type AttachmentCleanupOptions struct {
|
||||
GracePeriod time.Duration
|
||||
DryRun bool
|
||||
ListTimeout time.Duration
|
||||
}
|
||||
|
||||
type AttachmentCleanupService struct {
|
||||
repo repository.AttachmentRepository
|
||||
objects storage.ObjectCleanup
|
||||
options *AttachmentCleanupOptions
|
||||
}
|
||||
|
||||
type OrphanReport struct {
|
||||
Pages int `json:"s3_pages"`
|
||||
Objects int `json:"objects_scanned"`
|
||||
Checked int `json:"checked_in_db"`
|
||||
Busy int `json:"busy"`
|
||||
Candidates int `json:"orphan_candidates"`
|
||||
Deleted int `json:"objects_deleted"`
|
||||
}
|
||||
|
||||
func NewAttachmentCleanupService(repo repository.AttachmentRepository, objects storage.ObjectCleanup, options *AttachmentCleanupOptions) *AttachmentCleanupService {
|
||||
return &AttachmentCleanupService{repo: repo, objects: objects, options: options}
|
||||
}
|
||||
|
||||
func (s *AttachmentCleanupService) RunOnce(ctx context.Context) error {
|
||||
_, err := s.ScanOrphans(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *AttachmentCleanupService) ScanOrphans(ctx context.Context) (OrphanReport, error) {
|
||||
var report OrphanReport
|
||||
cutoff := time.Now().Add(-s.options.GracePeriod)
|
||||
var token *string
|
||||
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return report, err
|
||||
}
|
||||
|
||||
listCtx, cancel := context.WithTimeout(ctx, s.options.ListTimeout)
|
||||
objects, nextToken, err := s.objects.ListPage(listCtx, token, attachmentObjectPrefix)
|
||||
cancel()
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
report.Pages++
|
||||
|
||||
for _, obj := range objects {
|
||||
report.Objects++
|
||||
if !strings.HasPrefix(obj.Key, attachmentObjectPrefix) ||
|
||||
obj.LastModified.IsZero() || !obj.LastModified.Before(cutoff) {
|
||||
continue
|
||||
}
|
||||
|
||||
acquired, err := s.repo.WithObjectKeyLock(ctx, obj.Key, func(txCtx context.Context, txRepo repository.AttachmentTx) error {
|
||||
exists, err := txRepo.ExistsByObjectKey(txCtx, obj.Key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
report.Checked++
|
||||
if exists {
|
||||
return nil
|
||||
}
|
||||
report.Candidates++
|
||||
if s.options.DryRun {
|
||||
return nil
|
||||
}
|
||||
if err := s.objects.Delete(txCtx, obj.Key); err != nil {
|
||||
return err
|
||||
}
|
||||
report.Deleted++
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
if !acquired {
|
||||
report.Busy++
|
||||
}
|
||||
}
|
||||
|
||||
if nextToken == nil {
|
||||
return report, ctx.Err()
|
||||
}
|
||||
token = nextToken
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"highload/internal/repository"
|
||||
"highload/internal/storage"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const attachmentReconcilePageSize = 200
|
||||
const missingSampleLimit = 32
|
||||
|
||||
type attachmentReconcileStorage interface {
|
||||
Check(context.Context) error
|
||||
Head(context.Context, string) error
|
||||
PutIfAbsent(context.Context, string, string, io.ReadSeeker, int64) error
|
||||
}
|
||||
|
||||
type AttachmentReconciler struct {
|
||||
repo repository.AttachmentReconcileRepository
|
||||
objects attachmentReconcileStorage
|
||||
options AttachmentCleanupOptions
|
||||
}
|
||||
|
||||
type MissingReport struct {
|
||||
Pages int `json:"db_pages"`
|
||||
Rows int `json:"rows_scanned"`
|
||||
Heads int `json:"s3_head_attempts"`
|
||||
Missing int `json:"missing_objects"`
|
||||
SampleIDs []string `json:"missing_attachment_ids"`
|
||||
}
|
||||
|
||||
func NewAttachmentReconciler(repo repository.AttachmentReconcileRepository, objects attachmentReconcileStorage, options AttachmentCleanupOptions) *AttachmentReconciler {
|
||||
return &AttachmentReconciler{repo: repo, objects: objects, options: options}
|
||||
}
|
||||
|
||||
// ScanMissing checks old committed attachment rows using S3 metadata requests.
|
||||
func (s *AttachmentReconciler) ScanMissing(ctx context.Context) (MissingReport, error) {
|
||||
report := MissingReport{SampleIDs: []string{}}
|
||||
cutoff := time.Now().Add(-s.options.GracePeriod)
|
||||
if err := s.checkBucket(ctx); err != nil {
|
||||
return report, err
|
||||
}
|
||||
var afterKey string
|
||||
for {
|
||||
rows, err := s.repo.ListAttachmentKeys(ctx, afterKey, attachmentReconcilePageSize)
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
report.Pages++
|
||||
for _, row := range rows {
|
||||
report.Rows++
|
||||
if !strings.HasPrefix(row.ObjectKey, attachmentObjectPrefix) ||
|
||||
row.CreatedAt.IsZero() || !row.CreatedAt.Before(cutoff) {
|
||||
continue
|
||||
}
|
||||
report.Heads++
|
||||
present, err := s.objectPresent(ctx, row.ObjectKey)
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
if !present {
|
||||
report.Missing++
|
||||
if len(report.SampleIDs) < missingSampleLimit {
|
||||
report.SampleIDs = append(report.SampleIDs, row.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(rows) < attachmentReconcilePageSize {
|
||||
return report, ctx.Err()
|
||||
}
|
||||
afterKey = rows[len(rows)-1].ObjectKey
|
||||
}
|
||||
}
|
||||
|
||||
// Restore verifies the original bytes before writing a missing object under its existing key.
|
||||
func (s *AttachmentReconciler) Restore(ctx context.Context, id string, original io.Reader) (string, error) {
|
||||
attachment, err := s.repo.GetAttachmentByID(ctx, id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !strings.HasPrefix(attachment.ObjectKey, attachmentObjectPrefix) ||
|
||||
attachment.CreatedAt.IsZero() || !attachment.CreatedAt.Before(time.Now().Add(-s.options.GracePeriod)) {
|
||||
return "", errors.New("attachment is outside the restore scope or still within grace")
|
||||
}
|
||||
if attachment.SizeBytes <= 0 || attachment.SizeBytes > MaxAttachmentBytes {
|
||||
return "", errors.New("invalid original size in attachment metadata")
|
||||
}
|
||||
if err := s.checkBucket(ctx); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Read at most one original. Keep the verified bytes stable until Put completes.
|
||||
data, err := io.ReadAll(io.LimitReader(original, attachment.SizeBytes+1))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read backup original: %w", err)
|
||||
}
|
||||
sum := sha256.Sum256(data)
|
||||
if int64(len(data)) != attachment.SizeBytes || hex.EncodeToString(sum[:]) != attachment.SHA256 {
|
||||
return "", errors.New("backup original does not match the stored size and SHA-256")
|
||||
}
|
||||
|
||||
var result string
|
||||
acquired, err := s.repo.WithObjectKeyLock(ctx, attachment.ObjectKey, func(txCtx context.Context, txRepo repository.AttachmentTx) error {
|
||||
current, err := txRepo.GetAttachmentByID(txCtx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if current.ObjectKey != attachment.ObjectKey || current.SizeBytes != attachment.SizeBytes ||
|
||||
current.SHA256 != attachment.SHA256 || current.ContentType != attachment.ContentType ||
|
||||
!current.CreatedAt.Equal(attachment.CreatedAt) {
|
||||
return errors.New("attachment metadata changed during restore")
|
||||
}
|
||||
present, err := s.objectPresent(txCtx, current.ObjectKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if present {
|
||||
result = "already_present"
|
||||
return nil
|
||||
}
|
||||
if s.options.DryRun {
|
||||
result = "would_restore"
|
||||
return nil
|
||||
}
|
||||
if err := s.objects.PutIfAbsent(txCtx, current.ObjectKey, current.ContentType, bytes.NewReader(data), current.SizeBytes); err != nil {
|
||||
return err
|
||||
}
|
||||
result = "restored"
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !acquired {
|
||||
return "", errors.New("attachment key is busy; retry the restore")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *AttachmentReconciler) checkBucket(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.options.ListTimeout)
|
||||
defer cancel()
|
||||
return s.objects.Check(ctx)
|
||||
}
|
||||
|
||||
func (s *AttachmentReconciler) objectPresent(ctx context.Context, key string) (bool, error) {
|
||||
headCtx, cancel := context.WithTimeout(ctx, s.options.ListTimeout)
|
||||
defer cancel()
|
||||
err := s.objects.Head(headCtx, key)
|
||||
if errors.Is(err, storage.ErrObjectNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
return err == nil, err
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
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
|
||||
}
|
||||
|
||||
_, err = uuid.Parse(userID)
|
||||
|
||||
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"`
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"highload/internal/repository"
|
||||
"highload/internal/storage"
|
||||
)
|
||||
|
||||
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")
|
||||
ErrUnsupportMediaType = errors.New("unsupported mediaType")
|
||||
ErrPayloadTooLarge = errors.New("payload too large")
|
||||
)
|
||||
|
||||
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) || errors.Is(err, repository.ErrServerError):
|
||||
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)
|
||||
}
|
||||
|
||||
func convertStorageError(err error) error {
|
||||
var category error
|
||||
|
||||
switch {
|
||||
case errors.Is(err, storage.ErrObjectNotFound):
|
||||
category = ErrNotFound
|
||||
case errors.Is(err, storage.ErrServiceUnavailable):
|
||||
category = ErrServiceUnavailable
|
||||
case errors.Is(err, storage.ErrStorage):
|
||||
category = ErrServerError
|
||||
default:
|
||||
return err
|
||||
}
|
||||
|
||||
return fmt.Errorf("%w: %v", category, err)
|
||||
|
||||
}
|
||||
@@ -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
|
||||
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
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, attachmentIDs []string) (*model.Message, error) {
|
||||
|
||||
_, err := s.chatService.GetChatByID(ctx, chatID, userID)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
lenText := utf8.RuneCountInString(text)
|
||||
|
||||
if lenText > 4000 || (strings.TrimSpace(text) == "" && len(attachmentIDs) == 0) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
if len(attachmentIDs) > 10 {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]struct{}, len(attachmentIDs))
|
||||
for _, rawID := range attachmentIDs {
|
||||
id, err := uuid.Parse(rawID)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if _, exists := seen[id]; exists {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
|
||||
}
|
||||
|
||||
message, err := s.repo.CreateMessage(ctx, chatID, userID, text, key, attachmentIDs)
|
||||
|
||||
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"`
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user