chore: add lab5 files and merge env.example.

This commit is contained in:
Голиков Maximillian Антон
2026-11-14 16:12:32 +03:00
parent 470d9d6f1e
commit 0d1a4261f8
93 changed files with 7085 additions and 11 deletions
@@ -0,0 +1,21 @@
package domain
import "time"
type AttachmentVariant struct {
AttachmentID string
Name string
ObjectKey string
ContentType string
SizeBytes int64
Width int
Height int
SHA256 []byte
CreatedAt time.Time
}
const (
VariantThumbnail = "thumbnail"
VariantCrop = "crop"
VariantOptimized = "optimized"
)
+70
View File
@@ -0,0 +1,70 @@
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 (
AttachmentStatusQueued AttachmentStatus = "queued"
AttachmentStatusProcessing AttachmentStatus = "processing"
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
Attempts int // авторитетный счётчик попыток (в БД)
NextAttemptAt *time.Time // "не раньше"; nil = можно брать сразу
LockedUntil *time.Time // lease; nil = не арендовано
PipelineVersion int // guard в CompleteJob; в БД default 1
StagingKey string // S3-ключ оригинала до 202; "" в lab4-пути
Variants []AttachmentVariant
}
+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 }
+17
View File
@@ -0,0 +1,17 @@
package domain
import "time"
// FailedJob — реестр окончательно проваленных задач (DLQ-сторона).
// Заполняется worker'ом после исчерпания retry или при permanent-ошибке.
// Читается для операторского просмотра и для явного replay (Этап 5).
type FailedJob struct {
ID string
AttachmentID string
ReasonCode string // из jobcodes.go
Attempts int
LastErrorAt time.Time
ResolvedAt *time.Time // nil = не разобрана
Resolution string // "replayed", "manual_fix", ...
CreatedAt time.Time
}
+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)
}
+7
View File
@@ -0,0 +1,7 @@
package domain
type JobMessage struct {
AttachmentID string `json:"attachment_id"`
PipelineVersion int `json:"pipeline_version"`
Attempt int `json:"attempt"`
}
+10
View File
@@ -0,0 +1,10 @@
package domain
const (
JobErrorDecodeFailed = "decode_failed"
JobErrorTooLarge = "too_large"
JobErrorUnsupportedFormat = "unsupported_format"
JobErrorStorage = "storage_error"
JobErrorInternal = "internal_error"
JobErrorRetryExhausted = "retry_exhausted"
)
+28
View File
@@ -0,0 +1,28 @@
package domain
import "time"
const (
OutboxAggregateAttachment = "attachment"
OutboxEventProcess = "attachment.process"
)
// OutboxEntry — намерение опубликовать сообщение, записанное
// в одной транзакции с бизнес-изменением (transactional outbox).
//
// Инварианты:
// - PublishedAt == nil => ещё не опубликовано, publisher обязан дослать;
// - PublishedAt != nil => RabbitMQ принял сообщение,
// а не «мы вызвали Publish». At-least-once: повторная доставка
// возможна и нормальна, гасится идемпотентностью consumer'а.
//
type OutboxEntry struct {
ID string
AggregateType string
AggregateID string
EventType string
Payload []byte
CreatedAt time.Time
PublishedAt *time.Time
Attempts int
}
+77
View File
@@ -0,0 +1,77 @@
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
ExistingKeys(ctx context.Context, keys []string) ([]string, error)
CreateInTx(ctx context.Context, tx Tx, a *Attachment) error
ResetForReplay(ctx context.Context, tx Tx, id string) error
ListExpiredLeases(ctx context.Context, limit int) ([]Attachment, error)
ResetLease(ctx context.Context, id string) error
ListStagingToCleanup(ctx context.Context, limit int) ([]Attachment, error)
ClearStagingKey(ctx context.Context, id string) error
}
type OutboxRepository interface {
Enqueue(ctx context.Context, tx Tx, e *OutboxEntry) error
ClaimBatch(ctx context.Context, limit int) ([]OutboxEntry, error)
MarkPublished(ctx context.Context, ids []string) error
EnqueueDirect(ctx context.Context, e *OutboxEntry) error
}
type AttachmentJobRepository interface {
ClaimForProcessing(ctx context.Context, id string, version int, lease time.Duration) (*Attachment, error)
CompleteJob(ctx context.Context, id string, pipelineVersion int, variants []AttachmentVariant) (bool, error)
FailJob(ctx context.Context, id string, errorCode string) error
ScheduleRetry(ctx context.Context, id string, nextAttemptAt time.Time, errorCode string) error
}
type AttachmentVariantRepository interface {
Upsert(ctx context.Context, tx Tx, v *AttachmentVariant) error
ListByAttachment(ctx context.Context, id string) ([]AttachmentVariant, error)
}
type FailedJobRepository interface {
Record(ctx context.Context, f *FailedJob) error
Resolve(ctx context.Context, attachmentID string, resolution string) error
ResolveInTx(ctx context.Context, tx Tx, 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)
}
+18
View File
@@ -0,0 +1,18 @@
package domain
import "context"
// Tx — минимальная абстракция транзакции, нужная domain-слою.
// Реализуется адаптером над pgx.Tx в storage/postgres, поэтому
// domain не зависит от драйвера БД.
//
// Зачем: transactional outbox требует, чтобы бизнес-изменение
// (например, INSERT attachments) и INSERT outbox шли в одной
// транзакции. Без передачи транзакции в репозиторий эту гарантию
// не выразить.
//
// Метод один — Exec. Расширять по мере появления реальных
// потребителей, а не на будущее.
type Tx interface {
Exec(ctx context.Context, sql string, args ...any) error
}