package attachment import ( "context" "crypto/sha256" "errors" "io" "log/slog" "net/http" "time" "github.com/google/uuid" "messenger/internal/platform/apperr" "messenger/internal/platform/ident" ) type Service struct { attachments AttachmentRepository chats ChatMembership blobs Blobs config Config decode chan struct{} } type Config struct { MaxBytes int64 MaxPixels int64 } // A nil blobs dependency allows the text API to run without configured S3. // Binary operations report unavailability in that mode. func NewService(attachments AttachmentRepository, chats ChatMembership, blobs Blobs, cfg Config) *Service { if cfg.MaxBytes == 0 { cfg.MaxBytes = MaxUploadBytes } if cfg.MaxPixels == 0 { cfg.MaxPixels = MaxImagePixels } return &Service{ attachments: attachments, chats: chats, blobs: blobs, config: cfg, decode: make(chan struct{}, 1), } } func (s *Service) Upload(ctx context.Context, actor uuid.UUID, input UploadInput, body io.Reader) (Attachment, error) { if err := ValidateFilename(input.Filename); err != nil { return Attachment{}, err } if _, accepted := imageFormats[input.MIMEType]; !accepted { return Attachment{}, apperr.UnsupportedMedia("only image/png and image/jpeg are accepted") } ok, err := s.chats.IsMember(ctx, input.ChatID, actor) if err != nil { return Attachment{}, err } if !ok { return Attachment{}, apperr.NotFound("chat not found") } if input.SizeBytes > s.config.MaxBytes { return Attachment{}, apperr.PayloadTooLarge("file exceeds byte limit") } if input.SizeBytes <= 0 { return Attachment{}, apperr.Invalid("a nonempty body with Content-Length is required") } if s.blobs == nil { return Attachment{}, apperr.Unavailable("object storage is unavailable") } id := ident.New() stage := "staging/" + id.String() defer func() { cleanup, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() // A failed cleanup leaves a staging object for the reconciler's grace-based collection. if err := s.blobs.Delete(cleanup, stage); err != nil { slog.Warn("staging cleanup deferred", "key", stage, "error", err) } }() hash := sha256.New() counter := &countReader{r: io.LimitReader(body, s.config.MaxBytes+1)} err = s.blobs.Put(ctx, stage, io.TeeReader(counter, hash), input.SizeBytes, input.MIMEType) if err != nil { _, tooLarge := errors.AsType[*http.MaxBytesError](err) if counter.n > s.config.MaxBytes || tooLarge { return Attachment{}, apperr.PayloadTooLarge("file exceeds byte limit") } if errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, io.EOF) { return Attachment{}, apperr.Invalid("incomplete upload") } return Attachment{}, unavailable(err) } var extra [1]byte n, readErr := counter.Read(extra[:]) if counter.n > s.config.MaxBytes { return Attachment{}, apperr.PayloadTooLarge("file exceeds byte limit") } if counter.n != input.SizeBytes || n != 0 || !errors.Is(readErr, io.EOF) { return Attachment{}, apperr.Invalid("body length does not match Content-Length") } // Full decoding is bounded by dimensions and one decoder per replica. Body // transfer itself stays streaming and does not occupy the decoder slot. select { case s.decode <- struct{}{}: case <-ctx.Done(): return Attachment{}, unavailable(ctx.Err()) } err = s.validate(ctx, stage, input.MIMEType) <-s.decode if err != nil { return Attachment{}, err } a := Attachment{ ID: id, ChatID: input.ChatID, OwnerID: actor, Filename: input.Filename, FileHash: hash.Sum(nil), SizeBytes: input.SizeBytes, MIMEType: input.MIMEType, Status: FileReady, CreatedAt: ident.TimeOf(id), } if err := s.attachments.WithPublication(ctx, a, func(p Publication) error { if err := s.publishBlob(ctx, a, stage, p.FileReady()); err != nil { return err } return p.SaveReady(ctx) }); err != nil { return Attachment{}, err } return a, nil } func (s *Service) publishBlob(ctx context.Context, a Attachment, stagingKey string, fileReady bool) error { blobKey := BlobKey(a.FileHash) if fileReady { obj, err := s.blobs.Stat(ctx, blobKey) if err == nil && obj.Size == a.SizeBytes { return nil } if err != nil && !errors.Is(err, ErrObjectMissing) { return unavailable(err) } } // The hash is known after streaming. Copy the validated staging object to // its permanent CAS key while the repository's publication lock is held. if err := s.blobs.Copy(ctx, stagingKey, blobKey); err != nil { return unavailable(err) } return nil } func (s *Service) validate(ctx context.Context, stage, mime string) (err error) { r, err := s.blobs.Open(ctx, stage) if err != nil { return unavailable(err) } defer func() { if closeErr := r.Close(); closeErr != nil && err == nil { err = unavailable(closeErr) } }() tracked := &storageReader{reader: r} err = ValidateImage(tracked, mime, s.config.MaxPixels) if tracked.err != nil { return unavailable(tracked.err) } if ctx.Err() != nil { return unavailable(ctx.Err()) } return err } // Image sniffing can replace a reader failure with ErrFormat. Preserve the // storage failure independently, while ordinary EOF still means malformed bytes. type storageReader struct { reader io.Reader err error } func (r *storageReader) Read(p []byte) (int, error) { n, err := r.reader.Read(p) if err != nil && !errors.Is(err, io.EOF) { r.err = err } return n, err } func (s *Service) Get(ctx context.Context, actor, id uuid.UUID) (Attachment, error) { a, err := s.attachments.GetForMember(ctx, id, actor) if err != nil { return Attachment{}, err } if a.Status != FileReady { return Attachment{}, apperr.Conflict("attachment is not ready") } return a, nil } func (s *Service) Content(ctx context.Context, actor, id uuid.UUID) (Attachment, io.ReadCloser, error) { a, err := s.Get(ctx, actor, id) if err != nil { return Attachment{}, nil, err } if s.blobs == nil { return Attachment{}, nil, apperr.Unavailable("object storage is unavailable") } r, err := s.blobs.Open(ctx, BlobKey(a.FileHash)) if err != nil { return Attachment{}, nil, unavailable(err) } return a, r, nil } type countReader struct { r io.Reader n int64 } func (c *countReader) Read(b []byte) (int, error) { n, err := c.r.Read(b) c.n += int64(n) return n, err } func unavailable(err error) error { return apperr.Wrap(apperr.KindUnavailable, "object storage is unavailable", err) }