Доработайте публикацию и сверку вложений по итогам ревью
This commit is contained in:
@@ -15,40 +15,54 @@ import (
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
repo Repository
|
||||
blobs Blobs
|
||||
maxBytes, maxPixels int64
|
||||
decode chan struct{}
|
||||
attachments AttachmentRepository
|
||||
chats ChatMembership
|
||||
blobs Blobs
|
||||
config Config
|
||||
decode chan struct{}
|
||||
}
|
||||
|
||||
func NewService(repo Repository, blobs Blobs, maxBytes, maxPixels int64) *Service {
|
||||
if maxBytes == 0 {
|
||||
maxBytes = MaxUploadBytes
|
||||
}
|
||||
if maxPixels == 0 {
|
||||
maxPixels = MaxImagePixels
|
||||
}
|
||||
return &Service{repo: repo, blobs: blobs, maxBytes: maxBytes, maxPixels: maxPixels, decode: make(chan struct{}, 1)}
|
||||
type Config struct {
|
||||
MaxBytes int64
|
||||
MaxPixels int64
|
||||
}
|
||||
|
||||
func (s *Service) Upload(ctx context.Context, actor, chatID uuid.UUID, filename, mime string, size int64, body io.Reader) (Attachment, error) {
|
||||
if err := ValidateFilename(filename); err != nil {
|
||||
// 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 mime != "image/png" && mime != "image/jpeg" {
|
||||
if _, accepted := imageFormats[input.MIMEType]; !accepted {
|
||||
return Attachment{}, apperr.UnsupportedMedia("only image/png and image/jpeg are accepted")
|
||||
}
|
||||
ok, err := s.repo.IsMember(ctx, chatID, actor)
|
||||
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 size > s.maxBytes {
|
||||
if input.SizeBytes > s.config.MaxBytes {
|
||||
return Attachment{}, apperr.PayloadTooLarge("file exceeds byte limit")
|
||||
}
|
||||
if size <= 0 {
|
||||
if input.SizeBytes <= 0 {
|
||||
return Attachment{}, apperr.Invalid("a nonempty body with Content-Length is required")
|
||||
}
|
||||
if s.blobs == nil {
|
||||
@@ -59,16 +73,17 @@ func (s *Service) Upload(ctx context.Context, actor, chatID uuid.UUID, filename,
|
||||
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", "error", err)
|
||||
slog.Warn("staging cleanup deferred", "key", stage, "error", err)
|
||||
}
|
||||
}()
|
||||
hash := sha256.New()
|
||||
counter := &countReader{r: io.LimitReader(body, s.maxBytes+1)}
|
||||
err = s.blobs.Put(ctx, stage, io.TeeReader(counter, hash), size, mime)
|
||||
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.maxBytes || tooLarge {
|
||||
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) {
|
||||
@@ -78,10 +93,10 @@ func (s *Service) Upload(ctx context.Context, actor, chatID uuid.UUID, filename,
|
||||
}
|
||||
var extra [1]byte
|
||||
n, readErr := counter.Read(extra[:])
|
||||
if counter.n > s.maxBytes {
|
||||
if counter.n > s.config.MaxBytes {
|
||||
return Attachment{}, apperr.PayloadTooLarge("file exceeds byte limit")
|
||||
}
|
||||
if counter.n != size || n != 0 || !errors.Is(readErr, io.EOF) {
|
||||
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
|
||||
@@ -91,26 +106,64 @@ func (s *Service) Upload(ctx context.Context, actor, chatID uuid.UUID, filename,
|
||||
case <-ctx.Done():
|
||||
return Attachment{}, unavailable(ctx.Err())
|
||||
}
|
||||
err = s.validate(ctx, stage, mime)
|
||||
err = s.validate(ctx, stage, input.MIMEType)
|
||||
<-s.decode
|
||||
if err != nil {
|
||||
return Attachment{}, err
|
||||
}
|
||||
a := Attachment{ID: id, ChatID: chatID, OwnerID: actor, Filename: filename, FileHash: hash.Sum(nil), SizeBytes: size, MIMEType: mime, Status: "ready", CreatedAt: ident.TimeOf(id)}
|
||||
if err := s.repo.Publish(ctx, a, stage); err != nil {
|
||||
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) validate(ctx context.Context, stage, mime string) error {
|
||||
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 r.Close()
|
||||
defer func() {
|
||||
if closeErr := r.Close(); closeErr != nil && err == nil {
|
||||
err = unavailable(closeErr)
|
||||
}
|
||||
}()
|
||||
tracked := &storageReader{reader: r}
|
||||
err = ValidateImage(tracked, mime, s.maxPixels)
|
||||
err = ValidateImage(tracked, mime, s.config.MaxPixels)
|
||||
if tracked.err != nil {
|
||||
return unavailable(tracked.err)
|
||||
}
|
||||
@@ -136,11 +189,11 @@ func (r *storageReader) Read(p []byte) (int, error) {
|
||||
}
|
||||
|
||||
func (s *Service) Get(ctx context.Context, actor, id uuid.UUID) (Attachment, error) {
|
||||
a, err := s.repo.GetForMember(ctx, id, actor)
|
||||
a, err := s.attachments.GetForMember(ctx, id, actor)
|
||||
if err != nil {
|
||||
return Attachment{}, err
|
||||
}
|
||||
if a.Status != "ready" {
|
||||
if a.Status != FileReady {
|
||||
return Attachment{}, apperr.Conflict("attachment is not ready")
|
||||
}
|
||||
return a, nil
|
||||
@@ -166,7 +219,12 @@ type countReader struct {
|
||||
n int64
|
||||
}
|
||||
|
||||
func (c *countReader) Read(b []byte) (int, error) { n, e := c.r.Read(b); c.n += int64(n); return n, e }
|
||||
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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user