371 lines
14 KiB
Go
371 lines
14 KiB
Go
package service
|
||
|
||
import (
|
||
"bufio"
|
||
"bytes"
|
||
"context"
|
||
"crypto/sha256"
|
||
"encoding/hex"
|
||
"errors"
|
||
"image"
|
||
_ "image/jpeg" // DecodeConfig для раннего отказа по размерам
|
||
_ "image/png"
|
||
"io"
|
||
"log/slog"
|
||
"mime"
|
||
"strings"
|
||
"time"
|
||
"unicode"
|
||
"unicode/utf8"
|
||
|
||
"github.com/google/uuid"
|
||
|
||
"github.com/charawein/mtusi2026lab6/internal/domain"
|
||
"github.com/charawein/mtusi2026lab6/internal/imagecheck"
|
||
"github.com/charawein/mtusi2026lab6/internal/repository"
|
||
"github.com/charawein/mtusi2026lab6/internal/storage"
|
||
)
|
||
|
||
// Раскладка bucket (все ключи назначает сервер, filename в них не попадает):
|
||
//
|
||
// s/{chat}/{id} — staging: проверенный оригинал до обработки
|
||
// o/{chat}/{id} — опубликованный оригинал (worker копирует из staging)
|
||
// v/{chat}/{id}/p{ver}/{variant} — варианты версии pipeline ver
|
||
// a/{chat}/{id} — оригиналы lab4 (остаются на месте)
|
||
const (
|
||
ObjectPrefix = "a/"
|
||
StagingPrefix = "s/"
|
||
OriginalPrefix = "o/"
|
||
VariantPrefix = "v/"
|
||
)
|
||
|
||
type AttachmentRepository interface {
|
||
CreateIntent(ctx context.Context, a *domain.Attachment) error
|
||
MarkQueued(ctx context.Context, a *domain.Attachment, pipelineVersion, maxAttempts int) (string, error)
|
||
DeleteIntent(ctx context.Context, id string) error
|
||
GetForMember(ctx context.Context, id, userID string) (*domain.Attachment, error)
|
||
Variants(ctx context.Context, attachmentID string, version int) ([]domain.Variant, error)
|
||
}
|
||
|
||
type AttachmentService struct {
|
||
repo AttachmentRepository
|
||
chats repository.ChatRepository
|
||
store storage.Store
|
||
maxBytes int64
|
||
maxPixels int64
|
||
pipelineVersion int
|
||
maxAttempts int
|
||
}
|
||
|
||
func NewAttachmentService(repo AttachmentRepository, chats repository.ChatRepository, store storage.Store, maxBytes, maxPixels int64, pipelineVersion, maxAttempts int) *AttachmentService {
|
||
return &AttachmentService{repo: repo, chats: chats, store: store, maxBytes: maxBytes, maxPixels: maxPixels,
|
||
pipelineVersion: pipelineVersion, maxAttempts: maxAttempts}
|
||
}
|
||
|
||
// validateFilename: 1–255 code points, не только пробелы, без / \ NUL и управляющих.
|
||
func validateFilename(s string) bool {
|
||
if !utf8.ValidString(s) || strings.TrimSpace(s) == "" {
|
||
return false
|
||
}
|
||
if n := utf8.RuneCountInString(s); n < 1 || n > 255 {
|
||
return false
|
||
}
|
||
for _, r := range s {
|
||
if r == '/' || r == '\\' || r == 0 || unicode.IsControl(r) {
|
||
return false
|
||
}
|
||
}
|
||
return true
|
||
}
|
||
|
||
// declaredType нормализует Content-Type запроса; допустимы только PNG/JPEG.
|
||
func declaredType(h string) (string, bool) {
|
||
mt, _, err := mime.ParseMediaType(h)
|
||
if err != nil {
|
||
return "", false
|
||
}
|
||
mt = strings.ToLower(mt)
|
||
return mt, mt == imagecheck.PNG || mt == imagecheck.JPEG
|
||
}
|
||
|
||
// Upload принимает сырые байты одного изображения и возвращает снимок queued (202).
|
||
//
|
||
// Порядок: намерение в PostgreSQL (uploading) → потоковый PUT в S3-staging,
|
||
// параллельно SHA-256 и структурная проверка изображения → ОДНА транзакция:
|
||
// status=queued + задание + сообщение outbox. 202 возвращается только после
|
||
// COMMIT: в этот момент устойчиво сохранены проверенный оригинал (staging),
|
||
// метаданные и намерение обработки; broker для 202 не нужен (outbox опубликует).
|
||
//
|
||
// Ошибка до MarkQueued (проверка, PUT, обрыв клиента) компенсируется сразу:
|
||
// удаляются объект и намерение. Ошибка самого MarkQueued — неопределённый исход
|
||
// (COMMIT мог пройти): объект НЕ удаляется; остаток uploading+объект уберёт
|
||
// reconciler после grace. Состояния «queued без оригинала» не бывает.
|
||
func (s *AttachmentService) Upload(ctx context.Context, ownerID, chatID, filename, contentType string, body io.Reader, contentLength int64) (*domain.Attachment, error) {
|
||
parsed, err := uuid.Parse(chatID)
|
||
if err != nil {
|
||
return nil, ErrInvalidInput
|
||
}
|
||
chatID = parsed.String()
|
||
ok, err := s.chats.IsMember(ctx, chatID, ownerID)
|
||
if err != nil {
|
||
if errors.Is(err, repository.ErrNotFound) {
|
||
return nil, ErrNotFound
|
||
}
|
||
return nil, err
|
||
}
|
||
if !ok {
|
||
return nil, ErrNotFound
|
||
}
|
||
if !validateFilename(filename) {
|
||
return nil, ErrInvalidInput
|
||
}
|
||
declared, ok := declaredType(contentType)
|
||
if !ok {
|
||
return nil, ErrUnsupportedMedia
|
||
}
|
||
// Лимит размера — до чтения тела.
|
||
if contentLength > s.maxBytes {
|
||
return nil, ErrPayloadTooLarge
|
||
}
|
||
size := contentLength
|
||
if size < 0 {
|
||
// Без Content-Length (chunked): буфер не больше лимита + 1 байт.
|
||
buf, err := io.ReadAll(io.LimitReader(body, s.maxBytes+1))
|
||
if err != nil {
|
||
return nil, ErrInvalidInput
|
||
}
|
||
if int64(len(buf)) > s.maxBytes {
|
||
return nil, ErrPayloadTooLarge
|
||
}
|
||
body, size = bytes.NewReader(buf), int64(len(buf))
|
||
}
|
||
if size == 0 {
|
||
return nil, ErrUnsupportedMedia
|
||
}
|
||
|
||
// Формат — по содержимому; подмена Content-Type → 415.
|
||
br := bufio.NewReaderSize(body, 64*1024)
|
||
head, _ := br.Peek(int(min(size, 64*1024)))
|
||
format, ok := imagecheck.Sniff(head)
|
||
if !ok || format != declared {
|
||
return nil, ErrUnsupportedMedia
|
||
}
|
||
// Ранний отказ по пикселям, если заголовок уместился в первые 64 KiB.
|
||
if cfg, _, err := image.DecodeConfig(bytes.NewReader(head)); err == nil {
|
||
if int64(cfg.Width)*int64(cfg.Height) > s.maxPixels {
|
||
return nil, ErrPayloadTooLarge
|
||
}
|
||
}
|
||
|
||
now := nowUTC()
|
||
id := newID()
|
||
a := &domain.Attachment{
|
||
ID: id, ChatID: chatID, OwnerID: ownerID, Filename: filename,
|
||
ObjectKey: StagingPrefix + chatID + "/" + id,
|
||
Status: domain.AttachmentUploading, CreatedAt: now, UpdatedAt: now,
|
||
}
|
||
if err := s.repo.CreateIntent(ctx, a); err != nil {
|
||
return nil, err
|
||
}
|
||
|
||
sum, putErr := s.putValidated(ctx, a.ObjectKey, br, size, format)
|
||
if putErr != nil {
|
||
s.compensate(ctx, a, putErr)
|
||
return nil, putErr
|
||
}
|
||
|
||
a.Status = domain.AttachmentQueued
|
||
a.ContentType = format
|
||
a.SizeBytes = size
|
||
a.SHA256 = sum
|
||
a.StagingKey = a.ObjectKey
|
||
a.UpdatedAt = nowUTC()
|
||
// Байты уже сохранены: доводим учёт до конца, даже если клиент отвалился.
|
||
mctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
|
||
defer cancel()
|
||
if _, err := s.repo.MarkQueued(mctx, a, s.pipelineVersion, s.maxAttempts); err != nil {
|
||
s.markReadyFailed(ctx, a, err)
|
||
return nil, ErrUnavailable
|
||
}
|
||
return a, nil
|
||
}
|
||
|
||
var errClientBody = errors.New("request body read failed")
|
||
|
||
// trackingReader запоминает ошибку чтения, отличную от EOF.
|
||
type trackingReader struct {
|
||
r io.Reader
|
||
err error
|
||
}
|
||
|
||
func (t *trackingReader) Read(p []byte) (int, error) {
|
||
n, err := t.r.Read(p)
|
||
if err != nil && err != io.EOF {
|
||
t.err = err
|
||
}
|
||
return n, err
|
||
}
|
||
|
||
type bodyReader struct{ r io.Reader }
|
||
|
||
func (b bodyReader) Read(p []byte) (int, error) {
|
||
n, err := b.r.Read(p)
|
||
if err != nil && err != io.EOF {
|
||
return n, errors.Join(errClientBody, err)
|
||
}
|
||
return n, err
|
||
}
|
||
|
||
// putValidated пишет объект в S3 и одновременно проверяет изображение и считает
|
||
// SHA-256. Байты проходят потоком (pipe), в памяти — только буферы чтения.
|
||
func (s *AttachmentService) putValidated(ctx context.Context, key string, body io.Reader, size int64, format string) (string, error) {
|
||
pr, pw := io.Pipe()
|
||
valErr := make(chan error, 1)
|
||
go func() {
|
||
tr := &trackingReader{r: pr}
|
||
_, err := imagecheck.Validate(tr, format, s.maxPixels)
|
||
if tr.err != nil {
|
||
// Поток оборвали снаружи (PUT в S3 упал или клиент отвалился):
|
||
// изображение тут ни при чём, причину определит putErr.
|
||
valErr <- nil
|
||
return
|
||
}
|
||
if err != nil {
|
||
pr.CloseWithError(err) // прерывает PUT: дальше писать некуда
|
||
}
|
||
valErr <- err
|
||
}()
|
||
|
||
h := sha256.New()
|
||
src := io.TeeReader(io.TeeReader(bodyReader{body}, h), pw)
|
||
putErr := s.store.Put(ctx, key, src, size, format)
|
||
if putErr != nil {
|
||
pw.CloseWithError(putErr)
|
||
} else {
|
||
pw.Close()
|
||
}
|
||
vErr := <-valErr
|
||
|
||
switch {
|
||
case errors.Is(vErr, imagecheck.ErrTooLarge):
|
||
return "", ErrPayloadTooLarge
|
||
case errors.Is(vErr, imagecheck.ErrInvalid):
|
||
return "", ErrUnsupportedMedia
|
||
case errors.Is(putErr, errClientBody):
|
||
return "", ErrInvalidInput
|
||
case putErr != nil:
|
||
slog.Warn("attachment upload to s3 failed", "err", putErr)
|
||
return "", ErrUnavailable
|
||
case vErr != nil:
|
||
return "", ErrUnsupportedMedia
|
||
}
|
||
return hex.EncodeToString(h.Sum(nil)), nil
|
||
}
|
||
|
||
// markReadyFailed: исход UPDATE неизвестен — объект оставляем. Пробуем убрать
|
||
// намерение (DELETE ... WHERE status='uploading' безопасен при любом исходе:
|
||
// если UPDATE уже закоммичен, он ничего не удалит). Если и это не удалось —
|
||
// uploading+объект уберёт reconciler после grace period.
|
||
func (s *AttachmentService) markReadyFailed(ctx context.Context, a *domain.Attachment, cause error) {
|
||
cctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
|
||
defer cancel()
|
||
if err := s.repo.DeleteIntent(cctx, a.ID); err != nil {
|
||
slog.Warn("mark ready failed, intent left for reconciler", "attachment_id", a.ID, "cause", cause.Error(), "err", err)
|
||
return
|
||
}
|
||
slog.Warn("mark ready failed, object left for reconciler", "attachment_id", a.ID, "cause", cause.Error())
|
||
}
|
||
|
||
// compensate убирает следы неудачной загрузки. Работает и после обрыва клиента
|
||
// (контекст запроса отменён), поэтому использует отдельный контекст.
|
||
func (s *AttachmentService) compensate(ctx context.Context, a *domain.Attachment, cause error) {
|
||
cctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
|
||
defer cancel()
|
||
if err := s.store.Delete(cctx, a.ObjectKey); err != nil {
|
||
slog.Warn("compensation: delete object failed, reconciler will retry", "attachment_id", a.ID, "err", err)
|
||
}
|
||
if err := s.repo.DeleteIntent(cctx, a.ID); err != nil {
|
||
slog.Warn("compensation: delete intent failed, reconciler will retry", "attachment_id", a.ID, "err", err)
|
||
}
|
||
slog.Info("attachment upload compensated", "attachment_id", a.ID, "cause", cause.Error())
|
||
}
|
||
|
||
// Get возвращает метаданные вложения участнику его чата (queued/processing/
|
||
// ready/failed); у ready — варианты опубликованной версии pipeline.
|
||
func (s *AttachmentService) Get(ctx context.Context, userID, id string) (*domain.Attachment, error) {
|
||
parsed, err := uuid.Parse(id)
|
||
if err != nil {
|
||
return nil, ErrInvalidInput
|
||
}
|
||
a, err := s.repo.GetForMember(ctx, parsed.String(), userID)
|
||
if err != nil {
|
||
if errors.Is(err, repository.ErrNotFound) {
|
||
return nil, ErrNotFound
|
||
}
|
||
return nil, err
|
||
}
|
||
switch a.Status {
|
||
case domain.AttachmentReady:
|
||
if a.PipelineVersion > 0 {
|
||
if a.Variants, err = s.repo.Variants(ctx, a.ID, a.PipelineVersion); err != nil {
|
||
return nil, err
|
||
}
|
||
}
|
||
return a, nil
|
||
case domain.AttachmentQueued, domain.AttachmentProcessing, domain.AttachmentFailed:
|
||
return a, nil
|
||
case domain.AttachmentMissing:
|
||
// Метаданные есть, байтов нет (обнаружил reconciler): ошибка сервера, не клиента.
|
||
return nil, ErrUnavailable
|
||
default:
|
||
return nil, ErrNotFound // загрузка не завершена — объекта для клиента ещё нет
|
||
}
|
||
}
|
||
|
||
// Content — что отдавать клиенту: тип, размер и ключ объекта.
|
||
type Content struct {
|
||
ContentType string
|
||
Size int64
|
||
Key string
|
||
}
|
||
|
||
// Open открывает оригинал или вариант на чтение. Вызывающий закрывает ReadCloser.
|
||
// queued/processing/failed → 409 (объект не готов), отсутствующий у ready
|
||
// вариант → 404.
|
||
func (s *AttachmentService) Open(ctx context.Context, userID, id, variant string) (*Content, io.ReadCloser, error) {
|
||
a, err := s.Get(ctx, userID, id)
|
||
if err != nil {
|
||
return nil, nil, err
|
||
}
|
||
if a.Status != domain.AttachmentReady {
|
||
return nil, nil, ErrConflict
|
||
}
|
||
c := &Content{ContentType: a.ContentType, Size: a.SizeBytes, Key: a.ObjectKey}
|
||
if variant != "" && variant != "original" {
|
||
c = nil
|
||
for _, v := range a.Variants {
|
||
if v.Name == variant {
|
||
c = &Content{ContentType: v.ContentType, Size: v.SizeBytes, Key: v.ObjectKey}
|
||
}
|
||
}
|
||
if c == nil {
|
||
return nil, nil, ErrNotFound
|
||
}
|
||
}
|
||
rc, size, err := s.store.Get(ctx, c.Key)
|
||
if err != nil {
|
||
if errors.Is(err, storage.ErrNotFound) {
|
||
slog.Error("attachment object missing in s3", "attachment_id", a.ID)
|
||
} else {
|
||
slog.Warn("s3 get failed", "attachment_id", a.ID, "err", err)
|
||
}
|
||
return nil, nil, ErrUnavailable
|
||
}
|
||
if size != c.Size {
|
||
rc.Close()
|
||
slog.Error("attachment size mismatch", "attachment_id", a.ID, "variant", variant, "s3", size, "db", c.Size)
|
||
return nil, nil, ErrUnavailable
|
||
}
|
||
return c, rc, nil
|
||
}
|