From 97b43a9c98f4dfb573e7ce222efb55e0e4c5c591 Mon Sep 17 00:00:00 2001 From: kk10 Date: Mon, 16 Nov 2026 15:52:49 +0300 Subject: [PATCH] feat(worker): enforce image processing timeout with child process --- cmd/worker/main.go | 18 ++++++++++++ internal/worker/image.go | 46 ++++++++++++++--------------- internal/worker/image_process.go | 50 ++++++++++++++++++++++++++++++++ internal/worker/retry.go | 2 +- student-tests/worker_test.go | 43 +++++++++++++++++++++++++++ 5 files changed, 135 insertions(+), 24 deletions(-) create mode 100644 internal/worker/image_process.go diff --git a/cmd/worker/main.go b/cmd/worker/main.go index 9254e32..cbcbd49 100644 --- a/cmd/worker/main.go +++ b/cmd/worker/main.go @@ -2,6 +2,8 @@ package main import ( "context" + "errors" + "flag" "fmt" "os" "os/signal" @@ -17,6 +19,22 @@ import ( ) func main() { + maxPixels := flag.Int("process-image", 0, "process an image from stdin with the given pixel limit") + flag.Parse() + + if *maxPixels > 0 { + if err := worker.ProcessImage(*maxPixels); err != nil { + if errors.Is(err, worker.ErrInvalidSource) { + os.Exit(2) + } + + fmt.Fprintln(os.Stderr, "process image:", err) + os.Exit(1) + } + + return + } + if err := run(); err != nil { fmt.Fprintln(os.Stderr, "worker:", err) os.Exit(1) diff --git a/internal/worker/image.go b/internal/worker/image.go index b337da5..ae1e7a4 100644 --- a/internal/worker/image.go +++ b/internal/worker/image.go @@ -21,18 +21,18 @@ import ( "mtusi2026-messenger/internal/db" ) -var errInvalidSource = errors.New("invalid source image") +var ErrInvalidSource = errors.New("invalid source image") type imageVariant struct { - name db.AttachmentVariantName - data []byte - contentType string - width, height int + Name db.AttachmentVariantName + Data []byte + ContentType string + Width, Height int } func (w *Worker) process(ctx context.Context, row db.Attachment) ([]db.CreateAttachmentVariantParams, error) { if row.StagingKey == nil { - return nil, errInvalidSource + return nil, ErrInvalidSource } source, err := w.s3.Get(ctx, *row.StagingKey) @@ -60,7 +60,7 @@ func (w *Worker) process(ctx context.Context, row db.Attachment) ([]db.CreateAtt if size != int64(row.SizeBytes) || hex.EncodeToString(hash.Sum(nil)) != row.Sha256 { - return nil, errInvalidSource + return nil, ErrInvalidSource } if _, err := tmp.Seek(0, io.SeekStart); err != nil { @@ -78,7 +78,7 @@ func (w *Worker) process(ctx context.Context, row db.Attachment) ([]db.CreateAtt return nil, err } - images, err := imageVariants(tmp, w.maxPixels) + images, err := runImageProcess(ctx, tmp, w.maxPixels) <-w.decodeSlot if err != nil { return nil, err @@ -98,21 +98,21 @@ func (w *Worker) process(ctx context.Context, row db.Attachment) ([]db.CreateAtt variants := make([]db.CreateAttachmentVariantParams, 0, len(images)) for _, img := range images { - key := "variants/" + row.ID.String() + "/v" + strconv.Itoa(row.PipelineVersion) + "/" + string(img.name) - if err := w.s3.Put(ctx, key, bytes.NewReader(img.data), int64(len(img.data)), img.contentType); err != nil { + key := "variants/" + row.ID.String() + "/v" + strconv.Itoa(row.PipelineVersion) + "/" + string(img.Name) + if err := w.s3.Put(ctx, key, bytes.NewReader(img.Data), int64(len(img.Data)), img.ContentType); err != nil { return nil, err } - sum := sha256.Sum256(img.data) + sum := sha256.Sum256(img.Data) variants = append(variants, db.CreateAttachmentVariantParams{ AttachmentID: row.ID, PipelineVersion: row.PipelineVersion, - Variant: img.name, + Variant: img.Name, S3Key: key, - ContentType: img.contentType, - SizeBytes: len(img.data), - Width: img.width, - Height: img.height, + ContentType: img.ContentType, + SizeBytes: len(img.Data), + Width: img.Width, + Height: img.Height, Sha256: hex.EncodeToString(sum[:]), }) } @@ -127,7 +127,7 @@ func imageVariants(r io.ReadSeeker, maxPixels int) ([]imageVariant, error) { cfg.Width <= 0 || cfg.Height <= 0 || cfg.Width > maxPixels/cfg.Height { - return nil, errInvalidSource + return nil, ErrInvalidSource } if _, err := r.Seek(0, io.SeekStart); err != nil { @@ -136,7 +136,7 @@ func imageVariants(r io.ReadSeeker, maxPixels int) ([]imageVariant, error) { src, err := imaging.Decode(r, imaging.AutoOrientation(true)) if err != nil { - return nil, errInvalidSource + return nil, ErrInvalidSource } variants := make([]imageVariant, 0, 3) @@ -162,11 +162,11 @@ func imageVariants(r io.ReadSeeker, maxPixels int) ([]imageVariant, error) { } variants = append(variants, imageVariant{ - name: item.name, - contentType: contentType, - data: data, - width: item.image.Bounds().Dx(), - height: item.image.Bounds().Dy(), + Name: item.name, + ContentType: contentType, + Data: data, + Width: item.image.Bounds().Dx(), + Height: item.image.Bounds().Dy(), }) } diff --git a/internal/worker/image_process.go b/internal/worker/image_process.go new file mode 100644 index 0000000..4811d5a --- /dev/null +++ b/internal/worker/image_process.go @@ -0,0 +1,50 @@ +package worker + +import ( + "bytes" + "context" + "encoding/gob" + "errors" + "os" + "os/exec" + "strconv" +) + +func ProcessImage(maxPixels int) error { + variants, err := imageVariants(os.Stdin, maxPixels) + if err != nil { + return err + } + + return gob.NewEncoder(os.Stdout).Encode(variants) +} + +func runImageProcess(ctx context.Context, source *os.File, maxPixels int) ([]imageVariant, error) { + executable, err := os.Executable() + if err != nil { + return nil, err + } + + cmd := exec.CommandContext(ctx, executable, "-process-image", strconv.Itoa(maxPixels)) + cmd.Stdin = source + data, err := cmd.Output() + if ctx.Err() != nil { + return nil, ctx.Err() + } + + if err != nil { + var exitErr *exec.ExitError + if errors.As(err, &exitErr) && exitErr.ExitCode() == 2 { + return nil, ErrInvalidSource + } + + return nil, err + } + + var variants []imageVariant + if err := gob.NewDecoder(bytes.NewReader(data)).Decode(&variants); err != nil { + return nil, err + } + + return variants, nil +} diff --git a/internal/worker/retry.go b/internal/worker/retry.go index 5235962..b684fa4 100644 --- a/internal/worker/retry.go +++ b/internal/worker/retry.go @@ -31,7 +31,7 @@ func (w *Worker) finishFailure(ctx context.Context, job model.AttachmentJob, cau } code := "processing_failed" - permanent := errors.Is(cause, errInvalidSource) || errors.Is(cause, s3store.ErrObjectNotFound) + permanent := errors.Is(cause, ErrInvalidSource) || errors.Is(cause, s3store.ErrObjectNotFound) if permanent { code = "invalid_source" } else if errors.Is(cause, context.DeadlineExceeded) { diff --git a/student-tests/worker_test.go b/student-tests/worker_test.go index ef46d58..fd50e0c 100644 --- a/student-tests/worker_test.go +++ b/student-tests/worker_test.go @@ -229,3 +229,46 @@ func TestWorkerRetryExhausted(t *testing.T) { resp.Body.Close() t.Logf("PASS attachment=%s: %d attempts, failed/retry_exhausted, content/link rejected", att.ID, maxAttempts) } + +func TestWorkerProcessingTimeout(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + stopService(t, "worker") + if workerQueue(t) != "0:0" { + t.Fatal("run on an idle stand with an empty attachment queue") + } + + // Decode and resize of 36 million pixels must be interrupted by the short deadline. + resp := uploadAttachment(t, user, chat.ID, "large.png", "image/png", makePNG(t, 6000, 6000)) + requireStatus(t, resp, http.StatusAccepted) + var att dto.AttachmentResponse + mustDecode(t, resp, &att) + + testWorker := "worker-timeout-" + uuid.NewString() + t.Cleanup(func() { + workerCommand(t, "rm", "-f", testWorker) + }) + workerCommand(t, "compose", "run", "-d", "--no-deps", "--name", testWorker, + "-e", "JOB_TIMEOUT_SECONDS=1", "-e", "JOB_MAX_ATTEMPTS=1", "worker") + parentPID := workerCommand(t, "inspect", "--format", "{{.State.Pid}}", testWorker) + workerWait(t, "image child process", 5*time.Second, func() bool { + return strings.Contains(workerCommand(t, "top", testWorker, "-eo", "pid,args"), "-process-image") + }) + failed := waitAttachment(t, user, att.ID, "failed", 5*time.Second) + if failed.ErrorCode == nil || *failed.ErrorCode != "retry_exhausted" { + t.Fatal("expected retry_exhausted after processing deadline") + } + if strings.Contains(workerCommand(t, "top", testWorker, "-eo", "pid,args"), "-process-image") { + t.Fatal("image process survived its deadline") + } + if workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE attachment_id='"+att.ID.String()+"'") != "0" { + t.Fatal("timed-out processing published variants") + } + + // The same parent process must remain usable after terminating the image child. + uploadPNG(t, user, chat.ID) + after := workerCommand(t, "inspect", "--format", "{{.State.Pid}}", testWorker) + if parentPID != after || parentPID == "0" { + t.Fatal("parent worker restarted after the image timeout") + } +}