feat(lab5): durable async attachment pipeline through grade 4

- RabbitMQ quorum queue, persistent messages and publisher confirms
- S3 staging plus PostgreSQL attachments/jobs outbox transaction
- worker variants (thumbnail, crop, optimized WebP), DB lease and lease sweeper
- jittered retry, permanent failures, explicit replay and admission cap
- deterministic crash hooks, resilience script and evidence for grade 4
- async-aware custom tests, oversized pixel case, docs and changelog
This commit is contained in:
Mikhail Verkovykh
2026-11-15 00:30:36 +03:00
parent 28d68dc30b
commit 9e43faa536
48 changed files with 4077 additions and 333 deletions
+162
View File
@@ -0,0 +1,162 @@
package pipeline
import (
"encoding/binary"
"image"
"io"
)
// jpegOrientation returns the EXIF orientation (1..8) of a JPEG, or 1 when the
// file has no usable EXIF block. Go's image/jpeg intentionally ignores EXIF,
// so the worker applies the transform after decoding. The original bytes are
// never rewritten.
func jpegOrientation(r io.ReadSeeker) int {
defer func() { _, _ = r.Seek(0, 0) }()
if _, err := r.Seek(0, 0); err != nil {
return 1
}
var soi [2]byte
if _, err := io.ReadFull(r, soi[:]); err != nil || soi[0] != 0xff || soi[1] != 0xd8 {
return 1
}
for {
var prefix [1]byte
if _, err := io.ReadFull(r, prefix[:]); err != nil || prefix[0] != 0xff {
return 1
}
marker := byte(0xff)
for marker == 0xff {
if _, err := io.ReadFull(r, prefix[:]); err != nil {
return 1
}
marker = prefix[0]
}
// Markers without a length field, and start-of-scan where metadata
// after it cannot be an APP1 segment we care about.
if marker == 0xd8 || marker == 0xd9 || marker == 0xda ||
marker == 0x01 || (marker >= 0xd0 && marker <= 0xd7) {
return 1
}
var lengthBytes [2]byte
if _, err := io.ReadFull(r, lengthBytes[:]); err != nil {
return 1
}
length := int(binary.BigEndian.Uint16(lengthBytes[:]))
if length < 2 {
return 1
}
payloadLength := length - 2
if marker != 0xe1 || payloadLength < 6 {
if _, err := r.Seek(int64(payloadLength), io.SeekCurrent); err != nil {
return 1
}
continue
}
payload := make([]byte, payloadLength)
if _, err := io.ReadFull(r, payload); err != nil {
return 1
}
if string(payload[:6]) == "Exif\x00\x00" {
return parseTIFFOrientation(payload[6:])
}
}
}
func parseTIFFOrientation(data []byte) int {
if len(data) < 8 {
return 1
}
var order binary.ByteOrder
switch string(data[:2]) {
case "II":
order = binary.LittleEndian
case "MM":
order = binary.BigEndian
default:
return 1
}
if order.Uint16(data[2:4]) != 42 {
return 1
}
ifdOffset := int(order.Uint32(data[4:8]))
if ifdOffset < 8 || ifdOffset+2 > len(data) {
return 1
}
count := int(order.Uint16(data[ifdOffset : ifdOffset+2]))
position := ifdOffset + 2
for index := 0; index < count; index++ {
if position+12 > len(data) {
return 1
}
entry := data[position : position+12]
tag := order.Uint16(entry[0:2])
fieldType := order.Uint16(entry[2:4])
items := order.Uint32(entry[4:8])
if tag == 0x0112 && fieldType == 3 && items >= 1 {
if items == 1 {
value := int(order.Uint16(entry[8:10]))
if value >= 1 && value <= 8 {
return value
}
return 1
}
offset := int(order.Uint32(entry[8:12]))
if offset+2 > len(data) {
return 1
}
value := int(order.Uint16(data[offset : offset+2]))
if value >= 1 && value <= 8 {
return value
}
return 1
}
position += 12
}
return 1
}
// orient applies the eight EXIF orientation transforms. Every branch returns a
// new image except orientation 1, so the caller can treat the result as
// read-only.
func orient(src image.Image, orientation int) image.Image {
if orientation <= 1 || orientation > 8 {
return src
}
bounds := src.Bounds()
width, height := bounds.Dx(), bounds.Dy()
swap := orientation >= 5
outWidth, outHeight := width, height
if swap {
outWidth, outHeight = height, width
}
dst := image.NewRGBA(image.Rect(0, 0, outWidth, outHeight))
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
var nx, ny int
switch orientation {
case 2: // mirror horizontal
nx, ny = width-1-x, y
case 3: // rotate 180
nx, ny = width-1-x, height-1-y
case 4: // mirror vertical
nx, ny = x, height-1-y
case 5: // transpose
nx, ny = y, x
case 6: // rotate 90 clockwise
nx, ny = height-1-y, x
case 7: // transverse
nx, ny = height-1-y, width-1-x
case 8: // rotate 270 clockwise
nx, ny = y, width-1-x
}
dst.Set(nx, ny, src.At(bounds.Min.X+x, bounds.Min.Y+y))
}
}
return dst
}
+252
View File
@@ -0,0 +1,252 @@
// Package pipeline turns one validated original image into the required lab5
// variants. It is deterministic and side-effect free so a broker redelivery can
// simply overwrite the same keys with the same bytes.
package pipeline
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"image"
"image/color"
"image/jpeg"
_ "image/png"
"os"
"github.com/gen2brain/webp"
"golang.org/x/image/draw"
"golang.org/x/sync/semaphore"
)
const (
ThumbnailMax = 256
CropSize = 128
OptimizedMax = 1280
// Re-encoding drops EXIF/XMP/ICC payloads from variants. The original is
// copied byte-for-byte and keeps its metadata and checksum.
JPEGQuality = 85
WebPQuality = 82
WebPMethod = 4
)
type Processor struct {
maxPixels int64
budgetBytes int64
decodeBudget *semaphore.Weighted
}
// Encoded is one variant ready to be uploaded.
type Encoded struct {
Name string
ContentType string
Bytes []byte
Width int
Height int
SHA256 string
}
func New(maxPixels, decodeBudgetBytes int64) *Processor {
return &Processor{
maxPixels: maxPixels,
budgetBytes: decodeBudgetBytes,
decodeBudget: semaphore.NewWeighted(decodeBudgetBytes),
}
}
// Failure classifies pipeline errors for the retry policy. A corrupt image is
// permanent (retrying cannot help); I/O, lease expiry and dependency errors are
// transient.
type Failure struct {
Permanent bool
Code string
Err error
}
func (f *Failure) Error() string {
if f.Err == nil {
return f.Code
}
return f.Code + ": " + f.Err.Error()
}
func (f *Failure) Unwrap() error { return f.Err }
func permanent(code string, err error) *Failure {
return &Failure{Permanent: true, Code: code, Err: err}
}
func transient(code string, err error) *Failure {
return &Failure{Permanent: false, Code: code, Err: err}
}
// Process decodes the file once and returns all variants in memory. Worker
// concurrency and IMAGE_DECODE_MEMORY_MB bound the number of simultaneous
// decoded images, which is the memory-heavy part of the experiment.
func (p *Processor) Process(ctx context.Context, file *os.File) ([]Encoded, error) {
img, err := p.decode(ctx, file)
if err != nil {
return nil, err
}
thumbnail, err := renderJPEG("thumbnail", fitOnWhite(img, ThumbnailMax, ThumbnailMax))
if err != nil {
return nil, permanent("processing_failed", err)
}
crop, err := renderJPEG("crop", centerSquare(img, CropSize))
if err != nil {
return nil, permanent("processing_failed", err)
}
optimized, err := renderWebP(fitOnWhite(img, OptimizedMax, OptimizedMax))
if err != nil {
return nil, permanent("processing_failed", err)
}
return []Encoded{thumbnail, crop, optimized}, nil
}
func (p *Processor) decode(ctx context.Context, file *os.File) (image.Image, error) {
if _, err := file.Seek(0, 0); err != nil {
return nil, transient("storage_read_failed", err)
}
cfg, format, err := image.DecodeConfig(file)
if err != nil {
return nil, permanent("invalid_image", err)
}
if format != "png" && format != "jpeg" {
return nil, permanent("invalid_image", fmt.Errorf("unsupported format %q", format))
}
if cfg.Width <= 0 || cfg.Height <= 0 {
return nil, permanent("invalid_image", errors.New("empty image bounds"))
}
pixels := int64(cfg.Width) * int64(cfg.Height)
if pixels > p.maxPixels {
return nil, permanent("invalid_image", errors.New("image exceeds MAX_IMAGE_PIXELS"))
}
// AGENT: the semaphore is acquired before Decode, not after. A decoder
// allocates roughly width*height*4 bytes; without this gate several 40 MP
// files can OOM the worker even with a small HTTP concurrency.
weight := pixels * 4
if weight > p.budgetBytes {
return nil, permanent("invalid_image", errors.New("image exceeds decode memory budget"))
}
if err = p.decodeBudget.Acquire(ctx, weight); err != nil {
return nil, transient("processing_timeout", err)
}
defer p.decodeBudget.Release(weight)
orientation := jpegOrientation(file)
if _, err = file.Seek(0, 0); err != nil {
return nil, transient("storage_read_failed", err)
}
img, decodeErr := safeDecode(file)
if decodeErr != nil {
return nil, permanent("invalid_image", decodeErr)
}
bounds := img.Bounds()
if bounds.Dx() != cfg.Width || bounds.Dy() != cfg.Height {
return nil, permanent("invalid_image", errors.New("decoded bounds differ from header"))
}
return orient(img, orientation), nil
}
func safeDecode(file *os.File) (img image.Image, err error) {
defer func() {
if recovered := recover(); recovered != nil {
img = nil
err = fmt.Errorf("image decoder panic: %v", recovered)
}
}()
img, _, err = image.Decode(file)
return img, err
}
// fitOnWhite scales down to fit maxWidth x maxHeight, never up. The source is
// composited over white, which is the contract for JPEG variants with alpha.
func fitOnWhite(src image.Image, maxWidth, maxHeight int) *image.RGBA {
bounds := src.Bounds()
width, height := fitSize(bounds.Dx(), bounds.Dy(), maxWidth, maxHeight)
dst := image.NewRGBA(image.Rect(0, 0, width, height))
draw.Draw(dst, dst.Bounds(), &image.Uniform{C: color.White}, image.Point{}, draw.Src)
draw.CatmullRom.Scale(dst, dst.Bounds(), src, bounds, draw.Over, nil)
return dst
}
// centerSquare always produces CropSize x CropSize. Unlike thumbnails, the
// contract allows upscaling tiny sources for the crop variant.
func centerSquare(src image.Image, size int) *image.RGBA {
bounds := src.Bounds()
side := bounds.Dx()
if bounds.Dy() < side {
side = bounds.Dy()
}
x := bounds.Min.X + (bounds.Dx()-side)/2
y := bounds.Min.Y + (bounds.Dy()-side)/2
cropRect := image.Rect(x, y, x+side, y+side)
dst := image.NewRGBA(image.Rect(0, 0, size, size))
draw.Draw(dst, dst.Bounds(), &image.Uniform{C: color.White}, image.Point{}, draw.Src)
draw.CatmullRom.Scale(dst, dst.Bounds(), src, cropRect, draw.Over, nil)
return dst
}
// fitSize preserves aspect ratio, rounds down and clamps to at least 1 px.
// It deliberately never enlarges a small source.
func fitSize(width, height, maxWidth, maxHeight int) (int, int) {
if width <= maxWidth && height <= maxHeight {
return width, height
}
if width*maxHeight >= height*maxWidth {
newHeight := height * maxWidth / width
if newHeight < 1 {
newHeight = 1
}
return maxWidth, newHeight
}
newWidth := width * maxHeight / height
if newWidth < 1 {
newWidth = 1
}
return newWidth, maxHeight
}
func renderJPEG(name string, img image.Image) (Encoded, error) {
var buf bytes.Buffer
if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: JPEGQuality}); err != nil {
return Encoded{}, err
}
bounds := img.Bounds()
return Encoded{
Name: name,
ContentType: "image/jpeg",
Bytes: buf.Bytes(),
Width: bounds.Dx(),
Height: bounds.Dy(),
SHA256: digest(buf.Bytes()),
}, nil
}
func renderWebP(img image.Image) (Encoded, error) {
var buf bytes.Buffer
if err := webp.Encode(&buf, img, webp.Options{Quality: WebPQuality, Method: WebPMethod}); err != nil {
return Encoded{}, err
}
bounds := img.Bounds()
return Encoded{
Name: "optimized",
ContentType: "image/webp",
Bytes: buf.Bytes(),
Width: bounds.Dx(),
Height: bounds.Dy(),
SHA256: digest(buf.Bytes()),
}, nil
}
func digest(data []byte) string {
sum := sha256.Sum256(data)
return hex.EncodeToString(sum[:])
}
+177
View File
@@ -0,0 +1,177 @@
package pipeline
import (
"bytes"
"context"
"encoding/binary"
"image"
"image/color"
"image/jpeg"
"image/png"
"os"
"path/filepath"
"testing"
)
func TestFitSizePreservesAspectAndNeverUpscales(t *testing.T) {
cases := []struct {
w, h, maxW, maxH int
wantW, wantH int
}{
{320, 200, 256, 256, 256, 160},
{200, 320, 256, 256, 160, 256},
{100, 50, 256, 256, 100, 50},
{4000, 1000, 1280, 1280, 1280, 320},
{1000, 4000, 256, 256, 64, 256},
{1, 4000, 256, 256, 1, 256},
}
for _, tc := range cases {
w, h := fitSize(tc.w, tc.h, tc.maxW, tc.maxH)
if w != tc.wantW || h != tc.wantH {
t.Fatalf("fitSize(%d,%d,%d,%d) = %dx%d, want %dx%d",
tc.w, tc.h, tc.maxW, tc.maxH, w, h, tc.wantW, tc.wantH)
}
}
}
func TestProcessProducesContractVariants(t *testing.T) {
file := pngFile(t, 320, 200, false)
variants, err := New(40_000_000, 256<<20).Process(context.Background(), file)
if err != nil {
t.Fatalf("Process: %v", err)
}
if len(variants) != 3 {
t.Fatalf("got %d variants, want 3", len(variants))
}
byName := map[string]Encoded{}
for _, variant := range variants {
byName[variant.Name] = variant
}
thumbnail := byName["thumbnail"]
if thumbnail.ContentType != "image/jpeg" || thumbnail.Width != 256 || thumbnail.Height != 160 {
t.Fatalf("thumbnail = %s %dx%d, want image/jpeg 256x160",
thumbnail.ContentType, thumbnail.Width, thumbnail.Height)
}
decoded, err := jpeg.Decode(bytes.NewReader(thumbnail.Bytes))
if err != nil {
t.Fatalf("decode thumbnail: %v", err)
}
if decoded.Bounds().Dx() != 256 || decoded.Bounds().Dy() != 160 {
t.Fatalf("actual thumbnail bounds = %v", decoded.Bounds())
}
crop := byName["crop"]
if crop.ContentType != "image/jpeg" || crop.Width != 128 || crop.Height != 128 {
t.Fatalf("crop = %s %dx%d", crop.ContentType, crop.Width, crop.Height)
}
optimized := byName["optimized"]
if optimized.ContentType != "image/webp" || optimized.Width != 320 || optimized.Height != 200 {
t.Fatalf("optimized = %s %dx%d, want image/webp 320x200", optimized.ContentType, optimized.Width, optimized.Height)
}
}
func TestThumbnailCompositesAlphaOnWhite(t *testing.T) {
file := pngFile(t, 64, 64, true)
variants, err := New(40_000_000, 256<<20).Process(context.Background(), file)
if err != nil {
t.Fatalf("Process: %v", err)
}
decoded, err := jpeg.Decode(bytes.NewReader(variants[0].Bytes))
if err != nil {
t.Fatalf("decode thumbnail: %v", err)
}
r, g, b, _ := decoded.At(32, 32).RGBA()
if r < 0xf000 || g < 0xf000 || b < 0xf000 {
t.Fatalf("transparent pixel is not white: %04x %04x %04x", r, g, b)
}
}
func TestEXIFOrientationRotatesBeforeResize(t *testing.T) {
file := jpegFileWithOrientation(t, 320, 200, 6)
if got := jpegOrientation(file); got != 6 {
t.Fatalf("jpegOrientation = %d, want 6", got)
}
variants, err := New(40_000_000, 256<<20).Process(context.Background(), file)
if err != nil {
t.Fatalf("Process: %v", err)
}
if variants[0].Width != 160 || variants[0].Height != 256 {
t.Fatalf("oriented thumbnail = %dx%d, want 160x256", variants[0].Width, variants[0].Height)
}
}
func TestParseTIFFOrientationBigEndian(t *testing.T) {
tiff := []byte{
'M', 'M', 0x00, 0x2a, 0x00, 0x00, 0x00, 0x08,
0x00, 0x01,
0x01, 0x12, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x08, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
}
if got := parseTIFFOrientation(tiff); got != 8 {
t.Fatalf("parseTIFFOrientation = %d, want 8", got)
}
}
func pngFile(t *testing.T, width, height int, transparent bool) *os.File {
t.Helper()
img := image.NewRGBA(image.Rect(0, 0, width, height))
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
alpha := uint8(0xff)
if transparent {
alpha = 0
}
img.Set(x, y, color.RGBA{R: 10, G: 120, B: 200, A: alpha})
}
}
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
t.Fatalf("encode png: %v", err)
}
return tempFile(t, "image.png", buf.Bytes())
}
func jpegFileWithOrientation(t *testing.T, width, height int, orientation uint16) *os.File {
t.Helper()
img := image.NewRGBA(image.Rect(0, 0, width, height))
var buf bytes.Buffer
if err := jpeg.Encode(&buf, img, nil); err != nil {
t.Fatalf("encode jpeg: %v", err)
}
payload := []byte{'E', 'x', 'i', 'f', 0, 0}
tiff := make([]byte, 26)
copy(tiff, []byte{'I', 'I'})
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(payload, tiff...)
segment := append([]byte{0xff, 0xe1}, 0, 0)
binary.BigEndian.PutUint16(segment[2:4], uint16(len(payload)+2))
segment = append(segment, payload...)
data := append([]byte{}, buf.Bytes()[:2]...)
data = append(data, segment...)
data = append(data, buf.Bytes()[2:]...)
return tempFile(t, "oriented.jpg", data)
}
func tempFile(t *testing.T, name string, data []byte) *os.File {
t.Helper()
path := filepath.Join(t.TempDir(), name)
if err := os.WriteFile(path, data, 0o600); err != nil {
t.Fatalf("write %s: %v", path, err)
}
file, err := os.Open(path)
if err != nil {
t.Fatalf("open %s: %v", path, err)
}
t.Cleanup(func() { _ = file.Close() })
return file
}