chore: lab import lab4 backend and infrastructure as baseline
This commit is contained in:
@@ -0,0 +1,230 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Host string
|
||||
Port string
|
||||
DatabaseURL string
|
||||
SessionStore string
|
||||
CacheURL string
|
||||
SessionTTL time.Duration
|
||||
IdempotencyTTL time.Duration
|
||||
ShutdownDrain time.Duration
|
||||
|
||||
S3Endpoint string
|
||||
S3Bucket string
|
||||
S3UseSSL bool
|
||||
S3Region string
|
||||
S3AccessKey string
|
||||
S3SecretKey string
|
||||
|
||||
MaxUploadBytes int64
|
||||
MaxImagePixels int64
|
||||
|
||||
ReconcilerEnabled bool
|
||||
ReconcilerInterval time.Duration
|
||||
ReconcilerGracePeriod time.Duration
|
||||
}
|
||||
|
||||
func Load() (*Config, error) {
|
||||
dsn, err := readSecret("DATABASE_URL_FILE", "DATABASE_URL")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("database url: %w", err)
|
||||
}
|
||||
|
||||
cacheURL, err := readSecretOptional("CACHE_URL_FILE", "CACHE_URL")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cache url: %w", err)
|
||||
}
|
||||
|
||||
ttlSeconds, err := readInt("SESSION_TTL_SECONDS", 3600)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("SESSION_TTL_SECONDS: %w", err)
|
||||
}
|
||||
if ttlSeconds <= 0 {
|
||||
return nil, fmt.Errorf("SESSION_TTL_SECONDS должен быть положительным")
|
||||
}
|
||||
|
||||
idemSeconds, err := readInt("IDEMPOTENCY_TTL_SECONDS", 86400)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("IDEMPOTENCY_TTL_SECONDS: %w", err)
|
||||
}
|
||||
if idemSeconds <= 0 {
|
||||
return nil, fmt.Errorf("IDEMPOTENCY_TTL_SECONDS должен быть положительным")
|
||||
}
|
||||
|
||||
drainSeconds, err := readInt("SHUTDOWN_DRAIN_SECONDS", 3)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("SHUTDOWN_DRAIN_SECONDS: %w", err)
|
||||
}
|
||||
if drainSeconds < 0 {
|
||||
return nil, fmt.Errorf("SHUTDOWN_DRAIN_SECONDS не может быть отрицательным")
|
||||
}
|
||||
|
||||
store := strings.ToLower(getenv("SESSION_STORE", "postgres"))
|
||||
switch store {
|
||||
case "postgres", "redis", "valkey":
|
||||
default:
|
||||
return nil, fmt.Errorf("SESSION_STORE=%q не поддерживается", store)
|
||||
}
|
||||
|
||||
s3Endpoint := getenv("S3_ENDPOINT", "")
|
||||
s3Bucket := getenv("S3_BUCKET", "")
|
||||
s3UseSSL, err := readBool("S3_USE_SSL", false)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("S3_USE_SSL: %w", err)
|
||||
}
|
||||
s3Region := getenv("S3_REGION", "us-east-1")
|
||||
|
||||
s3AccessKey, err := readSecretOptional("S3_ACCESS_KEY_ID_FILE", "S3_ACCESS_KEY_ID")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("s3 access key: %w", err)
|
||||
}
|
||||
s3SecretKey, err := readSecretOptional("S3_SECRET_ACCESS_KEY_FILE", "S3_SECRET_ACCESS_KEY")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("s3 secret key: %w", err)
|
||||
}
|
||||
|
||||
maxUploadBytes, err := readInt64("MAX_UPLOAD_BYTES", 10485760)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("MAX_UPLOAD_BYTES: %w", err)
|
||||
}
|
||||
if maxUploadBytes <= 0 {
|
||||
return nil, fmt.Errorf("MAX_UPLOAD_BYTES должен быть положительным")
|
||||
}
|
||||
|
||||
maxImagePixels, err := readInt64("MAX_IMAGE_PIXELS", 40000000)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("MAX_IMAGE_PIXELS: %w", err)
|
||||
}
|
||||
if maxImagePixels <= 0 {
|
||||
return nil, fmt.Errorf("MAX_IMAGE_PIXELS должен быть положительным")
|
||||
}
|
||||
|
||||
reconcilerEnabled, err := readBool("RECONCILER_ENABLED", true)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("RECONCILER_ENABLED: %w", err)
|
||||
}
|
||||
reconcilerIntervalSec, err := readInt("RECONCILER_INTERVAL_SECONDS", 300)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("RECONCILER_INTERVAL_SECONDS: %w", err)
|
||||
}
|
||||
if reconcilerIntervalSec <= 0 {
|
||||
return nil, fmt.Errorf("RECONCILER_INTERVAL_SECONDS должен быть положительным")
|
||||
}
|
||||
reconcilerGraceSec, err := readInt("RECONCILER_GRACE_SECONDS", 3600)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("RECONCILER_GRACE_SECONDS: %w", err)
|
||||
}
|
||||
if reconcilerGraceSec <= 0 {
|
||||
return nil, fmt.Errorf("RECONCILER_GRACE_SECONDS должен быть положительным")
|
||||
}
|
||||
|
||||
return &Config{
|
||||
Host: getenv("APP_HOST", "0.0.0.0"),
|
||||
Port: getenv("APP_PORT", "8080"),
|
||||
DatabaseURL: dsn,
|
||||
SessionStore: store,
|
||||
CacheURL: cacheURL,
|
||||
SessionTTL: time.Duration(ttlSeconds) * time.Second,
|
||||
IdempotencyTTL: time.Duration(idemSeconds) * time.Second,
|
||||
ShutdownDrain: time.Duration(drainSeconds) * time.Second,
|
||||
|
||||
S3Endpoint: s3Endpoint,
|
||||
S3Bucket: s3Bucket,
|
||||
S3UseSSL: s3UseSSL,
|
||||
S3Region: s3Region,
|
||||
S3AccessKey: s3AccessKey,
|
||||
S3SecretKey: s3SecretKey,
|
||||
|
||||
MaxUploadBytes: maxUploadBytes,
|
||||
MaxImagePixels: maxImagePixels,
|
||||
|
||||
ReconcilerEnabled: reconcilerEnabled,
|
||||
ReconcilerInterval: time.Duration(reconcilerIntervalSec) * time.Second,
|
||||
ReconcilerGracePeriod: time.Duration(reconcilerGraceSec) * time.Second,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Config) S3Configured() bool {
|
||||
return c.S3Endpoint != "" &&
|
||||
c.S3Bucket != "" &&
|
||||
c.S3AccessKey != "" &&
|
||||
c.S3SecretKey != ""
|
||||
}
|
||||
|
||||
func getenv(key, def string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func readInt(key string, def int) (int, error) {
|
||||
v := os.Getenv(key)
|
||||
if v == "" {
|
||||
return def, nil
|
||||
}
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("не целое число: %q", v)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func readInt64(key string, def int64) (int64, error) {
|
||||
v := os.Getenv(key)
|
||||
if v == "" {
|
||||
return def, nil
|
||||
}
|
||||
n, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("не целое число: %q", v)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func readBool(key string, def bool) (bool, error) {
|
||||
v := os.Getenv(key)
|
||||
if v == "" {
|
||||
return def, nil
|
||||
}
|
||||
b, err := strconv.ParseBool(v)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("не bool: %q", v)
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func readSecret(fileEnv, envKey string) (string, error) {
|
||||
v, err := readSecretOptional(fileEnv, envKey)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if v == "" {
|
||||
return "", fmt.Errorf("не задан %s или %s", fileEnv, envKey)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func readSecretOptional(fileEnv, envKey string) (string, error) {
|
||||
if path := os.Getenv(fileEnv); path != "" {
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("чтение %s=%s: %w", fileEnv, path, err)
|
||||
}
|
||||
s := strings.TrimSpace(string(b))
|
||||
if s == "" {
|
||||
return "", fmt.Errorf("файл %s пуст", path)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
return os.Getenv(envKey), nil
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 }
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type VariantResponse struct {
|
||||
Name string `json:"name"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
|
||||
type AttachmentResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Status string `json:"status"`
|
||||
Variants []VariantResponse `json:"variants"`
|
||||
ErrorCode *string `json:"error_code"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
func AttachmentFromDomain(a *domain.Attachment) AttachmentResponse {
|
||||
variants := make([]VariantResponse, 0)
|
||||
errCode := a.ErrorCode
|
||||
return AttachmentResponse{
|
||||
ID: a.ID,
|
||||
ChatID: a.ChatID,
|
||||
OwnerID: a.OwnerID,
|
||||
Filename: a.Filename,
|
||||
ContentType: a.ContentType,
|
||||
SizeBytes: a.SizeBytes,
|
||||
SHA256: hex.EncodeToString(a.SHA256),
|
||||
Status: string(a.Status),
|
||||
Variants: variants,
|
||||
ErrorCode: errCode,
|
||||
CreatedAt: a.CreatedAt.UTC().Format(timeFormat),
|
||||
UpdatedAt: a.UpdatedAt.UTC().Format(timeFormat),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type CreateChatRequest struct {
|
||||
Title string `json:"title" binding:"required,min=1,max=100"`
|
||||
MemberIDs []string `json:"member_ids" binding:"required,min=1,max=100,dive,uuid"`
|
||||
}
|
||||
|
||||
type ChatResponse struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type ChatPageResponse struct {
|
||||
Items []ChatResponse `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func ChatFromDomain(c *domain.Chat) ChatResponse {
|
||||
return ChatResponse{
|
||||
ID: c.ID,
|
||||
Title: c.Title,
|
||||
MemberIDs: append([]string(nil), c.MemberIDs...),
|
||||
CreatedAt: c.CreatedAt.UTC().Format(timeFormat),
|
||||
}
|
||||
}
|
||||
|
||||
func ChatsFromDomain(items []domain.Chat) []ChatResponse {
|
||||
out := make([]ChatResponse, len(items))
|
||||
for i := range items {
|
||||
out[i] = ChatFromDomain(&items[i])
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
// делаем вложенный ответ через вкладку ErrorBody в обертку.
|
||||
|
||||
type ErrorBody struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
type ErrorResponse struct {
|
||||
Error ErrorBody `json:"error"`
|
||||
}
|
||||
|
||||
type coded interface {
|
||||
Code() domain.ErrorCode
|
||||
}
|
||||
|
||||
func ErrorFromDomain(err error, requestID string) ErrorResponse {
|
||||
var c coded
|
||||
if errors.As(err, &c) {
|
||||
code := c.Code()
|
||||
message := err.Error()
|
||||
if code == domain.CodeInternalError {
|
||||
message = "внутренняя ошибка"
|
||||
}
|
||||
return ErrorResponse{Error: ErrorBody{
|
||||
Code: string(code),
|
||||
Message: message,
|
||||
RequestID: requestID,
|
||||
}}
|
||||
}
|
||||
code := domain.CodeInternalError
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
code = domain.CodeNotFound
|
||||
case errors.Is(err, domain.ErrAlreadyExists):
|
||||
code = domain.CodeConflict
|
||||
case errors.Is(err, domain.ErrInvalidInput):
|
||||
code = domain.CodeInvalidRequest
|
||||
case errors.Is(err, domain.ErrUnauthorized):
|
||||
code = domain.CodeUnauthorized
|
||||
case errors.Is(err, domain.ErrUnsupportedMediaType):
|
||||
code = domain.CodeUnsupportedMediaType
|
||||
case errors.Is(err, domain.ErrUnavailable):
|
||||
code = domain.CodeUnavailable
|
||||
}
|
||||
message := err.Error()
|
||||
if code == domain.CodeInternalError {
|
||||
message = "внутренняя ошибка"
|
||||
}
|
||||
return ErrorResponse{Error: ErrorBody{
|
||||
Code: string(code),
|
||||
Message: message,
|
||||
RequestID: requestID,
|
||||
}}
|
||||
}
|
||||
|
||||
func StatusFromError(err error) int {
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return 404
|
||||
case errors.Is(err, domain.ErrAlreadyExists):
|
||||
return 409
|
||||
case errors.Is(err, domain.ErrInvalidInput):
|
||||
return 400
|
||||
case errors.Is(err, domain.ErrUnauthorized):
|
||||
return 401
|
||||
case errors.Is(err, domain.ErrUnsupportedMediaType):
|
||||
return 415
|
||||
case errors.Is(err, domain.ErrUnavailable):
|
||||
return 503
|
||||
case errors.Is(err, domain.ErrPayloadTooLarge):
|
||||
return 413
|
||||
case errors.Is(err, domain.ErrConflict):
|
||||
return 409
|
||||
default:
|
||||
return 500
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package dto
|
||||
|
||||
type HealthResponse struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type CreateMessageRequest struct {
|
||||
Text string `json:"text" binding:"max=4000"`
|
||||
AttachmentIDs []string `json:"attachment_ids" binding:"max=10,dive,uuid"`
|
||||
}
|
||||
|
||||
type MessageResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type MessagePageResponse struct {
|
||||
Items []MessageResponse `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func MessageFromDomain(m *domain.Message) MessageResponse {
|
||||
ids := m.AttachmentIDs
|
||||
if ids == nil {
|
||||
ids = []string{}
|
||||
}
|
||||
return MessageResponse{
|
||||
ID: m.ID,
|
||||
ChatID: m.ChatID,
|
||||
SenderID: m.SenderID,
|
||||
Text: m.Text,
|
||||
AttachmentIDs: ids,
|
||||
CreatedAt: m.CreatedAt.UTC().Format(timeFormat),
|
||||
}
|
||||
}
|
||||
|
||||
func MessagesFromDomain(items []domain.Message) []MessageResponse {
|
||||
out := make([]MessageResponse, len(items))
|
||||
for i := range items {
|
||||
out[i] = MessageFromDomain(&items[i])
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type SessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
User UserResponse `json:"user"`
|
||||
}
|
||||
|
||||
func SessionResponseFromDomain(s *domain.Session, token string, u *domain.User) SessionResponse {
|
||||
return SessionResponse{
|
||||
Token: token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: s.ExpiresAt.UTC().Format(timeFormat),
|
||||
User: UserFromDomain(u),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
const timeFormat = "2006-01-02T15:04:05.000000Z07:00"
|
||||
|
||||
type CreateUserRequest struct {
|
||||
Username string `json:"username" binding:"required,min=3,max=32"`
|
||||
DisplayName string `json:"display_name" binding:"required,min=1,max=100"`
|
||||
Password string `json:"password" binding:"required,min=12,max=512"`
|
||||
}
|
||||
|
||||
type UserResponse struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
func UserFromDomain(u *domain.User) UserResponse {
|
||||
return UserResponse{
|
||||
ID: u.ID,
|
||||
Username: u.Username,
|
||||
DisplayName: u.DisplayName,
|
||||
CreatedAt: u.CreatedAt.UTC().Format(timeFormat),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"mime"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
"high-loud-apps-labs/internal/httpapi/middleware"
|
||||
"high-loud-apps-labs/internal/service"
|
||||
)
|
||||
|
||||
type AttachmentHandler struct {
|
||||
svc *service.AttachmentService
|
||||
}
|
||||
|
||||
func NewAttachmentHandler(svc *service.AttachmentService) *AttachmentHandler {
|
||||
return &AttachmentHandler{svc: svc}
|
||||
}
|
||||
|
||||
func (h *AttachmentHandler) Upload(c *gin.Context) {
|
||||
me := middleware.CurrentUser(c)
|
||||
|
||||
chatID, err := parseUUIDPathParam(c, "chat_id")
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
filename := c.Query("filename")
|
||||
if filename == "" {
|
||||
respondError(c, &domain.ValidationError{
|
||||
Field: "filename",
|
||||
Message: "обязателен",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
mediaType, _, err := mime.ParseMediaType(c.GetHeader("Content-Type"))
|
||||
if err != nil || (mediaType != "image/png" && mediaType != "image/jpeg") {
|
||||
respondError(c, &domain.UnsupportedMediaTypeError{
|
||||
MediaType: c.GetHeader("Content-Type"),
|
||||
Expected: "image/png или image/jpeg",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
att, err := h.svc.Upload(c.Request.Context(), me.ID, chatID, filename, c.Request.Body)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, dto.AttachmentFromDomain(att))
|
||||
}
|
||||
|
||||
func (h *AttachmentHandler) Get(c *gin.Context) {
|
||||
me := middleware.CurrentUser(c)
|
||||
|
||||
attachmentID, err := parseUUIDPathParam(c, "attachment_id")
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
a, err := h.svc.Get(c.Request.Context(), me.ID, attachmentID)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.AttachmentFromDomain(a))
|
||||
}
|
||||
|
||||
func (h *AttachmentHandler) Content(c *gin.Context) {
|
||||
me := middleware.CurrentUser(c)
|
||||
|
||||
attachmentID, err := parseUUIDPathParam(c, "attachment_id")
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
variant := c.DefaultQuery("variant", "original")
|
||||
if variant != "original" {
|
||||
respondError(c, &domain.NotFoundError{Entity: "variant", ID: variant})
|
||||
return
|
||||
}
|
||||
|
||||
rc, size, contentType, err := h.svc.Download(c.Request.Context(), me.ID, attachmentID)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
defer func() { _ = rc.Close() }()
|
||||
|
||||
c.DataFromReader(http.StatusOK, size, contentType, rc, nil)
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
"high-loud-apps-labs/internal/httpapi/middleware"
|
||||
"high-loud-apps-labs/internal/service"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
sessions *service.SessionService
|
||||
}
|
||||
|
||||
func NewAuthHandler(sessions *service.SessionService) *AuthHandler {
|
||||
return &AuthHandler{sessions: sessions}
|
||||
}
|
||||
|
||||
func (h *AuthHandler) CreateSession(c *gin.Context) {
|
||||
username, password, err := parseBasicAuth(c)
|
||||
if err != nil {
|
||||
respondBasicChallenge(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
session, token, user, err := h.sessions.Login(c.Request.Context(), username, password)
|
||||
if err != nil {
|
||||
respondBasicChallenge(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, dto.SessionResponseFromDomain(session, token, user))
|
||||
}
|
||||
|
||||
// RevokeCurrent отзывает текущую сессию. Токен уже проверен BearerAuth,
|
||||
// поэтому здесь его достаточно передать в SessionService.
|
||||
func (h *AuthHandler) RevokeCurrent(c *gin.Context) {
|
||||
token := middleware.CurrentToken(c)
|
||||
if token == "" {
|
||||
respondError(c, &domain.UnauthorizedError{Reason: "нет токена"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.sessions.Revoke(c.Request.Context(), token); err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// parseBasicAuth читает Authorization: Basic base64(username:password).
|
||||
func parseBasicAuth(c *gin.Context) (string, string, error) {
|
||||
const prefix = "Basic "
|
||||
|
||||
auth := c.GetHeader("Authorization")
|
||||
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
|
||||
return "", "", &domain.UnauthorizedError{Reason: "требуется Basic"}
|
||||
}
|
||||
|
||||
decoded, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
|
||||
if err != nil {
|
||||
return "", "", &domain.UnauthorizedError{Reason: "некорректный Base64"}
|
||||
}
|
||||
|
||||
username, password, ok := strings.Cut(string(decoded), ":")
|
||||
if !ok || username == "" {
|
||||
return "", "", &domain.UnauthorizedError{Reason: "некорректный Basic-формат"}
|
||||
}
|
||||
|
||||
return username, password, nil
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
func bindStrictJSON(c *gin.Context, dst any) error {
|
||||
ct := c.GetHeader("Content-Type")
|
||||
mediaType, _, err := mime.ParseMediaType(ct)
|
||||
if ct == "" || err != nil || !strings.EqualFold(mediaType, "application/json") {
|
||||
return &domain.UnsupportedMediaTypeError{MediaType: ct}
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
return &badRequestError{msg: "не удалось прочитать тело запроса"}
|
||||
}
|
||||
_ = c.Request.Body.Close()
|
||||
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
dec.DisallowUnknownFields()
|
||||
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
return &badRequestError{msg: "тело запроса обязательно"}
|
||||
}
|
||||
return &badRequestError{msg: err.Error()}
|
||||
}
|
||||
|
||||
// Отклоняем любой непустой остаток после первого JSON-значения.
|
||||
var extra json.RawMessage
|
||||
if err := dec.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return &badRequestError{msg: "тело запроса содержит данные после JSON"}
|
||||
}
|
||||
|
||||
if v := binding.Validator; v != nil {
|
||||
if err := v.ValidateStruct(dst); err != nil {
|
||||
return &badRequestError{msg: err.Error()}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
"high-loud-apps-labs/internal/httpapi/middleware"
|
||||
"high-loud-apps-labs/internal/service"
|
||||
)
|
||||
|
||||
type ChatHandler struct {
|
||||
chats *service.ChatService
|
||||
}
|
||||
|
||||
func NewChatHandler(chats *service.ChatService) *ChatHandler {
|
||||
return &ChatHandler{chats: chats}
|
||||
}
|
||||
|
||||
func (h *ChatHandler) Create(c *gin.Context) {
|
||||
var req dto.CreateChatRequest
|
||||
if err := bindStrictJSON(c, &req); err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
me := middleware.CurrentUser(c)
|
||||
|
||||
chat, err := h.chats.Create(c.Request.Context(), me.ID, req.Title, req.MemberIDs)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, dto.ChatFromDomain(chat))
|
||||
}
|
||||
|
||||
func (h *ChatHandler) Get(c *gin.Context) {
|
||||
me := middleware.CurrentUser(c)
|
||||
|
||||
chatID, err := parseUUIDPathParam(c, "chat_id")
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := h.chats.Get(c.Request.Context(), me.ID, chatID)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.ChatFromDomain(chat))
|
||||
}
|
||||
|
||||
func (h *ChatHandler) List(c *gin.Context) {
|
||||
me := middleware.CurrentUser(c)
|
||||
limit, cursor, err := parseListQuery(c)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
items, next, err := h.chats.List(c.Request.Context(), me.ID, limit, cursor)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.ChatPageResponse{
|
||||
Items: dto.ChatsFromDomain(items),
|
||||
NextCursor: next,
|
||||
})
|
||||
}
|
||||
|
||||
func parseListQuery(c *gin.Context) (int, *string, error) {
|
||||
limit := 50
|
||||
if v := c.Query("limit"); v != "" {
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil || n < 1 || n > 100 {
|
||||
return 0, nil, &badRequestError{msg: "limit должен быть целым 1..100"}
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
var cursor *string
|
||||
if v := c.Query("cursor"); v != "" {
|
||||
cursor = &v
|
||||
}
|
||||
return limit, cursor, nil
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
)
|
||||
|
||||
type HealthCheck func(ctx context.Context) error
|
||||
|
||||
type HealthHandler struct {
|
||||
checks []HealthCheck
|
||||
ready *atomic.Bool
|
||||
}
|
||||
|
||||
func NewHealthHandler(checks ...HealthCheck) *HealthHandler {
|
||||
return &HealthHandler{checks: checks}
|
||||
}
|
||||
|
||||
func (h *HealthHandler) WithReadyFlag(v *atomic.Bool) *HealthHandler {
|
||||
h.ready = v
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *HealthHandler) Live(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, dto.HealthResponse{Status: "ok"})
|
||||
}
|
||||
|
||||
func (h *HealthHandler) Ready(c *gin.Context) {
|
||||
if h.ready != nil && !h.ready.Load() {
|
||||
respondError(c, &domain.UnavailableError{Reason: "shutting down"})
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
for _, check := range h.checks {
|
||||
if check == nil {
|
||||
continue
|
||||
}
|
||||
if err := check(ctx); err != nil {
|
||||
respondError(c, &domain.UnavailableError{Reason: "зависимость недоступна"})
|
||||
return
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.HealthResponse{Status: "ok"})
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"regexp"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
"high-loud-apps-labs/internal/httpapi/middleware"
|
||||
"high-loud-apps-labs/internal/service"
|
||||
)
|
||||
|
||||
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
type MessageHandler struct {
|
||||
messages *service.MessageService
|
||||
}
|
||||
|
||||
func NewMessageHandler(messages *service.MessageService) *MessageHandler {
|
||||
return &MessageHandler{messages: messages}
|
||||
}
|
||||
|
||||
func (h *MessageHandler) Create(c *gin.Context) {
|
||||
var req dto.CreateMessageRequest
|
||||
if err := bindStrictJSON(c, &req); err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
key := c.GetHeader("Idempotency-Key")
|
||||
if key == "" || !idempotencyKeyPattern.MatchString(key) {
|
||||
respondError(c, &badRequestError{
|
||||
msg: "Idempotency-Key обязателен и должен соответствовать ^[A-Za-z0-9._:-]{1,128}$",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
me := middleware.CurrentUser(c)
|
||||
|
||||
chatID, err := parseUUIDPathParam(c, "chat_id")
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.messages.Create(
|
||||
c.Request.Context(),
|
||||
me.ID,
|
||||
chatID,
|
||||
req.Text,
|
||||
req.AttachmentIDs,
|
||||
key,
|
||||
c.Request.URL.Path,
|
||||
)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.Data(result.Status, "application/json", result.Body)
|
||||
}
|
||||
|
||||
func (h *MessageHandler) List(c *gin.Context) {
|
||||
me := middleware.CurrentUser(c)
|
||||
|
||||
chatID, err := parseUUIDPathParam(c, "chat_id")
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
limit, cursor, err := parseListQuery(c)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
items, next, err := h.messages.List(c.Request.Context(), me.ID, chatID, limit, cursor)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.MessagePageResponse{
|
||||
Items: dto.MessagesFromDomain(items),
|
||||
NextCursor: next,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
"high-loud-apps-labs/internal/httpapi/middleware"
|
||||
)
|
||||
|
||||
type badRequestError struct{ msg string }
|
||||
|
||||
func (e *badRequestError) Error() string { return e.msg }
|
||||
func (e *badRequestError) Unwrap() error { return domain.ErrInvalidInput }
|
||||
func (e *badRequestError) Code() domain.ErrorCode { return domain.CodeInvalidRequest }
|
||||
|
||||
func parseUUIDPathParam(c *gin.Context, name string) (string, error) {
|
||||
raw := c.Param(name)
|
||||
if raw == "" {
|
||||
return "", &badRequestError{msg: "параметр " + name + " обязателен"}
|
||||
}
|
||||
|
||||
id, err := uuid.Parse(raw)
|
||||
if err != nil {
|
||||
return "", &badRequestError{msg: "параметр " + name + " должен быть корректным UUID"}
|
||||
}
|
||||
|
||||
return id.String(), nil
|
||||
}
|
||||
|
||||
func respondError(c *gin.Context, err error) {
|
||||
reqID := middleware.GetRequestID(c)
|
||||
c.JSON(dto.StatusFromError(err), dto.ErrorFromDomain(err, reqID))
|
||||
}
|
||||
|
||||
// respondBasicChallenge выставляет WWW-Authenticate для 401 на /auth/sessions.
|
||||
// На не-401 ответах заголовок не ставится как по контракту нужно
|
||||
func respondBasicChallenge(c *gin.Context, err error) {
|
||||
if dto.StatusFromError(err) == 401 {
|
||||
c.Header("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
}
|
||||
respondError(c, err)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
"high-loud-apps-labs/internal/httpapi/middleware"
|
||||
"high-loud-apps-labs/internal/service"
|
||||
)
|
||||
|
||||
type UserHandler struct {
|
||||
users *service.UserService
|
||||
}
|
||||
|
||||
func NewUserHandler(users *service.UserService) *UserHandler {
|
||||
return &UserHandler{users: users}
|
||||
}
|
||||
|
||||
func (h *UserHandler) Create(c *gin.Context) {
|
||||
var req dto.CreateUserRequest
|
||||
if err := bindStrictJSON(c, &req); err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
u, err := h.users.Create(c.Request.Context(), req.Username, req.DisplayName, req.Password)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, dto.UserFromDomain(u))
|
||||
}
|
||||
|
||||
func (h *UserHandler) Current(c *gin.Context) {
|
||||
u := middleware.CurrentUser(c)
|
||||
if u == nil {
|
||||
respondError(c, &badRequestError{msg: "нет текущего пользователя"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.UserFromDomain(u))
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
)
|
||||
|
||||
func Auth(users domain.UserRepository) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
id := c.GetHeader("X-User-Id")
|
||||
if id == "" {
|
||||
abortUnauthorized(c, "требуется X-User-Id")
|
||||
return
|
||||
}
|
||||
|
||||
u, err := users.GetByID(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
abortUnauthorized(c, "неизвестный пользователь")
|
||||
return
|
||||
}
|
||||
|
||||
c.Set(CurrentUserKey, u)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func abortUnauthorized(c *gin.Context, msg string) {
|
||||
reqID := GetRequestID(c)
|
||||
body := dto.ErrorFromDomain(
|
||||
&domain.UnauthorizedError{Reason: msg},
|
||||
reqID,
|
||||
)
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, body)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
"high-loud-apps-labs/internal/service"
|
||||
)
|
||||
|
||||
const authTimeout = 3 * time.Second
|
||||
|
||||
// BearerAuth читает Authorization: Bearer <token>, проверяет сессию
|
||||
// через SessionService и кладёт пользователя и токен в контекст.
|
||||
func BearerAuth(sessions *service.SessionService) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
token, ok := parseBearerToken(c)
|
||||
if !ok {
|
||||
abortBearer(c, "требуется Bearer")
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), authTimeout)
|
||||
defer cancel()
|
||||
|
||||
user, err := sessions.Resolve(ctx, token)
|
||||
if err != nil {
|
||||
abortBearerWithErr(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.Set(CurrentUserKey, user)
|
||||
c.Set(CurrentTokenKey, token)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// parseBearerToken читает Authorization: Bearer <opaque-token>.
|
||||
func parseBearerToken(c *gin.Context) (string, bool) {
|
||||
const prefix = "Bearer "
|
||||
auth := c.GetHeader("Authorization")
|
||||
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
|
||||
return "", false
|
||||
}
|
||||
token := strings.TrimSpace(auth[len(prefix):])
|
||||
if token == "" {
|
||||
return "", false
|
||||
}
|
||||
return token, true
|
||||
}
|
||||
|
||||
func abortBearer(c *gin.Context, reason string) {
|
||||
abortBearerWithErr(c, &domain.UnauthorizedError{Reason: reason})
|
||||
}
|
||||
|
||||
// abortBearerWithErr формирует ответ на ошибку аутентификации.
|
||||
// Заголовок WWW-Authenticate: Bearer выставляется только на 401;
|
||||
// при 503 (недоступность БД/кэша) — обычный ответ ошибки без challenge.
|
||||
func abortBearerWithErr(c *gin.Context, err error) {
|
||||
reqID := GetRequestID(c)
|
||||
status := dto.StatusFromError(err)
|
||||
if status == 401 {
|
||||
c.Header("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
}
|
||||
c.AbortWithStatusJSON(status, dto.ErrorFromDomain(err, reqID))
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
CurrentUserKey = "current_user"
|
||||
CurrentTokenKey = "current_token"
|
||||
)
|
||||
|
||||
func CurrentUser(c *gin.Context) *domain.User {
|
||||
if v, ok := c.Get(CurrentUserKey); ok {
|
||||
if u, ok := v.(*domain.User); ok {
|
||||
return u
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func CurrentToken(c *gin.Context) string {
|
||||
if v, ok := c.Get(CurrentTokenKey); ok {
|
||||
if s, ok := v.(string); ok {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const InstanceIDHeader = "X-Instance-Id"
|
||||
|
||||
var instanceID = resolveInstanceID()
|
||||
|
||||
func resolveInstanceID() string {
|
||||
if v := os.Getenv("INSTANCE_ID"); v != "" {
|
||||
return v
|
||||
}
|
||||
if v, err := os.Hostname(); err == nil && v != "" {
|
||||
return v
|
||||
}
|
||||
return uuid.NewString()
|
||||
}
|
||||
|
||||
func Instance() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Writer.Header().Set(InstanceIDHeader, instanceID)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func GetInstanceID() string { return instanceID }
|
||||
@@ -0,0 +1,32 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
RequestIDKey = "request_id"
|
||||
RequestIDHeader = "X-Request-Id"
|
||||
)
|
||||
|
||||
func RequestID() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
id := c.GetHeader(RequestIDHeader)
|
||||
if id == "" {
|
||||
id = uuid.NewString()
|
||||
}
|
||||
c.Set(RequestIDKey, id)
|
||||
c.Writer.Header().Set(RequestIDHeader, id)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func GetRequestID(c *gin.Context) string {
|
||||
if v, ok := c.Get(RequestIDKey); ok {
|
||||
if s, ok := v.(string); ok {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/httpapi/handler"
|
||||
"high-loud-apps-labs/internal/httpapi/middleware"
|
||||
)
|
||||
|
||||
type Handlers struct {
|
||||
Health *handler.HealthHandler
|
||||
User *handler.UserHandler
|
||||
Chat *handler.ChatHandler
|
||||
Message *handler.MessageHandler
|
||||
Auth *handler.AuthHandler
|
||||
Attachment *handler.AttachmentHandler
|
||||
}
|
||||
|
||||
func NewRouter(h Handlers, auth gin.HandlerFunc) *gin.Engine {
|
||||
gin.EnableJsonDecoderDisallowUnknownFields()
|
||||
|
||||
r := gin.New()
|
||||
r.Use(gin.Logger())
|
||||
r.Use(gin.Recovery())
|
||||
r.Use(middleware.RequestID())
|
||||
r.Use(middleware.Instance())
|
||||
|
||||
r.GET("/health/live", h.Health.Live)
|
||||
r.GET("/health/ready", h.Health.Ready)
|
||||
|
||||
api := r.Group("/api/v1")
|
||||
{
|
||||
api.POST("/users", h.User.Create)
|
||||
api.POST("/auth/sessions", h.Auth.CreateSession)
|
||||
}
|
||||
|
||||
protected := api.Group("")
|
||||
protected.Use(auth)
|
||||
{
|
||||
protected.DELETE("/auth/sessions/current", h.Auth.RevokeCurrent)
|
||||
|
||||
protected.GET("/users/me", h.User.Current)
|
||||
protected.POST("/chats", h.Chat.Create)
|
||||
protected.GET("/chats", h.Chat.List)
|
||||
protected.GET("/chats/:chat_id", h.Chat.Get)
|
||||
protected.POST("/chats/:chat_id/messages", h.Message.Create)
|
||||
protected.GET("/chats/:chat_id/messages", h.Message.List)
|
||||
|
||||
if h.Attachment != nil {
|
||||
protected.POST("/chats/:chat_id/attachments", h.Attachment.Upload)
|
||||
protected.GET("/attachments/:attachment_id", h.Attachment.Get)
|
||||
protected.GET("/attachments/:attachment_id/content", h.Attachment.Content)
|
||||
}
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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}
|
||||
}
|
||||
@@ -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, ¶llelism); 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)
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
func (r *ChatRepo) Create(ctx context.Context, chat *domain.Chat) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
stored := *chat
|
||||
stored.MemberIDs = append([]string(nil), chat.MemberIDs...)
|
||||
r.chats[chat.ID] = &stored
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *ChatRepo) GetByID(ctx context.Context, id string) (*domain.Chat, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
c, ok := r.chats[id]
|
||||
if !ok {
|
||||
return nil, &domain.NotFoundError{Entity: "chat", ID: id}
|
||||
}
|
||||
copy := *c
|
||||
copy.MemberIDs = append([]string(nil), c.MemberIDs...)
|
||||
return ©, nil
|
||||
}
|
||||
|
||||
func (r *ChatRepo) ListByMember(ctx context.Context, userID string, limit int, cursor *string) ([]domain.Chat, *string, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
scope := "chats:" + userID
|
||||
|
||||
all := make([]domain.Chat, 0)
|
||||
for _, c := range r.chats {
|
||||
for _, m := range c.MemberIDs {
|
||||
if m == userID {
|
||||
copy := *c
|
||||
copy.MemberIDs = append([]string(nil), c.MemberIDs...)
|
||||
all = append(all, copy)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
slices.SortFunc(all, func(a, b domain.Chat) int {
|
||||
if lessThan(a.CreatedAt, a.ID, b.CreatedAt, b.ID) {
|
||||
return -1
|
||||
}
|
||||
if lessThan(b.CreatedAt, b.ID, a.CreatedAt, a.ID) {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
|
||||
start := 0
|
||||
if cursor != nil {
|
||||
t, id, err := decodeCursor(*cursor, scope)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
start = len(all)
|
||||
for i, c := range all {
|
||||
if lessThan(t, id, c.CreatedAt, c.ID) {
|
||||
start = i
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if start >= len(all) {
|
||||
return []domain.Chat{}, nil, nil
|
||||
}
|
||||
end := start + limit
|
||||
if end > len(all) {
|
||||
end = len(all)
|
||||
}
|
||||
page := all[start:end]
|
||||
|
||||
var next *string
|
||||
if end < len(all) {
|
||||
last := page[len(page)-1]
|
||||
c := encodeCursor(scope, last.CreatedAt, last.ID)
|
||||
next = &c
|
||||
}
|
||||
|
||||
return page, next, nil
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
func encodeCursor(scope string, createdAt time.Time, id string) string {
|
||||
raw := scope + "|" + createdAt.UTC().Format(time.RFC3339Nano) + "|" + id
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
func decodeCursor(cursor, expectedScope string) (time.Time, string, error) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return time.Time{}, "", badCursor()
|
||||
}
|
||||
parts := strings.SplitN(string(data), "|", 3)
|
||||
if len(parts) != 3 {
|
||||
return time.Time{}, "", badCursor()
|
||||
}
|
||||
if parts[0] != expectedScope {
|
||||
return time.Time{}, "", badCursor()
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil {
|
||||
return time.Time{}, "", badCursor()
|
||||
}
|
||||
return t, parts[2], nil
|
||||
}
|
||||
|
||||
func badCursor() error {
|
||||
return &domain.ValidationError{
|
||||
Field: "cursor",
|
||||
Message: "некорректный формат",
|
||||
}
|
||||
}
|
||||
|
||||
func lessThan(aTime time.Time, aID string, bTime time.Time, bID string) bool {
|
||||
if aTime.Equal(bTime) {
|
||||
return aID < bID
|
||||
}
|
||||
return aTime.Before(bTime)
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
func (r *MessageRepo) Create(ctx context.Context, message *domain.Message) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
stored := *message
|
||||
r.messages[message.ChatID] = append(r.messages[message.ChatID], stored)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *MessageRepo) ListByChat(ctx context.Context, chatID string, limit int, cursor *string) ([]domain.Message, *string, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
scope := "messages:" + chatID
|
||||
|
||||
var (
|
||||
afterTime time.Time
|
||||
afterID string
|
||||
hasCursor bool
|
||||
)
|
||||
if cursor != nil {
|
||||
t, id, err := decodeCursor(*cursor, scope)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
afterTime = t
|
||||
afterID = id
|
||||
hasCursor = true
|
||||
}
|
||||
|
||||
src := r.messages[chatID]
|
||||
if len(src) == 0 {
|
||||
return []domain.Message{}, nil, nil
|
||||
}
|
||||
|
||||
all := make([]domain.Message, len(src))
|
||||
copy(all, src)
|
||||
|
||||
slices.SortFunc(all, func(a, b domain.Message) int {
|
||||
if lessThan(a.CreatedAt, a.ID, b.CreatedAt, b.ID) {
|
||||
return -1
|
||||
}
|
||||
if lessThan(b.CreatedAt, b.ID, a.CreatedAt, a.ID) {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
|
||||
start := 0
|
||||
if hasCursor {
|
||||
start = len(all)
|
||||
for i, m := range all {
|
||||
if lessThan(afterTime, afterID, m.CreatedAt, m.ID) {
|
||||
start = i
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if start >= len(all) {
|
||||
return []domain.Message{}, nil, nil
|
||||
}
|
||||
end := start + limit
|
||||
if end > len(all) {
|
||||
end = len(all)
|
||||
}
|
||||
page := all[start:end]
|
||||
|
||||
var next *string
|
||||
if end < len(all) {
|
||||
last := page[len(page)-1]
|
||||
c := encodeCursor(scope, last.CreatedAt, last.ID)
|
||||
next = &c
|
||||
}
|
||||
|
||||
return page, next, nil
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type Storage struct {
|
||||
mu sync.RWMutex
|
||||
users map[string]*domain.User
|
||||
chats map[string]*domain.Chat
|
||||
messages map[string][]domain.Message
|
||||
}
|
||||
|
||||
func New() *Storage {
|
||||
return &Storage{
|
||||
users: make(map[string]*domain.User),
|
||||
chats: make(map[string]*domain.Chat),
|
||||
messages: make(map[string][]domain.Message),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Storage) Users() *UserRepo { return &UserRepo{s} }
|
||||
func (s *Storage) Chats() *ChatRepo { return &ChatRepo{s} }
|
||||
func (s *Storage) Messages() *MessageRepo { return &MessageRepo{s} }
|
||||
|
||||
type UserRepo struct{ *Storage }
|
||||
type ChatRepo struct{ *Storage }
|
||||
type MessageRepo struct{ *Storage }
|
||||
|
||||
var _ domain.UserRepository = (*UserRepo)(nil)
|
||||
var _ domain.ChatRepository = (*ChatRepo)(nil)
|
||||
var _ domain.MessageRepository = (*MessageRepo)(nil)
|
||||
@@ -0,0 +1,59 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
func (r *UserRepo) Create(ctx context.Context, user *domain.User) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
for _, u := range r.users {
|
||||
if u.Username == user.Username {
|
||||
return &domain.AlreadyExistsError{
|
||||
Entity: "user",
|
||||
Field: "username",
|
||||
Value: user.Username,
|
||||
}
|
||||
}
|
||||
}
|
||||
stored := *user
|
||||
r.users[user.ID] = &stored
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *UserRepo) GetByID(ctx context.Context, id string) (*domain.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
u, ok := r.users[id]
|
||||
if !ok {
|
||||
return nil, &domain.NotFoundError{Entity: "user", ID: id}
|
||||
}
|
||||
copy := *u
|
||||
return ©, nil
|
||||
}
|
||||
|
||||
func (r *UserRepo) GetByUsername(ctx context.Context, username string) (*domain.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
for _, u := range r.users {
|
||||
if u.Username == username {
|
||||
copy := *u
|
||||
return ©, nil
|
||||
}
|
||||
}
|
||||
return nil, &domain.NotFoundError{Entity: "user", ID: username}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"time"
|
||||
)
|
||||
|
||||
// pending -> ready (успешный upload)
|
||||
// pending -> failed (отказ upload или reconciler)
|
||||
type AttachmentRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewAttachmentRepo(pool *pgxpool.Pool) *AttachmentRepo {
|
||||
return &AttachmentRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) Create(ctx context.Context, a *domain.Attachment) error {
|
||||
const q = `
|
||||
INSERT INTO attachments
|
||||
(id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
object_key, status, error_code, created_at, updated_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5, $6, $7, $8, $9, NULL, $10, $10)`
|
||||
_, err := r.pool.Exec(ctx, q,
|
||||
a.ID, a.ChatID, a.OwnerID, a.Filename, a.ContentType, a.SizeBytes,
|
||||
a.SHA256, a.ObjectKey, string(a.Status), a.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
if uniqueViolation(err) {
|
||||
return &domain.AlreadyExistsError{
|
||||
Entity: "attachment",
|
||||
Field: "object_key",
|
||||
Value: a.ObjectKey,
|
||||
}
|
||||
}
|
||||
if foreignKeyViolation(err) {
|
||||
return &domain.NotFoundError{Entity: "chat", ID: a.ChatID}
|
||||
}
|
||||
if checkViolation(err) {
|
||||
return &domain.ValidationError{
|
||||
Field: "attachment",
|
||||
Message: "нарушено ограничение целостности",
|
||||
}
|
||||
}
|
||||
return mapError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) GetByID(ctx context.Context, id string) (*domain.Attachment, error) {
|
||||
const q = `
|
||||
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
object_key, status, error_code, created_at, updated_at
|
||||
FROM attachments
|
||||
WHERE id = $1::uuid
|
||||
`
|
||||
a := &domain.Attachment{}
|
||||
var status string
|
||||
err := r.pool.QueryRow(ctx, q, id).
|
||||
Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType,
|
||||
&a.SizeBytes, &a.SHA256, &a.ObjectKey, &status, &a.ErrorCode,
|
||||
&a.CreatedAt, &a.UpdatedAt)
|
||||
if err != nil {
|
||||
return nil, notFound(err, "attachment", id)
|
||||
}
|
||||
a.Status = domain.AttachmentStatus(status)
|
||||
return a, nil
|
||||
}
|
||||
|
||||
// MarkReady переводит pending -> ready. Идемпотентна.
|
||||
func (r *AttachmentRepo) MarkReady(ctx context.Context, id string) error {
|
||||
const q = `
|
||||
UPDATE attachments
|
||||
SET status = 'ready', updated_at = now()
|
||||
WHERE id = $1::uuid AND status = 'pending'
|
||||
`
|
||||
tag, err := r.pool.Exec(ctx, q, id)
|
||||
if err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
if tag.RowsAffected() > 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var status string
|
||||
err = r.pool.QueryRow(ctx, `SELECT status FROM attachments WHERE id = $1::uuid`, id).
|
||||
Scan(&status)
|
||||
if err != nil {
|
||||
return notFound(err, "attachment", id)
|
||||
}
|
||||
switch domain.AttachmentStatus(status) {
|
||||
case domain.AttachmentStatusReady:
|
||||
return nil // idempotent no-op
|
||||
case domain.AttachmentStatusFailed:
|
||||
return &domain.ConflictError{Reason: "нельзя перевести failed-вложение в ready"}
|
||||
default:
|
||||
return &domain.ConflictError{Reason: "некорректное состояние вложения"}
|
||||
}
|
||||
}
|
||||
|
||||
// MarkFailed переводит pending -> failed. Идемпотентна.
|
||||
func (r *AttachmentRepo) MarkFailed(ctx context.Context, id, errorCode string) error {
|
||||
if errorCode == "" {
|
||||
return &domain.ValidationError{Field: "error_code", Message: "не может быть пустым"}
|
||||
}
|
||||
const q = `
|
||||
UPDATE attachments
|
||||
SET status = 'failed', error_code = $2, updated_at = now()
|
||||
WHERE id = $1::uuid AND status = 'pending'
|
||||
`
|
||||
tag, err := r.pool.Exec(ctx, q, id, errorCode)
|
||||
if err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
if tag.RowsAffected() > 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var status string
|
||||
err = r.pool.QueryRow(ctx, `SELECT status FROM attachments WHERE id = $1::uuid`, id).
|
||||
Scan(&status)
|
||||
if err != nil {
|
||||
return notFound(err, "attachment", id)
|
||||
}
|
||||
switch domain.AttachmentStatus(status) {
|
||||
case domain.AttachmentStatusFailed, domain.AttachmentStatusReady:
|
||||
return nil
|
||||
default:
|
||||
return &domain.ConflictError{Reason: "некорректное состояние вложения"}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) ListStalePending(ctx context.Context, olderThan time.Time, limit int) ([]domain.Attachment, error) {
|
||||
if limit <= 0 {
|
||||
return []domain.Attachment{}, nil
|
||||
}
|
||||
const q = `
|
||||
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
object_key, status, error_code, created_at, updated_at
|
||||
FROM attachments
|
||||
WHERE status = 'pending' AND created_at < $1
|
||||
ORDER BY created_at
|
||||
LIMIT $2
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, olderThan, limit)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
out := make([]domain.Attachment, 0, limit)
|
||||
for rows.Next() {
|
||||
var a domain.Attachment
|
||||
var status string
|
||||
if err := rows.Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename,
|
||||
&a.ContentType, &a.SizeBytes, &a.SHA256, &a.ObjectKey,
|
||||
&status, &a.ErrorCode, &a.CreatedAt, &a.UpdatedAt); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
a.Status = domain.AttachmentStatus(status)
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, mapError(rows.Err())
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) DeletePending(ctx context.Context, id string) error {
|
||||
const q = `DELETE FROM attachments WHERE id = $1::uuid AND status = 'pending'`
|
||||
if _, err := r.pool.Exec(ctx, q, id); err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) ExistingKeys(ctx context.Context, keys []string) ([]string, error) {
|
||||
if len(keys) == 0 {
|
||||
return []string{}, nil
|
||||
}
|
||||
const q = `SELECT object_key FROM attachments WHERE object_key = ANY($1::text[])`
|
||||
rows, err := r.pool.Query(ctx, q, keys)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
out := make([]string, 0, len(keys))
|
||||
for rows.Next() {
|
||||
var k string
|
||||
if err := rows.Scan(&k); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
out = append(out, k)
|
||||
}
|
||||
return out, mapError(rows.Err())
|
||||
}
|
||||
|
||||
var _ domain.AttachmentRepository = (*AttachmentRepo)(nil)
|
||||
@@ -0,0 +1,195 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type ChatRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewChatRepo(pool *pgxpool.Pool) *ChatRepo {
|
||||
return &ChatRepo{pool: pool}
|
||||
}
|
||||
|
||||
// Create атомарно создаёт чат и его участников.
|
||||
func (r *ChatRepo) Create(ctx context.Context, chat *domain.Chat) error {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
const qChat = `INSERT INTO chats (id, title, created_at) VALUES ($1::uuid, $2, $3)`
|
||||
if _, err := tx.Exec(ctx, qChat, chat.ID, chat.Title, chat.CreatedAt); err != nil {
|
||||
if checkViolation(err) {
|
||||
return &domain.ValidationError{Field: "chat", Message: "нарушено ограничение целостности"}
|
||||
}
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
const qMember = `INSERT INTO chat_members (chat_id, user_id) VALUES ($1::uuid, $2::uuid)`
|
||||
for _, uid := range chat.MemberIDs {
|
||||
if _, err := tx.Exec(ctx, qMember, chat.ID, uid); err != nil {
|
||||
if foreignKeyViolation(err) {
|
||||
return &domain.ValidationError{
|
||||
Field: "member_ids",
|
||||
Message: "неизвестный участник " + uid,
|
||||
}
|
||||
}
|
||||
if uniqueViolation(err) {
|
||||
return &domain.ValidationError{
|
||||
Field: "member_ids",
|
||||
Message: "дубликаты запрещены",
|
||||
}
|
||||
}
|
||||
return mapError(err)
|
||||
}
|
||||
}
|
||||
|
||||
return mapError(tx.Commit(ctx))
|
||||
}
|
||||
|
||||
func (r *ChatRepo) GetByID(ctx context.Context, id string) (*domain.Chat, error) {
|
||||
const q = `SELECT id, title, created_at FROM chats WHERE id = $1::uuid`
|
||||
c := &domain.Chat{}
|
||||
err := r.pool.QueryRow(ctx, q, id).Scan(&c.ID, &c.Title, &c.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, notFound(err, "chat", id)
|
||||
}
|
||||
members, err := r.loadMembers(ctx, []string{c.ID})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.MemberIDs = members[c.ID]
|
||||
if c.MemberIDs == nil {
|
||||
c.MemberIDs = []string{}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (r *ChatRepo) ListByMember(ctx context.Context, userID string, limit int, cursor *string) ([]domain.Chat, *string, error) {
|
||||
scope := "chats:" + userID
|
||||
|
||||
var (
|
||||
afterTime time.Time
|
||||
afterID string
|
||||
hasCursor bool
|
||||
)
|
||||
if cursor != nil {
|
||||
t, id, err := decodeCursor(*cursor, scope)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
afterTime = t
|
||||
afterID = id
|
||||
hasCursor = true
|
||||
}
|
||||
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if hasCursor {
|
||||
const q = `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE m.user_id = $1::uuid
|
||||
AND (c.created_at, c.id) > ($2, $3::uuid)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4
|
||||
`
|
||||
rows, err = r.pool.Query(ctx, q, userID, afterTime, afterID, limit+1)
|
||||
} else {
|
||||
const q = `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE m.user_id = $1::uuid
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $2
|
||||
`
|
||||
rows, err = r.pool.Query(ctx, q, userID, limit+1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, mapError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
page := make([]domain.Chat, 0, limit)
|
||||
for rows.Next() {
|
||||
var c domain.Chat
|
||||
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
|
||||
return nil, nil, mapError(err)
|
||||
}
|
||||
page = append(page, c)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, mapError(err)
|
||||
}
|
||||
|
||||
var next *string
|
||||
if len(page) > limit {
|
||||
page = page[:limit]
|
||||
last := page[len(page)-1]
|
||||
c := encodeCursor(scope, last.CreatedAt, last.ID)
|
||||
next = &c
|
||||
}
|
||||
|
||||
if len(page) > 0 {
|
||||
ids := make([]string, len(page))
|
||||
for i := range page {
|
||||
ids[i] = page[i].ID
|
||||
}
|
||||
members, err := r.loadMembers(ctx, ids)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
for i := range page {
|
||||
if m, ok := members[page[i].ID]; ok {
|
||||
page[i].MemberIDs = m
|
||||
} else {
|
||||
page[i].MemberIDs = []string{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return page, next, nil
|
||||
}
|
||||
|
||||
// loadMembers одним запросом собирает участников для указанных чатов.
|
||||
func (r *ChatRepo) loadMembers(ctx context.Context, chatIDs []string) (map[string][]string, error) {
|
||||
if len(chatIDs) == 0 {
|
||||
return map[string][]string{}, nil
|
||||
}
|
||||
const q = `
|
||||
SELECT chat_id, user_id
|
||||
FROM chat_members
|
||||
WHERE chat_id = ANY($1::uuid[])
|
||||
ORDER BY chat_id, user_id
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, chatIDs)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
result := make(map[string][]string, len(chatIDs))
|
||||
for rows.Next() {
|
||||
var chatID, userID string
|
||||
if err := rows.Scan(&chatID, &userID); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
result[chatID] = append(result[chatID], userID)
|
||||
}
|
||||
return result, mapError(rows.Err())
|
||||
}
|
||||
|
||||
var _ domain.ChatRepository = (*ChatRepo)(nil)
|
||||
@@ -0,0 +1,46 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Взял за основу что в inmemery делал
|
||||
func encodeCursor(scope string, createdAt time.Time, id string) string {
|
||||
raw := scope + "|" + createdAt.UTC().Format(time.RFC3339Nano) + "|" + id
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
func decodeCursor(cursor, expectedScope string) (time.Time, string, error) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return time.Time{}, "", badCursor()
|
||||
}
|
||||
parts := strings.SplitN(string(data), "|", 3)
|
||||
if len(parts) != 3 {
|
||||
return time.Time{}, "", badCursor()
|
||||
}
|
||||
if parts[0] != expectedScope {
|
||||
return time.Time{}, "", badCursor()
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil {
|
||||
return time.Time{}, "", badCursor()
|
||||
}
|
||||
if _, err := uuid.Parse(parts[2]); err != nil {
|
||||
return time.Time{}, "", badCursor()
|
||||
}
|
||||
return t, parts[2], nil
|
||||
}
|
||||
|
||||
func badCursor() error {
|
||||
return &domain.ValidationError{
|
||||
Field: "cursor",
|
||||
Message: "некорректный формат",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/pressly/goose/v3"
|
||||
|
||||
"high-loud-apps-labs/migrations"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
URL string
|
||||
MaxConns int32
|
||||
MinConns int32
|
||||
MaxConnLifetime time.Duration
|
||||
MaxConnIdleTime time.Duration
|
||||
ConnectTimeout time.Duration
|
||||
}
|
||||
|
||||
func Connect(ctx context.Context, cfg Config) (*pgxpool.Pool, error) {
|
||||
if cfg.URL == "" {
|
||||
return nil, fmt.Errorf("DATABASE_URL пустой")
|
||||
}
|
||||
|
||||
poolCfg, err := pgxpool.ParseConfig(cfg.URL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("разбор DATABASE_URL: %w", err)
|
||||
}
|
||||
if cfg.MaxConns > 0 {
|
||||
poolCfg.MaxConns = cfg.MaxConns
|
||||
}
|
||||
if cfg.MinConns > 0 {
|
||||
poolCfg.MinConns = cfg.MinConns
|
||||
}
|
||||
if cfg.MaxConnLifetime > 0 {
|
||||
poolCfg.MaxConnLifetime = cfg.MaxConnLifetime
|
||||
}
|
||||
if cfg.MaxConnIdleTime > 0 {
|
||||
poolCfg.MaxConnIdleTime = cfg.MaxConnIdleTime
|
||||
}
|
||||
if cfg.ConnectTimeout > 0 {
|
||||
poolCfg.ConnConfig.ConnectTimeout = cfg.ConnectTimeout
|
||||
}
|
||||
poolCfg.HealthCheckPeriod = 10 * time.Second
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolCfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("создание пула: %w", err)
|
||||
}
|
||||
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping БД: %w", err)
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
func RunMigrations(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
db := stdlib.OpenDBFromPool(pool)
|
||||
|
||||
goose.SetBaseFS(migrations.FS)
|
||||
if err := goose.SetDialect("postgres"); err != nil {
|
||||
return fmt.Errorf("goose dialect: %w", err)
|
||||
}
|
||||
if err := goose.UpContext(ctx, db, "."); err != nil {
|
||||
return fmt.Errorf("применение миграций: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jackc/pgerrcode"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type coded interface {
|
||||
Code() domain.ErrorCode
|
||||
}
|
||||
|
||||
// mapError переводит ошибки драйвера в доменные.
|
||||
func mapError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var c coded
|
||||
if errors.As(err, &c) {
|
||||
return err
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return &domain.UnavailableError{Reason: "превышено время ожидания БД"}
|
||||
}
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return &domain.UnavailableError{Reason: "запрос отменён"}
|
||||
}
|
||||
return &domain.UnavailableError{Reason: err.Error()}
|
||||
}
|
||||
|
||||
func notFound(err error, entity, id string) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return &domain.NotFoundError{Entity: entity, ID: id}
|
||||
}
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
func uniqueViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
return pgErr.Code == pgerrcode.UniqueViolation
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func foreignKeyViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
return pgErr.Code == pgerrcode.ForeignKeyViolation
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func checkViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
return pgErr.Code == pgerrcode.CheckViolation
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type MessageRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewMessageRepo(pool *pgxpool.Pool) *MessageRepo {
|
||||
return &MessageRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *MessageRepo) Create(ctx context.Context, m *domain.Message) error {
|
||||
const q = `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, q, m.ID, m.ChatID, m.SenderID, m.Text, m.CreatedAt)
|
||||
if err != nil {
|
||||
if foreignKeyViolation(err) {
|
||||
return &domain.NotFoundError{Entity: "chat", ID: m.ChatID}
|
||||
}
|
||||
if checkViolation(err) {
|
||||
return &domain.ValidationError{Field: "text", Message: "нарушено ограничение"}
|
||||
}
|
||||
return mapError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *MessageRepo) CreateIdempotent(
|
||||
ctx context.Context,
|
||||
scope domain.IdempotencyScope,
|
||||
requestHash []byte,
|
||||
fresh *domain.Message,
|
||||
freshResponse []byte,
|
||||
ttl time.Duration,
|
||||
) (*domain.CreateIdempotentResult, error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
// 1) Убираем просроченную запись, чтобы ON CONFLICT сработал
|
||||
// только на живой, а не на истёкшей строке.
|
||||
if _, err := tx.Exec(ctx, `
|
||||
DELETE FROM idempotency_keys
|
||||
WHERE user_id = $1::uuid AND method = $2 AND path = $3 AND key = $4
|
||||
AND expires_at <= now()
|
||||
`, scope.UserID, scope.Method, scope.Path, scope.Key); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
|
||||
// 2) Резервируем слот. Если параллельная реплика уже вставила —
|
||||
// Postgres заблокирует конфликтный INSERT и мы увидим RowsAffected=0
|
||||
// только после того, как конкурент закоммитит или откатится.
|
||||
expiresAt := time.Now().UTC().Add(ttl)
|
||||
tag, err := tx.Exec(ctx, `
|
||||
INSERT INTO idempotency_keys
|
||||
(user_id, method, path, key, request_hash, response_status, response_body, expires_at)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5, $6, $7, $8)
|
||||
ON CONFLICT (user_id, method, path, key) DO NOTHING
|
||||
`, scope.UserID, scope.Method, scope.Path, scope.Key,
|
||||
requestHash, http.StatusCreated, freshResponse, expiresAt)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
|
||||
// 3) Слот занят — читаем сохранённый ответ в этой же транзакции.
|
||||
if tag.RowsAffected() == 0 {
|
||||
var (
|
||||
storedHash []byte
|
||||
storedStatus int
|
||||
storedBody []byte
|
||||
)
|
||||
err := tx.QueryRow(ctx, `
|
||||
SELECT request_hash, response_status, response_body
|
||||
FROM idempotency_keys
|
||||
WHERE user_id = $1::uuid AND method = $2 AND path = $3 AND key = $4
|
||||
`, scope.UserID, scope.Method, scope.Path, scope.Key).
|
||||
Scan(&storedHash, &storedStatus, &storedBody)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(storedHash, requestHash) {
|
||||
return nil, &domain.IdempotencyConflictError{Key: scope.Key}
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
return &domain.CreateIdempotentResult{
|
||||
Status: storedStatus,
|
||||
Body: storedBody,
|
||||
Replayed: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 4) Слот наш — валидируем вложения, вставляем сообщение, линкуем
|
||||
// вложения. Всё в одной транзакции: при ошибке на любом шаге
|
||||
// откатывается и idempotency-ключ, и сообщение, и связи.
|
||||
if err := r.validateAttachments(ctx, tx, fresh.ChatID, fresh.AttachmentIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
|
||||
`, fresh.ID, fresh.ChatID, fresh.SenderID, fresh.Text, fresh.CreatedAt); err != nil {
|
||||
if foreignKeyViolation(err) {
|
||||
return nil, &domain.NotFoundError{Entity: "chat", ID: fresh.ChatID}
|
||||
}
|
||||
if checkViolation(err) {
|
||||
return nil, &domain.ValidationError{Field: "text", Message: "нарушено ограничение"}
|
||||
}
|
||||
return nil, mapError(err)
|
||||
}
|
||||
|
||||
if err := r.linkAttachments(ctx, tx, fresh.ID, fresh.AttachmentIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
return &domain.CreateIdempotentResult{
|
||||
Status: http.StatusCreated,
|
||||
Body: freshResponse,
|
||||
Replayed: false,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *MessageRepo) ListByChat(ctx context.Context, chatID string, limit int, cursor *string) ([]domain.Message, *string, error) {
|
||||
scope := "messages:" + chatID
|
||||
|
||||
var (
|
||||
afterTime time.Time
|
||||
afterID string
|
||||
hasCursor bool
|
||||
)
|
||||
if cursor != nil {
|
||||
t, id, err := decodeCursor(*cursor, scope)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
afterTime = t
|
||||
afterID = id
|
||||
hasCursor = true
|
||||
}
|
||||
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if hasCursor {
|
||||
const q = `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1::uuid
|
||||
AND (created_at, id) > ($2, $3::uuid)
|
||||
ORDER BY created_at, id
|
||||
LIMIT $4
|
||||
`
|
||||
rows, err = r.pool.Query(ctx, q, chatID, afterTime, afterID, limit+1)
|
||||
} else {
|
||||
const q = `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1::uuid
|
||||
ORDER BY created_at, id
|
||||
LIMIT $2
|
||||
`
|
||||
rows, err = r.pool.Query(ctx, q, chatID, limit+1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
page := make([]domain.Message, 0, limit)
|
||||
for rows.Next() {
|
||||
var m domain.Message
|
||||
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
page = append(page, m)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
var next *string
|
||||
if len(page) > limit {
|
||||
page = page[:limit]
|
||||
last := page[len(page)-1]
|
||||
c := encodeCursor(scope, last.CreatedAt, last.ID)
|
||||
next = &c
|
||||
}
|
||||
|
||||
if len(page) > 0 {
|
||||
msgIDs := make([]string, len(page))
|
||||
for i := range page {
|
||||
msgIDs[i] = page[i].ID
|
||||
}
|
||||
links, err := r.loadAttachmentIDs(ctx, msgIDs)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
for i := range page {
|
||||
if ids, ok := links[page[i].ID]; ok {
|
||||
page[i].AttachmentIDs = ids
|
||||
} else {
|
||||
page[i].AttachmentIDs = []string{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return page, next, nil
|
||||
}
|
||||
|
||||
func (r *MessageRepo) validateAttachments(ctx context.Context, tx pgx.Tx, chatID string, ids []string) error {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
const q = `SELECT id, chat_id, status FROM attachments WHERE id = ANY($1::uuid[])`
|
||||
rows, err := tx.Query(ctx, q, ids)
|
||||
if err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
type info struct {
|
||||
chatID string
|
||||
status domain.AttachmentStatus
|
||||
}
|
||||
found := make(map[string]info, len(ids))
|
||||
for rows.Next() {
|
||||
var id, chID, st string
|
||||
if err := rows.Scan(&id, &chID, &st); err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
found[id] = info{chatID: chID, status: domain.AttachmentStatus(st)}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
for _, id := range ids {
|
||||
a, ok := found[id]
|
||||
if !ok || a.chatID != chatID {
|
||||
return &domain.NotFoundError{Entity: "attachment", ID: id}
|
||||
}
|
||||
if a.status != domain.AttachmentStatusReady {
|
||||
return &domain.ConflictError{Reason: "вложение " + id + " не готово"}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *MessageRepo) linkAttachments(ctx context.Context, tx pgx.Tx, messageID string, ids []string) error {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
const q = `INSERT INTO message_attachments (message_id, attachment_id, position) VALUES ($1::uuid, $2::uuid, $3)`
|
||||
for i, id := range ids {
|
||||
if _, err := tx.Exec(ctx, q, messageID, id, int16(i)); err != nil {
|
||||
if foreignKeyViolation(err) {
|
||||
return &domain.NotFoundError{Entity: "attachment", ID: id}
|
||||
}
|
||||
if uniqueViolation(err) {
|
||||
return &domain.ValidationError{Field: "attachment_ids", Message: "дубликаты запрещены"}
|
||||
}
|
||||
if checkViolation(err) {
|
||||
return &domain.ValidationError{Field: "attachment_ids", Message: "нарушено ограничение"}
|
||||
}
|
||||
return mapError(err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *MessageRepo) loadAttachmentIDs(ctx context.Context, messageIDs []string) (map[string][]string, error) {
|
||||
if len(messageIDs) == 0 {
|
||||
return map[string][]string{}, nil
|
||||
}
|
||||
const q = `
|
||||
SELECT message_id, attachment_id
|
||||
FROM message_attachments
|
||||
WHERE message_id = ANY($1::uuid[])
|
||||
ORDER BY message_id, position
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, messageIDs)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
result := make(map[string][]string, len(messageIDs))
|
||||
for rows.Next() {
|
||||
var msgID, attID string
|
||||
if err := rows.Scan(&msgID, &attID); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
result[msgID] = append(result[msgID], attID)
|
||||
}
|
||||
return result, mapError(rows.Err())
|
||||
}
|
||||
|
||||
var _ domain.MessageRepository = (*MessageRepo)(nil)
|
||||
@@ -0,0 +1,59 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type SessionRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewSessionRepo(pool *pgxpool.Pool) *SessionRepo {
|
||||
return &SessionRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *SessionRepo) Create(ctx context.Context, s *domain.Session) error {
|
||||
const q = `
|
||||
INSERT INTO sessions (token_hash, user_id, expires_at, created_at)
|
||||
VALUES ($1, $2::uuid, $3, $4)
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, q, s.TokenHash, s.UserID, s.ExpiresAt, s.CreatedAt)
|
||||
if err != nil {
|
||||
if uniqueViolation(err) {
|
||||
return &domain.AlreadyExistsError{
|
||||
Entity: "session",
|
||||
Field: "token_hash",
|
||||
Value: "",
|
||||
}
|
||||
}
|
||||
return mapError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *SessionRepo) GetByTokenHash(ctx context.Context, tokenHash []byte) (*domain.Session, error) {
|
||||
const q = `
|
||||
SELECT token_hash, user_id, expires_at, created_at
|
||||
FROM sessions
|
||||
WHERE token_hash = $1
|
||||
`
|
||||
s := &domain.Session{}
|
||||
err := r.pool.QueryRow(ctx, q, tokenHash).
|
||||
Scan(&s.TokenHash, &s.UserID, &s.ExpiresAt, &s.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, notFound(err, "session", "")
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (r *SessionRepo) DeleteByTokenHash(ctx context.Context, tokenHash []byte) error {
|
||||
const q = `DELETE FROM sessions WHERE token_hash = $1`
|
||||
_, err := r.pool.Exec(ctx, q, tokenHash)
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
var _ domain.SessionRepository = (*SessionRepo)(nil)
|
||||
@@ -0,0 +1,19 @@
|
||||
package postgres
|
||||
|
||||
import "github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
type Storage struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool) *Storage {
|
||||
return &Storage{pool: pool}
|
||||
}
|
||||
|
||||
func (s *Storage) Pool() *pgxpool.Pool { return s.pool }
|
||||
|
||||
func (s *Storage) Users() *UserRepo { return &UserRepo{pool: s.pool} }
|
||||
func (s *Storage) Chats() *ChatRepo { return &ChatRepo{pool: s.pool} }
|
||||
func (s *Storage) Messages() *MessageRepo { return &MessageRepo{pool: s.pool} }
|
||||
func (s *Storage) Sessions() *SessionRepo { return &SessionRepo{pool: s.pool} }
|
||||
func (s *Storage) Attachments() *AttachmentRepo { return &AttachmentRepo{pool: s.pool} }
|
||||
@@ -0,0 +1,76 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type UserRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewUserRepo(pool *pgxpool.Pool) *UserRepo {
|
||||
return &UserRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *UserRepo) Create(ctx context.Context, user *domain.User) error {
|
||||
const q = `
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5)
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, q,
|
||||
user.ID, user.Username, user.DisplayName, user.PasswordHash, user.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
if uniqueViolation(err) {
|
||||
return &domain.AlreadyExistsError{
|
||||
Entity: "user",
|
||||
Field: "username",
|
||||
Value: user.Username,
|
||||
}
|
||||
}
|
||||
if checkViolation(err) {
|
||||
return &domain.ValidationError{
|
||||
Field: "user",
|
||||
Message: "нарушено ограничение целостности",
|
||||
}
|
||||
}
|
||||
return mapError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *UserRepo) GetByID(ctx context.Context, id string) (*domain.User, error) {
|
||||
const q = `
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users
|
||||
WHERE id = $1::uuid
|
||||
`
|
||||
u := &domain.User{}
|
||||
err := r.pool.QueryRow(ctx, q, id).
|
||||
Scan(&u.ID, &u.Username, &u.DisplayName, &u.PasswordHash, &u.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, notFound(err, "user", id)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (r *UserRepo) GetByUsername(ctx context.Context, username string) (*domain.User, error) {
|
||||
const q = `
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users
|
||||
WHERE username = $1
|
||||
`
|
||||
u := &domain.User{}
|
||||
err := r.pool.QueryRow(ctx, q, username).
|
||||
Scan(&u.ID, &u.Username, &u.DisplayName, &u.PasswordHash, &u.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, notFound(err, "user", username)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
var _ domain.UserRepository = (*UserRepo)(nil)
|
||||
@@ -0,0 +1,33 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func NewClient(url string) (*redis.Client, error) {
|
||||
opt, err := redis.ParseURL(url)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("разбор URL: %w", err)
|
||||
}
|
||||
|
||||
opt.DialTimeout = 700 * time.Millisecond
|
||||
opt.ReadTimeout = 700 * time.Millisecond
|
||||
opt.WriteTimeout = 700 * time.Millisecond
|
||||
opt.MaxRetries = 1
|
||||
opt.PoolSize = 10
|
||||
opt.ConnMaxIdleTime = time.Minute
|
||||
|
||||
client := redis.NewClient(opt)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
if err := client.Ping(ctx).Err(); err != nil {
|
||||
_ = client.Close()
|
||||
return nil, fmt.Errorf("ping: %w", err)
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type coded interface {
|
||||
Code() domain.ErrorCode
|
||||
}
|
||||
|
||||
// mapError переводит ошибки драйвера в доменные.
|
||||
// Любая недоступность redis (dial/read/write/context) → UnavailableError (503).
|
||||
func mapError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var c coded
|
||||
if errors.As(err, &c) {
|
||||
return err
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return &domain.UnavailableError{Reason: "превышено время ожидания redis"}
|
||||
}
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return &domain.UnavailableError{Reason: "запрос отменён"}
|
||||
}
|
||||
return &domain.UnavailableError{Reason: err.Error()}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
const sessionKeyPrefix = "session:"
|
||||
|
||||
type SessionRepo struct {
|
||||
client *redis.Client
|
||||
}
|
||||
|
||||
func NewSessionRepo(client *redis.Client) *SessionRepo {
|
||||
return &SessionRepo{client: client}
|
||||
}
|
||||
|
||||
type sessionValue struct {
|
||||
UserID string `json:"user_id"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func (r *SessionRepo) key(tokenHash []byte) string {
|
||||
return sessionKeyPrefix + hex.EncodeToString(tokenHash)
|
||||
}
|
||||
|
||||
func (r *SessionRepo) Create(ctx context.Context, s *domain.Session) error {
|
||||
ttl := time.Until(s.ExpiresAt)
|
||||
if ttl <= 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
data, err := json.Marshal(sessionValue{
|
||||
UserID: s.UserID,
|
||||
ExpiresAt: s.ExpiresAt.UTC(),
|
||||
CreatedAt: s.CreatedAt.UTC(),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("сериализация сессии: %w", err)
|
||||
}
|
||||
|
||||
return mapError(r.client.Set(ctx, r.key(s.TokenHash), data, ttl).Err())
|
||||
}
|
||||
|
||||
func (r *SessionRepo) GetByTokenHash(ctx context.Context, tokenHash []byte) (*domain.Session, error) {
|
||||
data, err := r.client.Get(ctx, r.key(tokenHash)).Bytes()
|
||||
if err != nil {
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return nil, &domain.NotFoundError{Entity: "session"}
|
||||
}
|
||||
return nil, mapError(err)
|
||||
}
|
||||
|
||||
var sv sessionValue
|
||||
if err := json.Unmarshal(data, &sv); err != nil {
|
||||
return nil, fmt.Errorf("разбор сессии: %w", err)
|
||||
}
|
||||
|
||||
return &domain.Session{
|
||||
TokenHash: tokenHash,
|
||||
UserID: sv.UserID,
|
||||
ExpiresAt: sv.ExpiresAt,
|
||||
CreatedAt: sv.CreatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *SessionRepo) DeleteByTokenHash(ctx context.Context, tokenHash []byte) error {
|
||||
return mapError(r.client.Del(ctx, r.key(tokenHash)).Err())
|
||||
}
|
||||
|
||||
var _ domain.SessionRepository = (*SessionRepo)(nil)
|
||||
@@ -0,0 +1,98 @@
|
||||
package s3
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Endpoint string
|
||||
Bucket string
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
UseSSL bool
|
||||
Region string
|
||||
}
|
||||
|
||||
type MinioStorage struct {
|
||||
client *minio.Client
|
||||
bucket string
|
||||
}
|
||||
|
||||
func New(ctx context.Context, cfg Config) (*MinioStorage, error) {
|
||||
client, err := minio.New(cfg.Endpoint, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
|
||||
Secure: cfg.UseSSL,
|
||||
Region: cfg.Region,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
exists, err := client.BucketExists(ctx, cfg.Bucket)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
if !exists {
|
||||
return nil, &domain.UnavailableError{Reason: "s3 bucket отсутствует"}
|
||||
}
|
||||
|
||||
return &MinioStorage{client: client, bucket: cfg.Bucket}, nil
|
||||
}
|
||||
|
||||
func (s *MinioStorage) Ping(ctx context.Context) error {
|
||||
_, err := s.client.BucketExists(ctx, s.bucket)
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
func (s *MinioStorage) Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error {
|
||||
_, err := s.client.PutObject(ctx, s.bucket, key, r, size, minio.PutObjectOptions{
|
||||
ContentType: contentType,
|
||||
})
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
func (s *MinioStorage) Get(ctx context.Context, key string) (io.ReadCloser, int64, string, error) {
|
||||
obj, err := s.client.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
return nil, 0, "", mapError(err)
|
||||
}
|
||||
|
||||
stat, err := obj.Stat()
|
||||
if err != nil {
|
||||
_ = obj.Close()
|
||||
return nil, 0, "", mapError(err)
|
||||
}
|
||||
|
||||
return obj, stat.Size, stat.ContentType, nil
|
||||
}
|
||||
|
||||
func (s *MinioStorage) Delete(ctx context.Context, key string) error {
|
||||
err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{})
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
func (s *MinioStorage) List(ctx context.Context, prefix string) ([]domain.ObjectInfo, error) {
|
||||
out := make([]domain.ObjectInfo, 0)
|
||||
for obj := range s.client.ListObjects(ctx, s.bucket, minio.ListObjectsOptions{
|
||||
Prefix: prefix,
|
||||
Recursive: true,
|
||||
}) {
|
||||
if obj.Err != nil {
|
||||
return nil, mapError(obj.Err)
|
||||
}
|
||||
out = append(out, domain.ObjectInfo{
|
||||
Key: obj.Key,
|
||||
LastModified: obj.LastModified,
|
||||
Size: obj.Size,
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
var _ domain.ObjectStorage = (*MinioStorage)(nil)
|
||||
@@ -0,0 +1,42 @@
|
||||
package s3
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type coded interface {
|
||||
Code() domain.ErrorCode
|
||||
}
|
||||
|
||||
func mapError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var c coded
|
||||
if errors.As(err, &c) {
|
||||
return err
|
||||
}
|
||||
var resp minio.ErrorResponse
|
||||
if errors.As(err, &resp) {
|
||||
switch resp.Code {
|
||||
case "NoSuchKey", "NotFound":
|
||||
return &domain.NotFoundError{Entity: "object"}
|
||||
case "NoSuchBucket":
|
||||
return &domain.UnavailableError{Reason: "s3 bucket отсутствует"}
|
||||
case "AccessDenied", "InvalidAccessKeyId", "SignatureDoesNotMatch":
|
||||
return &domain.UnavailableError{Reason: "s3 доступ запрещён"}
|
||||
}
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return &domain.UnavailableError{Reason: "превышено время ожидания s3"}
|
||||
}
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return &domain.UnavailableError{Reason: "запрос отменён"}
|
||||
}
|
||||
return &domain.UnavailableError{Reason: err.Error()}
|
||||
}
|
||||
Reference in New Issue
Block a user