chore: lab import lab4 backend and infrastructure as baseline

This commit is contained in:
Голиков Maximillian Антон
2026-11-06 20:21:23 +03:00
parent 276dbdad8a
commit 4bba40d098
68 changed files with 5315 additions and 0 deletions
+209
View File
@@ -0,0 +1,209 @@
package service
import (
"bytes"
"context"
"crypto/sha256"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"net/http"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/google/uuid"
"high-loud-apps-labs/internal/domain"
)
type AttachmentService struct {
attachments domain.AttachmentRepository
chats domain.ChatRepository
storage domain.ObjectStorage
maxBytes int64
maxPixels int64
decodeSem chan struct{}
}
func NewAttachmentService(
attachments domain.AttachmentRepository,
chats domain.ChatRepository,
storage domain.ObjectStorage,
maxBytes, maxPixels int64,
) *AttachmentService {
return &AttachmentService{
attachments: attachments,
chats: chats,
storage: storage,
maxBytes: maxBytes,
maxPixels: maxPixels,
// 40M pixels × 4 bytes (RGBA8) = 160 MB per full decode.
// API_MEMORY=256M → только один decode безопасен.
decodeSem: make(chan struct{}, 1),
}
}
// Upload принимает тело, валидирует PNG/JPEG по содержимому,
// кладёт в pending, загружает в S3, переводит в ready.
// При ошибке Put компенсирует MarkFailed.
func (s *AttachmentService) Upload(
ctx context.Context,
ownerID, chatID, filename string,
body io.Reader,
) (*domain.Attachment, error) {
if err := s.ensureMember(ctx, ownerID, chatID); err != nil {
return nil, err
}
if err := validateFilename(filename); err != nil {
return nil, err
}
limited := io.LimitReader(body, s.maxBytes+1)
buf, err := io.ReadAll(limited)
if err != nil {
return nil, &domain.UnavailableError{Reason: "не удалось прочитать тело загрузки"}
}
if int64(len(buf)) > s.maxBytes {
return nil, &domain.PayloadTooLargeError{Limit: s.maxBytes}
}
if len(buf) == 0 {
return nil, &domain.ValidationError{Field: "body", Message: "пустой файл"}
}
contentType := http.DetectContentType(buf)
if contentType != "image/png" && contentType != "image/jpeg" {
return nil, &domain.UnsupportedMediaTypeError{
MediaType: contentType,
Expected: "image/png или image/jpeg",
}
}
cfg, _, err := image.DecodeConfig(bytes.NewReader(buf))
if err != nil {
return nil, &domain.UnsupportedMediaTypeError{
MediaType: contentType,
Expected: "целостный image/png или image/jpeg",
}
}
if int64(cfg.Width)*int64(cfg.Height) > s.maxPixels {
return nil, &domain.PayloadTooLargeError{
Limit: s.maxPixels,
Message: "изображение превышает лимит пикселей",
}
}
if err := s.verifyIntegrity(ctx, buf, contentType); err != nil {
return nil, err
}
sha := sha256.Sum256(buf)
id := uuid.NewString()
objectKey := "chats/" + chatID + "/" + id
now := time.Now().UTC()
a := &domain.Attachment{
ID: id,
ChatID: chatID,
OwnerID: ownerID,
Filename: filename,
ContentType: contentType,
SizeBytes: int64(len(buf)),
SHA256: sha[:],
ObjectKey: objectKey,
Status: domain.AttachmentStatusPending,
CreatedAt: now,
UpdatedAt: now,
}
if err := s.attachments.Create(ctx, a); err != nil {
return nil, err
}
if err := s.storage.Put(ctx, objectKey, bytes.NewReader(buf), int64(len(buf)), contentType); err != nil {
// Компенсация: pending → failed. Reconciler не будет трогать failed.
_ = s.attachments.MarkFailed(ctx, a.ID, "upload_failed")
return nil, err
}
if err := s.attachments.MarkReady(ctx, a.ID); err != nil {
// S3 has the object, DB still pending. Reconciler очистит по grace period.
return nil, err
}
a.Status = domain.AttachmentStatusReady
return a, nil
}
func (s *AttachmentService) verifyIntegrity(ctx context.Context, buf []byte, contentType string) error {
select {
case s.decodeSem <- struct{}{}:
case <-ctx.Done():
return &domain.UnavailableError{Reason: "ожидание декодирования"}
}
defer func() { <-s.decodeSem }()
if _, _, err := image.Decode(bytes.NewReader(buf)); err != nil {
return &domain.UnsupportedMediaTypeError{
MediaType: contentType,
Expected: "целостный " + contentType + " (без обрезки/повреждений)",
}
}
return nil
}
func (s *AttachmentService) Get(ctx context.Context, userID, attachmentID string) (*domain.Attachment, error) {
a, err := s.attachments.GetByID(ctx, attachmentID)
if err != nil {
return nil, err
}
if err := s.ensureMember(ctx, userID, a.ChatID); err != nil {
return nil, err
}
return a, nil
}
func (s *AttachmentService) Download(
ctx context.Context,
userID, attachmentID string,
) (io.ReadCloser, int64, string, error) {
a, err := s.Get(ctx, userID, attachmentID)
if err != nil {
return nil, 0, "", err
}
if a.Status != domain.AttachmentStatusReady {
return nil, 0, "", &domain.ConflictError{Reason: "вложение не готово"}
}
return s.storage.Get(ctx, a.ObjectKey)
}
func (s *AttachmentService) ensureMember(ctx context.Context, userID, chatID string) error {
c, err := s.chats.GetByID(ctx, chatID)
if err != nil {
return err
}
for _, m := range c.MemberIDs {
if m == userID {
return nil
}
}
return &domain.NotFoundError{Entity: "chat", ID: chatID}
}
func validateFilename(name string) error {
if strings.TrimSpace(name) == "" {
return &domain.ValidationError{Field: "filename", Message: "не может быть пустым или состоять только из пробелов"}
}
if utf8.RuneCountInString(name) > 255 {
return &domain.ValidationError{Field: "filename", Message: "не более 255 символов"}
}
if strings.ContainsAny(name, "/\\\x00") {
return &domain.ValidationError{Field: "filename", Message: "содержит недопустимые символы"}
}
for _, r := range name {
if unicode.IsControl(r) {
return &domain.ValidationError{Field: "filename", Message: "содержит управляющие символы"}
}
}
return nil
}
+95
View File
@@ -0,0 +1,95 @@
package service
import (
"context"
"errors"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
"high-loud-apps-labs/internal/domain"
)
type ChatService struct {
chats domain.ChatRepository
users domain.UserRepository
}
func NewChatService(chats domain.ChatRepository, users domain.UserRepository) *ChatService {
return &ChatService{chats: chats, users: users}
}
func (s *ChatService) Create(ctx context.Context, creatorID, title string, memberIDs []string) (*domain.Chat, error) {
if strings.TrimSpace(title) == "" {
return nil, &domain.ValidationError{
Field: "title",
Message: "не может состоять только из пробелов",
}
}
if utf8.RuneCountInString(title) > 100 {
return nil, &domain.ValidationError{
Field: "title",
Message: "не более 100 символов",
}
}
seen := make(map[string]struct{}, len(memberIDs))
for _, id := range memberIDs {
if _, dup := seen[id]; dup {
return nil, &domain.ValidationError{
Field: "member_ids",
Message: "дубликаты запрещены",
}
}
seen[id] = struct{}{}
}
if _, ok := seen[creatorID]; !ok {
return nil, &domain.ValidationError{
Field: "member_ids",
Message: "создатель должен входить в список участников",
}
}
for _, id := range memberIDs {
if _, err := s.users.GetByID(ctx, id); err != nil {
if errors.Is(err, domain.ErrNotFound) {
return nil, &domain.ValidationError{
Field: "member_ids",
Message: "неизвестный участник " + id,
}
}
return nil, err
}
}
c := &domain.Chat{
ID: uuid.NewString(),
Title: title,
MemberIDs: append([]string(nil), memberIDs...),
CreatedAt: time.Now().UTC(),
}
if err := s.chats.Create(ctx, c); err != nil {
return nil, err
}
return c, nil
}
func (s *ChatService) Get(ctx context.Context, userID, chatID string) (*domain.Chat, error) {
c, err := s.chats.GetByID(ctx, chatID)
if err != nil {
return nil, err
}
for _, m := range c.MemberIDs {
if m == userID {
return c, nil
}
}
return nil, &domain.NotFoundError{Entity: "chat", ID: chatID}
}
func (s *ChatService) List(ctx context.Context, userID string, limit int, cursor *string) ([]domain.Chat, *string, error) {
return s.chats.ListByMember(ctx, userID, limit, cursor)
}
+122
View File
@@ -0,0 +1,122 @@
package service
import (
"context"
"encoding/json"
"net/http"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
"high-loud-apps-labs/internal/domain"
"high-loud-apps-labs/internal/httpapi/dto"
)
type MessageService struct {
messages domain.MessageRepository
chats domain.ChatRepository
idempotencyTTL time.Duration
}
func NewMessageService(
messages domain.MessageRepository,
chats domain.ChatRepository,
idempotencyTTL time.Duration,
) *MessageService {
return &MessageService{
messages: messages,
chats: chats,
idempotencyTTL: idempotencyTTL,
}
}
func (s *MessageService) Create(
ctx context.Context,
senderID, chatID, text string,
attachmentIDs []string,
idempotencyKey, requestPath string,
) (*domain.CreateIdempotentResult, error) {
trimmed := strings.TrimSpace(text)
if trimmed == "" && len(attachmentIDs) == 0 {
return nil, &domain.ValidationError{
Field: "text",
Message: "text или attachment_ids обязательны",
}
}
if utf8.RuneCountInString(text) > 4000 {
return nil, &domain.ValidationError{
Field: "text",
Message: "не более 4000 символов",
}
}
if len(attachmentIDs) > 10 {
return nil, &domain.ValidationError{
Field: "attachment_ids",
Message: "не более 10",
}
}
seen := make(map[string]struct{}, len(attachmentIDs))
for _, id := range attachmentIDs {
if _, dup := seen[id]; dup {
return nil, &domain.ValidationError{
Field: "attachment_ids",
Message: "дубликаты запрещены",
}
}
seen[id] = struct{}{}
}
if err := s.ensureMember(ctx, senderID, chatID); err != nil {
return nil, err
}
fresh := &domain.Message{
ID: uuid.NewString(),
ChatID: chatID,
SenderID: senderID,
Text: text,
AttachmentIDs: append([]string(nil), attachmentIDs...),
CreatedAt: time.Now().UTC(),
}
body, err := json.Marshal(dto.MessageFromDomain(fresh))
if err != nil {
return nil, err
}
return s.messages.CreateIdempotent(
ctx,
domain.IdempotencyScope{
UserID: senderID,
Method: http.MethodPost,
Path: requestPath,
Key: idempotencyKey,
},
domain.RequestHash(text, attachmentIDs),
fresh,
body,
s.idempotencyTTL,
)
}
func (s *MessageService) List(ctx context.Context, userID, chatID string, limit int, cursor *string) ([]domain.Message, *string, error) {
if err := s.ensureMember(ctx, userID, chatID); err != nil {
return nil, nil, err
}
return s.messages.ListByChat(ctx, chatID, limit, cursor)
}
func (s *MessageService) ensureMember(ctx context.Context, userID, chatID string) error {
c, err := s.chats.GetByID(ctx, chatID)
if err != nil {
return err
}
for _, m := range c.MemberIDs {
if m == userID {
return nil
}
}
return &domain.NotFoundError{Entity: "chat", ID: chatID}
}
+112
View File
@@ -0,0 +1,112 @@
package service
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
)
// PasswordHasher хеширует пароли и проверяет пароль сохранённого хеша.
type PasswordHasher interface {
Hash(password string) (string, error)
Verify(password, encoded string) (bool, error)
}
type Argon2idHasher struct {
memory uint32
iterations uint32
parallelism uint8
saltLength uint32
keyLength uint32
}
func NewArgon2idHasher() *Argon2idHasher {
return &Argon2idHasher{
memory: 64 * 1024,
iterations: 3,
parallelism: 4,
saltLength: 16,
keyLength: 32,
}
}
func (h *Argon2idHasher) Hash(password string) (string, error) {
salt := make([]byte, h.saltLength)
if _, err := rand.Read(salt); err != nil {
return "", fmt.Errorf("генерация соли: %w", err)
}
key := argon2.IDKey(
[]byte(password),
salt,
h.iterations,
h.memory,
h.parallelism,
h.keyLength,
)
return fmt.Sprintf(
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version,
h.memory,
h.iterations,
h.parallelism,
base64.RawStdEncoding.EncodeToString(salt),
base64.RawStdEncoding.EncodeToString(key),
), nil
}
// Verify сравнивает пароль с сохранённым PHC-хешем.
// Возвращает false и nil при неверном пароле.
// Возвращает false и ошибку, если строка хеша повреждена или несовместима.
func (h *Argon2idHasher) Verify(password, encoded string) (bool, error) {
parts := strings.Split(encoded, "$")
if len(parts) != 6 || parts[1] != "argon2id" {
return false, errors.New("некорректный формат хеша")
}
var version int
if n, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || n != 1 {
return false, errors.New("некорректная версия хеша")
}
if version != argon2.Version {
return false, errors.New("неподдерживаемая версия Argon2")
}
var (
memory uint32
iterations uint32
parallelism uint8
)
if n, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &iterations, &parallelism); err != nil || n != 3 {
return false, errors.New("некорректные параметры хеша")
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil {
return false, errors.New("некорректная соль")
}
wantKey, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil {
return false, errors.New("некорректный ключ")
}
gotKey := argon2.IDKey(
[]byte(password),
salt,
iterations,
memory,
parallelism,
uint32(len(wantKey)),
)
return subtle.ConstantTimeCompare(gotKey, wantKey) == 1, nil
}
var _ PasswordHasher = (*Argon2idHasher)(nil)
+176
View File
@@ -0,0 +1,176 @@
package service
import (
"context"
"log"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"high-loud-apps-labs/internal/domain"
)
const advisoryLockKey int64 = 0x4D5455534904
type Reconciler struct {
attachments domain.AttachmentRepository
storage domain.ObjectStorage
pool *pgxpool.Pool
gracePeriod time.Duration
batchSize int
}
func NewReconciler(
attachments domain.AttachmentRepository,
storage domain.ObjectStorage,
pool *pgxpool.Pool,
gracePeriod time.Duration,
) *Reconciler {
if gracePeriod <= 0 {
gracePeriod = time.Hour
}
return &Reconciler{
attachments: attachments,
storage: storage,
pool: pool,
gracePeriod: gracePeriod,
batchSize: 100,
}
}
func (r *Reconciler) Run(ctx context.Context, interval time.Duration) {
if interval <= 0 {
interval = 5 * time.Minute
}
ticker := time.NewTicker(interval)
defer ticker.Stop()
log.Printf("reconciler: started, interval=%s grace=%s", interval, r.gracePeriod)
r.tick(ctx)
for {
select {
case <-ctx.Done():
log.Println("reconciler: stopped")
return
case <-ticker.C:
r.tick(ctx)
}
}
}
func (r *Reconciler) tick(ctx context.Context) {
acquired, release, err := r.acquireLock(ctx)
if err != nil {
log.Printf("reconciler: acquire lock: %v", err)
return
}
if !acquired {
return
}
defer release()
pendingDeleted := r.sweepPending(ctx)
orphansDeleted := r.sweepOrphans(ctx)
if pendingDeleted > 0 || orphansDeleted > 0 {
log.Printf("reconciler: sweep done pending=%d orphans=%d", pendingDeleted, orphansDeleted)
}
}
func (r *Reconciler) acquireLock(ctx context.Context) (bool, func(), error) {
conn, err := r.pool.Acquire(ctx)
if err != nil {
return false, nil, err
}
var ok bool
if err := conn.QueryRow(ctx, `SELECT pg_try_advisory_lock($1)`, advisoryLockKey).Scan(&ok); err != nil {
conn.Release()
return false, nil, err
}
if !ok {
conn.Release()
return false, nil, nil
}
release := func() {
unlockCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if _, err := conn.Exec(unlockCtx, `SELECT pg_advisory_unlock($1)`, advisoryLockKey); err != nil {
log.Printf("reconciler: unlock: %v", err)
}
conn.Release()
}
return true, release, nil
}
func (r *Reconciler) sweepPending(ctx context.Context) int {
cutoff := time.Now().UTC().Add(-r.gracePeriod)
stale, err := r.attachments.ListStalePending(ctx, cutoff, r.batchSize)
if err != nil {
log.Printf("reconciler: list stale pending: %v", err)
return 0
}
deleted := 0
for _, a := range stale {
if err := r.storage.Delete(ctx, a.ObjectKey); err != nil {
log.Printf("reconciler: delete object %s: %v", a.ObjectKey, err)
continue
}
if err := r.attachments.DeletePending(ctx, a.ID); err != nil {
log.Printf("reconciler: delete pending row %s: %v", a.ID, err)
continue
}
deleted++
}
return deleted
}
func (r *Reconciler) sweepOrphans(ctx context.Context) int {
objects, err := r.storage.List(ctx, "chats/")
if err != nil {
log.Printf("reconciler: list objects: %v", err)
return 0
}
if len(objects) == 0 {
return 0
}
cutoff := time.Now().UTC().Add(-r.gracePeriod)
keys := make([]string, 0, len(objects))
for _, o := range objects {
if o.LastModified.Before(cutoff) {
keys = append(keys, o.Key)
}
}
if len(keys) == 0 {
return 0
}
existing, err := r.attachments.ExistingKeys(ctx, keys)
if err != nil {
log.Printf("reconciler: existing keys: %v", err)
return 0
}
inDB := make(map[string]struct{}, len(existing))
for _, k := range existing {
inDB[k] = struct{}{}
}
deleted := 0
for _, k := range keys {
if _, ok := inDB[k]; ok {
continue
}
if err := r.storage.Delete(ctx, k); err != nil {
log.Printf("reconciler: delete orphan %s: %v", k, err)
continue
}
deleted++
}
return deleted
}
+127
View File
@@ -0,0 +1,127 @@
package service
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"errors"
"fmt"
"time"
"high-loud-apps-labs/internal/domain"
)
// SessionService отвечает за вход, проверку и отзыв сессий.
type SessionService struct {
users domain.UserRepository
sessions domain.SessionRepository
hasher PasswordHasher
ttl time.Duration
}
// NewSessionService создаёт сервис с заданным TTL сессий.
func NewSessionService(
users domain.UserRepository,
sessions domain.SessionRepository,
hasher PasswordHasher,
ttl time.Duration,
) *SessionService {
return &SessionService{
users: users,
sessions: sessions,
hasher: hasher,
ttl: ttl,
}
}
// Login проверяет username/password и создаёт новую сессию.
// Возвращает сессию, открытый токен и пользователя.
// Открытый токен уходит клиенту; в БД сохраняется только его SHA-256.
func (s *SessionService) Login(ctx context.Context, username, password string) (*domain.Session, string, *domain.User, error) {
user, err := s.users.GetByUsername(ctx, username)
if err != nil {
if errors.Is(err, domain.ErrNotFound) {
return nil, "", nil, &domain.UnauthorizedError{Reason: "неверные учётные данные"}
}
return nil, "", nil, err
}
ok, err := s.hasher.Verify(password, user.PasswordHash)
if err != nil {
return nil, "", nil, err
}
if !ok {
return nil, "", nil, &domain.UnauthorizedError{Reason: "неверные учётные данные"}
}
token, err := generateToken()
if err != nil {
return nil, "", nil, err
}
tokenHash := sha256.Sum256([]byte(token))
now := time.Now().UTC()
session := &domain.Session{
TokenHash: tokenHash[:],
UserID: user.ID,
ExpiresAt: now.Add(s.ttl),
CreatedAt: now,
}
if err := s.sessions.Create(ctx, session); err != nil {
return nil, "", nil, err
}
return session, token, user, nil
}
// Resolve проверяет токен и возвращает пользователя сессии.
// Истёкший, отозванный или неизвестный токен - UnauthorizedError по контракту
func (s *SessionService) Resolve(ctx context.Context, token string) (*domain.User, error) {
if token == "" {
return nil, &domain.UnauthorizedError{Reason: "пустой токен"}
}
tokenHash := sha256.Sum256([]byte(token))
session, err := s.sessions.GetByTokenHash(ctx, tokenHash[:])
if err != nil {
if errors.Is(err, domain.ErrNotFound) {
return nil, &domain.UnauthorizedError{Reason: "неизвестный токен"}
}
return nil, err
}
if !session.ExpiresAt.After(time.Now().UTC()) {
return nil, &domain.UnauthorizedError{Reason: "сессия истекла"}
}
user, err := s.users.GetByID(ctx, session.UserID)
if err != nil {
if errors.Is(err, domain.ErrNotFound) {
return nil, &domain.UnauthorizedError{Reason: "пользователь сессии не найден"}
}
return nil, err
}
return user, nil
}
// Revoke удаляет сессию по токену.
func (s *SessionService) Revoke(ctx context.Context, token string) error {
if token == "" {
return nil
}
tokenHash := sha256.Sum256([]byte(token))
return s.sessions.DeleteByTokenHash(ctx, tokenHash[:])
}
// generateToken возвращает 32 случайных байта в base64url без паддинга=.
func generateToken() (string, error) {
buf := make([]byte, 32)
if _, err := rand.Read(buf); err != nil {
return "", fmt.Errorf("генерация токена: %w", err)
}
return base64.RawURLEncoding.EncodeToString(buf), nil
}
+78
View File
@@ -0,0 +1,78 @@
package service
import (
"context"
"regexp"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
"high-loud-apps-labs/internal/domain"
)
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
type UserService struct {
users domain.UserRepository
hasher PasswordHasher
}
func NewUserService(users domain.UserRepository, hasher PasswordHasher) *UserService {
return &UserService{users: users, hasher: hasher}
}
func (s *UserService) Create(ctx context.Context, username, displayName, password string) (*domain.User, error) {
if !usernamePattern.MatchString(username) {
return nil, &domain.ValidationError{
Field: "username",
Message: "должен соответствовать ^[a-z0-9_]{3,32}$",
}
}
if strings.TrimSpace(displayName) == "" {
return nil, &domain.ValidationError{
Field: "display_name",
Message: "не может состоять только из пробелов",
}
}
if utf8.RuneCountInString(displayName) > 100 {
return nil, &domain.ValidationError{
Field: "display_name",
Message: "не более 100 символов",
}
}
passwordRunes := utf8.RuneCountInString(password)
if passwordRunes < 12 || passwordRunes > 128 {
return nil, &domain.ValidationError{
Field: "password",
Message: "длина 12–128 символов",
}
}
hash, err := s.hasher.Hash(password)
if err != nil {
return nil, err
}
u := &domain.User{
ID: uuid.NewString(),
Username: username,
DisplayName: displayName,
PasswordHash: hash,
CreatedAt: time.Now().UTC(),
}
if err := s.users.Create(ctx, u); err != nil {
return nil, err
}
return u, nil
}
func (s *UserService) GetByID(ctx context.Context, id string) (*domain.User, error) {
return s.users.GetByID(ctx, id)
}
func (s *UserService) GetByUsername(ctx context.Context, username string) (*domain.User, error) {
return s.users.GetByUsername(ctx, username)
}