170 lines
5.1 KiB
Go
170 lines
5.1 KiB
Go
package attachment
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"fmt"
|
|
"gitea.privcloud.tech/mtusi2026/internal/pkg/telemetry"
|
|
"go.opentelemetry.io/otel/trace"
|
|
"image"
|
|
_ "image/jpeg"
|
|
_ "image/png"
|
|
"io"
|
|
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
"unicode"
|
|
"unicode/utf8"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"gitea.privcloud.tech/mtusi2026/internal/config"
|
|
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
|
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
|
|
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
const Prefix = "originals/"
|
|
const StagingPrefix = "staging/"
|
|
|
|
type Membership interface {
|
|
GetForMember(context.Context, dto.ChatMember) (*dto.Chat, error)
|
|
}
|
|
type Service struct {
|
|
Repo Repository
|
|
Store ObjectStore
|
|
Config *config.Attachment
|
|
chats Membership
|
|
tm TransactionManager
|
|
outbox Outbox
|
|
Jobs *config.Pipeline
|
|
uploads, decoders chan struct{}
|
|
}
|
|
|
|
func New(repo Repository, store ObjectStore, c *config.Attachment, chats Membership) *Service {
|
|
return &Service{Repo: repo, Store: store, Config: c, chats: chats, uploads: make(chan struct{}, c.Uploads), decoders: make(chan struct{}, c.Decoders)}
|
|
}
|
|
func ValidFilename(s string) bool {
|
|
if strings.TrimSpace(s) == "" || !utf8.ValidString(s) || utf8.RuneCountInString(s) < 1 || utf8.RuneCountInString(s) > 255 {
|
|
return false
|
|
}
|
|
for _, r := range s {
|
|
if r == '/' || r == '\\' || unicode.IsControl(r) {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
func (s *Service) Configure(tm TransactionManager, outbox Outbox, jobs *config.Pipeline) {
|
|
s.tm = tm
|
|
s.outbox = outbox
|
|
s.Jobs = jobs
|
|
}
|
|
func (s *Service) Upload(ctx context.Context, req dto.UploadAttachment) (out *contracts.Attachment, err error) {
|
|
ctx, sp := telemetry.Start(ctx, "attachment.upload", trace.SpanKindInternal)
|
|
defer func() { telemetry.End(sp, err) }()
|
|
if _, e := s.chats.GetForMember(ctx, dto.ChatMember{UserID: req.UserID, ChatID: req.ChatID}); e != nil {
|
|
return nil, e
|
|
}
|
|
select {
|
|
case s.uploads <- struct{}{}:
|
|
defer func() { <-s.uploads }()
|
|
default:
|
|
return nil, apperr.New(apperr.CodeTooManyRequests, "upload capacity exceeded")
|
|
}
|
|
f, e := os.CreateTemp("", "attachment-*")
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
defer os.Remove(f.Name())
|
|
defer f.Close()
|
|
hash := sha256.New()
|
|
size, e := io.Copy(io.MultiWriter(f, hash), io.LimitReader(req.Body, s.Config.MaxBytes+1))
|
|
if e != nil {
|
|
return nil, apperr.New(apperr.CodeBadRequest, "incomplete upload")
|
|
}
|
|
if size > s.Config.MaxBytes {
|
|
return nil, apperr.New(apperr.CodePayloadTooLarge, "upload too large")
|
|
}
|
|
if e = s.Validate(ctx, f, req.ContentType); e != nil {
|
|
return nil, e
|
|
}
|
|
now := time.Now().UTC().Truncate(time.Microsecond)
|
|
id := uuid.New()
|
|
key := StagingPrefix + id.String()
|
|
a := &dto.AttachmentRecord{Key: key, StagingKey: key, PipelineVersion: 1, VariantKeys: map[string]string{}, Public: contracts.Attachment{Id: id, ChatId: req.ChatID, OwnerId: req.UserID, Filename: req.Filename, ContentType: contracts.AttachmentContentType(req.ContentType), SizeBytes: int(size), Sha256: fmt.Sprintf("%x", hash.Sum(nil)), Status: "queued", Variants: []contracts.Variant{}, CreatedAt: now, UpdatedAt: now}}
|
|
_, unlock, e := s.Repo.Lock(ctx, key)
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
defer unlock()
|
|
if _, e = f.Seek(0, 0); e != nil {
|
|
return nil, e
|
|
}
|
|
if e = s.Store.Put(ctx, key, req.ContentType, f, size); e != nil {
|
|
return nil, Unavailable()
|
|
}
|
|
s.Fault(ctx, "after_staging", id)
|
|
if e = s.tm.RunInTransaction(ctx, nil, func(tx pgx.Tx) error {
|
|
if e := s.Repo.InsertTx(ctx, tx, a); e != nil {
|
|
return e
|
|
}
|
|
return s.newJob(ctx, tx, a)
|
|
}); e != nil {
|
|
return nil, e
|
|
}
|
|
s.Fault(ctx, "after_upload_commit", id)
|
|
return &a.Public, nil
|
|
}
|
|
func (s *Service) Validate(ctx context.Context, f *os.File, mt string) error {
|
|
if _, e := f.Seek(0, 0); e != nil {
|
|
return e
|
|
}
|
|
cfg, format, e := image.DecodeConfig(f)
|
|
if e != nil || ("image/"+format) != mt {
|
|
return apperr.New(apperr.CodeUnsupportedMediaType, "invalid image or MIME mismatch")
|
|
}
|
|
if cfg.Width <= 0 || cfg.Height <= 0 || int64(cfg.Width) > s.Config.MaxPixels/int64(cfg.Height) {
|
|
return apperr.New(apperr.CodePayloadTooLarge, "image pixel limit exceeded")
|
|
}
|
|
select {
|
|
case s.decoders <- struct{}{}:
|
|
defer func() { <-s.decoders }()
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
}
|
|
if _, e = f.Seek(0, 0); e != nil {
|
|
return e
|
|
}
|
|
if e = validateImage(ctx, f.Name()); e != nil {
|
|
return apperr.New(apperr.CodeUnsupportedMediaType, "corrupt image")
|
|
}
|
|
return ctx.Err()
|
|
}
|
|
func (s *Service) Get(ctx context.Context, user, id uuid.UUID) (*dto.AttachmentRecord, error) {
|
|
a, e := s.Repo.Get(ctx, id)
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
if _, e = s.chats.GetForMember(ctx, dto.ChatMember{UserID: user, ChatID: a.Public.ChatId}); e != nil {
|
|
return nil, e
|
|
}
|
|
if a.Missing {
|
|
return nil, Unavailable()
|
|
}
|
|
return a, nil
|
|
}
|
|
func Unavailable() error { return apperr.New(apperr.CodeUnavailable, "attachment storage unavailable") }
|
|
func ManagedKey(key string) bool {
|
|
if managedPipelineKey(key) {
|
|
return true
|
|
}
|
|
if !strings.HasPrefix(key, Prefix) {
|
|
return false
|
|
}
|
|
id, e := uuid.Parse(strings.TrimPrefix(key, Prefix))
|
|
return e == nil && key == Prefix+id.String()
|
|
}
|