forked from mtusi2026/mtusi2026lab5
ЛР 5: асинхронная обработка изображений, уровень 5
This commit is contained in:
@@ -0,0 +1,128 @@
|
||||
// Package imagecheck определяет тип изображения по содержимому и проверяет, что файл целый.
|
||||
package imagecheck
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrUnsupported — не PNG/JPEG либо файл повреждён.
|
||||
ErrUnsupported = errors.New("imagecheck: not a valid PNG or JPEG")
|
||||
// ErrTooManyPixels — размеры из заголовка превышают лимит.
|
||||
ErrTooManyPixels = errors.New("imagecheck: too many pixels")
|
||||
// ErrBusy — очередь на декодирование не подошла за decodeWait.
|
||||
ErrBusy = errors.New("imagecheck: decoder is busy")
|
||||
)
|
||||
|
||||
var (
|
||||
pngMagic = []byte("\x89PNG\r\n\x1a\n")
|
||||
jpegMagic = []byte{0xff, 0xd8, 0xff}
|
||||
)
|
||||
|
||||
const (
|
||||
// decodeWait ограничивает ожидание очереди на декодирование. Вместе с записью в S3 и БД ответ
|
||||
// должен уложиться в timeout server балансировщика (15 с): лучше честный 429, чем 504.
|
||||
decodeWait = 5 * time.Second
|
||||
// Файл читается с диска маленькими порциями; буфер убирает лишние системные вызовы.
|
||||
readBuffer = 64 << 10
|
||||
)
|
||||
|
||||
type format struct {
|
||||
contentType string
|
||||
config func(io.Reader) (image.Config, error)
|
||||
decode func(io.Reader) (image.Image, error)
|
||||
}
|
||||
|
||||
func detect(head []byte) (format, bool) {
|
||||
switch {
|
||||
case bytes.HasPrefix(head, pngMagic):
|
||||
return format{domain.ContentTypePNG, png.DecodeConfig, png.Decode}, true
|
||||
case bytes.HasPrefix(head, jpegMagic):
|
||||
return format{domain.ContentTypeJPEG, jpeg.DecodeConfig, jpeg.Decode}, true
|
||||
}
|
||||
return format{}, false
|
||||
}
|
||||
|
||||
func read(r io.ReadSeeker) (format, error) {
|
||||
if _, err := r.Seek(0, io.SeekStart); err != nil {
|
||||
return format{}, err
|
||||
}
|
||||
head := make([]byte, len(pngMagic))
|
||||
n, err := io.ReadFull(r, head)
|
||||
if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
return format{}, err
|
||||
}
|
||||
f, ok := detect(head[:n])
|
||||
if !ok {
|
||||
return format{}, ErrUnsupported
|
||||
}
|
||||
if _, err := r.Seek(0, io.SeekStart); err != nil {
|
||||
return format{}, err
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// Checker ограничивает расход памяти на проверку: размеры читаются из заголовка без распаковки,
|
||||
// а полное декодирование выполняется только в пределах лимита пикселей и по одному за раз.
|
||||
// Декодирование 40 Мп занимает сотни мегабайт, поэтому параллелить его нельзя.
|
||||
type Checker struct {
|
||||
maxPixels int64
|
||||
decoding chan struct{}
|
||||
}
|
||||
|
||||
func New(maxPixels int64) *Checker {
|
||||
return &Checker{maxPixels: maxPixels, decoding: make(chan struct{}, 1)}
|
||||
}
|
||||
|
||||
// Inspect определяет истинный Content-Type по сигнатуре и проверяет размеры из заголовка. Пиксели
|
||||
// не распаковываются, поэтому «бомба» и подмена типа отклоняются почти без затрат.
|
||||
func (c *Checker) Inspect(r io.ReadSeeker) (string, error) {
|
||||
f, err := read(r)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
cfg, err := f.config(bufio.NewReaderSize(r, readBuffer))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%w: header", ErrUnsupported)
|
||||
}
|
||||
if cfg.Width <= 0 || cfg.Height <= 0 {
|
||||
return "", fmt.Errorf("%w: empty image", ErrUnsupported)
|
||||
}
|
||||
if int64(cfg.Width) > c.maxPixels || int64(cfg.Width)*int64(cfg.Height) > c.maxPixels {
|
||||
return "", ErrTooManyPixels
|
||||
}
|
||||
return f.contentType, nil
|
||||
}
|
||||
|
||||
// Decode полностью декодирует файл, уже прошедший Inspect. Результат не нужен: важно, что файл целый.
|
||||
func (c *Checker) Decode(ctx context.Context, r io.ReadSeeker) error {
|
||||
timer := time.NewTimer(decodeWait)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case c.decoding <- struct{}{}:
|
||||
defer func() { <-c.decoding }()
|
||||
case <-timer.C:
|
||||
return ErrBusy
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
f, err := read(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := f.decode(bufio.NewReaderSize(r, readBuffer)); err != nil {
|
||||
return fmt.Errorf("%w: body", ErrUnsupported)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user