forked from mtusi2026/mtusi2026lab6
feat(lab6): add observability and SLO burn-rate alerts
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RetryDelay returns exponential backoff with deterministic per-job jitter in
|
||||
// [0.5, 1.5). Determinism makes retries reproducible while still avoiding a
|
||||
// synchronized retry wave across different jobs.
|
||||
func RetryDelay(jobID string, nextAttempt int, base, maximum time.Duration) time.Duration {
|
||||
if base <= 0 {
|
||||
base = time.Millisecond
|
||||
}
|
||||
if maximum < base {
|
||||
maximum = base
|
||||
}
|
||||
exponent := nextAttempt - 2
|
||||
if exponent < 0 {
|
||||
exponent = 0
|
||||
}
|
||||
delay := base
|
||||
for index := 0; index < exponent && delay < maximum; index++ {
|
||||
if delay > maximum/2 {
|
||||
delay = maximum
|
||||
break
|
||||
}
|
||||
delay *= 2
|
||||
}
|
||||
if delay > maximum {
|
||||
delay = maximum
|
||||
}
|
||||
sum := sha256.Sum256([]byte(jobID + ":" + strconv.Itoa(nextAttempt)))
|
||||
fraction := float64(binary.BigEndian.Uint64(sum[:8])) / float64(^uint64(0))
|
||||
jittered := time.Duration(float64(delay) * (0.5 + fraction))
|
||||
if jittered > maximum {
|
||||
return maximum
|
||||
}
|
||||
if jittered < time.Millisecond {
|
||||
return time.Millisecond
|
||||
}
|
||||
return jittered
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRetryDelayUsesBoundedExponentialJitter(t *testing.T) {
|
||||
base := 200 * time.Millisecond
|
||||
maximum := 2 * time.Second
|
||||
previousCeiling := time.Duration(0)
|
||||
for attempt := 2; attempt <= 8; attempt++ {
|
||||
delay := RetryDelay("job-a", attempt, base, maximum)
|
||||
if delay < time.Millisecond || delay > maximum {
|
||||
t.Fatalf("attempt %d delay out of bounds: %v", attempt, delay)
|
||||
}
|
||||
ceiling := base << (attempt - 2)
|
||||
if ceiling > maximum {
|
||||
ceiling = maximum
|
||||
}
|
||||
upper := ceiling + ceiling/2
|
||||
if upper > maximum {
|
||||
upper = maximum
|
||||
}
|
||||
if delay < ceiling/2 || delay > upper {
|
||||
t.Fatalf("attempt %d delay %v outside jitter range [%v,%v]", attempt, delay, ceiling/2, upper)
|
||||
}
|
||||
if ceiling < previousCeiling {
|
||||
t.Fatalf("backoff ceiling decreased")
|
||||
}
|
||||
previousCeiling = ceiling
|
||||
}
|
||||
if first, second := RetryDelay("job-a", 3, base, maximum), RetryDelay("job-a", 3, base, maximum); first != second {
|
||||
t.Fatalf("jitter must be reproducible: %v != %v", first, second)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab6/internal/adapter/objectstore"
|
||||
"mtusi2026lab6/internal/domain"
|
||||
)
|
||||
|
||||
type StagingCleanupStore interface {
|
||||
LookupAttachmentByStagingKey(ctx context.Context, stagingKey string) (
|
||||
attachmentID string,
|
||||
status domain.AttachmentStatus,
|
||||
updatedAt time.Time,
|
||||
found bool,
|
||||
err error,
|
||||
)
|
||||
ListReadyStagingKeys(ctx context.Context, limit int) (map[string]string, error)
|
||||
ClearAttachmentStagingKey(ctx context.Context, attachmentID, stagingKey string) error
|
||||
}
|
||||
|
||||
type StagingObjectStore interface {
|
||||
List(ctx context.Context, prefix string) ([]objectstore.StoredObject, error)
|
||||
Delete(ctx context.Context, key string) error
|
||||
}
|
||||
|
||||
type StagingCleaner struct {
|
||||
store StagingCleanupStore
|
||||
objects StagingObjectStore
|
||||
retention time.Duration
|
||||
}
|
||||
|
||||
func NewStagingCleaner(
|
||||
store StagingCleanupStore,
|
||||
objects StagingObjectStore,
|
||||
retention time.Duration,
|
||||
) (*StagingCleaner, error) {
|
||||
if store == nil || objects == nil {
|
||||
return nil, fmt.Errorf("cleanup store and object store are required")
|
||||
}
|
||||
if retention <= 0 {
|
||||
return nil, fmt.Errorf("staging retention must be positive")
|
||||
}
|
||||
return &StagingCleaner{store: store, objects: objects, retention: retention}, nil
|
||||
}
|
||||
|
||||
func (cleaner *StagingCleaner) RunOnce(ctx context.Context, now time.Time) (int, error) {
|
||||
objects, err := cleaner.objects.List(ctx, "staging/")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
present := make(map[string]struct{}, len(objects))
|
||||
for _, object := range objects {
|
||||
present[object.Key] = struct{}{}
|
||||
}
|
||||
|
||||
// A previous worker may have deleted the object and crashed before clearing
|
||||
// metadata. Once the result is ready, clearing such a stale pointer is safe.
|
||||
readyKeys, err := cleaner.store.ListReadyStagingKeys(ctx, 1000)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
for key, attachmentID := range readyKeys {
|
||||
if _, exists := present[key]; exists {
|
||||
continue
|
||||
}
|
||||
if err = cleaner.store.ClearAttachmentStagingKey(ctx, attachmentID, key); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
cutoff := now.UTC().Add(-cleaner.retention)
|
||||
deleted := 0
|
||||
for _, object := range objects {
|
||||
attachmentID, status, updatedAt, found, lookupErr :=
|
||||
cleaner.store.LookupAttachmentByStagingKey(ctx, object.Key)
|
||||
if lookupErr != nil {
|
||||
return deleted, lookupErr
|
||||
}
|
||||
safeToDelete := false
|
||||
switch {
|
||||
case found && status == domain.AttachmentStatusReady:
|
||||
// Result metadata is already committed, so staging is redundant.
|
||||
safeToDelete = true
|
||||
case found && status == domain.AttachmentStatusFailed &&
|
||||
!updatedAt.After(cutoff) && !object.LastModified.After(cutoff):
|
||||
safeToDelete = true
|
||||
case !found && !object.LastModified.After(cutoff):
|
||||
// An old object without DB metadata is an orphan from a failed or
|
||||
// ambiguous upload transaction.
|
||||
safeToDelete = true
|
||||
}
|
||||
if !safeToDelete {
|
||||
continue
|
||||
}
|
||||
if err = cleaner.objects.Delete(ctx, object.Key); err != nil {
|
||||
return deleted, err
|
||||
}
|
||||
if found {
|
||||
if err = cleaner.store.ClearAttachmentStagingKey(
|
||||
ctx,
|
||||
attachmentID,
|
||||
object.Key,
|
||||
); err != nil {
|
||||
return deleted, err
|
||||
}
|
||||
}
|
||||
deleted++
|
||||
}
|
||||
return deleted, nil
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab6/internal/adapter/objectstore"
|
||||
"mtusi2026lab6/internal/domain"
|
||||
)
|
||||
|
||||
type cleanupReference struct {
|
||||
id string
|
||||
status domain.AttachmentStatus
|
||||
updatedAt time.Time
|
||||
}
|
||||
|
||||
type cleanupStoreFake struct {
|
||||
references map[string]cleanupReference
|
||||
cleared map[string]bool
|
||||
}
|
||||
|
||||
func (store *cleanupStoreFake) LookupAttachmentByStagingKey(
|
||||
_ context.Context,
|
||||
key string,
|
||||
) (string, domain.AttachmentStatus, time.Time, bool, error) {
|
||||
reference, found := store.references[key]
|
||||
return reference.id, reference.status, reference.updatedAt, found, nil
|
||||
}
|
||||
|
||||
func (store *cleanupStoreFake) ListReadyStagingKeys(
|
||||
_ context.Context,
|
||||
_ int,
|
||||
) (map[string]string, error) {
|
||||
keys := make(map[string]string)
|
||||
for key, reference := range store.references {
|
||||
if reference.status == domain.AttachmentStatusReady {
|
||||
keys[key] = reference.id
|
||||
}
|
||||
}
|
||||
return keys, nil
|
||||
}
|
||||
func (store *cleanupStoreFake) ClearAttachmentStagingKey(
|
||||
_ context.Context,
|
||||
_ string,
|
||||
key string,
|
||||
) error {
|
||||
store.cleared[key] = true
|
||||
return nil
|
||||
}
|
||||
|
||||
type cleanupObjectsFake struct {
|
||||
objects []objectstore.StoredObject
|
||||
deleted map[string]bool
|
||||
}
|
||||
|
||||
func (objects *cleanupObjectsFake) List(
|
||||
context.Context,
|
||||
string,
|
||||
) ([]objectstore.StoredObject, error) {
|
||||
return objects.objects, nil
|
||||
}
|
||||
|
||||
func (objects *cleanupObjectsFake) Delete(_ context.Context, key string) error {
|
||||
objects.deleted[key] = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestStagingCleanerPreservesActiveWorkAndAppliesRetention(t *testing.T) {
|
||||
now := time.Date(2026, time.November, 5, 12, 0, 0, 0, time.UTC)
|
||||
old := now.Add(-25 * time.Hour)
|
||||
recent := now.Add(-time.Hour)
|
||||
store := &cleanupStoreFake{
|
||||
references: map[string]cleanupReference{
|
||||
"staging/ready": {id: "ready", status: domain.AttachmentStatusReady, updatedAt: recent},
|
||||
"staging/ready-missing": {id: "ready-missing", status: domain.AttachmentStatusReady, updatedAt: recent},
|
||||
"staging/failed-old": {id: "failed-old", status: domain.AttachmentStatusFailed, updatedAt: old},
|
||||
"staging/failed-recent": {id: "failed-recent", status: domain.AttachmentStatusFailed, updatedAt: recent},
|
||||
"staging/queued-old": {id: "queued-old", status: domain.AttachmentStatusQueued, updatedAt: old},
|
||||
},
|
||||
cleared: make(map[string]bool),
|
||||
}
|
||||
objects := &cleanupObjectsFake{
|
||||
objects: []objectstore.StoredObject{
|
||||
{Key: "staging/ready", LastModified: recent},
|
||||
{Key: "staging/failed-old", LastModified: old},
|
||||
{Key: "staging/failed-recent", LastModified: recent},
|
||||
{Key: "staging/queued-old", LastModified: old},
|
||||
{Key: "staging/orphan-old", LastModified: old},
|
||||
{Key: "staging/orphan-recent", LastModified: recent},
|
||||
},
|
||||
deleted: make(map[string]bool),
|
||||
}
|
||||
cleaner, err := NewStagingCleaner(store, objects, 24*time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
deleted, err := cleaner.RunOnce(context.Background(), now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if deleted != 3 {
|
||||
t.Fatalf("deleted %d objects, want 3", deleted)
|
||||
}
|
||||
for _, key := range []string{"staging/ready", "staging/failed-old", "staging/orphan-old"} {
|
||||
if !objects.deleted[key] {
|
||||
t.Errorf("expected %s to be deleted", key)
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"staging/failed-recent", "staging/queued-old", "staging/orphan-recent"} {
|
||||
if objects.deleted[key] {
|
||||
t.Errorf("active/recent %s was deleted", key)
|
||||
}
|
||||
}
|
||||
if !store.cleared["staging/ready"] || !store.cleared["staging/ready-missing"] ||
|
||||
!store.cleared["staging/failed-old"] {
|
||||
t.Fatal("deleted referenced staging keys were not cleared")
|
||||
}
|
||||
if store.cleared["staging/orphan-old"] {
|
||||
t.Fatal("orphan must not clear nonexistent metadata")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"image/jpeg"
|
||||
"io"
|
||||
"math"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab6/internal/application"
|
||||
"mtusi2026lab6/internal/domain"
|
||||
|
||||
"github.com/disintegration/imaging"
|
||||
webp "github.com/mayahiro/go-webp"
|
||||
)
|
||||
|
||||
type pipelineProfile struct {
|
||||
thumbnailJPEGQuality int
|
||||
cropJPEGQuality int
|
||||
optimizedWebPQuality int
|
||||
}
|
||||
|
||||
func profileForPipeline(version int) (pipelineProfile, bool) {
|
||||
switch version {
|
||||
case 1:
|
||||
return pipelineProfile{thumbnailJPEGQuality: 85, cropJPEGQuality: 85, optimizedWebPQuality: 80}, true
|
||||
case 2:
|
||||
return pipelineProfile{thumbnailJPEGQuality: 90, cropJPEGQuality: 90, optimizedWebPQuality: 85}, true
|
||||
default:
|
||||
return pipelineProfile{}, false
|
||||
}
|
||||
}
|
||||
|
||||
type JobStore interface {
|
||||
GetAttachmentForProcessing(ctx context.Context, attachmentID string) (domain.Attachment, error)
|
||||
CompleteAttachmentJob(
|
||||
ctx context.Context,
|
||||
job domain.AttachmentJob,
|
||||
variants []domain.AttachmentVariant,
|
||||
updatedAt time.Time,
|
||||
) (bool, error)
|
||||
ClearAttachmentStagingKey(ctx context.Context, attachmentID, stagingKey string) error
|
||||
}
|
||||
|
||||
type FaultHook func(job domain.AttachmentJob) error
|
||||
|
||||
type ProcessorHooks struct {
|
||||
BeforeObjects FaultHook
|
||||
AfterObjects FaultHook
|
||||
}
|
||||
|
||||
type Processor struct {
|
||||
store JobStore
|
||||
objects application.ObjectStore
|
||||
now func() time.Time
|
||||
beforeObjects FaultHook
|
||||
afterObjects FaultHook
|
||||
}
|
||||
|
||||
type PermanentError struct {
|
||||
Code string
|
||||
Err error
|
||||
}
|
||||
|
||||
func (err *PermanentError) Error() string { return err.Code + ": " + err.Err.Error() }
|
||||
func (err *PermanentError) Unwrap() error { return err.Err }
|
||||
|
||||
func NewProcessor(
|
||||
store JobStore,
|
||||
objects application.ObjectStore,
|
||||
hooks ...ProcessorHooks,
|
||||
) (*Processor, error) {
|
||||
if store == nil || objects == nil {
|
||||
return nil, fmt.Errorf("job store and object store are required")
|
||||
}
|
||||
var configured ProcessorHooks
|
||||
if len(hooks) > 0 {
|
||||
configured = hooks[0]
|
||||
}
|
||||
return &Processor{
|
||||
store: store,
|
||||
objects: objects,
|
||||
now: func() time.Time { return time.Now().UTC() },
|
||||
beforeObjects: configured.BeforeObjects,
|
||||
afterObjects: configured.AfterObjects,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (processor *Processor) Process(ctx context.Context, job domain.AttachmentJob) error {
|
||||
attachment, err := processor.store.GetAttachmentForProcessing(ctx, job.AttachmentID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("load attachment metadata: %w", err)
|
||||
}
|
||||
if attachment.PipelineVersion != job.PipelineVersion {
|
||||
return &PermanentError{Code: "stale_pipeline", Err: fmt.Errorf("pipeline version mismatch")}
|
||||
}
|
||||
profile, supported := profileForPipeline(job.PipelineVersion)
|
||||
if !supported {
|
||||
return &PermanentError{Code: "unsupported_pipeline", Err: fmt.Errorf("pipeline version %d is not supported", job.PipelineVersion)}
|
||||
}
|
||||
if attachment.StagingKey == "" {
|
||||
return &PermanentError{Code: "staging_expired", Err: fmt.Errorf("staging object is no longer retained")}
|
||||
}
|
||||
|
||||
object, err := processor.objects.Get(ctx, attachment.StagingKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read staging object: %w", err)
|
||||
}
|
||||
defer object.Body.Close()
|
||||
|
||||
staged, err := os.CreateTemp("", "mtusi-worker-original-*")
|
||||
if err != nil {
|
||||
return fmt.Errorf("create worker staging file: %w", err)
|
||||
}
|
||||
stagedPath := staged.Name()
|
||||
defer func() {
|
||||
_ = staged.Close()
|
||||
_ = os.Remove(stagedPath)
|
||||
}()
|
||||
|
||||
hasher := sha256.New()
|
||||
copied, err := io.Copy(
|
||||
io.MultiWriter(staged, hasher),
|
||||
io.LimitReader(object.Body, domain.MaxAttachmentSizeBytes+1),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("copy staging object: %w", err)
|
||||
}
|
||||
if copied != attachment.SizeBytes ||
|
||||
object.SizeBytes != attachment.SizeBytes ||
|
||||
hex.EncodeToString(hasher.Sum(nil)) != attachment.SHA256 {
|
||||
return &PermanentError{Code: "invalid_image", Err: fmt.Errorf("staging object integrity mismatch")}
|
||||
}
|
||||
if err = ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = staged.Seek(0, io.SeekStart); err != nil {
|
||||
return fmt.Errorf("rewind staged image: %w", err)
|
||||
}
|
||||
config, _, err := image.DecodeConfig(staged)
|
||||
if err != nil {
|
||||
return &PermanentError{Code: "invalid_image", Err: fmt.Errorf("decode staged image config: %w", err)}
|
||||
}
|
||||
if config.Width < 1 || config.Height < 1 ||
|
||||
int64(config.Width) > int64(domain.MaxAttachmentPixels)/int64(config.Height) {
|
||||
return &PermanentError{Code: "invalid_image", Err: fmt.Errorf("decoded image dimensions are unsafe")}
|
||||
}
|
||||
if _, err = staged.Seek(0, io.SeekStart); err != nil {
|
||||
return fmt.Errorf("rewind staged image: %w", err)
|
||||
}
|
||||
decoded, err := imaging.Decode(staged, imaging.AutoOrientation(true))
|
||||
if err != nil {
|
||||
return &PermanentError{Code: "invalid_image", Err: fmt.Errorf("decode staged image: %w", err)}
|
||||
}
|
||||
if err = ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
bounds := decoded.Bounds()
|
||||
width, height := bounds.Dx(), bounds.Dy()
|
||||
if width < 1 || height < 1 ||
|
||||
int64(width) > int64(domain.MaxAttachmentPixels)/int64(height) {
|
||||
return &PermanentError{Code: "invalid_image", Err: fmt.Errorf("oriented image dimensions are unsafe")}
|
||||
}
|
||||
|
||||
opaque := image.NewRGBA(image.Rect(0, 0, width, height))
|
||||
draw.Draw(opaque, opaque.Bounds(), &image.Uniform{C: color.White}, image.Point{}, draw.Src)
|
||||
draw.Draw(opaque, opaque.Bounds(), decoded, bounds.Min, draw.Over)
|
||||
|
||||
thumbnailWidth, thumbnailHeight := fitDimensions(width, height, 256)
|
||||
thumbnail := imaging.Resize(opaque, thumbnailWidth, thumbnailHeight, imaging.Lanczos)
|
||||
thumbnailBytes, err := encodeJPEG(thumbnail, profile.thumbnailJPEGQuality)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode thumbnail: %w", err)
|
||||
}
|
||||
|
||||
cropSide := width
|
||||
if height < cropSide {
|
||||
cropSide = height
|
||||
}
|
||||
cropped := imaging.CropCenter(opaque, cropSide, cropSide)
|
||||
cropped = imaging.Resize(cropped, 128, 128, imaging.Lanczos)
|
||||
cropBytes, err := encodeJPEG(cropped, profile.cropJPEGQuality)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode crop: %w", err)
|
||||
}
|
||||
|
||||
optimizedWidth, optimizedHeight := fitDimensions(width, height, 1280)
|
||||
optimized := decoded
|
||||
if optimizedWidth != width || optimizedHeight != height {
|
||||
optimized = imaging.Resize(decoded, optimizedWidth, optimizedHeight, imaging.Lanczos)
|
||||
}
|
||||
var optimizedBuffer bytes.Buffer
|
||||
if err = webp.EncodeContext(ctx, &optimizedBuffer, optimized, &webp.Options{
|
||||
Compression: webp.CompressionLossy,
|
||||
Quality: profile.optimizedWebPQuality,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("encode optimized WebP: %w", err)
|
||||
}
|
||||
optimizedBytes := optimizedBuffer.Bytes()
|
||||
|
||||
baseKey := strings.TrimSuffix(attachment.ObjectKey, "/original") +
|
||||
fmt.Sprintf("/v%d/", job.PipelineVersion)
|
||||
variants := []domain.AttachmentVariant{
|
||||
newVariant("thumbnail", "image/jpeg", baseKey+"thumbnail.jpg",
|
||||
thumbnailBytes, thumbnailWidth, thumbnailHeight, job.PipelineVersion),
|
||||
newVariant("crop", "image/jpeg", baseKey+"crop.jpg",
|
||||
cropBytes, 128, 128, job.PipelineVersion),
|
||||
newVariant("optimized", "image/webp", baseKey+"optimized.webp",
|
||||
optimizedBytes, optimizedWidth, optimizedHeight, job.PipelineVersion),
|
||||
}
|
||||
|
||||
if processor.beforeObjects != nil {
|
||||
if err = processor.beforeObjects(job); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err = staged.Seek(0, io.SeekStart); err != nil {
|
||||
return fmt.Errorf("rewind original for publication: %w", err)
|
||||
}
|
||||
if err = processor.objects.Put(ctx, application.ObjectPut{
|
||||
Key: attachment.ObjectKey,
|
||||
ContentType: attachment.ContentType,
|
||||
SizeBytes: attachment.SizeBytes,
|
||||
Body: staged,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("publish original: %w", err)
|
||||
}
|
||||
variantBodies := [][]byte{thumbnailBytes, cropBytes, optimizedBytes}
|
||||
for index, variant := range variants {
|
||||
if err = processor.objects.Put(ctx, application.ObjectPut{
|
||||
Key: variant.ObjectKey,
|
||||
ContentType: variant.ContentType,
|
||||
SizeBytes: variant.SizeBytes,
|
||||
Body: bytes.NewReader(variantBodies[index]),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("publish %s: %w", variant.Name, err)
|
||||
}
|
||||
}
|
||||
if processor.afterObjects != nil {
|
||||
if err = processor.afterObjects(job); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
applied, err := processor.store.CompleteAttachmentJob(
|
||||
ctx,
|
||||
job,
|
||||
variants,
|
||||
processor.now(),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("commit attachment result: %w", err)
|
||||
}
|
||||
if !applied {
|
||||
return nil
|
||||
}
|
||||
|
||||
cleanupContext, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second)
|
||||
defer cancel()
|
||||
if err = processor.objects.Delete(cleanupContext, attachment.StagingKey); err == nil {
|
||||
_ = processor.store.ClearAttachmentStagingKey(
|
||||
cleanupContext,
|
||||
attachment.ID,
|
||||
attachment.StagingKey,
|
||||
)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func fitDimensions(width, height, maximum int) (int, int) {
|
||||
scale := math.Min(1, math.Min(float64(maximum)/float64(width), float64(maximum)/float64(height)))
|
||||
resultWidth := int(math.Floor(float64(width) * scale))
|
||||
resultHeight := int(math.Floor(float64(height) * scale))
|
||||
if resultWidth < 1 {
|
||||
resultWidth = 1
|
||||
}
|
||||
if resultHeight < 1 {
|
||||
resultHeight = 1
|
||||
}
|
||||
return resultWidth, resultHeight
|
||||
}
|
||||
|
||||
func encodeJPEG(source image.Image, quality int) ([]byte, error) {
|
||||
var encoded bytes.Buffer
|
||||
if err := jpeg.Encode(&encoded, source, &jpeg.Options{Quality: quality}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return encoded.Bytes(), nil
|
||||
}
|
||||
|
||||
func newVariant(
|
||||
name string,
|
||||
contentType string,
|
||||
objectKey string,
|
||||
body []byte,
|
||||
width int,
|
||||
height int,
|
||||
pipelineVersion int,
|
||||
) domain.AttachmentVariant {
|
||||
digest := sha256.Sum256(body)
|
||||
return domain.AttachmentVariant{
|
||||
Name: name,
|
||||
ContentType: contentType,
|
||||
SizeBytes: int64(len(body)),
|
||||
Width: width,
|
||||
Height: height,
|
||||
SHA256: hex.EncodeToString(digest[:]),
|
||||
ObjectKey: objectKey,
|
||||
PipelineVersion: pipelineVersion,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab6/internal/application"
|
||||
"mtusi2026lab6/internal/domain"
|
||||
|
||||
xwebp "golang.org/x/image/webp"
|
||||
)
|
||||
|
||||
type processorStoreFake struct {
|
||||
attachment domain.Attachment
|
||||
variants []domain.AttachmentVariant
|
||||
cleared bool
|
||||
}
|
||||
|
||||
func (store *processorStoreFake) GetAttachmentForProcessing(
|
||||
context.Context,
|
||||
string,
|
||||
) (domain.Attachment, error) {
|
||||
return store.attachment, nil
|
||||
}
|
||||
|
||||
func (store *processorStoreFake) CompleteAttachmentJob(
|
||||
_ context.Context,
|
||||
_ domain.AttachmentJob,
|
||||
variants []domain.AttachmentVariant,
|
||||
_ time.Time,
|
||||
) (bool, error) {
|
||||
store.variants = append([]domain.AttachmentVariant(nil), variants...)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (store *processorStoreFake) ClearAttachmentStagingKey(
|
||||
context.Context,
|
||||
string,
|
||||
string,
|
||||
) error {
|
||||
store.cleared = true
|
||||
return nil
|
||||
}
|
||||
|
||||
type objectStoreFake struct {
|
||||
objects map[string][]byte
|
||||
}
|
||||
|
||||
func (store *objectStoreFake) Put(_ context.Context, object application.ObjectPut) error {
|
||||
body, err := io.ReadAll(object.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
store.objects[object.Key] = body
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *objectStoreFake) Get(
|
||||
_ context.Context,
|
||||
key string,
|
||||
) (application.ObjectContent, error) {
|
||||
body := store.objects[key]
|
||||
return application.ObjectContent{
|
||||
Body: io.NopCloser(bytes.NewReader(body)),
|
||||
SizeBytes: int64(len(body)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (store *objectStoreFake) Delete(_ context.Context, key string) error {
|
||||
delete(store.objects, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestProcessorCompositesAlphaAndStripsMetadata(t *testing.T) {
|
||||
source := image.NewNRGBA(image.Rect(0, 0, 32, 16))
|
||||
for y := 0; y < 16; y++ {
|
||||
for x := 0; x < 32; x++ {
|
||||
if x < 16 {
|
||||
source.SetNRGBA(x, y, color.NRGBA{R: 255, A: 0})
|
||||
} else {
|
||||
source.SetNRGBA(x, y, color.NRGBA{A: 255})
|
||||
}
|
||||
}
|
||||
}
|
||||
var encoded bytes.Buffer
|
||||
if err := png.Encode(&encoded, source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store, objects, processor, job := processorFixture(t, encoded.Bytes(), "image/png", 32, 16)
|
||||
if err := processor.Process(context.Background(), job); err != nil {
|
||||
t.Fatalf("process transparent PNG: %v", err)
|
||||
}
|
||||
|
||||
thumbnail := decodeJPEG(t, objects.objects[variantKey(store.variants, "thumbnail")])
|
||||
if got := thumbnail.Bounds().Size(); got.X != 32 || got.Y != 16 {
|
||||
t.Fatalf("thumbnail size = %v, want 32x16 without upscale", got)
|
||||
}
|
||||
white := color.RGBAModel.Convert(thumbnail.At(2, 8)).(color.RGBA)
|
||||
black := color.RGBAModel.Convert(thumbnail.At(29, 8)).(color.RGBA)
|
||||
if white.R < 220 || white.G < 220 || white.B < 220 {
|
||||
t.Fatalf("transparent pixel was not composited on white: %#v", white)
|
||||
}
|
||||
if black.R > 40 || black.G > 40 || black.B > 40 {
|
||||
t.Fatalf("opaque black pixel changed unexpectedly: %#v", black)
|
||||
}
|
||||
|
||||
optimizedBytes := objects.objects[variantKey(store.variants, "optimized")]
|
||||
optimized, err := xwebp.Decode(bytes.NewReader(optimizedBytes))
|
||||
if err != nil {
|
||||
t.Fatalf("decode optimized WebP: %v", err)
|
||||
}
|
||||
if got := optimized.Bounds().Size(); got.X != 32 || got.Y != 16 {
|
||||
t.Fatalf("optimized size = %v, want 32x16 without upscale", got)
|
||||
}
|
||||
_, _, _, alpha := optimized.At(2, 8).RGBA()
|
||||
if alpha > 0x0800 {
|
||||
t.Fatalf("optimized WebP did not preserve transparent alpha: %d", alpha)
|
||||
}
|
||||
for _, metadataChunk := range [][]byte{[]byte("EXIF"), []byte("XMP "), []byte("ICCP")} {
|
||||
if bytes.Contains(optimizedBytes, metadataChunk) {
|
||||
t.Fatalf("optimized WebP unexpectedly contains metadata chunk %q", metadataChunk)
|
||||
}
|
||||
}
|
||||
if !store.cleared {
|
||||
t.Fatal("successful processing did not clear staging metadata")
|
||||
}
|
||||
if _, exists := objects.objects[store.attachment.StagingKey]; exists {
|
||||
t.Fatal("successful processing did not delete staging object")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessorAppliesEXIFOrientation(t *testing.T) {
|
||||
source := image.NewRGBA(image.Rect(0, 0, 40, 20))
|
||||
var raw bytes.Buffer
|
||||
if err := jpeg.Encode(&raw, source, &jpeg.Options{Quality: 90}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
oriented := injectEXIFOrientation(t, raw.Bytes(), 6)
|
||||
store, objects, processor, job := processorFixture(t, oriented, "image/jpeg", 40, 20)
|
||||
if err := processor.Process(context.Background(), job); err != nil {
|
||||
t.Fatalf("process oriented JPEG: %v", err)
|
||||
}
|
||||
thumbnail := decodeJPEG(t, objects.objects[variantKey(store.variants, "thumbnail")])
|
||||
if got := thumbnail.Bounds().Size(); got.X != 20 || got.Y != 40 {
|
||||
t.Fatalf("thumbnail size after orientation = %v, want 20x40", got)
|
||||
}
|
||||
optimized, err := xwebp.Decode(bytes.NewReader(
|
||||
objects.objects[variantKey(store.variants, "optimized")],
|
||||
))
|
||||
if err != nil {
|
||||
t.Fatalf("decode optimized WebP: %v", err)
|
||||
}
|
||||
if got := optimized.Bounds().Size(); got.X != 20 || got.Y != 40 {
|
||||
t.Fatalf("optimized size after orientation = %v, want 20x40", got)
|
||||
}
|
||||
crop := decodeJPEG(t, objects.objects[variantKey(store.variants, "crop")])
|
||||
if got := crop.Bounds().Size(); got.X != 128 || got.Y != 128 {
|
||||
t.Fatalf("crop size = %v, want 128x128", got)
|
||||
}
|
||||
}
|
||||
|
||||
func processorFixture(
|
||||
t *testing.T,
|
||||
body []byte,
|
||||
contentType string,
|
||||
width int,
|
||||
height int,
|
||||
) (*processorStoreFake, *objectStoreFake, *Processor, domain.AttachmentJob) {
|
||||
t.Helper()
|
||||
digest := sha256.Sum256(body)
|
||||
attachment := domain.Attachment{
|
||||
ID: "attachment",
|
||||
ChatID: "chat",
|
||||
OwnerID: "owner",
|
||||
ObjectKey: "attachments/chat/attachment/original",
|
||||
StagingKey: "staging/attachment/original",
|
||||
ContentType: contentType,
|
||||
SizeBytes: int64(len(body)),
|
||||
SHA256: hex.EncodeToString(digest[:]),
|
||||
Width: width,
|
||||
Height: height,
|
||||
PipelineVersion: 1,
|
||||
Status: domain.AttachmentStatusProcessing,
|
||||
}
|
||||
store := &processorStoreFake{attachment: attachment}
|
||||
objects := &objectStoreFake{objects: map[string][]byte{attachment.StagingKey: body}}
|
||||
processor, err := NewProcessor(store, objects)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return store, objects, processor, domain.AttachmentJob{
|
||||
JobID: "job",
|
||||
AttachmentID: attachment.ID,
|
||||
PipelineVersion: 1,
|
||||
Attempt: 1,
|
||||
MaxAttempts: 5,
|
||||
Status: domain.AttachmentJobProcessing,
|
||||
}
|
||||
}
|
||||
|
||||
func variantKey(variants []domain.AttachmentVariant, name string) string {
|
||||
for _, variant := range variants {
|
||||
if variant.Name == name {
|
||||
return variant.ObjectKey
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func decodeJPEG(t *testing.T, body []byte) image.Image {
|
||||
t.Helper()
|
||||
decoded, err := jpeg.Decode(bytes.NewReader(body))
|
||||
if err != nil {
|
||||
t.Fatalf("decode JPEG: %v", err)
|
||||
}
|
||||
return decoded
|
||||
}
|
||||
|
||||
func injectEXIFOrientation(t *testing.T, source []byte, orientation uint16) []byte {
|
||||
t.Helper()
|
||||
if len(source) < 2 || source[0] != 0xFF || source[1] != 0xD8 {
|
||||
t.Fatal("source is not JPEG")
|
||||
}
|
||||
var tiff bytes.Buffer
|
||||
tiff.WriteString("II")
|
||||
_ = binary.Write(&tiff, binary.LittleEndian, uint16(42))
|
||||
_ = binary.Write(&tiff, binary.LittleEndian, uint32(8))
|
||||
_ = binary.Write(&tiff, binary.LittleEndian, uint16(1))
|
||||
_ = binary.Write(&tiff, binary.LittleEndian, uint16(0x0112))
|
||||
_ = binary.Write(&tiff, binary.LittleEndian, uint16(3))
|
||||
_ = binary.Write(&tiff, binary.LittleEndian, uint32(1))
|
||||
_ = binary.Write(&tiff, binary.LittleEndian, orientation)
|
||||
_ = binary.Write(&tiff, binary.LittleEndian, uint16(0))
|
||||
_ = binary.Write(&tiff, binary.LittleEndian, uint32(0))
|
||||
payload := append([]byte("Exif\x00\x00"), tiff.Bytes()...)
|
||||
var segment bytes.Buffer
|
||||
segment.Write([]byte{0xFF, 0xE1})
|
||||
if err := binary.Write(&segment, binary.BigEndian, uint16(len(payload)+2)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
segment.Write(payload)
|
||||
result := append([]byte(nil), source[:2]...)
|
||||
result = append(result, segment.Bytes()...)
|
||||
result = append(result, source[2:]...)
|
||||
return result
|
||||
}
|
||||
Reference in New Issue
Block a user