forked from mtusi2026/mtusi2026lab6
257 lines
7.6 KiB
Go
257 lines
7.6 KiB
Go
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
|
|
}
|