Files
mtusi2026lab5/internal/imageproc/imageproc.go
T
Vladislav Kunetskiy 01b885e846 lab5: очереди и асинхронная обработка изображений
Durable staging handoff, transactional outbox, at-least-once worker with lease fencing, idempotent versioned pipeline, three variants, operator tooling, contract tests and evidence. Includes the review fixes: reprocess source selection and failure settlement, replay guards, stale-job retirement, PNG structural/raster validation, migration rollback safety and audit events.
2026-10-31 14:34:24 +03:00

260 lines
6.7 KiB
Go

// Package imageproc turns one decoded original into the contract variants.
// Output bytes are deterministic for a given pipeline version, source bytes and
// encoder versions; the worker uses that property for idempotent retries.
package imageproc
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"fmt"
"image"
"image/color"
"image/jpeg"
_ "image/png" // register the PNG decoder
"io"
"math"
"os"
"github.com/gen2brain/webp"
xdraw "golang.org/x/image/draw"
"mtusi-messenger/internal/domain"
)
const (
thumbnailMax = 256
cropSize = 128
optimizedMax = 1280
defaultMethod = 2
)
// Params are immutable per pipeline version. They are compiled into the binary
// so a retry can never silently produce different bytes than the first attempt.
type Params struct {
JPEGQuality int
WebPQuality int
WebPMethod int
}
// Pipeline returns the versioned encoder parameters. Only v1 and v2 are
// defined; the course baseline is v1.
func Pipeline(version int) (Params, bool) {
switch version {
case 1:
return Params{JPEGQuality: 85, WebPQuality: 80, WebPMethod: defaultMethod}, true
case 2:
return Params{JPEGQuality: 70, WebPQuality: 65, WebPMethod: 4}, true
default:
return Params{}, false
}
}
// Image is one encoded variant.
type Image struct {
Name domain.VariantName
ContentType string
Data []byte
SizeBytes int64
Width int
Height int
SHA256 string
}
// Load decodes a PNG/JPEG file, applies EXIF orientation and composites alpha
// on white. The returned image is always *image.RGBA, which bounds the variant
// encoders to 8-bit output.
func Load(path string, maxPixels int64) (image.Image, string, error) {
file, err := os.Open(path)
if err != nil {
return nil, "", fmt.Errorf("open source: %w", err)
}
defer file.Close()
cfg, format, err := image.DecodeConfig(file)
if err != nil {
return nil, "", fmt.Errorf("decode config: %w", err)
}
if cfg.Width <= 0 || cfg.Height <= 0 {
return nil, "", fmt.Errorf("invalid dimensions %dx%d", cfg.Width, cfg.Height)
}
if maxPixels > 0 && int64(cfg.Width)*int64(cfg.Height) > maxPixels {
return nil, "", fmt.Errorf("image has %d pixels, limit %d", int64(cfg.Width)*int64(cfg.Height), maxPixels)
}
if _, err := file.Seek(0, io.SeekStart); err != nil {
return nil, "", fmt.Errorf("rewind source: %w", err)
}
decoded, _, err := image.Decode(file)
if err != nil {
return nil, "", fmt.Errorf("decode image: %w", err)
}
orientation := 1
if format == "jpeg" {
if _, err := file.Seek(0, io.SeekStart); err == nil {
orientation = readEXIFOrientation(file)
}
}
return toWhiteRGBA(decoded, orientation), format, nil
}
func toWhiteRGBA(src image.Image, orientation int) image.Image {
transformed := orient(src, orientation)
bounds := transformed.Bounds()
dst := image.NewRGBA(image.Rect(0, 0, bounds.Dx(), bounds.Dy()))
xdraw.Draw(dst, dst.Bounds(), image.NewUniform(color.White), image.Point{}, xdraw.Src)
xdraw.Draw(dst, dst.Bounds(), transformed, bounds.Min, xdraw.Over)
return dst
}
// orient applies the eight EXIF orientation values. The result has the same
// bounds as the source except for 90-degree rotations.
func orient(src image.Image, orientation int) image.Image {
if orientation < 2 || orientation > 8 {
return src
}
b := src.Bounds()
w, h := b.Dx(), b.Dy()
width, height := w, h
if orientation >= 5 {
width, height = h, w
}
dst := image.NewRGBA(image.Rect(0, 0, width, height))
for y := range h {
for x := range w {
nx, ny := orientPoint(orientation, x, y, w, h)
dst.Set(nx, ny, src.At(b.Min.X+x, b.Min.Y+y))
}
}
return dst
}
func orientPoint(orientation, x, y, w, h int) (int, int) {
switch orientation {
case 2:
return w - 1 - x, y
case 3:
return w - 1 - x, h - 1 - y
case 4:
return x, h - 1 - y
case 5:
return y, x
case 6:
return h - 1 - y, x
case 7:
return h - 1 - y, w - 1 - x
case 8:
return y, w - 1 - x
default:
return x, y
}
}
// Thumbnail fits inside 256x256 without upscaling; dimensions are floored and
// never below 1 px.
func Thumbnail(src image.Image, params Params) (Image, error) {
return encodeJPEG(fit(src, thumbnailMax, thumbnailMax, false), domain.VariantThumbnail, params)
}
// Crop takes the centered square and scales it to 128x128. Upscaling small
// sources is allowed by the contract.
func Crop(src image.Image, params Params) (Image, error) {
b := src.Bounds()
side := b.Dx()
if b.Dy() < side {
side = b.Dy()
}
left := b.Min.X + (b.Dx()-side)/2
top := b.Min.Y + (b.Dy()-side)/2
square := image.NewRGBA(image.Rect(0, 0, side, side))
xdraw.Draw(square, square.Bounds(), src, image.Pt(left, top), xdraw.Src)
dst := image.NewRGBA(image.Rect(0, 0, cropSize, cropSize))
xdraw.CatmullRom.Scale(dst, dst.Bounds(), square, square.Bounds(), xdraw.Over, nil)
return encodeJPEG(dst, domain.VariantCrop, params)
}
// Optimized fits inside 1280x1280 without upscaling and encodes WebP. Metadata
// is stripped because the output is a fresh re-encode.
func Optimized(src image.Image, params Params) (Image, error) {
dst := fit(src, optimizedMax, optimizedMax, false)
var buf bytes.Buffer
if err := webp.Encode(&buf, dst, webp.Options{
Quality: params.WebPQuality,
Method: params.WebPMethod,
}); err != nil {
return Image{}, fmt.Errorf("encode webp: %w", err)
}
return newImage(domain.VariantOptimized, "image/webp", buf.Bytes(), dst.Bounds().Dx(), dst.Bounds().Dy()), nil
}
func encodeJPEG(dst image.Image, name domain.VariantName, params Params) (Image, error) {
var buf bytes.Buffer
if err := jpeg.Encode(&buf, dst, &jpeg.Options{Quality: params.JPEGQuality}); err != nil {
return Image{}, fmt.Errorf("encode jpeg: %w", err)
}
return newImage(name, "image/jpeg", buf.Bytes(), dst.Bounds().Dx(), dst.Bounds().Dy()), nil
}
func newImage(name domain.VariantName, contentType string, data []byte, width, height int) Image {
sum := sha256.Sum256(data)
return Image{
Name: name,
ContentType: contentType,
Data: data,
SizeBytes: int64(len(data)),
Width: width,
Height: height,
SHA256: hex.EncodeToString(sum[:]),
}
}
// fit scales src into maxWidth x maxHeight preserving aspect ratio, floors the
// dimensions, enforces at least 1 px and, unless allowUpscale is set, never
// enlarges the source.
func fit(src image.Image, maxWidth, maxHeight int, allowUpscale bool) *image.RGBA {
b := src.Bounds()
w, h := b.Dx(), b.Dy()
scale := math.Min(float64(maxWidth)/float64(w), float64(maxHeight)/float64(h))
if !allowUpscale && scale > 1 {
scale = 1
}
width := int(math.Floor(float64(w) * scale))
height := int(math.Floor(float64(h) * scale))
if width < 1 {
width = 1
}
if height < 1 {
height = 1
}
dst := image.NewRGBA(image.Rect(0, 0, width, height))
xdraw.CatmullRom.Scale(dst, dst.Bounds(), src, b, xdraw.Over, nil)
return dst
}