fix: enforce pipeline lifecycle limits

This commit is contained in:
2026-10-30 13:45:49 +03:00
parent 3835106125
commit aa5d6a6e16
20 changed files with 770 additions and 308 deletions
@@ -1,6 +1,7 @@
package transform
import (
"context"
"encoding/binary"
"errors"
"image"
@@ -9,11 +10,14 @@ import (
var errInvalidEXIF = errors.New("invalid EXIF metadata")
func jpegOrientation(data []byte) (int, error) {
func jpegOrientation(ctx context.Context, data []byte) (int, error) {
if len(data) < 2 || data[0] != 0xff || data[1] != 0xd8 {
return 0, errInvalidEXIF
}
for offset := 2; offset < len(data); {
if err := contextError(ctx); err != nil {
return 0, err
}
if data[offset] != 0xff {
return 0, errInvalidEXIF
}
@@ -43,12 +47,12 @@ func jpegOrientation(data []byte) (int, error) {
if marker != 0xe1 || len(payload) < 6 || string(payload[:6]) != "Exif\x00\x00" {
continue
}
return tiffOrientation(payload[6:])
return tiffOrientation(ctx, payload[6:])
}
return 1, nil
}
func tiffOrientation(data []byte) (int, error) {
func tiffOrientation(ctx context.Context, data []byte) (int, error) {
if len(data) < 8 {
return 0, errInvalidEXIF
}
@@ -74,6 +78,9 @@ func tiffOrientation(data []byte) (int, error) {
return 0, errInvalidEXIF
}
for index := uint64(0); index < count; index++ {
if err := contextError(ctx); err != nil {
return 0, err
}
entry := data[entriesStart+index*12 : entriesStart+(index+1)*12]
if order.Uint16(entry[:2]) != 0x0112 {
continue
@@ -90,7 +97,7 @@ func tiffOrientation(data []byte) (int, error) {
return 1, nil
}
func applyOrientation(source image.Image, orientation int) *image.NRGBA {
func applyOrientation(ctx context.Context, source image.Image, orientation int) (*image.NRGBA, error) {
bounds := source.Bounds()
width, height := bounds.Dx(), bounds.Dy()
outputWidth, outputHeight := width, height
@@ -99,12 +106,20 @@ func applyOrientation(source image.Image, orientation int) *image.NRGBA {
}
output := image.NewNRGBA(image.Rect(0, 0, outputWidth, outputHeight))
for y := 0; y < outputHeight; y++ {
if err := contextError(ctx); err != nil {
return nil, err
}
for x := 0; x < outputWidth; x++ {
if x&255 == 0 {
if err := contextError(ctx); err != nil {
return nil, err
}
}
sourceX, sourceY := orientedSourcePoint(x, y, width, height, orientation)
output.Set(x, y, source.At(bounds.Min.X+sourceX, bounds.Min.Y+sourceY))
}
}
return output
return output, nil
}
func orientedSourcePoint(x, y, width, height, orientation int) (int, int) {
@@ -128,11 +143,19 @@ func orientedSourcePoint(x, y, width, height, orientation int) (int, int) {
}
}
func flattenWhite(source image.Image) *image.NRGBA {
func flattenWhite(ctx context.Context, source image.Image) (*image.NRGBA, error) {
bounds := source.Bounds()
output := image.NewNRGBA(image.Rect(0, 0, bounds.Dx(), bounds.Dy()))
for y := 0; y < bounds.Dy(); y++ {
if err := contextError(ctx); err != nil {
return nil, err
}
for x := 0; x < bounds.Dx(); x++ {
if x&255 == 0 {
if err := contextError(ctx); err != nil {
return nil, err
}
}
r, g, b, a := source.At(bounds.Min.X+x, bounds.Min.Y+y).RGBA()
output.SetNRGBA(x, y, color.NRGBA{
R: uint8((r + 0xffff - a) / 0x101),
@@ -142,5 +165,5 @@ func flattenWhite(source image.Image) *image.NRGBA {
})
}
}
return output
return output, nil
}
@@ -9,6 +9,7 @@ import (
"image"
"image/jpeg"
_ "image/png"
"io"
"math"
"net/http"
@@ -78,7 +79,7 @@ func (p *Processor) Process(ctx context.Context, data []byte, declaredContentTyp
if err := contextError(ctx); err != nil {
return Result{}, err
}
img, format, width, height, orientation, err := p.decode(data, declaredContentType)
img, format, width, height, orientation, err := p.decode(ctx, data, declaredContentType)
if err != nil {
return Result{}, err
}
@@ -86,12 +87,12 @@ func (p *Processor) Process(ctx context.Context, data []byte, declaredContentTyp
return Result{}, err
}
oriented := applyOrientation(img, orientation)
if err := contextError(ctx); err != nil {
oriented, err := applyOrientation(ctx, img, orientation)
if err != nil {
return Result{}, err
}
opaque := flattenWhite(oriented)
if err := contextError(ctx); err != nil {
opaque, err := flattenWhite(ctx, oriented)
if err != nil {
return Result{}, err
}
result := Result{
@@ -99,7 +100,10 @@ func (p *Processor) Process(ctx context.Context, data []byte, declaredContentTyp
Orientation: orientation,
}
thumbnail := fit(opaque, 256, 256, false)
thumbnail, err := fitContext(ctx, opaque, 256, 256, false)
if err != nil {
return Result{}, err
}
result.Thumbnail, err = encodeJPEG(thumbnail, p.config.JPEGQuality)
if err != nil {
return Result{}, err
@@ -109,7 +113,10 @@ func (p *Processor) Process(ctx context.Context, data []byte, declaredContentTyp
}
crop := centeredSquare(opaque)
crop = resize(crop, 128, 128)
crop, err = resizeContext(ctx, crop, 128, 128)
if err != nil {
return Result{}, err
}
result.Crop, err = encodeJPEG(crop, p.config.JPEGQuality)
if err != nil {
return Result{}, err
@@ -118,7 +125,10 @@ func (p *Processor) Process(ctx context.Context, data []byte, declaredContentTyp
return Result{}, err
}
optimized := fit(opaque, 1280, 1280, false)
optimized, err := fitContext(ctx, opaque, 1280, 1280, false)
if err != nil {
return Result{}, err
}
result.Optimized, err = encodeWebP(optimized, p.config.WebPQuality, p.config.WebPMethod)
if err != nil {
return Result{}, err
@@ -129,7 +139,11 @@ func (p *Processor) Process(ctx context.Context, data []byte, declaredContentTyp
return result, nil
}
func (p *Processor) decode(data []byte, declaredContentType string) (image.Image, string, int, int, int, error) {
func (p *Processor) decode(
ctx context.Context,
data []byte,
declaredContentType string,
) (image.Image, string, int, int, int, error) {
if declaredContentType != "image/jpeg" && declaredContentType != "image/png" {
return nil, "", 0, 0, 0, ErrUnsupportedMedia
}
@@ -142,27 +156,48 @@ func (p *Processor) decode(data []byte, declaredContentType string) (image.Image
if http.DetectContentType(data) != declaredContentType {
return nil, "", 0, 0, 0, ErrUnsupportedMedia
}
config, format, err := image.DecodeConfig(bytes.NewReader(data))
config, format, err := image.DecodeConfig(contextReader{ctx: ctx, reader: bytes.NewReader(data)})
if contextErr := contextError(ctx); contextErr != nil {
return nil, "", 0, 0, 0, contextErr
}
if err != nil || contentType(format) != declaredContentType || config.Width < 1 || config.Height < 1 {
return nil, "", 0, 0, 0, ErrInvalidImage
}
if int64(config.Width) > p.config.MaxPixels/int64(config.Height) {
return nil, "", 0, 0, 0, ErrPayloadTooLarge
}
img, decodedFormat, err := image.Decode(bytes.NewReader(data))
img, decodedFormat, err := image.Decode(contextReader{ctx: ctx, reader: bytes.NewReader(data)})
if contextErr := contextError(ctx); contextErr != nil {
return nil, "", 0, 0, 0, contextErr
}
if err != nil || decodedFormat != format {
return nil, "", 0, 0, 0, ErrInvalidImage
}
orientation := 1
if format == "jpeg" {
orientation, err = jpegOrientation(data)
orientation, err = jpegOrientation(ctx, data)
if err != nil {
if contextErr := contextError(ctx); contextErr != nil {
return nil, "", 0, 0, 0, contextErr
}
return nil, "", 0, 0, 0, ErrInvalidImage
}
}
return img, declaredContentType, config.Width, config.Height, orientation, nil
}
type contextReader struct {
ctx context.Context
reader io.Reader
}
func (r contextReader) Read(buffer []byte) (int, error) {
if err := contextError(r.ctx); err != nil {
return 0, err
}
return r.reader.Read(buffer)
}
func contextError(ctx context.Context) error {
select {
case <-ctx.Done():
@@ -64,7 +64,10 @@ func TestFlattenWhiteCompositesAlpha(t *testing.T) {
source.SetNRGBA(0, 0, color.NRGBA{R: 10, G: 20, B: 30, A: 0})
source.SetNRGBA(1, 0, color.NRGBA{R: 100, G: 50, B: 0, A: 128})
result := flattenWhite(source)
result, err := flattenWhite(context.Background(), source)
if err != nil {
t.Fatalf("flatten image: %v", err)
}
if got := result.NRGBAAt(0, 0); got != (color.NRGBA{R: 255, G: 255, B: 255, A: 255}) {
t.Fatalf("transparent pixel: got %#v", got)
}
@@ -154,6 +157,28 @@ func TestProcessHonorsCanceledContext(t *testing.T) {
}
}
func TestResizeStopsAfterCancellation(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
source := cancelingImage{
Image: image.NewNRGBA(image.Rect(0, 0, 256, 256)),
cancel: cancel,
}
_, err := resizeContext(ctx, source, 128, 128)
if !errors.Is(err, context.Canceled) {
t.Fatalf("error: got %v, want %v", err, context.Canceled)
}
}
type cancelingImage struct {
image.Image
cancel context.CancelFunc
}
func (i cancelingImage) At(x, y int) color.Color {
i.cancel()
return i.Image.At(x, y)
}
func TestEstimateMemoryWeight(t *testing.T) {
weight, err := EstimateMemoryWeight(1000, 320, 200)
if err != nil {
@@ -1,14 +1,21 @@
package transform
import (
"context"
"image"
"image/color"
)
func fit(source image.Image, maxWidth, maxHeight int, upscale bool) *image.NRGBA {
func fitContext(
ctx context.Context,
source image.Image,
maxWidth int,
maxHeight int,
upscale bool,
) (*image.NRGBA, error) {
bounds := source.Bounds()
width, height := fitDimensions(bounds.Dx(), bounds.Dy(), maxWidth, maxHeight, upscale)
return resize(source, width, height)
return resizeContext(ctx, source, width, height)
}
func fitDimensions(width, height, maxWidth, maxHeight int, upscale bool) (int, int) {
@@ -43,15 +50,23 @@ func (i croppedImage) At(x, y int) color.Color {
return i.source.At(i.offset.X+x, i.offset.Y+y)
}
func resize(source image.Image, width, height int) *image.NRGBA {
func resizeContext(ctx context.Context, source image.Image, width, height int) (*image.NRGBA, error) {
bounds := source.Bounds()
if bounds.Dx() == width && bounds.Dy() == height {
return copyNRGBA(source)
return copyNRGBAContext(ctx, source)
}
output := image.NewNRGBA(image.Rect(0, 0, width, height))
for y := 0; y < height; y++ {
if err := contextError(ctx); err != nil {
return nil, err
}
y0, y1, fy := sampleCoordinate(y, height, bounds.Dy())
for x := 0; x < width; x++ {
if x&255 == 0 {
if err := contextError(ctx); err != nil {
return nil, err
}
}
x0, x1, fx := sampleCoordinate(x, width, bounds.Dx())
c00 := color.NRGBAModel.Convert(source.At(bounds.Min.X+x0, bounds.Min.Y+y0)).(color.NRGBA)
c10 := color.NRGBAModel.Convert(source.At(bounds.Min.X+x1, bounds.Min.Y+y0)).(color.NRGBA)
@@ -60,7 +75,7 @@ func resize(source image.Image, width, height int) *image.NRGBA {
output.SetNRGBA(x, y, interpolate(c00, c10, c01, c11, fx, fy))
}
}
return output
return output, nil
}
func sampleCoordinate(destination, destinationSize, sourceSize int) (int, int, uint32) {
@@ -93,13 +108,21 @@ func interpolateChannel(c00, c10, c01, c11 uint8, fx, fy uint32) uint8 {
return uint8((value + 1<<31) >> 32)
}
func copyNRGBA(source image.Image) *image.NRGBA {
func copyNRGBAContext(ctx context.Context, source image.Image) (*image.NRGBA, error) {
bounds := source.Bounds()
output := image.NewNRGBA(image.Rect(0, 0, bounds.Dx(), bounds.Dy()))
for y := 0; y < bounds.Dy(); y++ {
if err := contextError(ctx); err != nil {
return nil, err
}
for x := 0; x < bounds.Dx(); x++ {
if x&255 == 0 {
if err := contextError(ctx); err != nil {
return nil, err
}
}
output.Set(x, y, source.At(bounds.Min.X+x, bounds.Min.Y+y))
}
}
return output
return output, nil
}
+60 -4
View File
@@ -27,6 +27,7 @@ import (
type Repository interface {
AttachmentJob(context.Context, string) (model.AttachmentJob, error)
ClaimAttachmentJob(context.Context, string, string, int, int, string, time.Duration) (model.AttachmentJobLease, error)
RenewAttachmentJobLease(context.Context, model.AttachmentJobLease, time.Duration) (bool, error)
CompleteAttachmentJob(context.Context, model.AttachmentJobLease, []model.Variant) (model.JobMutationResult, error)
RetryAttachmentJob(context.Context, model.AttachmentJobLease, string, time.Time) (model.JobMutationResult, error)
FailAttachmentJob(context.Context, model.AttachmentJobLease, string) (model.JobMutationResult, error)
@@ -59,6 +60,7 @@ type Config struct {
WorkerID string
Concurrency int
LeaseDuration time.Duration
HeartbeatInterval time.Duration
ProcessingTimeout time.Duration
ReclaimInterval time.Duration
MaxAttempts int
@@ -119,6 +121,7 @@ func New(
func validateConfig(config Config) error {
if config.WorkerID == "" || config.Concurrency < 1 || config.LeaseDuration <= 0 ||
config.HeartbeatInterval <= 0 || config.HeartbeatInterval >= config.LeaseDuration ||
config.ProcessingTimeout <= 0 || config.ProcessingTimeout >= config.LeaseDuration ||
config.ReclaimInterval <= 0 || config.MaxAttempts < 1 || config.RetryBase <= 0 ||
config.RetryMax < config.RetryBase || config.MaxBytes < 1 || config.MaxPixels < 1 || config.MemoryBytes < 1 {
@@ -218,9 +221,17 @@ func (w *Worker) ProcessDelivery(ctx context.Context, delivery redisstream.Deliv
return ErrInjectedFailure
}
processingCtx, cancel := context.WithTimeout(ctx, w.config.ProcessingTimeout)
processingCtx, cancelProcessing := context.WithTimeout(ctx, w.config.ProcessingTimeout)
heartbeatCtx, cancelHeartbeat := context.WithCancel(ctx)
heartbeatDone := make(chan error, 1)
go func() { heartbeatDone <- w.maintainLease(heartbeatCtx, cancelProcessing, lease) }()
variants, err := w.process(processingCtx, lease)
cancel()
cancelProcessing()
cancelHeartbeat()
heartbeatErr := <-heartbeatDone
if heartbeatErr != nil {
return heartbeatErr
}
if err != nil {
result, err = w.resolveProcessingFailure(ctx, delivery, lease, err)
return err
@@ -252,6 +263,34 @@ func (w *Worker) ProcessDelivery(ctx context.Context, delivery redisstream.Deliv
return nil
}
func (w *Worker) maintainLease(
ctx context.Context,
cancelProcessing context.CancelFunc,
lease model.AttachmentJobLease,
) error {
ticker := time.NewTicker(w.config.HeartbeatInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return nil
case <-ticker.C:
renewed, err := w.repository.RenewAttachmentJobLease(ctx, lease, w.config.LeaseDuration)
if err != nil {
if ctx.Err() != nil {
return nil
}
cancelProcessing()
return fmt.Errorf("renew attachment job lease: %w", err)
}
if !renewed {
cancelProcessing()
return model.ErrStaleLease
}
}
}
}
func (w *Worker) resolveClaim(
ctx context.Context,
delivery redisstream.Delivery,
@@ -295,15 +334,18 @@ func (w *Worker) process(ctx context.Context, lease model.AttachmentJobLease) ([
return nil, err
}
defer func() { _ = body.Close() }()
data, err := io.ReadAll(io.LimitReader(body, w.config.MaxBytes+1))
data, err := io.ReadAll(io.LimitReader(contextReader{ctx: ctx, reader: body}, w.config.MaxBytes+1))
if err != nil {
return nil, err
}
if int64(len(data)) > w.config.MaxBytes {
return nil, transform.ErrPayloadTooLarge
}
imageConfig, _, err := image.DecodeConfig(bytes.NewReader(data))
imageConfig, _, err := image.DecodeConfig(contextReader{ctx: ctx, reader: bytes.NewReader(data)})
if err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
return nil, transform.ErrInvalidImage
}
weight, err := transform.EstimateMemoryWeight(int64(len(data)), imageConfig.Width, imageConfig.Height)
@@ -346,6 +388,20 @@ func (w *Worker) process(ctx context.Context, lease model.AttachmentJobLease) ([
return result, nil
}
type contextReader struct {
ctx context.Context
reader io.Reader
}
func (r contextReader) Read(buffer []byte) (int, error) {
select {
case <-r.ctx.Done():
return 0, r.ctx.Err()
default:
return r.reader.Read(buffer)
}
}
var errWorkerCapacity = errors.New("image exceeds worker memory budget")
func variantObjectKey(attachmentID string, pipelineVersion int, name string, value transform.Variant) string {
@@ -1,13 +1,16 @@
package worker
import (
"context"
"errors"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/require"
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/messenger/attachment/transform"
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/objectstore"
)
@@ -46,11 +49,61 @@ func TestProcessingErrorClassification(t *testing.T) {
}
}
func TestLeaseHeartbeatRenewsUntilCanceled(t *testing.T) {
var renewals atomic.Int32
repository := &repositoryStub{renew: func(context.Context, model.AttachmentJobLease, time.Duration) (bool, error) {
renewals.Add(1)
return true, nil
}}
config := validConfig()
config.HeartbeatInterval = 5 * time.Millisecond
worker := &Worker{repository: repository, config: config}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- worker.maintainLease(ctx, cancel, testLease()) }()
require.Eventually(t, func() bool { return renewals.Load() >= 2 }, time.Second, time.Millisecond)
cancel()
require.NoError(t, <-done)
}
func TestLeaseHeartbeatCancelsProcessingWhenLeaseIsLost(t *testing.T) {
repository := &repositoryStub{renew: func(context.Context, model.AttachmentJobLease, time.Duration) (bool, error) {
return false, nil
}}
config := validConfig()
config.HeartbeatInterval = time.Millisecond
worker := &Worker{repository: repository, config: config}
ctx, cancel := context.WithCancel(context.Background())
err := worker.maintainLease(ctx, cancel, testLease())
require.ErrorIs(t, err, model.ErrStaleLease)
require.ErrorIs(t, ctx.Err(), context.Canceled)
}
type repositoryStub struct {
Repository
renew func(context.Context, model.AttachmentJobLease, time.Duration) (bool, error)
}
func (s *repositoryStub) RenewAttachmentJobLease(
ctx context.Context,
lease model.AttachmentJobLease,
duration time.Duration,
) (bool, error) {
return s.renew(ctx, lease, duration)
}
func testLease() model.AttachmentJobLease {
return model.AttachmentJobLease{Job: model.AttachmentJob{
ID: "11111111-1111-4111-8111-111111111111", LeaseToken: "lease-token", LeaseOwner: "worker-1",
}}
}
func validConfig() Config {
return Config{
WorkerID: "worker-1", Concurrency: 2, LeaseDuration: 30 * time.Second,
ProcessingTimeout: 20 * time.Second, ReclaimInterval: 5 * time.Second,
MaxAttempts: 5, RetryBase: time.Second, RetryMax: 30 * time.Second,
HeartbeatInterval: 5 * time.Second, ProcessingTimeout: 20 * time.Second,
ReclaimInterval: 5 * time.Second,
MaxAttempts: 5, RetryBase: time.Second, RetryMax: 30 * time.Second,
MaxBytes: 10 * 1024 * 1024, MaxPixels: 40_000_000, MemoryBytes: 704 * 1024 * 1024,
}
}