Реализовать уровень 4 и упорядочить структуру backend
Добавить crop и WebP, изолированную обработку с таймаутом, lease token, backoff с jitter, реестр failed, безопасный replay и очистку staging. Добавить проверки crash-окон и восстановления. Разделить запуск API, CLI-команды, фоновые процессы и инфраструктуру по пакетам.
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
package workers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
|
||||
"messenger/src/backend/internal/faults"
|
||||
"messenger/src/backend/repositories"
|
||||
"messenger/src/backend/services"
|
||||
)
|
||||
|
||||
func processImage(ctx context.Context, objects services.AttachmentObjects, a repositories.Attachment, staging string) ([]repositories.Variant, string, error) {
|
||||
return publishImage(ctx, objects, a, staging, func(ctx context.Context, data []byte) ([]encodedVariant, string, error) {
|
||||
return renderInSubprocess(ctx, a.ID, data)
|
||||
})
|
||||
}
|
||||
|
||||
func publishImage(ctx context.Context, objects services.AttachmentObjects, a repositories.Attachment, staging string, render imageRenderer) ([]repositories.Variant, string, error) {
|
||||
reader, err := objects.Get(ctx, staging)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(reader, services.MaxUploadBytes+1))
|
||||
reader.Close()
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
digest := sha256.Sum256(data)
|
||||
if len(data) > int(services.MaxUploadBytes) || int64(len(data)) != a.SizeBytes || hex.EncodeToString(digest[:]) != a.SHA256 {
|
||||
return nil, "invalid_image", errors.New("invalid staging checksum or size")
|
||||
}
|
||||
variants, code, err := render(ctx, data)
|
||||
if err != nil {
|
||||
return nil, code, err
|
||||
}
|
||||
if err = objects.Put(ctx, a.ObjectKey, bytes.NewReader(data), a.SizeBytes, a.ContentType); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
metadata := []repositories.Variant{}
|
||||
for _, variant := range variants {
|
||||
extension := ".jpg"
|
||||
if variant.Metadata.Name == "optimized" {
|
||||
extension = ".webp"
|
||||
}
|
||||
key := "variants/" + a.ID + "/v1/" + variant.Metadata.Name + extension
|
||||
if err = objects.Put(ctx, key, bytes.NewReader(variant.Data), int64(len(variant.Data)), variant.Metadata.ContentType); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
metadata = append(metadata, variant.Metadata)
|
||||
}
|
||||
faults.Crash("after_object_before_commit", a.ID)
|
||||
return metadata, "", nil
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package workers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"os/exec"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/image/webp"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
)
|
||||
|
||||
type imageObjects map[string][]byte
|
||||
|
||||
func (o imageObjects) Get(_ context.Context, key string) (io.ReadCloser, error) {
|
||||
return io.NopCloser(bytes.NewReader(o[key])), nil
|
||||
}
|
||||
func (o imageObjects) Put(_ context.Context, key string, r io.Reader, _ int64, _ string) error {
|
||||
b, e := io.ReadAll(r)
|
||||
o[key] = b
|
||||
return e
|
||||
}
|
||||
func TestThumbnailContract(t *testing.T) {
|
||||
if _, err := exec.LookPath("cwebp"); err != nil {
|
||||
t.Skip("cwebp: use Docker builder tests")
|
||||
}
|
||||
for _, size := range [][4]int{{320, 200, 256, 160}, {200, 320, 160, 256}, {17, 9, 17, 9}, {1000, 1, 256, 1}} {
|
||||
t.Run(fmt.Sprintf("%dx%d", size[0], size[1]), func(t *testing.T) {
|
||||
var source bytes.Buffer
|
||||
if err := png.Encode(&source, image.NewNRGBA(image.Rect(0, 0, size[0], size[1]))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
digest := sha256.Sum256(source.Bytes())
|
||||
o := imageObjects{"staging": source.Bytes()}
|
||||
a := repositories.Attachment{ID: "sample", ObjectKey: "originals/sample", SizeBytes: int64(source.Len()), SHA256: hex.EncodeToString(digest[:]), ContentType: "image/png"}
|
||||
variants, code, err := publishImage(context.Background(), o, a, "staging", renderImage)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", code, err)
|
||||
}
|
||||
thumb, err := jpeg.Decode(bytes.NewReader(o["variants/sample/v1/thumbnail.jpg"]))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(variants) != 3 {
|
||||
t.Fatal("three variants required")
|
||||
}
|
||||
crop, err := jpeg.Decode(bytes.NewReader(o["variants/sample/v1/crop.jpg"]))
|
||||
if err != nil || crop.Bounds().Dx() != 128 || crop.Bounds().Dy() != 128 {
|
||||
t.Fatal("invalid crop", err)
|
||||
}
|
||||
optimized, err := webp.Decode(bytes.NewReader(o["variants/sample/v1/optimized.webp"]))
|
||||
if err != nil || optimized.Bounds().Dx() != size[0] || optimized.Bounds().Dy() != size[1] {
|
||||
t.Fatal("invalid optimized", err)
|
||||
}
|
||||
wantW, wantH := size[2], size[3]
|
||||
if thumb.Bounds().Dx() != wantW || thumb.Bounds().Dy() != wantH || variants[0].Width != wantW || variants[0].Height != wantH {
|
||||
t.Fatalf("wrong dimensions: %v", thumb.Bounds())
|
||||
}
|
||||
pixel := color.RGBAModel.Convert(thumb.At(0, 0)).(color.RGBA)
|
||||
if pixel.R < 250 || pixel.G < 250 || pixel.B < 250 {
|
||||
t.Fatal("alpha not composited on white")
|
||||
}
|
||||
if !bytes.Equal(o[a.ObjectKey], source.Bytes()) {
|
||||
t.Fatal("original changed")
|
||||
}
|
||||
first := append([]byte{}, o["variants/sample/v1/thumbnail.jpg"]...)
|
||||
if _, _, err = publishImage(context.Background(), o, a, "staging", renderImage); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(o) != 5 || !bytes.Equal(first, o["variants/sample/v1/thumbnail.jpg"]) {
|
||||
t.Fatal("redelivery changed or multiplied effects")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestThumbnailAppliesEXIFOrientation(t *testing.T) {
|
||||
if _, err := exec.LookPath("cwebp"); err != nil {
|
||||
t.Skip("cwebp: use Docker builder tests")
|
||||
}
|
||||
var source bytes.Buffer
|
||||
if err := jpeg.Encode(&source, image.NewRGBA(image.Rect(0, 0, 320, 200)), nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// APP1 Exif, little-endian TIFF, one SHORT Orientation entry with value 6.
|
||||
exif := []byte{'E', 'x', 'i', 'f', 0, 0, 'I', 'I', 42, 0, 8, 0, 0, 0, 1, 0, 0x12, 1, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0}
|
||||
data := append([]byte{}, source.Bytes()[:2]...)
|
||||
data = append(data, 0xff, 0xe1, 0, byte(len(exif)+2))
|
||||
data = append(data, exif...)
|
||||
data = append(data, source.Bytes()[2:]...)
|
||||
digest := sha256.Sum256(data)
|
||||
o := imageObjects{"staging": data}
|
||||
a := repositories.Attachment{ID: "rotated", ObjectKey: "originals/rotated", SizeBytes: int64(len(data)), SHA256: hex.EncodeToString(digest[:]), ContentType: "image/jpeg"}
|
||||
variants, _, err := publishImage(context.Background(), o, a, "staging", renderImage)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if variants[0].Width != 160 || variants[0].Height != 256 {
|
||||
t.Fatalf("orientation ignored: %+v", variants[0])
|
||||
}
|
||||
if !bytes.Equal(o[a.ObjectKey], data) {
|
||||
t.Fatal("original EXIF modified")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOptimizedBoundsAndCenteredCrop(t *testing.T) {
|
||||
if _, err := exec.LookPath("cwebp"); err != nil {
|
||||
t.Skip("cwebp: use Docker builder tests")
|
||||
}
|
||||
var original bytes.Buffer
|
||||
if err := png.Encode(&original, image.NewNRGBA(image.Rect(0, 0, 1600, 1000))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
variants, _, err := renderImage(context.Background(), original.Bytes())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
optimized, err := webp.Decode(bytes.NewReader(variants[2].Data))
|
||||
if err != nil || optimized.Bounds().Dx() != 1280 || optimized.Bounds().Dy() != 800 {
|
||||
t.Fatal("optimized must fit 1280x1280", err)
|
||||
}
|
||||
stripe := image.NewNRGBA(image.Rect(0, 0, 4, 2))
|
||||
for y := 0; y < 2; y++ {
|
||||
for x := 0; x < 4; x++ {
|
||||
c := color.NRGBA{G: 255, A: 255}
|
||||
if x == 0 {
|
||||
c = color.NRGBA{R: 255, A: 255}
|
||||
}
|
||||
if x == 3 {
|
||||
c = color.NRGBA{B: 255, A: 255}
|
||||
}
|
||||
stripe.SetNRGBA(x, y, c)
|
||||
}
|
||||
}
|
||||
original = bytes.Buffer{}
|
||||
if err = png.Encode(&original, stripe); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
variants, _, err = renderImage(context.Background(), original.Bytes())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crop, err := jpeg.Decode(bytes.NewReader(variants[1].Data))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pixel := color.NRGBAModel.Convert(crop.At(64, 64)).(color.NRGBA)
|
||||
if pixel.G < 240 || pixel.R > 15 || pixel.B > 15 {
|
||||
t.Fatal("crop did not preserve the green center", pixel)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package workers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func positiveEnv(name string, fallback int) (int, error) {
|
||||
s := os.Getenv(name)
|
||||
if s == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
n, e := strconv.Atoi(s)
|
||||
if e != nil || n < 1 || n > 3600 {
|
||||
return 0, errors.New("invalid " + name)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package workers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"time"
|
||||
|
||||
"messenger/src/backend/internal/faults"
|
||||
"messenger/src/backend/repositories"
|
||||
"messenger/src/backend/services"
|
||||
)
|
||||
|
||||
type boundedOutput struct{ bytes.Buffer }
|
||||
|
||||
func (b *boundedOutput) Write(data []byte) (int, error) {
|
||||
if b.Len()+len(data) > 8*1024*1024 {
|
||||
return 0, errors.New("image result exceeds limit")
|
||||
}
|
||||
return b.Buffer.Write(data)
|
||||
}
|
||||
|
||||
func renderInSubprocess(ctx context.Context, id string, data []byte) ([]encodedVariant, string, error) {
|
||||
seconds, err := positiveEnv("JOB_TIMEOUT_SECONDS", 60)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
task, cancel := context.WithTimeout(ctx, time.Duration(seconds)*time.Second)
|
||||
defer cancel()
|
||||
executable, err := os.Executable()
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
// The parent owns scratch files, so killing a child cannot leak its PNG files.
|
||||
directory, err := os.MkdirTemp("", "image-job-*")
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
defer os.RemoveAll(directory)
|
||||
command := exec.CommandContext(task, executable, "image-process", id)
|
||||
// No database, broker or S3 credentials are needed by a decoder.
|
||||
command.Env = []string{"PATH=/usr/bin:/bin", "GOMAXPROCS=1", "GOMEMLIMIT=256MiB", "WORKER_MAX_PIXELS=" + workerPixelLimit(), "PIPELINE_FAULT_DIR=" + os.Getenv("PIPELINE_FAULT_DIR")}
|
||||
command.Env = append(command.Env, "TMPDIR="+directory)
|
||||
isolateImageProcess(command)
|
||||
command.Stdin = bytes.NewReader(data)
|
||||
var output boundedOutput
|
||||
command.Stdout = &output
|
||||
err = command.Run()
|
||||
if task.Err() != nil {
|
||||
return nil, "", repositories.ErrProcessingTimeout
|
||||
}
|
||||
if err != nil {
|
||||
return nil, "", errors.New("image child terminated")
|
||||
}
|
||||
var result imageResult
|
||||
if err = json.Unmarshal(output.Bytes(), &result); err != nil {
|
||||
return nil, "", errors.New("invalid image child output")
|
||||
}
|
||||
if result.ErrorCode != "" {
|
||||
return nil, result.ErrorCode, errors.New("invalid image")
|
||||
}
|
||||
if len(result.Variants) != 3 {
|
||||
return nil, "", errors.New("incomplete image child output")
|
||||
}
|
||||
return result.Variants, "", nil
|
||||
}
|
||||
|
||||
func workerPixelLimit() string {
|
||||
if value := os.Getenv("WORKER_MAX_PIXELS"); value != "" {
|
||||
return value
|
||||
}
|
||||
return "8000000"
|
||||
}
|
||||
|
||||
func RunImageChild(args []string) error {
|
||||
if len(args) != 1 {
|
||||
return errors.New("image id required")
|
||||
}
|
||||
if faults.Take("transform_delay", args[0]) {
|
||||
time.Sleep(time.Hour)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(os.Stdin, services.MaxUploadBytes+1))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(data) > int(services.MaxUploadBytes) {
|
||||
return json.NewEncoder(os.Stdout).Encode(imageResult{ErrorCode: "invalid_image"})
|
||||
}
|
||||
variants, code, err := renderImage(context.Background(), data)
|
||||
if err != nil && code == "" {
|
||||
return err
|
||||
}
|
||||
return json.NewEncoder(os.Stdout).Encode(imageResult{Variants: variants, ErrorCode: code})
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package workers
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
func isolateImageProcess(command *exec.Cmd) {
|
||||
command.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
// Kill the whole group, including cwebp, on timeout or shutdown.
|
||||
command.Cancel = func() error { return syscall.Kill(-command.Process.Pid, syscall.SIGKILL) }
|
||||
command.WaitDelay = time.Second
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package workers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
|
||||
"github.com/disintegration/imaging"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
"messenger/src/backend/services"
|
||||
)
|
||||
|
||||
type encodedVariant struct {
|
||||
Metadata repositories.Variant `json:"metadata"`
|
||||
Data []byte `json:"data"`
|
||||
}
|
||||
type imageResult struct {
|
||||
Variants []encodedVariant `json:"variants"`
|
||||
ErrorCode string `json:"error_code"`
|
||||
}
|
||||
type imageRenderer func(context.Context, []byte) ([]encodedVariant, string, error)
|
||||
|
||||
func fitSize(w, h, limit int) (int, int) {
|
||||
if w > limit || h > limit {
|
||||
if w >= h {
|
||||
h = max(1, h*limit/w)
|
||||
w = limit
|
||||
} else {
|
||||
w = max(1, w*limit/h)
|
||||
h = limit
|
||||
}
|
||||
}
|
||||
return w, h
|
||||
}
|
||||
func opaque(source image.Image) image.Image {
|
||||
result := image.NewRGBA(source.Bounds())
|
||||
draw.Draw(result, result.Bounds(), &image.Uniform{C: color.White}, image.Point{}, draw.Src)
|
||||
draw.Draw(result, result.Bounds(), source, source.Bounds().Min, draw.Over)
|
||||
return result
|
||||
}
|
||||
|
||||
// renderImage runs only in the disposable image child in production. DecodeConfig
|
||||
// bounds pixels before allocation; the container bounds total memory to 512 MiB.
|
||||
func renderImage(ctx context.Context, data []byte) ([]encodedVariant, string, error) {
|
||||
pixels, err := strconv.Atoi(workerPixelLimit())
|
||||
if err != nil || pixels < 1 || int64(pixels) > services.MaxImagePixels {
|
||||
return nil, "", errors.New("invalid WORKER_MAX_PIXELS")
|
||||
}
|
||||
config, _, err := image.DecodeConfig(bytes.NewReader(data))
|
||||
if err != nil || config.Width < 1 || config.Height < 1 || int64(config.Width) > int64(pixels)/int64(config.Height) {
|
||||
return nil, "invalid_image", errors.New("image dimensions exceed worker limit")
|
||||
}
|
||||
source, err := imaging.Decode(bytes.NewReader(data), imaging.AutoOrientation(true))
|
||||
if err != nil {
|
||||
return nil, "invalid_image", err
|
||||
}
|
||||
result := []encodedVariant{}
|
||||
appendVariant := func(name, mime string, img image.Image, body []byte) {
|
||||
digest := sha256.Sum256(body)
|
||||
result = append(result, encodedVariant{repositories.Variant{Name: name, ContentType: mime, SizeBytes: int64(len(body)), Width: img.Bounds().Dx(), Height: img.Bounds().Dy(), SHA256: hex.EncodeToString(digest[:])}, body})
|
||||
}
|
||||
w, h := fitSize(source.Bounds().Dx(), source.Bounds().Dy(), 256)
|
||||
thumbnail := opaque(imaging.Resize(source, w, h, imaging.Lanczos))
|
||||
var body bytes.Buffer
|
||||
if err = jpeg.Encode(&body, thumbnail, &jpeg.Options{Quality: 85}); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
appendVariant("thumbnail", "image/jpeg", thumbnail, body.Bytes())
|
||||
crop := opaque(imaging.Fill(source, 128, 128, imaging.Center, imaging.Lanczos))
|
||||
body = bytes.Buffer{}
|
||||
if err = jpeg.Encode(&body, crop, &jpeg.Options{Quality: 85}); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
appendVariant("crop", "image/jpeg", crop, body.Bytes())
|
||||
w, h = fitSize(source.Bounds().Dx(), source.Bounds().Dy(), 1280)
|
||||
optimized := imaging.Resize(source, w, h, imaging.Lanczos)
|
||||
directory, err := os.MkdirTemp("", "image-process-*")
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
defer os.RemoveAll(directory)
|
||||
input := directory + "/input.png"
|
||||
file, err := os.Create(input)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
err = png.Encode(file, optimized)
|
||||
closeErr := file.Close()
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if closeErr != nil {
|
||||
return nil, "", closeErr
|
||||
}
|
||||
command := exec.CommandContext(ctx, "cwebp", "-quiet", "-q", "80", "-m", "4", "-metadata", "none", input, "-o", "-")
|
||||
webp, err := command.Output()
|
||||
if err != nil {
|
||||
return nil, "", errors.New("WebP encoding failed")
|
||||
}
|
||||
appendVariant("optimized", "image/webp", optimized, webp)
|
||||
return result, "", nil
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package workers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"messenger/src/backend/internal/faults"
|
||||
"messenger/src/backend/repositories"
|
||||
"messenger/src/backend/services"
|
||||
)
|
||||
|
||||
func RunPipeline(mode string, args []string) error {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
db, err := repositories.OpenDatabase(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer db.Close()
|
||||
store := repositories.NewAttachmentStore(db)
|
||||
data, err := os.ReadFile(os.Getenv("BROKER_URL_FILE"))
|
||||
if err != nil {
|
||||
return errors.New("cannot read broker URL")
|
||||
}
|
||||
|
||||
address := strings.TrimSpace(string(data))
|
||||
if mode == "broker-publish" {
|
||||
var job repositories.Job
|
||||
if len(args) != 1 || json.Unmarshal([]byte(args[0]), &job) != nil || job.SchemaVersion != 1 || job.Type != "attachment.process.v1" {
|
||||
return errors.New("valid internal job JSON required")
|
||||
}
|
||||
broker, e := repositories.NewJobBroker(ctx, address)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
defer broker.Close()
|
||||
publishCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
return broker.Publish(publishCtx, []byte(args[0]))
|
||||
}
|
||||
maxAttempts, err := positiveEnv("JOB_MAX_ATTEMPTS", 5)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
seconds, err := positiveEnv("JOB_TIMEOUT_SECONDS", 60)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
timeout := time.Duration(seconds) * time.Second
|
||||
objects, err := repositories.NewObjectStoreFromEnvironment()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for ctx.Err() == nil {
|
||||
broker, e := repositories.NewJobBroker(ctx, address)
|
||||
if e == nil {
|
||||
if mode == "dispatcher" {
|
||||
e = dispatchJobs(ctx, store, broker)
|
||||
} else {
|
||||
e = consumeJobs(ctx, store, objects, broker, maxAttempts, timeout)
|
||||
}
|
||||
broker.Close()
|
||||
}
|
||||
if e != nil && ctx.Err() == nil {
|
||||
log.Print("pipeline: broker session interrupted; reconnecting")
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func dispatchJobs(ctx context.Context, store *repositories.AttachmentStore, broker *repositories.JobBroker) error {
|
||||
for ctx.Err() == nil {
|
||||
jobs, err := store.QueuedJobs(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, job := range jobs {
|
||||
faults.Crash("after_commit_before_publish", job.AttachmentID)
|
||||
payload, err := json.Marshal(job)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
publishCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
err = broker.Publish(publishCtx, payload)
|
||||
cancel()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Only confirmed publications are marked. Uncertainty causes safe duplicates.
|
||||
if err = store.MarkPublished(ctx, job.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func consumeJobs(ctx context.Context, store *repositories.AttachmentStore, objects services.AttachmentObjects, broker *repositories.JobBroker, maxAttempts int, timeout time.Duration) error {
|
||||
deliveries, err := broker.Consume()
|
||||
if err != nil {
|
||||
return errors.New("RabbitMQ consumer unavailable")
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case message, ok := <-deliveries:
|
||||
if !ok {
|
||||
return errors.New("RabbitMQ consumer disconnected")
|
||||
}
|
||||
var job repositories.Job
|
||||
if json.Unmarshal(message.Body, &job) != nil || job.SchemaVersion != 1 || job.Type != "attachment.process.v1" {
|
||||
log.Print("worker: invalid internal job rejected")
|
||||
if err = message.Reject(false); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
task, cancel := context.WithTimeout(ctx, timeout+15*time.Second)
|
||||
token, workErr := store.StartAttempt(task, job, timeout+15*time.Second, maxAttempts)
|
||||
if workErr == nil && token != "" {
|
||||
workErr = store.ProcessJob(task, job, token, maxAttempts, func(a repositories.Attachment, staging string) ([]repositories.Variant, string, error) {
|
||||
return processImage(task, objects, a, staging)
|
||||
})
|
||||
}
|
||||
cancel()
|
||||
completed := token != "" && workErr == nil
|
||||
if workErr == nil && token == "" {
|
||||
completed, workErr = store.JobTerminal(ctx, job.ID)
|
||||
}
|
||||
// Ack after COMMIT of ready/failed or durable retry intent, or terminal no-op.
|
||||
// A closed connection automatically returns unacked deliveries to RabbitMQ.
|
||||
if completed {
|
||||
faults.Crash("after_commit_before_ack", job.AttachmentID)
|
||||
if objectStore, ok := objects.(*repositories.ObjectStore); ok {
|
||||
cleanupCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
_, cleanupErr := store.CleanupJobStaging(cleanupCtx, job.ID, 24*time.Hour, false, objectStore.Delete)
|
||||
cancel()
|
||||
if cleanupErr != nil {
|
||||
log.Print("worker: staging cleanup deferred")
|
||||
}
|
||||
}
|
||||
if err = message.Ack(false); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if err = message.Nack(false, true); err != nil {
|
||||
return err
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user