Files
mtusi2026lab4/internal/attachment/service.go
T
2026-10-28 22:41:10 +03:00

133 lines
5.1 KiB
Go

package attachment
import (
"context"
"errors"
"io"
"log"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/minio/minio-go/v7"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
const UploadTimeout = 45 * time.Second
const MinimumGrace = 90 * time.Second
type Attachment struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
OwnerID string `json:"owner_id"`
Filename string `json:"filename"`
ContentType string `json:"content_type"`
Size int64 `json:"size_bytes"`
SHA256 string `json:"sha256"`
Status string `json:"status"`
Variants []any `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Key string `json:"-"`
}
type Service struct {
Pool *pgxpool.Pool
Store *Store
slots chan struct{}
}
func New(pool *pgxpool.Pool, store *Store) *Service {
return &Service{Pool: pool, Store: store, slots: make(chan struct{}, 1)}
}
func (s *Service) Ready(ctx context.Context) error { return s.Store.Ready(ctx) }
func (s *Service) Upload(ctx context.Context, chatID, userID, name, contentType string, body io.Reader) (Attachment, error) {
if err := ValidateFilename(name); err != nil {
return Attachment{}, err
}
ctx, cancel := context.WithTimeout(ctx, UploadTimeout)
defer cancel()
select {
case s.slots <- struct{}{}:
defer func() { <-s.slots }()
case <-ctx.Done():
return Attachment{}, unavailable()
}
original, err := Spool(ctx, body, contentType)
if err != nil {
return Attachment{}, err
}
defer original.Close()
a := Attachment{ID: uuid.NewString(), ChatID: chatID, OwnerID: userID, Filename: name, ContentType: original.ContentType, Size: original.Size, SHA256: original.SHA256, Status: "ready", Variants: []any{}}
a.Key = "original/" + a.ID
tx, err := s.Pool.Begin(ctx)
if err != nil {
return Attachment{}, unavailable()
}
defer tx.Rollback(context.Background())
// Keep the object lock through PUT, metadata insert and COMMIT. A crash releases
// the lock; the grace protects a still-running client PUT at the S3 server.
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, a.Key); err != nil {
return Attachment{}, unavailable()
}
_, err = s.Store.Client.PutObject(ctx, s.Store.Bucket, a.Key, original.File, a.Size, minio.PutObjectOptions{ContentType: a.ContentType, DisableMultipart: true, UserMetadata: map[string]string{"sha256": a.SHA256}})
if err != nil {
return Attachment{}, unavailable()
}
err = tx.QueryRow(ctx, `INSERT INTO attachments(id,chat_id,uploader_id,filename,object_key,content_type,size_bytes,sha256,width,height) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) RETURNING created_at`, a.ID, a.ChatID, a.OwnerID, a.Filename, a.Key, a.ContentType, a.Size, a.SHA256, original.Width, original.Height).Scan(&a.CreatedAt)
if err != nil {
log.Print("attachment metadata failed; orphan retained for grace-period reconciliation")
return Attachment{}, unavailable()
}
// Never DELETE on an ambiguous COMMIT failure: the DB may have committed. A
// later reconciler checks both stores under the same lock before any cleanup.
if err = tx.Commit(ctx); err != nil {
return Attachment{}, unavailable()
}
a.UpdatedAt = a.CreatedAt
return a, nil
}
func (s *Service) Get(ctx context.Context, id, userID string) (Attachment, error) {
parsed, err := uuid.Parse(id)
if err != nil {
return Attachment{}, appError(domain.ErrorInvalid, "Некорректный attachment_id")
}
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
a := Attachment{Variants: []any{}}
err = s.Pool.QueryRow(ctx, `SELECT a.id::text,a.chat_id::text,a.uploader_id::text,a.filename,a.object_key,a.content_type,a.size_bytes,a.sha256,a.status,a.error_code,a.created_at FROM attachments a JOIN chat_members m ON m.chat_id=a.chat_id WHERE a.id=$1 AND m.user_id=$2`, parsed.String(), userID).Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.Key, &a.ContentType, &a.Size, &a.SHA256, &a.Status, &a.ErrorCode, &a.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return Attachment{}, appError(domain.ErrorNotFound, "Объект не найден")
}
if err != nil {
return Attachment{}, unavailable()
}
a.UpdatedAt = a.CreatedAt
// Keep the mandatory lab4 ready-only metadata schema. Failed originals are
// represented by 409; internal status remains inspectable in reconciliation.
if a.Status != "ready" {
return Attachment{}, appError(domain.ErrorConflict, "Оригинал вложения недоступен")
}
return a, nil
}
func (s *Service) Content(ctx context.Context, a Attachment) (*minio.Object, error) {
if a.Status != "ready" {
return nil, appError(domain.ErrorConflict, "Вложение не готово")
}
obj, err := s.Store.Client.GetObject(ctx, s.Store.Bucket, a.Key, minio.GetObjectOptions{})
if err != nil {
return nil, unavailable()
}
if _, err = obj.Stat(); err != nil {
obj.Close()
if IsMissing(err) {
return nil, appError(domain.ErrorConflict, "Оригинал вложения недоступен")
}
return nil, unavailable()
}
return obj, nil
}