chore: import lab5 baseline

This commit is contained in:
2026-11-01 14:46:14 +03:00
parent 470d9d6f1e
commit 8b1cedea26
97 changed files with 14849 additions and 1 deletions
@@ -0,0 +1,104 @@
package pipeline
import (
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var workerDurationBuckets = []float64{0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 15, 20, 30, 60}
type Metrics struct {
workerInFlight prometheus.Gauge
workerJobs *prometheus.CounterVec
workerDuration *prometheus.HistogramVec
workerRetries prometheus.Counter
workerReclaimed prometheus.Counter
outboxPublished prometheus.Counter
outboxPublishFailure prometheus.Counter
outboxRecovered prometheus.Counter
handler http.Handler
}
func NewMetrics() *Metrics {
registry := prometheus.NewRegistry()
metrics := &Metrics{
workerInFlight: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: "messenger", Subsystem: "attachment_worker", Name: "jobs_in_flight",
Help: "Attachment jobs currently processed by this worker.",
}),
workerJobs: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "messenger", Subsystem: "attachment_worker", Name: "jobs_total",
Help: "Completed attachment job deliveries by result.",
}, []string{"result"}),
workerDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: "messenger", Subsystem: "attachment_worker", Name: "job_duration_seconds",
Help: "Attachment job delivery processing duration.", Buckets: workerDurationBuckets,
}, []string{"result"}),
workerRetries: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: "messenger", Subsystem: "attachment_worker", Name: "retries_total",
Help: "Attachment jobs scheduled for another attempt.",
}),
workerReclaimed: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: "messenger", Subsystem: "attachment_worker", Name: "reclaimed_deliveries_total",
Help: "Redis Stream deliveries reclaimed after their idle timeout.",
}),
outboxPublished: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: "messenger", Subsystem: "outbox", Name: "published_total",
Help: "Outbox events confirmed by Redis Streams.",
}),
outboxPublishFailure: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: "messenger", Subsystem: "outbox", Name: "publish_failures_total",
Help: "Outbox events whose Redis Streams publish failed.",
}),
outboxRecovered: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: "messenger", Subsystem: "outbox", Name: "recovered_leases_total",
Help: "Expired outbox leases returned for publication.",
}),
}
registry.MustRegister(
metrics.workerInFlight, metrics.workerJobs, metrics.workerDuration,
metrics.workerRetries, metrics.workerReclaimed, metrics.outboxPublished,
metrics.outboxPublishFailure, metrics.outboxRecovered,
collectors.NewGoCollector(), collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
)
metrics.handler = promhttp.HandlerFor(registry, promhttp.HandlerOpts{})
return metrics
}
func (m *Metrics) Handler() http.Handler {
return m.handler
}
func (m *Metrics) ObserveStarted() {
m.workerInFlight.Inc()
}
func (m *Metrics) ObserveFinished(result string, duration time.Duration) {
m.workerInFlight.Dec()
m.workerJobs.WithLabelValues(result).Inc()
m.workerDuration.WithLabelValues(result).Observe(duration.Seconds())
}
func (m *Metrics) ObserveRetry() {
m.workerRetries.Inc()
}
func (m *Metrics) ObserveReclaimed(count int) {
m.workerReclaimed.Add(float64(count))
}
func (m *Metrics) ObservePublished() {
m.outboxPublished.Inc()
}
func (m *Metrics) ObservePublishFailure() {
m.outboxPublishFailure.Inc()
}
func (m *Metrics) ObserveRecovered(count int) {
m.outboxRecovered.Add(float64(count))
}
+237
View File
@@ -0,0 +1,237 @@
package attachment
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"log/slog"
"math"
"mime"
"net/http"
"time"
"github.com/google/uuid"
"golang.org/x/sync/semaphore"
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
)
type Repository interface {
ChatForUser(context.Context, string, string) (model.Chat, error)
CreatePendingAttachment(context.Context, model.Attachment) (model.Attachment, error)
QueueAttachmentWithJobAndOutbox(context.Context, string, string, model.AttachmentJob, string, string) (model.Attachment, error)
DeletePendingAttachment(context.Context, string, string) error
AttachmentForUser(context.Context, string, string) (model.Attachment, error)
AttachmentVariantForUser(context.Context, string, string, string) (model.Attachment, model.Variant, error)
}
type ObjectStore interface {
Put(context.Context, string, string, []byte) error
Get(context.Context, string) (io.ReadCloser, error)
Delete(context.Context, string) error
}
type Config struct {
MaxBytes int64
MaxPixels int64
BodyMemoryBytes int64
DecodeMemoryBytes int64
CleanupTimeout time.Duration
PipelineVersion int
}
type Upload struct {
ChatID string
OwnerID string
Filename string
ContentType string
ContentLength int64
Body io.Reader
Traceparent string
Tracestate string
}
type Content struct {
Attachment model.Attachment
Variant model.Variant
Body io.ReadCloser
}
type Service struct {
repository Repository
objects ObjectStore
config Config
bodyMemory *semaphore.Weighted
decodeMemory *semaphore.Weighted
logger *slog.Logger
}
func NewService(logger *slog.Logger, repository Repository, objects ObjectStore, config Config) (*Service, error) {
if config.MaxBytes < 1 || config.MaxPixels < 1 || config.MaxPixels > math.MaxInt64/8 || config.CleanupTimeout <= 0 || config.PipelineVersion < 1 {
return nil, errors.New("invalid attachment service configuration")
}
if config.BodyMemoryBytes < config.MaxBytes {
return nil, errors.New("attachment body memory must fit one maximum upload")
}
if config.DecodeMemoryBytes < config.MaxPixels*8 {
return nil, errors.New("attachment decode memory must fit one maximum image")
}
return &Service{
repository: repository, objects: objects, config: config,
bodyMemory: semaphore.NewWeighted(config.BodyMemoryBytes),
decodeMemory: semaphore.NewWeighted(config.DecodeMemoryBytes), logger: logger,
}, nil
}
func (s *Service) Upload(ctx context.Context, input Upload) (model.Attachment, error) {
if _, err := s.repository.ChatForUser(ctx, input.ChatID, input.OwnerID); err != nil {
return model.Attachment{}, mapDependencyError(err)
}
data, contentType, release, err := s.readImage(input)
if err != nil {
return model.Attachment{}, err
}
defer release()
attachmentID := uuid.NewString()
stagingKey := "staging/" + attachmentID + "/" + uuid.NewString()
digest := sha256.Sum256(data)
pending, err := s.repository.CreatePendingAttachment(ctx, model.Attachment{
ID: attachmentID, ChatID: input.ChatID, OwnerID: input.OwnerID, Filename: input.Filename,
ContentType: contentType, SizeBytes: int64(len(data)), SHA256: hex.EncodeToString(digest[:]),
ObjectKey: stagingKey, StagingKey: stagingKey, Status: model.AttachmentPending,
PipelineVersion: s.config.PipelineVersion,
})
if err != nil {
return model.Attachment{}, mapDependencyError(err)
}
if err := s.objects.Put(ctx, stagingKey, contentType, data); err != nil {
s.logger.Error("attachment staging write failed", "attachment_id", pending.ID, "error", err)
s.deletePending(pending.ID, stagingKey)
return model.Attachment{}, model.ErrUnavailable
}
createdAt := time.Now().UTC()
queued, err := s.repository.QueueAttachmentWithJobAndOutbox(ctx, pending.ID, stagingKey, model.AttachmentJob{
ID: uuid.NewString(), AttachmentID: pending.ID, PipelineVersion: s.config.PipelineVersion,
Attempt: 1, Status: model.AttachmentJobQueued, AvailableAt: createdAt, CreatedAt: createdAt,
}, input.Traceparent, input.Tracestate)
if err != nil {
s.logger.Error("attachment queue transaction failed", "attachment_id", pending.ID, "error", err)
return model.Attachment{}, mapDependencyError(err)
}
return queued, nil
}
func (s *Service) deletePending(attachmentID, stagingKey string) {
cleanupCtx, cancel := context.WithTimeout(context.Background(), s.config.CleanupTimeout)
defer cancel()
if err := s.repository.DeletePendingAttachment(cleanupCtx, attachmentID, stagingKey); err != nil {
s.logger.Error("pending attachment cleanup failed", "attachment_id", attachmentID, "error", err)
}
}
func (s *Service) Metadata(ctx context.Context, attachmentID, userID string) (model.Attachment, error) {
attachment, err := s.repository.AttachmentForUser(ctx, attachmentID, userID)
if err != nil {
return model.Attachment{}, mapDependencyError(err)
}
return attachment, nil
}
func (s *Service) Content(ctx context.Context, attachmentID, userID, variantName string) (Content, error) {
attachment, variant, err := s.repository.AttachmentVariantForUser(ctx, attachmentID, userID, variantName)
if err != nil {
return Content{}, mapDependencyError(err)
}
body, err := s.objects.Get(ctx, variant.ObjectKey)
if err != nil {
return Content{}, model.ErrUnavailable
}
return Content{Attachment: attachment, Variant: variant, Body: body}, nil
}
func (s *Service) readImage(input Upload) ([]byte, string, func(), error) {
mediaType, parameters, err := mime.ParseMediaType(input.ContentType)
if err != nil || len(parameters) != 0 || mediaType != "image/png" && mediaType != "image/jpeg" {
return nil, "", nil, model.ErrUnsupportedMedia
}
if input.ContentLength > s.config.MaxBytes {
return nil, "", nil, model.ErrPayloadTooLarge
}
reservation := s.config.MaxBytes
if !s.bodyMemory.TryAcquire(reservation) {
return nil, "", nil, model.ErrCapacity
}
releaseBody := func() { s.bodyMemory.Release(reservation) }
data, err := io.ReadAll(io.LimitReader(input.Body, s.config.MaxBytes+1))
if err != nil {
releaseBody()
return nil, "", nil, model.ErrInvalidInput
}
if int64(len(data)) > s.config.MaxBytes {
releaseBody()
return nil, "", nil, model.ErrPayloadTooLarge
}
if len(data) == 0 {
releaseBody()
return nil, "", nil, model.ErrUnsupportedMedia
}
detected := http.DetectContentType(data)
if detected != mediaType {
releaseBody()
return nil, "", nil, model.ErrUnsupportedMedia
}
imageConfig, format, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil || imageContentType(format) != mediaType {
releaseBody()
return nil, "", nil, model.ErrUnsupportedMedia
}
if imageConfig.Width < 1 || imageConfig.Height < 1 || int64(imageConfig.Width) > s.config.MaxPixels/int64(imageConfig.Height) {
releaseBody()
return nil, "", nil, model.ErrPayloadTooLarge
}
pixels := int64(imageConfig.Width) * int64(imageConfig.Height)
decodeBytes := pixels * 8
if !s.decodeMemory.TryAcquire(decodeBytes) {
releaseBody()
return nil, "", nil, model.ErrCapacity
}
if _, format, err := image.Decode(bytes.NewReader(data)); err != nil || imageContentType(format) != mediaType {
s.decodeMemory.Release(decodeBytes)
releaseBody()
return nil, "", nil, model.ErrUnsupportedMedia
}
release := func() {
s.decodeMemory.Release(decodeBytes)
releaseBody()
}
return data, mediaType, release, nil
}
func imageContentType(format string) string {
switch format {
case "png":
return "image/png"
case "jpeg":
return "image/jpeg"
default:
return ""
}
}
func mapDependencyError(err error) error {
switch {
case errors.Is(err, model.ErrNotFound):
return model.ErrNotFound
case errors.Is(err, model.ErrConflict):
return model.ErrConflict
default:
return model.ErrUnavailable
}
}
@@ -0,0 +1,220 @@
package attachment
import (
"bytes"
"context"
"errors"
"image"
"image/color"
"image/png"
"io"
"log/slog"
"math"
"testing"
"time"
"github.com/stretchr/testify/require"
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
)
func TestUploadLifecycle(t *testing.T) {
data := pngFixture(t, 2, 2)
events := make([]string, 0, 3)
repository := &repositoryStub{events: &events}
objects := &objectStub{events: &events}
service := newTestService(t, repository, objects, 1024, 4)
result, err := service.Upload(context.Background(), upload(data, "image/png"))
require.NoError(t, err)
require.Equal(t, model.AttachmentQueued, result.Status)
require.Equal(t, []string{"pending", "put", "queued"}, events)
}
func TestUploadValidation(t *testing.T) {
data := pngFixture(t, 2, 2)
tests := []struct {
name string
contentType string
data []byte
maxBytes int64
maxPixels int64
want error
}{
{name: "spoofed MIME", contentType: "image/jpeg", data: data, maxBytes: 1024, maxPixels: 4, want: model.ErrUnsupportedMedia},
{name: "too many pixels", contentType: "image/png", data: data, maxBytes: 1024, maxPixels: 3, want: model.ErrPayloadTooLarge},
{name: "too many bytes", contentType: "image/png", data: data, maxBytes: int64(len(data) - 1), maxPixels: 4, want: model.ErrPayloadTooLarge},
{name: "damaged", contentType: "image/png", data: data[:16], maxBytes: 1024, maxPixels: 4, want: model.ErrUnsupportedMedia},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
service := newTestService(t, &repositoryStub{}, &objectStub{}, test.maxBytes, test.maxPixels)
input := upload(test.data, test.contentType)
_, err := service.Upload(context.Background(), input)
require.ErrorIs(t, err, test.want)
})
}
}
func TestUploadUsesSeparateBodyAndDecodeBudgets(t *testing.T) {
data := pngFixture(t, 2, 2)
service := newTestService(t, &repositoryStub{}, &objectStub{}, 1024, 4)
require.True(t, service.bodyMemory.TryAcquire(1024))
_, err := service.Upload(context.Background(), upload(data, "image/png"))
require.ErrorIs(t, err, model.ErrCapacity)
service.bodyMemory.Release(1024)
require.True(t, service.decodeMemory.TryAcquire(32))
_, err = service.Upload(context.Background(), upload(data, "image/png"))
require.ErrorIs(t, err, model.ErrCapacity)
service.decodeMemory.Release(32)
}
func TestUploadReleasesBodyMemoryAfterOversizedDimensions(t *testing.T) {
oversized := pngFixture(t, 3, 2)
valid := pngFixture(t, 2, 2)
service := newTestService(t, &repositoryStub{}, &objectStub{}, 1024, 4)
_, err := service.Upload(context.Background(), upload(oversized, "image/png"))
require.ErrorIs(t, err, model.ErrPayloadTooLarge)
_, err = service.Upload(context.Background(), upload(valid, "image/png"))
require.NoError(t, err)
}
func TestNewServiceRejectsDecodeBudgetOverflow(t *testing.T) {
_, err := NewService(
slog.New(slog.NewTextHandler(io.Discard, nil)), &repositoryStub{}, &objectStub{},
Config{
MaxBytes: 1024, MaxPixels: math.MaxInt64/8 + 1, BodyMemoryBytes: 1024,
DecodeMemoryBytes: math.MaxInt64, CleanupTimeout: time.Second, PipelineVersion: 1,
},
)
require.Error(t, err)
}
func TestUploadCleansPendingMetadataWhenObjectWriteFails(t *testing.T) {
data := pngFixture(t, 2, 2)
repository := &repositoryStub{}
objects := &objectStub{putErr: errors.New("s3 unavailable")}
service := newTestService(t, repository, objects, 1024, 4)
_, err := service.Upload(context.Background(), upload(data, "image/png"))
require.ErrorIs(t, err, model.ErrUnavailable)
require.True(t, repository.pendingDeleted)
}
func TestUploadKeepsStagingAfterQueueFailure(t *testing.T) {
data := pngFixture(t, 2, 2)
repository := &repositoryStub{queueErr: errors.New("connection lost")}
objects := &objectStub{}
service := newTestService(t, repository, objects, 1024, 4)
_, err := service.Upload(context.Background(), upload(data, "image/png"))
require.ErrorIs(t, err, model.ErrUnavailable)
require.False(t, objects.deleted)
require.False(t, repository.pendingDeleted)
}
func newTestService(t *testing.T, repository Repository, objects ObjectStore, maxBytes, maxPixels int64) *Service {
t.Helper()
service, err := NewService(
slog.New(slog.NewTextHandler(io.Discard, nil)), repository, objects,
Config{
MaxBytes: maxBytes, MaxPixels: maxPixels, BodyMemoryBytes: maxBytes,
DecodeMemoryBytes: maxPixels * 8, CleanupTimeout: time.Second, PipelineVersion: 1,
},
)
require.NoError(t, err)
return service
}
func upload(data []byte, contentType string) Upload {
return Upload{
ChatID: "chat", OwnerID: "owner", Filename: "photo.png", ContentType: contentType,
ContentLength: int64(len(data)), Body: bytes.NewReader(data),
}
}
type repositoryStub struct {
events *[]string
queueErr error
pendingDeleted bool
pending model.Attachment
}
func (*repositoryStub) ChatForUser(context.Context, string, string) (model.Chat, error) {
return model.Chat{}, nil
}
func (s *repositoryStub) CreatePendingAttachment(_ context.Context, attachment model.Attachment) (model.Attachment, error) {
attachment.Status = model.AttachmentPending
s.pending = attachment
s.record("pending")
return attachment, nil
}
func (s *repositoryStub) QueueAttachmentWithJobAndOutbox(
context.Context,
string,
string,
model.AttachmentJob,
string,
string,
) (model.Attachment, error) {
if s.queueErr != nil {
return model.Attachment{}, s.queueErr
}
s.pending.Status = model.AttachmentQueued
s.record("queued")
return s.pending, nil
}
func (s *repositoryStub) DeletePendingAttachment(context.Context, string, string) error {
s.pendingDeleted = true
return nil
}
func (s *repositoryStub) AttachmentForUser(context.Context, string, string) (model.Attachment, error) {
return s.pending, nil
}
func (s *repositoryStub) AttachmentVariantForUser(context.Context, string, string, string) (model.Attachment, model.Variant, error) {
return s.pending, model.Variant{}, nil
}
func (s *repositoryStub) record(event string) {
if s.events != nil {
*s.events = append(*s.events, event)
}
}
type objectStub struct {
events *[]string
putErr error
deleted bool
}
func (s *objectStub) Put(context.Context, string, string, []byte) error {
if s.events != nil {
*s.events = append(*s.events, "put")
}
return s.putErr
}
func (*objectStub) Get(context.Context, string) (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(nil)), nil
}
func (s *objectStub) Delete(context.Context, string) error {
s.deleted = true
return nil
}
func pngFixture(t *testing.T, width, height int) []byte {
t.Helper()
var data bytes.Buffer
value := image.NewRGBA(image.Rect(0, 0, width, height))
value.Set(0, 0, color.White)
require.NoError(t, png.Encode(&data, value))
return data.Bytes()
}
@@ -0,0 +1,169 @@
package transform
import (
"context"
"encoding/binary"
"errors"
"image"
"image/color"
)
var errInvalidEXIF = errors.New("invalid EXIF metadata")
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
}
for offset < len(data) && data[offset] == 0xff {
offset++
}
if offset >= len(data) {
return 0, errInvalidEXIF
}
marker := data[offset]
offset++
if marker == 0xd9 || marker == 0xda {
return 1, nil
}
if marker == 0x01 || marker >= 0xd0 && marker <= 0xd7 {
continue
}
if offset+2 > len(data) {
return 0, errInvalidEXIF
}
length := int(binary.BigEndian.Uint16(data[offset : offset+2]))
if length < 2 || offset+length > len(data) {
return 0, errInvalidEXIF
}
payload := data[offset+2 : offset+length]
offset += length
if marker != 0xe1 || len(payload) < 6 || string(payload[:6]) != "Exif\x00\x00" {
continue
}
return tiffOrientation(ctx, payload[6:])
}
return 1, nil
}
func tiffOrientation(ctx context.Context, data []byte) (int, error) {
if len(data) < 8 {
return 0, errInvalidEXIF
}
var order binary.ByteOrder
switch string(data[:2]) {
case "II":
order = binary.LittleEndian
case "MM":
order = binary.BigEndian
default:
return 0, errInvalidEXIF
}
if order.Uint16(data[2:4]) != 42 {
return 0, errInvalidEXIF
}
ifdOffset := uint64(order.Uint32(data[4:8]))
if ifdOffset > uint64(len(data)-2) {
return 0, errInvalidEXIF
}
count := uint64(order.Uint16(data[ifdOffset : ifdOffset+2]))
entriesStart := ifdOffset + 2
if count > (uint64(len(data))-entriesStart)/12 {
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
}
if order.Uint16(entry[2:4]) != 3 || order.Uint32(entry[4:8]) != 1 {
return 0, errInvalidEXIF
}
orientation := int(order.Uint16(entry[8:10]))
if orientation < 1 || orientation > 8 {
return 0, errInvalidEXIF
}
return orientation, nil
}
return 1, nil
}
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
if orientation >= 5 {
outputWidth, outputHeight = height, width
}
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, nil
}
func orientedSourcePoint(x, y, width, height, orientation int) (int, int) {
switch orientation {
case 2:
return width - 1 - x, y
case 3:
return width - 1 - x, height - 1 - y
case 4:
return x, height - 1 - y
case 5:
return y, x
case 6:
return y, height - 1 - x
case 7:
return width - 1 - y, height - 1 - x
case 8:
return width - 1 - y, x
default:
return x, y
}
}
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),
G: uint8((g + 0xffff - a) / 0x101),
B: uint8((b + 0xffff - a) / 0x101),
A: 0xff,
})
}
}
return output, nil
}
@@ -0,0 +1,272 @@
package transform
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"image"
"image/jpeg"
_ "image/png"
"io"
"math"
"net/http"
"github.com/deepteams/webp"
)
const (
// DefaultJPEGQuality is used for thumbnail and crop variants.
DefaultJPEGQuality = 85
// DefaultWebPQuality keeps the optimized variant visually close to the source while reducing its size.
DefaultWebPQuality = 82
// DefaultWebPMethod selects the encoder's balanced quality and CPU mode.
DefaultWebPMethod = 4
)
var (
ErrInvalidConfig = errors.New("invalid image transform configuration")
ErrUnsupportedMedia = errors.New("unsupported image media type")
ErrPayloadTooLarge = errors.New("image exceeds configured limits")
ErrInvalidImage = errors.New("invalid image data")
)
type Config struct {
MaxBytes int64
MaxPixels int64
JPEGQuality int
WebPQuality float32
WebPMethod int
}
type Variant struct {
Bytes []byte
ContentType string
Width int
Height int
SHA256 string
}
type Result struct {
Original Variant
Thumbnail Variant
Crop Variant
Optimized Variant
Orientation int
}
type Processor struct {
config Config
}
func DefaultConfig(maxBytes, maxPixels int64) Config {
return Config{
MaxBytes: maxBytes, MaxPixels: maxPixels,
JPEGQuality: DefaultJPEGQuality, WebPQuality: DefaultWebPQuality, WebPMethod: DefaultWebPMethod,
}
}
func NewProcessor(config Config) (*Processor, error) {
if config.MaxBytes < 1 || config.MaxPixels < 1 || config.JPEGQuality < 1 || config.JPEGQuality > 100 ||
config.WebPQuality < 1 || config.WebPQuality > 100 || config.WebPMethod < 0 || config.WebPMethod > 6 {
return nil, ErrInvalidConfig
}
return &Processor{config: config}, nil
}
func (p *Processor) Process(ctx context.Context, data []byte, declaredContentType string) (Result, error) {
if err := contextError(ctx); err != nil {
return Result{}, err
}
img, format, width, height, orientation, err := p.decode(ctx, data, declaredContentType)
if err != nil {
return Result{}, err
}
if err := contextError(ctx); err != nil {
return Result{}, err
}
oriented, err := applyOrientation(ctx, img, orientation)
if err != nil {
return Result{}, err
}
opaque, err := flattenWhite(ctx, oriented)
if err != nil {
return Result{}, err
}
result := Result{
Original: variant(data, format, width, height),
Orientation: orientation,
}
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
}
if err := contextError(ctx); err != nil {
return Result{}, err
}
crop := centeredSquare(opaque)
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
}
if err := contextError(ctx); err != nil {
return Result{}, err
}
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
}
if err := contextError(ctx); err != nil {
return Result{}, err
}
return result, nil
}
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
}
if len(data) == 0 {
return nil, "", 0, 0, 0, ErrInvalidImage
}
if int64(len(data)) > p.config.MaxBytes {
return nil, "", 0, 0, 0, ErrPayloadTooLarge
}
if http.DetectContentType(data) != declaredContentType {
return nil, "", 0, 0, 0, ErrUnsupportedMedia
}
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(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(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():
return ctx.Err()
default:
return nil
}
}
func contentType(format string) string {
switch format {
case "jpeg":
return "image/jpeg"
case "png":
return "image/png"
default:
return ""
}
}
func encodeJPEG(img image.Image, quality int) (Variant, error) {
var output bytes.Buffer
if err := jpeg.Encode(&output, img, &jpeg.Options{Quality: quality}); err != nil {
return Variant{}, err
}
bounds := img.Bounds()
return variant(output.Bytes(), "image/jpeg", bounds.Dx(), bounds.Dy()), nil
}
func encodeWebP(img image.Image, quality float32, method int) (Variant, error) {
var output bytes.Buffer
options := &webp.EncoderOptions{Quality: quality, Method: method}
if err := webp.Encode(&output, img, options); err != nil {
return Variant{}, err
}
bounds := img.Bounds()
return variant(output.Bytes(), "image/webp", bounds.Dx(), bounds.Dy()), nil
}
func variant(data []byte, contentType string, width, height int) Variant {
digest := sha256.Sum256(data)
return Variant{
Bytes: data, ContentType: contentType, Width: width, Height: height,
SHA256: hex.EncodeToString(digest[:]),
}
}
// EstimateMemoryWeight returns a conservative reservation for the input, decoded source,
// orientation and alpha copies, variant working buffer, and encoded variant buffers.
func EstimateMemoryWeight(inputBytes int64, width, height int) (int64, error) {
if inputBytes < 0 || width < 1 || height < 1 || int64(width) > math.MaxInt64/int64(height) {
return 0, ErrInvalidImage
}
pixels := int64(width) * int64(height)
optimizedPixels := fittedPixels(width, height, 1280, 1280)
thumbnailPixels := fittedPixels(width, height, 256, 256)
const cropPixels int64 = 128 * 128
if pixels > (math.MaxInt64-inputBytes)/16 {
return 0, ErrPayloadTooLarge
}
weight := inputBytes + pixels*16
variants := (optimizedPixels + thumbnailPixels + cropPixels) * 4
if variants > math.MaxInt64-weight {
return 0, ErrPayloadTooLarge
}
return weight + variants, nil
}
func fittedPixels(width, height, maxWidth, maxHeight int) int64 {
newWidth, newHeight := fitDimensions(width, height, maxWidth, maxHeight, false)
return int64(newWidth) * int64(newHeight)
}
@@ -0,0 +1,261 @@
package transform
import (
"bytes"
"context"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"errors"
"image"
"image/color"
"image/jpeg"
"image/png"
"testing"
"github.com/deepteams/webp"
)
func TestProcessProducesExpectedVariants(t *testing.T) {
source := image.NewNRGBA(image.Rect(0, 0, 320, 200))
fillGradient(source)
data := encodePNG(t, source)
processor := newTestProcessor(t, int64(len(data))+1, 320*200)
result, err := processor.Process(context.Background(), data, "image/png")
if err != nil {
t.Fatalf("process image: %v", err)
}
assertVariant(t, result.Original, "image/png", 320, 200)
assertVariant(t, result.Thumbnail, "image/jpeg", 256, 160)
assertVariant(t, result.Crop, "image/jpeg", 128, 128)
assertVariant(t, result.Optimized, "image/webp", 320, 200)
if !bytes.Equal(result.Original.Bytes, data) {
t.Fatal("original bytes changed")
}
digest := sha256.Sum256(data)
if result.Original.SHA256 != hex.EncodeToString(digest[:]) {
t.Fatalf("unexpected original digest: %s", result.Original.SHA256)
}
if _, err := webp.Decode(bytes.NewReader(result.Optimized.Bytes)); err != nil {
t.Fatalf("decode optimized WebP: %v", err)
}
}
func TestProcessDoesNotUpscaleFitVariants(t *testing.T) {
source := image.NewNRGBA(image.Rect(0, 0, 64, 32))
fillGradient(source)
data := encodePNG(t, source)
processor := newTestProcessor(t, int64(len(data))+1, 64*32)
result, err := processor.Process(context.Background(), data, "image/png")
if err != nil {
t.Fatalf("process image: %v", err)
}
assertVariant(t, result.Thumbnail, "image/jpeg", 64, 32)
assertVariant(t, result.Optimized, "image/webp", 64, 32)
assertVariant(t, result.Crop, "image/jpeg", 128, 128)
}
func TestFlattenWhiteCompositesAlpha(t *testing.T) {
source := image.NewNRGBA(image.Rect(0, 0, 2, 1))
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, 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)
}
if got := result.NRGBAAt(1, 0); got != (color.NRGBA{R: 177, G: 152, B: 127, A: 255}) {
t.Fatalf("semi-transparent pixel: got %#v", got)
}
}
func TestProcessAppliesEXIFOrientation(t *testing.T) {
source := image.NewNRGBA(image.Rect(0, 0, 3, 2))
fillGradient(source)
data := injectOrientation(t, encodeJPEGForTest(t, source), 6)
processor := newTestProcessor(t, int64(len(data))+1, 3*2)
result, err := processor.Process(context.Background(), data, "image/jpeg")
if err != nil {
t.Fatalf("process image: %v", err)
}
if result.Orientation != 6 {
t.Fatalf("orientation: got %d, want 6", result.Orientation)
}
assertVariant(t, result.Original, "image/jpeg", 3, 2)
assertVariant(t, result.Thumbnail, "image/jpeg", 2, 3)
assertVariant(t, result.Optimized, "image/webp", 2, 3)
}
func TestProcessRejectsInvalidInputs(t *testing.T) {
valid := encodePNG(t, image.NewNRGBA(image.Rect(0, 0, 11, 10)))
tests := []struct {
name string
data []byte
contentType string
maxPixels int64
want error
}{
{name: "MIME mismatch", data: valid, contentType: "image/jpeg", maxPixels: 200, want: ErrUnsupportedMedia},
{name: "unsupported MIME", data: valid, contentType: "image/gif", maxPixels: 200, want: ErrUnsupportedMedia},
{name: "pixel limit", data: valid, contentType: "image/png", maxPixels: 100, want: ErrPayloadTooLarge},
{name: "corrupted", data: valid[:len(valid)-12], contentType: "image/png", maxPixels: 200, want: ErrInvalidImage},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
processor := newTestProcessor(t, int64(len(valid))+1, test.maxPixels)
_, err := processor.Process(context.Background(), test.data, test.contentType)
if !errors.Is(err, test.want) {
t.Fatalf("error: got %v, want %v", err, test.want)
}
})
}
}
func TestProcessIsDeterministic(t *testing.T) {
source := image.NewNRGBA(image.Rect(0, 0, 48, 31))
fillGradient(source)
data := encodePNG(t, source)
processor := newTestProcessor(t, int64(len(data))+1, 48*31)
first, err := processor.Process(context.Background(), data, "image/png")
if err != nil {
t.Fatalf("first process: %v", err)
}
second, err := processor.Process(context.Background(), data, "image/png")
if err != nil {
t.Fatalf("second process: %v", err)
}
for name, variants := range map[string][2]Variant{
"thumbnail": {first.Thumbnail, second.Thumbnail},
"crop": {first.Crop, second.Crop},
"optimized": {first.Optimized, second.Optimized},
} {
if !bytes.Equal(variants[0].Bytes, variants[1].Bytes) {
t.Fatalf("%s bytes differ", name)
}
}
}
func TestProcessHonorsCanceledContext(t *testing.T) {
processor := newTestProcessor(t, 1024, 100)
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := processor.Process(ctx, []byte("unused"), "image/png")
if !errors.Is(err, context.Canceled) {
t.Fatalf("error: got %v, want %v", err, context.Canceled)
}
}
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 {
t.Fatalf("estimate memory: %v", err)
}
want := int64(1000 + 320*200*16 + (320*200+256*160+128*128)*4)
if weight != want {
t.Fatalf("weight: got %d, want %d", weight, want)
}
}
func newTestProcessor(t *testing.T, maxBytes, maxPixels int64) *Processor {
t.Helper()
processor, err := NewProcessor(DefaultConfig(maxBytes, maxPixels))
if err != nil {
t.Fatalf("new processor: %v", err)
}
return processor
}
func assertVariant(t *testing.T, variant Variant, contentType string, width, height int) {
t.Helper()
if variant.ContentType != contentType || variant.Width != width || variant.Height != height {
t.Fatalf("variant: got type=%s dimensions=%dx%d, want type=%s dimensions=%dx%d",
variant.ContentType, variant.Width, variant.Height, contentType, width, height)
}
if len(variant.Bytes) == 0 || variant.SHA256 == "" {
t.Fatal("variant has no bytes or digest")
}
}
func fillGradient(img *image.NRGBA) {
for y := 0; y < img.Bounds().Dy(); y++ {
for x := 0; x < img.Bounds().Dx(); x++ {
img.SetNRGBA(x, y, color.NRGBA{R: uint8(x), G: uint8(y), B: uint8(x + y), A: 255})
}
}
}
func encodePNG(t *testing.T, img image.Image) []byte {
t.Helper()
var output bytes.Buffer
if err := png.Encode(&output, img); err != nil {
t.Fatalf("encode PNG: %v", err)
}
return output.Bytes()
}
func encodeJPEGForTest(t *testing.T, img image.Image) []byte {
t.Helper()
var output bytes.Buffer
if err := jpeg.Encode(&output, img, &jpeg.Options{Quality: 100}); err != nil {
t.Fatalf("encode JPEG: %v", err)
}
return output.Bytes()
}
func injectOrientation(t *testing.T, data []byte, orientation uint16) []byte {
t.Helper()
if len(data) < 2 || data[0] != 0xff || data[1] != 0xd8 {
t.Fatal("not a JPEG")
}
tiff := make([]byte, 26)
copy(tiff[:2], "II")
binary.LittleEndian.PutUint16(tiff[2:4], 42)
binary.LittleEndian.PutUint32(tiff[4:8], 8)
binary.LittleEndian.PutUint16(tiff[8:10], 1)
binary.LittleEndian.PutUint16(tiff[10:12], 0x0112)
binary.LittleEndian.PutUint16(tiff[12:14], 3)
binary.LittleEndian.PutUint32(tiff[14:18], 1)
binary.LittleEndian.PutUint16(tiff[18:20], orientation)
payload := append([]byte("Exif\x00\x00"), tiff...)
segment := []byte{0xff, 0xe1, 0, 0}
binary.BigEndian.PutUint16(segment[2:4], uint16(len(payload)+2))
result := make([]byte, 0, len(data)+len(segment)+len(payload))
result = append(result, data[:2]...)
result = append(result, segment...)
result = append(result, payload...)
return append(result, data[2:]...)
}
@@ -0,0 +1,128 @@
package transform
import (
"context"
"image"
"image/color"
)
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 resizeContext(ctx, source, width, height)
}
func fitDimensions(width, height, maxWidth, maxHeight int, upscale bool) (int, int) {
if !upscale && width <= maxWidth && height <= maxHeight {
return width, height
}
if int64(width)*int64(maxHeight) > int64(height)*int64(maxWidth) {
newHeight := max(1, int(int64(height)*int64(maxWidth)/int64(width)))
return maxWidth, newHeight
}
newWidth := max(1, int(int64(width)*int64(maxHeight)/int64(height)))
return newWidth, maxHeight
}
func centeredSquare(source image.Image) image.Image {
bounds := source.Bounds()
size := min(bounds.Dx(), bounds.Dy())
left := bounds.Min.X + (bounds.Dx()-size)/2
top := bounds.Min.Y + (bounds.Dy()-size)/2
return croppedImage{source: source, bounds: image.Rect(0, 0, size, size), offset: image.Pt(left, top)}
}
type croppedImage struct {
source image.Image
bounds image.Rectangle
offset image.Point
}
func (i croppedImage) ColorModel() color.Model { return i.source.ColorModel() }
func (i croppedImage) Bounds() image.Rectangle { return i.bounds }
func (i croppedImage) At(x, y int) color.Color {
return i.source.At(i.offset.X+x, i.offset.Y+y)
}
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 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)
c01 := color.NRGBAModel.Convert(source.At(bounds.Min.X+x0, bounds.Min.Y+y1)).(color.NRGBA)
c11 := color.NRGBAModel.Convert(source.At(bounds.Min.X+x1, bounds.Min.Y+y1)).(color.NRGBA)
output.SetNRGBA(x, y, interpolate(c00, c10, c01, c11, fx, fy))
}
}
return output, nil
}
func sampleCoordinate(destination, destinationSize, sourceSize int) (int, int, uint32) {
coordinate := ((int64(2*destination+1)*int64(sourceSize))<<15)/int64(destinationSize) - 1<<15
if coordinate <= 0 {
return 0, min(1, sourceSize-1), 0
}
maximum := int64(sourceSize-1) << 16
if coordinate >= maximum {
return sourceSize - 1, sourceSize - 1, 0
}
first := int(coordinate >> 16)
return first, first + 1, uint32(coordinate & 0xffff)
}
func interpolate(c00, c10, c01, c11 color.NRGBA, fx, fy uint32) color.NRGBA {
return color.NRGBA{
R: interpolateChannel(c00.R, c10.R, c01.R, c11.R, fx, fy),
G: interpolateChannel(c00.G, c10.G, c01.G, c11.G, fx, fy),
B: interpolateChannel(c00.B, c10.B, c01.B, c11.B, fx, fy),
A: interpolateChannel(c00.A, c10.A, c01.A, c11.A, fx, fy),
}
}
func interpolateChannel(c00, c10, c01, c11 uint8, fx, fy uint32) uint8 {
const one uint64 = 1 << 16
top := uint64(c00)*(one-uint64(fx)) + uint64(c10)*uint64(fx)
bottom := uint64(c01)*(one-uint64(fx)) + uint64(c11)*uint64(fx)
value := top*(one-uint64(fy)) + bottom*uint64(fy)
return uint8((value + 1<<31) >> 32)
}
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, nil
}
@@ -0,0 +1,508 @@
package worker
import (
"bytes"
"context"
"errors"
"fmt"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"log/slog"
"math"
"path"
"strings"
"sync"
"time"
"golang.org/x/sync/semaphore"
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/broker/redisstream"
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/messenger/attachment/transform"
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/objectstore"
)
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)
RecoverExpiredAttachmentJobs(context.Context, int, int, time.Time) (model.RecoveryResult, error)
}
type Broker interface {
Read(context.Context) ([]redisstream.Delivery, error)
Reclaim(context.Context, string) ([]redisstream.Delivery, string, error)
}
type ObjectStore interface {
Get(context.Context, string) (io.ReadCloser, error)
Put(context.Context, string, string, []byte) error
Delete(context.Context, string) error
}
type ImageProcessor interface {
Process(context.Context, []byte, string) (transform.Result, error)
}
type Metrics interface {
ObserveStarted()
ObserveFinished(string, time.Duration)
ObserveRetry()
ObserveReclaimed(int)
}
type Config struct {
WorkerID string
Concurrency int
LeaseDuration time.Duration
HeartbeatInterval time.Duration
ProcessingTimeout time.Duration
ReclaimInterval time.Duration
MaxAttempts int
RetryBase time.Duration
RetryMax time.Duration
MaxBytes int64
MaxPixels int64
MemoryBytes int64
}
type FaultPoint string
const (
FaultNone FaultPoint = ""
FaultBeforeSideEffect FaultPoint = "before_side_effect"
FaultAfterSideEffect FaultPoint = "after_side_effect"
FaultAfterCommit FaultPoint = "after_commit"
)
var ErrInjectedFailure = errors.New("injected worker failure")
type Worker struct {
logger *slog.Logger
repository Repository
broker Broker
objects ObjectStore
processor ImageProcessor
metrics Metrics
config Config
memory *semaphore.Weighted
now func() time.Time
}
func New(
logger *slog.Logger,
repository Repository,
broker Broker,
objects ObjectStore,
processor ImageProcessor,
metrics Metrics,
config Config,
) (*Worker, error) {
if logger == nil || repository == nil || broker == nil || objects == nil || processor == nil {
return nil, errors.New("worker dependencies are required")
}
if err := validateConfig(config); err != nil {
return nil, err
}
if metrics == nil {
metrics = nopMetrics{}
}
return &Worker{
logger: logger, repository: repository, broker: broker, objects: objects,
processor: processor, metrics: metrics, config: config,
memory: semaphore.NewWeighted(config.MemoryBytes), now: time.Now,
}, nil
}
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 {
return errors.New("invalid worker configuration")
}
const maximumVariantPixels int64 = 1280*1280 + 256*256 + 128*128
if config.MaxPixels > (math.MaxInt64-config.MaxBytes-maximumVariantPixels*4)/16 ||
config.MaxBytes+config.MaxPixels*16+maximumVariantPixels*4 > config.MemoryBytes {
return errors.New("worker memory must fit one maximum image")
}
return nil
}
func (w *Worker) Run(ctx context.Context) error {
lastReclaim := time.Time{}
reclaimCursor := "0-0"
for ctx.Err() == nil {
deliveries, err := w.broker.Read(ctx)
if err != nil {
if ctx.Err() != nil {
return nil
}
return err
}
w.processBatch(ctx, deliveries)
if w.now().Sub(lastReclaim) < w.config.ReclaimInterval {
continue
}
recovery, err := w.repository.RecoverExpiredAttachmentJobs(
ctx, w.config.Concurrency*4, w.config.MaxAttempts, w.now().Add(w.config.RetryBase),
)
if err != nil {
return fmt.Errorf("recover expired attachment jobs: %w", err)
}
if recovery.Requeued > 0 || recovery.Failed > 0 {
w.logger.Info("expired attachment jobs recovered", "requeued", recovery.Requeued, "failed", recovery.Failed)
}
deliveries, next, err := w.broker.Reclaim(ctx, reclaimCursor)
if err != nil {
if ctx.Err() != nil {
return nil
}
return err
}
w.metrics.ObserveReclaimed(len(deliveries))
w.processBatch(ctx, deliveries)
reclaimCursor = next
if reclaimCursor == "" {
reclaimCursor = "0-0"
}
lastReclaim = w.now()
}
return nil
}
func (w *Worker) processBatch(ctx context.Context, deliveries []redisstream.Delivery) {
limit := make(chan struct{}, w.config.Concurrency)
var group sync.WaitGroup
for _, delivery := range deliveries {
if ctx.Err() != nil {
break
}
limit <- struct{}{}
group.Add(1)
go func(delivery redisstream.Delivery) {
defer group.Done()
defer func() { <-limit }()
if err := w.ProcessDelivery(ctx, delivery, FaultNone); err != nil && ctx.Err() == nil {
w.logger.Error("attachment job delivery failed", "message_id", delivery.ID, "error", err)
}
}(delivery)
}
group.Wait()
}
func (w *Worker) ProcessDelivery(ctx context.Context, delivery redisstream.Delivery, fault FaultPoint) error {
started := w.now()
w.metrics.ObserveStarted()
result := "transient_error"
defer func() { w.metrics.ObserveFinished(result, w.now().Sub(started)) }()
if delivery.DecodeError != nil {
result = "invalid_job"
return delivery.ToFailed(ctx, redisstream.FailedDelivery{Code: "invalid_job", FailedAt: w.now()})
}
envelope := delivery.Envelope
lease, err := w.repository.ClaimAttachmentJob(
ctx, envelope.JobID.String(), envelope.AttachmentID.String(), envelope.PipelineVersion, envelope.Attempt,
w.config.WorkerID, w.config.LeaseDuration,
)
if err != nil {
result, err = w.resolveClaim(ctx, delivery, envelope, err)
return err
}
if fault == FaultBeforeSideEffect {
result = "injected_failure"
return ErrInjectedFailure
}
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)
cancelProcessing()
cancelHeartbeat()
heartbeatErr := <-heartbeatDone
if heartbeatErr != nil {
return heartbeatErr
}
if err != nil {
result, err = w.resolveProcessingFailure(ctx, delivery, lease, err)
return err
}
if fault == FaultAfterSideEffect {
result = "injected_failure"
return ErrInjectedFailure
}
mutation, err := w.repository.CompleteAttachmentJob(ctx, lease, variants)
if err != nil {
return fmt.Errorf("complete attachment job: %w", err)
}
if mutation == model.JobMutationApplied && strings.HasPrefix(lease.Attachment.StagingKey, "staging/") {
if err := w.objects.Delete(context.WithoutCancel(ctx), lease.Attachment.StagingKey); err != nil {
w.logger.Warn("staging cleanup failed", "attachment_id", lease.Attachment.ID, "error", err)
}
}
if mutation != model.JobMutationApplied && mutation != model.JobMutationAlreadyComplete && mutation != model.JobMutationStale {
return fmt.Errorf("unexpected completion result %q", mutation)
}
if fault == FaultAfterCommit {
result = "injected_failure"
return ErrInjectedFailure
}
if err := delivery.Ack(ctx); err != nil {
return err
}
result = "ready"
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,
envelope redisstream.Envelope,
claimErr error,
) (string, error) {
switch {
case errors.Is(claimErr, model.ErrNotFound), errors.Is(claimErr, model.ErrInvalidInput):
return "invalid_job", delivery.ToFailed(ctx, redisstream.FailedDelivery{Code: "invalid_job", FailedAt: w.now()})
case errors.Is(claimErr, model.ErrJobComplete), errors.Is(claimErr, model.ErrStaleAttempt), errors.Is(claimErr, model.ErrStalePipeline):
return "duplicate", delivery.Ack(ctx)
case errors.Is(claimErr, model.ErrJobBusy):
return "duplicate", delivery.Ack(ctx)
case errors.Is(claimErr, model.ErrJobNotDue):
return "not_due", nil
case errors.Is(claimErr, model.ErrConflict):
job, err := w.repository.AttachmentJob(ctx, envelope.JobID.String())
if err != nil {
return "transient_error", fmt.Errorf("inspect conflicting job: %w", err)
}
switch job.Status {
case model.AttachmentJobReady:
return "duplicate", delivery.Ack(ctx)
case model.AttachmentJobFailed:
code := "processing_failed"
if job.ErrorCode != nil {
code = *job.ErrorCode
}
return "failed", delivery.ToFailed(ctx, redisstream.FailedDelivery{Code: code, FailedAt: w.now()})
default:
return "transient_error", fmt.Errorf("claim attachment job: %w", claimErr)
}
default:
return "transient_error", fmt.Errorf("claim attachment job: %w", claimErr)
}
}
func (w *Worker) process(ctx context.Context, lease model.AttachmentJobLease) ([]model.Variant, error) {
body, err := w.objects.Get(ctx, lease.Attachment.StagingKey)
if err != nil {
return nil, err
}
defer func() { _ = body.Close() }()
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(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)
if err != nil {
return nil, err
}
if weight > w.config.MemoryBytes {
return nil, errWorkerCapacity
}
if err := w.memory.Acquire(ctx, weight); err != nil {
return nil, err
}
defer w.memory.Release(weight)
processed, err := w.processor.Process(ctx, data, lease.Attachment.ContentType)
if err != nil {
return nil, err
}
variants := []struct {
name string
value transform.Variant
}{
{name: "original", value: processed.Original},
{name: "thumbnail", value: processed.Thumbnail},
{name: "crop", value: processed.Crop},
{name: "optimized", value: processed.Optimized},
}
result := make([]model.Variant, 0, len(variants))
for _, item := range variants {
objectKey := variantObjectKey(lease.Attachment.ID, lease.Job.PipelineVersion, item.name, item.value)
if err := w.objects.Put(ctx, objectKey, item.value.ContentType, item.value.Bytes); err != nil {
return nil, err
}
result = append(result, model.Variant{
Name: item.name, ContentType: item.value.ContentType, SizeBytes: int64(len(item.value.Bytes)),
SHA256: item.value.SHA256, Width: item.value.Width, Height: item.value.Height,
ObjectKey: objectKey, PipelineVersion: lease.Job.PipelineVersion,
})
}
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 {
extension := ".bin"
switch value.ContentType {
case "image/png":
extension = ".png"
case "image/jpeg":
extension = ".jpg"
case "image/webp":
extension = ".webp"
}
return path.Join(
"attachments", attachmentID, "pipelines", fmt.Sprintf("%d", pipelineVersion),
name, value.SHA256+extension,
)
}
func (w *Worker) resolveProcessingFailure(
ctx context.Context,
delivery redisstream.Delivery,
lease model.AttachmentJobLease,
processingErr error,
) (string, error) {
code, permanent := processingError(processingErr)
if permanent || lease.Job.Attempt >= w.config.MaxAttempts {
if !permanent {
code = "retry_exhausted"
}
mutation, err := w.repository.FailAttachmentJob(ctx, lease, code)
if err != nil {
return "transient_error", fmt.Errorf("fail attachment job: %w", err)
}
if mutation == model.JobMutationStale || mutation == model.JobMutationAlreadyComplete {
return "duplicate", delivery.Ack(ctx)
}
if mutation != model.JobMutationApplied {
return "transient_error", fmt.Errorf("unexpected failure result %q", mutation)
}
return "failed", delivery.ToFailed(ctx, redisstream.FailedDelivery{Code: code, FailedAt: w.now()})
}
nextAttempt := w.now().Add(w.retryDelay(lease.Job.ID, lease.Job.Attempt))
mutation, err := w.repository.RetryAttachmentJob(ctx, lease, code, nextAttempt)
if err != nil {
return "transient_error", fmt.Errorf("retry attachment job: %w", err)
}
if mutation == model.JobMutationStale || mutation == model.JobMutationAlreadyComplete {
return "duplicate", delivery.Ack(ctx)
}
if mutation != model.JobMutationApplied {
return "transient_error", fmt.Errorf("unexpected retry result %q", mutation)
}
w.metrics.ObserveRetry()
return "retry", delivery.Ack(ctx)
}
func processingError(err error) (string, bool) {
switch {
case errors.Is(err, transform.ErrInvalidImage), errors.Is(err, transform.ErrUnsupportedMedia):
return "invalid_image", true
case errors.Is(err, transform.ErrPayloadTooLarge):
return "image_too_large", true
case errors.Is(err, objectstore.ErrNotFound):
return "source_missing", true
case errors.Is(err, errWorkerCapacity):
return "worker_capacity", true
default:
return "processing_failed", false
}
}
func (w *Worker) retryDelay(jobID string, attempt int) time.Duration {
delay := w.config.RetryBase
for step := 1; step < attempt && delay < w.config.RetryMax; step++ {
if delay > w.config.RetryMax/2 {
delay = w.config.RetryMax
break
}
delay *= 2
}
if delay > w.config.RetryMax {
delay = w.config.RetryMax
}
var hash uint64
for index := range jobID {
hash = hash*131 + uint64(jobID[index])
}
jitterRange := min(delay/4, w.config.RetryMax-delay)
if jitterRange <= 0 {
return delay
}
jitter := time.Duration(hash % uint64(jitterRange))
if delay > time.Duration(math.MaxInt64)-jitter {
return delay
}
return delay + jitter
}
type nopMetrics struct{}
func (nopMetrics) ObserveStarted() {}
func (nopMetrics) ObserveFinished(string, time.Duration) {}
func (nopMetrics) ObserveRetry() {}
func (nopMetrics) ObserveReclaimed(int) {}
@@ -0,0 +1,109 @@
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"
)
func TestConfigRequiresEnoughMemoryForMaximumImage(t *testing.T) {
config := validConfig()
require.NoError(t, validateConfig(config))
config.MemoryBytes = 384 * 1024 * 1024
require.ErrorContains(t, validateConfig(config), "memory must fit")
}
func TestRetryDelayIsBounded(t *testing.T) {
worker := &Worker{config: Config{RetryBase: time.Second, RetryMax: 4 * time.Second}}
for attempt := 1; attempt <= 10; attempt++ {
delay := worker.retryDelay("11111111-1111-4111-8111-111111111111", attempt)
require.GreaterOrEqual(t, delay, time.Second)
require.LessOrEqual(t, delay, 4*time.Second)
}
}
func TestProcessingErrorClassification(t *testing.T) {
tests := []struct {
err error
code string
permanent bool
}{
{err: transform.ErrInvalidImage, code: "invalid_image", permanent: true},
{err: transform.ErrPayloadTooLarge, code: "image_too_large", permanent: true},
{err: objectstore.ErrNotFound, code: "source_missing", permanent: true},
{err: errors.New("temporary S3 failure"), code: "processing_failed", permanent: false},
}
for _, test := range tests {
code, permanent := processingError(test.err)
require.Equal(t, test.code, code)
require.Equal(t, test.permanent, permanent)
}
}
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,
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,
}
}