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.
This commit is contained in:
Vladislav Kunetskiy
2026-10-31 14:34:24 +03:00
parent 6c5ba026f1
commit 01b885e846
99 changed files with 10164 additions and 1452 deletions
+118
View File
@@ -0,0 +1,118 @@
package imageproc
import (
"encoding/binary"
"io"
)
const (
exifMaxBytes = 64 << 10
exifTagOrient = 0x0112
)
// readEXIFOrientation extracts only IFD0 Orientation from a JPEG APP1 segment.
// The parser is deliberately small and bounded: no TIFF offsets are trusted and
// the whole segment is capped at 64 KiB, so attacker-controlled EXIF cannot make
// the worker allocate unbounded memory.
func readEXIFOrientation(r io.Reader) int {
data, err := io.ReadAll(io.LimitReader(r, exifMaxBytes))
if err != nil || len(data) < 4 || data[0] != 0xff || data[1] != 0xd8 {
return 1
}
pos := 2
for pos+4 <= len(data) {
if data[pos] != 0xff {
return 1
}
marker := data[pos+1]
pos += 2
// Standalone markers without a length field.
if marker == 0xd8 || marker == 0xd9 || marker == 0x01 || (marker >= 0xd0 && marker <= 0xd7) {
continue
}
if pos+2 > len(data) {
return 1
}
length := int(binary.BigEndian.Uint16(data[pos : pos+2]))
if length < 2 || pos+length > len(data) {
return 1
}
segment := data[pos+2 : pos+length]
pos += length
if marker != 0xe1 || len(segment) < 6 {
continue
}
if string(segment[:6]) != "Exif\x00\x00" {
continue
}
return parseTIFFOrientation(segment[6:])
}
return 1
}
func parseTIFFOrientation(tiff []byte) int {
if len(tiff) < 8 {
return 1
}
var order binary.ByteOrder
switch string(tiff[:2]) {
case "II":
order = binary.LittleEndian
case "MM":
order = binary.BigEndian
default:
return 1
}
if order.Uint16(tiff[2:4]) != 42 {
return 1
}
ifdOffset := int(order.Uint32(tiff[4:8]))
if ifdOffset < 8 || ifdOffset+2 > len(tiff) {
return 1
}
count := int(order.Uint16(tiff[ifdOffset : ifdOffset+2]))
if count > 512 {
count = 512
}
entry := ifdOffset + 2
for range count {
if entry+12 > len(tiff) {
return 1
}
tag := order.Uint16(tiff[entry : entry+2])
typ := order.Uint16(tiff[entry+2 : entry+4])
n := order.Uint32(tiff[entry+4 : entry+8])
if tag == exifTagOrient && typ == 3 && n == 1 {
value := order.Uint16(tiff[entry+8 : entry+10])
if value >= 1 && value <= 8 {
return int(value)
}
return 1
}
entry += 12
}
return 1
}
+259
View File
@@ -0,0 +1,259 @@
// 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
}
+222
View File
@@ -0,0 +1,222 @@
package imageproc_test
import (
"bytes"
"encoding/binary"
"image"
"image/color"
"image/jpeg"
"image/png"
"os"
"path/filepath"
"testing"
"github.com/gen2brain/webp"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/imageproc"
)
func writePNG(t *testing.T, width, height int, alpha bool) string {
t.Helper()
img := image.NewNRGBA(image.Rect(0, 0, width, height))
for x := range width {
for y := range height {
a := uint8(255)
if alpha && x < width/2 && y < height/2 {
a = 0
}
img.Set(x, y, color.NRGBA{R: 200, G: 40, B: 20, A: a})
}
}
var buf bytes.Buffer
require.NoError(t, png.Encode(&buf, img))
path := filepath.Join(t.TempDir(), "source.png")
require.NoError(t, os.WriteFile(path, buf.Bytes(), 0o600))
return path
}
func writeJPEG(t *testing.T, width, height, orientation int) string {
t.Helper()
img := image.NewRGBA(image.Rect(0, 0, width, height))
for x := range width {
for y := range height {
img.Set(x, y, color.RGBA{R: 200, G: 40, B: 20, A: 255})
}
}
var raw bytes.Buffer
require.NoError(t, jpeg.Encode(&raw, img, &jpeg.Options{Quality: 95}))
data := append([]byte(nil), raw.Bytes()...)
if orientation > 1 {
data = insertEXIFOrientation(t, data, uint16(orientation))
}
path := filepath.Join(t.TempDir(), "source.jpg")
require.NoError(t, os.WriteFile(path, data, 0o600))
return path
}
func insertEXIFOrientation(t *testing.T, jpegBytes []byte, orientation uint16) []byte {
t.Helper()
// TIFF: II, 42, IFD0 at offset 8, one entry (0x0112 SHORT 1 = orientation).
tiff := make([]byte, 8+2+12+4)
binary.LittleEndian.PutUint16(tiff[0:2], 0x4949)
binary.LittleEndian.PutUint16(tiff[2:4], 42)
binary.LittleEndian.PutUint32(tiff[4:8], 8)
binary.LittleEndian.PutUint16(tiff[8:10], 1)
binary.LittleEndian.PutUint16(tiff[10:12], 0x0112)
binary.LittleEndian.PutUint16(tiff[12:14], 3)
binary.LittleEndian.PutUint32(tiff[14:18], 1)
binary.LittleEndian.PutUint16(tiff[18:20], orientation)
payload := append([]byte("Exif\x00\x00"), tiff...)
segment := make([]byte, 4+len(payload))
segment[0] = 0xff
segment[1] = 0xe1
binary.BigEndian.PutUint16(segment[2:4], uint16(len(payload)+2))
copy(segment[4:], payload)
// Insert immediately after SOI (before the first DQT/SOF).
out := append([]byte(nil), jpegBytes[:2]...)
out = append(out, segment...)
out = append(out, jpegBytes[2:]...)
return out
}
func decodeConfig(t *testing.T, data []byte) image.Config {
t.Helper()
cfg, _, err := image.DecodeConfig(bytes.NewReader(data))
require.NoError(t, err)
return cfg
}
func TestThumbnailContract(t *testing.T) {
params, ok := imageproc.Pipeline(1)
require.True(t, ok)
cases := []struct {
name string
width int
height int
expected [2]int
}{
{"320x200", 320, 200, [2]int{256, 160}},
{"no upscale 64x64", 64, 64, [2]int{64, 64}},
{"no upscale 64x40", 64, 40, [2]int{64, 40}},
{"floor 1000x10", 1000, 10, [2]int{256, 2}},
{"height limited", 100, 320, [2]int{80, 256}},
{"minimum 1x1", 1, 1, [2]int{1, 1}},
}
for _, test := range cases {
t.Run(test.name, func(t *testing.T) {
img, _, err := imageproc.Load(writePNG(t, test.width, test.height, false), 40_000_000)
require.NoError(t, err)
thumb, err := imageproc.Thumbnail(img, params)
require.NoError(t, err)
cfg := decodeConfig(t, thumb.Data)
require.Equal(t, test.expected[0], cfg.Width)
require.Equal(t, test.expected[1], cfg.Height)
require.Equal(t, test.expected[0], thumb.Width)
require.Equal(t, test.expected[1], thumb.Height)
require.Equal(t, "image/jpeg", thumb.ContentType)
require.NotContains(t, string(thumb.Data), "Exif")
})
}
}
func TestCropAndOptimized(t *testing.T) {
params, ok := imageproc.Pipeline(1)
require.True(t, ok)
img, _, err := imageproc.Load(writePNG(t, 320, 200, false), 40_000_000)
require.NoError(t, err)
crop, err := imageproc.Crop(img, params)
require.NoError(t, err)
cfg := decodeConfig(t, crop.Data)
require.Equal(t, 128, cfg.Width)
require.Equal(t, 128, cfg.Height)
optimized, err := imageproc.Optimized(img, params)
require.NoError(t, err)
cfg = decodeConfig(t, optimized.Data)
require.Equal(t, 320, cfg.Width)
require.Equal(t, 200, cfg.Height)
require.Equal(t, "image/webp", optimized.ContentType)
decoded, err := webp.Decode(bytes.NewReader(optimized.Data))
require.NoError(t, err)
require.Equal(t, 320, decoded.Bounds().Dx())
require.Equal(t, 200, decoded.Bounds().Dy())
}
func TestEXIFOrientationChangesThumbnailDimensions(t *testing.T) {
params, ok := imageproc.Pipeline(1)
require.True(t, ok)
for _, orientation := range []int{6, 8} {
img, _, err := imageproc.Load(writeJPEG(t, 320, 200, orientation), 40_000_000)
require.NoError(t, err)
thumb, err := imageproc.Thumbnail(img, params)
require.NoError(t, err)
cfg := decodeConfig(t, thumb.Data)
require.Equal(t, 160, cfg.Width, "orientation %d", orientation)
require.Equal(t, 256, cfg.Height, "orientation %d", orientation)
}
}
func TestAlphaCompositedOnWhite(t *testing.T) {
params, ok := imageproc.Pipeline(1)
require.True(t, ok)
img, _, err := imageproc.Load(writePNG(t, 100, 100, true), 40_000_000)
require.NoError(t, err)
thumb, err := imageproc.Thumbnail(img, params)
require.NoError(t, err)
decoded, err := jpeg.Decode(bytes.NewReader(thumb.Data))
require.NoError(t, err)
r, g, b, _ := decoded.At(0, 0).RGBA()
require.Greater(t, r, uint32(0xf000), "transparent corner must be white")
require.Greater(t, g, uint32(0xf000), "transparent corner must be white")
require.Greater(t, b, uint32(0xf000), "transparent corner must be white")
}
func TestPipelineVersionsDiffer(t *testing.T) {
v1, ok := imageproc.Pipeline(1)
require.True(t, ok)
v2, ok := imageproc.Pipeline(2)
require.True(t, ok)
require.NotEqual(t, v1, v2)
_, ok = imageproc.Pipeline(3)
require.False(t, ok)
}
func TestVariantNames(t *testing.T) {
require.Equal(t, "image/jpeg", domain.VariantThumbnail.ContentType())
require.Equal(t, "image/jpeg", domain.VariantCrop.ContentType())
require.Equal(t, "image/webp", domain.VariantOptimized.ContentType())
require.Equal(t, "thumbnail.jpg", domain.VariantThumbnail.ObjectName())
require.Equal(t, "optimized.webp", domain.VariantOptimized.ObjectName())
}