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
+61
View File
@@ -0,0 +1,61 @@
package domain
import "time"
type Health struct {
Status string
}
type User struct {
ID string
Username string
DisplayName string
PasswordHash string // в DTO UserResponse его не будет
CreatedAt time.Time
}
type Chat struct {
ID string
Title string
MemberIDs []string
CreatedAt time.Time
}
type Message struct {
ID string
ChatID string
SenderID string
Text string
AttachmentIDs []string
CreatedAt time.Time
}
type Session struct {
TokenHash []byte
UserID string
ExpiresAt time.Time
CreatedAt time.Time
}
type AttachmentStatus string
const (
AttachmentStatusPending AttachmentStatus = "pending"
AttachmentStatusReady AttachmentStatus = "ready"
AttachmentStatusFailed AttachmentStatus = "failed"
)
type Attachment struct {
ID string
ChatID string
OwnerID string
Filename string
ContentType string
SizeBytes int64
SHA256 []byte
ObjectKey string
Status AttachmentStatus
ErrorCode *string
CreatedAt time.Time
UpdatedAt time.Time
}
+197
View File
@@ -0,0 +1,197 @@
package domain
// Этот файл — единственный источник доменных ошибок.
// Правила:
// 1. sentinel-ошибки (ErrXxx) нужны для errors.Is.
// 2. типы *XxxError нужны для errors.As и для поля code в JSON.
// 3. У каждого типа есть Code() ErrorCode — через него DTO маппит
// в HTTP-код (StatusFromError в httpapi/dto/error.go).
// 4. В Error() пишем только то, что безопасно показать клиенту:
// без SQL, stack trace, путей, credential'ов.
import (
"errors"
"fmt"
)
// ===================================================================
// ErrorCode — машинный код для JSON {"error":{"code":"..."}}
// ===================================================================
type ErrorCode string
const (
CodeInvalidRequest ErrorCode = "invalid_request" // 400
CodeUnauthorized ErrorCode = "unauthorized" // 401
CodeNotFound ErrorCode = "not_found" // 404
CodeConflict ErrorCode = "conflict" // 409
CodePayloadTooLarge ErrorCode = "payload_too_large" // 413
CodeUnsupportedMediaType ErrorCode = "unsupported_media_type" // 415
CodeUnavailable ErrorCode = "unavailable" // 503
CodeInternalError ErrorCode = "internal_error" // 500
)
// ===================================================================
// Sentinel-ошибки (errors.Is)
// ===================================================================
var (
ErrNotFound = errors.New("не найдено")
ErrAlreadyExists = errors.New("уже существует")
ErrInvalidInput = errors.New("некорректные данные")
ErrUnauthorized = errors.New("требуется аутентификация")
ErrUnsupportedMediaType = errors.New("неподдерживаемый тип содержимого")
ErrPayloadTooLarge = errors.New("превышен допустимый размер")
ErrUnavailable = errors.New("сервис недоступен")
ErrConflict = errors.New("конфликт")
)
// ===================================================================
// 404 Not Found
// ===================================================================
type NotFoundError struct {
Entity string
ID string
}
func (e *NotFoundError) Error() string {
return fmt.Sprintf("%s с id %q не найден", e.Entity, e.ID)
}
func (e *NotFoundError) Unwrap() error { return ErrNotFound }
func (e *NotFoundError) Code() ErrorCode { return CodeNotFound }
// ===================================================================
// 409 Conflict
// ===================================================================
// AlreadyExistsError — конфликт уникальности (например, username занят).
// Отдельно от ConflictError: другой смысл, но оба дают HTTP 409.
type AlreadyExistsError struct {
Entity string
Field string
Value string
}
func (e *AlreadyExistsError) Error() string {
return fmt.Sprintf("%s с %s %q уже существует", e.Entity, e.Field, e.Value)
}
func (e *AlreadyExistsError) Unwrap() error { return ErrAlreadyExists }
func (e *AlreadyExistsError) Code() ErrorCode { return CodeConflict }
// IdempotencyConflictError — тот же Idempotency-Key, но другое тело запроса.
type IdempotencyConflictError struct {
Key string
}
func (e *IdempotencyConflictError) Error() string {
return "Idempotency-Key " + e.Key + " уже использован с другим телом запроса"
}
func (e *IdempotencyConflictError) Unwrap() error { return ErrAlreadyExists }
func (e *IdempotencyConflictError) Code() ErrorCode { return CodeConflict }
// ConflictError — конфликт бизнес-состояния, а не уникальности.
// Примеры: "вложение ещё не готово", "нельзя перевести failed-вложение в ready".
// Reason — короткая безопасная фраза, идёт клиенту как message.
type ConflictError struct{ Reason string }
func (e *ConflictError) Error() string { return e.Reason }
func (e *ConflictError) Unwrap() error { return ErrConflict }
func (e *ConflictError) Code() ErrorCode { return CodeConflict }
// ===================================================================
// 400 Bad Request
// ===================================================================
// ValidationError — неверное поле или формат.
type ValidationError struct {
Field string
Message string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("ошибка валидации поля %q: %s", e.Field, e.Message)
}
func (e *ValidationError) Unwrap() error { return ErrInvalidInput }
func (e *ValidationError) Code() ErrorCode { return CodeInvalidRequest }
// ===================================================================
// 401 Unauthorized
// ===================================================================
// UnauthorizedError — нет/просрочен/отозван токен, неверные credentials.
// Reason — только для логов, в JSON не попадает (по контракту все 401
// должны иметь одинаковое сообщение, чтобы не перебирать username).
type UnauthorizedError struct {
Reason string
}
func (e *UnauthorizedError) Error() string {
return "требуется аутентификация"
}
func (e *UnauthorizedError) Unwrap() error { return ErrUnauthorized }
func (e *UnauthorizedError) Code() ErrorCode { return CodeUnauthorized }
// ===================================================================
// 415 Unsupported Media Type
// ===================================================================
// UnsupportedMediaTypeError — неверный Content-Type.
//
// ВАЖНО: сейчас текст жёстко про application/json. Для lab4 (вложения)
// ожидается image/png или image/jpeg. Прежде чем использовать этот тип
// в AttachmentHandler, добавить поле Expected string (дефолт application/json)
// или сделать отдельный тип — не переиспользовать как есть, иначе клиент
// увидит неверную подсказку.
type UnsupportedMediaTypeError struct {
MediaType string
Expected string
}
func (e *UnsupportedMediaTypeError) Error() string {
expected := e.Expected
if expected == "" {
expected = "application/json"
}
if e.MediaType == "" {
return "требуется Content-Type: " + expected
}
return fmt.Sprintf("неподдерживаемый Content-Type %q; требуется %s", e.MediaType, expected)
}
func (e *UnsupportedMediaTypeError) Unwrap() error { return ErrUnsupportedMediaType }
func (e *UnsupportedMediaTypeError) Code() ErrorCode { return CodeUnsupportedMediaType }
// ===================================================================
// 413 Payload Too Large
// ===================================================================
// PayloadTooLargeError — тело больше лимита.
// Message опционален: если пуст — формируется из Limit.
type PayloadTooLargeError struct {
Limit int64
Message string
}
func (e *PayloadTooLargeError) Error() string {
if e.Message != "" {
return e.Message
}
return fmt.Sprintf("превышен лимит %d байт", e.Limit)
}
func (e *PayloadTooLargeError) Unwrap() error { return ErrPayloadTooLarge }
func (e *PayloadTooLargeError) Code() ErrorCode { return CodePayloadTooLarge }
// ===================================================================
// 503 Service Unavailable
// ===================================================================
// UnavailableError — недоступна критичная зависимость (БД, кэш, S3).
// Reason — только для логов; клиент видит общее сообщение по контракту,
// чтобы не раскрывать имена сервисов и топологию.
type UnavailableError struct{ Reason string }
func (e *UnavailableError) Error() string {
return "сервис временно недоступен"
}
func (e *UnavailableError) Unwrap() error { return ErrUnavailable }
func (e *UnavailableError) Code() ErrorCode { return CodeUnavailable }
+33
View File
@@ -0,0 +1,33 @@
package domain
import (
"crypto/sha256"
)
type IdempotencyScope struct {
UserID string
Method string
Path string
Key string
}
type CreateIdempotentResult struct {
Status int
Body []byte
Replayed bool
}
func RequestHash(text string, attachmentIDs []string) []byte {
if len(attachmentIDs) == 0 {
sum := sha256.Sum256([]byte(text))
return sum[:]
}
h := sha256.New()
h.Write([]byte(text))
h.Write([]byte{0})
for _, id := range attachmentIDs {
h.Write([]byte(id))
h.Write([]byte{0})
}
return h.Sum(nil)
}
+47
View File
@@ -0,0 +1,47 @@
package domain
import (
"context"
"time"
)
type UserRepository interface {
Create(ctx context.Context, user *User) error
GetByID(ctx context.Context, id string) (*User, error)
GetByUsername(ctx context.Context, username string) (*User, error)
}
type ChatRepository interface {
Create(ctx context.Context, chat *Chat) error
GetByID(ctx context.Context, id string) (*Chat, error)
ListByMember(ctx context.Context, userID string, limit int, cursor *string) ([]Chat, *string, error)
}
type MessageRepository interface {
Create(ctx context.Context, message *Message) error
ListByChat(ctx context.Context, chatID string, limit int, cursor *string) ([]Message, *string, error)
CreateIdempotent(
ctx context.Context,
scope IdempotencyScope,
requestHash []byte,
fresh *Message,
freshResponse []byte,
ttl time.Duration,
) (*CreateIdempotentResult, error)
}
type SessionRepository interface {
Create(ctx context.Context, session *Session) error
GetByTokenHash(ctx context.Context, tokenHash []byte) (*Session, error)
DeleteByTokenHash(ctx context.Context, tokenHash []byte) error
}
type AttachmentRepository interface {
Create(ctx context.Context, a *Attachment) error
GetByID(ctx context.Context, id string) (*Attachment, error)
MarkReady(ctx context.Context, id string) error
MarkFailed(ctx context.Context, id string, errorCode string) error
ListStalePending(ctx context.Context, olderThan time.Time, limit int) ([]Attachment, error)
ExistingKeys(ctx context.Context, keys []string) ([]string, error)
DeletePending(ctx context.Context, id string) error
}
+21
View File
@@ -0,0 +1,21 @@
package domain
import (
"context"
"io"
"time"
)
type ObjectInfo struct {
Key string
LastModified time.Time
Size int64
}
type ObjectStorage interface {
Ping(ctx context.Context) error
Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error
Get(ctx context.Context, key string) (io.ReadCloser, int64, string, error)
Delete(ctx context.Context, key string) error
List(ctx context.Context, prefix string) ([]ObjectInfo, error)
}