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,
}
}
+193
View File
@@ -0,0 +1,193 @@
package httpapi
import (
"errors"
"io"
"mime"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/messenger/attachment"
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
)
func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request) *apiError {
started := time.Now()
result := "client_error"
defer func() {
s.metrics.attachmentUploads.WithLabelValues(result).Inc()
s.metrics.attachmentDuration.Observe(time.Since(started).Seconds())
}()
if r.Method != http.MethodPost {
return methodNotAllowed(w, http.MethodPost)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
chatID, valid := canonicalID(strings.Split(r.URL.Path, "/")[4])
if !valid {
return invalidRequest()
}
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
return invalidRequest()
}
filename, valid := attachmentFilename(query)
if !valid {
return invalidRequest()
}
uploaded, err := s.attachments.Upload(r.Context(), attachment.Upload{
ChatID: chatID, OwnerID: user.ID, Filename: filename,
ContentType: r.Header.Get("Content-Type"), ContentLength: r.ContentLength, Body: r.Body,
Traceparent: traceparent(r.Header.Get("traceparent")), Tracestate: tracestate(r.Header.Get("tracestate")),
})
if err != nil {
if errors.Is(err, model.ErrCapacity) {
result = "capacity_rejected"
w.Header().Set("Retry-After", "1")
} else if errors.Is(err, model.ErrUnavailable) {
result = "dependency_error"
}
return attachmentError(err)
}
result = "success"
s.metrics.attachmentBytes.Add(float64(uploaded.SizeBytes))
writeJSON(w, http.StatusAccepted, uploaded)
return nil
}
func attachmentFilename(query url.Values) (string, bool) {
if len(query) != 1 || len(query["filename"]) != 1 {
return "", false
}
filename := query["filename"][0]
length := utf8.RuneCountInString(filename)
if !utf8.ValidString(filename) || strings.TrimSpace(filename) == "" || length < 1 || length > 255 {
return "", false
}
for _, char := range filename {
if char == '/' || char == '\\' || char == 0 || unicode.IsControl(char) {
return "", false
}
}
return filename, true
}
func (s *Server) attachmentMetadata(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
attachmentID, apiErr := attachmentIDFromRequest(r)
if apiErr != nil {
return apiErr
}
value, err := s.attachments.Metadata(r.Context(), attachmentID, user.ID)
if err != nil {
return attachmentError(err)
}
writeJSON(w, http.StatusOK, value)
return nil
}
func (s *Server) attachmentContent(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
query, err := url.ParseQuery(r.URL.RawQuery)
variant, valid := attachmentVariant(query)
if err != nil || !valid {
return invalidRequest()
}
attachmentID, apiErr := attachmentIDFromRequest(r)
if apiErr != nil {
return apiErr
}
content, err := s.attachments.Content(r.Context(), attachmentID, user.ID, variant)
if err != nil {
return attachmentError(err)
}
defer func() { _ = content.Body.Close() }()
w.Header().Set("Content-Type", content.Variant.ContentType)
w.Header().Set("Content-Length", strconv.FormatInt(content.Variant.SizeBytes, 10))
w.Header().Set("Content-Disposition", mime.FormatMediaType("inline", map[string]string{"filename": content.Attachment.Filename}))
w.WriteHeader(http.StatusOK)
if _, err := io.Copy(w, content.Body); err != nil {
s.logger.Warn("attachment download interrupted", "attachment_id", content.Attachment.ID, "error", err)
}
return nil
}
func attachmentVariant(query url.Values) (string, bool) {
if len(query) == 0 {
return "original", true
}
if len(query) != 1 || len(query["variant"]) != 1 {
return "", false
}
switch query["variant"][0] {
case "original", "thumbnail", "crop", "optimized":
return query["variant"][0], true
default:
return "", false
}
}
var traceparentPattern = regexp.MustCompile(`^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$`)
func traceparent(value string) string {
if traceparentPattern.MatchString(value) {
return value
}
return ""
}
func tracestate(value string) string {
if len(value) <= 512 {
return value
}
return ""
}
func attachmentIDFromRequest(r *http.Request) (string, *apiError) {
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
attachmentID, valid := canonicalID(parts[3])
if !valid {
return "", invalidRequest()
}
return attachmentID, nil
}
func attachmentError(err error) *apiError {
switch {
case errors.Is(err, model.ErrNotFound):
return notFound()
case errors.Is(err, model.ErrInvalidInput):
return invalidRequest()
case errors.Is(err, model.ErrUnsupportedMedia):
return &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "unsupported image type"}
case errors.Is(err, model.ErrPayloadTooLarge):
return &apiError{http.StatusRequestEntityTooLarge, errorCodePayloadTooLarge, "image is too large"}
case errors.Is(err, model.ErrCapacity):
return &apiError{http.StatusTooManyRequests, errorCodeRateLimited, "image capacity is temporarily exhausted"}
case errors.Is(err, model.ErrConflict):
return &apiError{http.StatusConflict, errorCodeConflict, "attachment is not ready"}
default:
return unavailable()
}
}
+111
View File
@@ -0,0 +1,111 @@
package httpapi
import (
"errors"
"io"
"net/http"
"strings"
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
)
func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodPost {
return methodNotAllowed(w, http.MethodPost)
}
body, err := io.ReadAll(io.LimitReader(r.Body, 1))
if err != nil || len(body) != 0 {
return invalidRequest()
}
username, passwordValue, ok := singleBasicAuth(r)
if !ok {
return unauthorized()
}
credentials, err := s.userRepository.UserByUsername(r.Context(), username)
if errors.Is(err, model.ErrNotFound) {
if _, verifyErr := s.passwords.Verify(passwordValue, s.passwords.DummyHash()); verifyErr != nil {
return internalError()
}
return unauthorized()
}
if err != nil {
return unavailable()
}
verified, err := s.passwords.Verify(passwordValue, credentials.PasswordHash)
if err != nil {
return internalError()
}
if !verified {
return unauthorized()
}
token, expiresAt, err := s.sessions.Create(r.Context(), credentials.ID, s.sessionTTL)
if err != nil {
return unavailable()
}
writeJSON(w, http.StatusCreated, struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt string `json:"expires_at"`
User User `json:"user"`
}{token, "Bearer", model.FormatTime(expiresAt), credentials.User})
return nil
}
func singleBasicAuth(r *http.Request) (string, string, bool) {
if len(r.Header.Values("Authorization")) != 1 {
return "", "", false
}
username, passwordValue, ok := r.BasicAuth()
return username, passwordValue, ok && username != ""
}
func (s *Server) revokeSession(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodDelete {
return methodNotAllowed(w, http.MethodDelete)
}
_, token, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
if err := s.sessions.Delete(r.Context(), token); errors.Is(err, model.ErrSessionNotFound) {
return unauthorized()
} else if err != nil {
return unavailable()
}
w.WriteHeader(http.StatusNoContent)
return nil
}
func (s *Server) authenticate(r *http.Request) (User, string, *apiError) {
values := r.Header.Values("Authorization")
if len(values) != 1 {
return User{}, "", unauthorized()
}
scheme, token, found := strings.Cut(values[0], " ")
if !found || !strings.EqualFold(scheme, "Bearer") || token == "" || strings.ContainsAny(token, " \t\r\n") {
return User{}, "", unauthorized()
}
userID, err := s.sessions.UserID(r.Context(), token)
if errors.Is(err, model.ErrSessionNotFound) || errors.Is(err, model.ErrInvalidToken) {
return User{}, "", unauthorized()
}
if err != nil {
return User{}, "", unavailable()
}
user, err := s.userRepository.UserByID(r.Context(), userID)
if errors.Is(err, model.ErrNotFound) {
_ = s.sessions.Delete(r.Context(), token)
return User{}, "", unauthorized()
}
if err != nil {
return User{}, "", unavailable()
}
return user, token, nil
}
func authenticationChallenge(r *http.Request) string {
if r.URL.Path == "/api/v1/auth/sessions" {
return `Basic realm="messenger", charset="UTF-8"`
}
return `Bearer realm="messenger"`
}
+61
View File
@@ -0,0 +1,61 @@
package httpapi
import (
"encoding/json"
"net/http"
)
const (
errorCodeInvalidRequest = "invalid_request"
errorCodeUnauthorized = "unauthorized"
errorCodeNotFound = "not_found"
errorCodeInternal = "internal_error"
errorCodeUnsupportedMediaType = "unsupported_media_type"
errorCodePayloadTooLarge = "payload_too_large"
errorCodeUnavailable = "unavailable"
errorCodeConflict = "conflict"
errorCodeRateLimited = "rate_limited"
)
type apiError struct {
status int
code string
message string
}
func methodNotAllowed(w http.ResponseWriter, allowed string) *apiError {
w.Header().Set("Allow", allowed)
return &apiError{http.StatusMethodNotAllowed, errorCodeInvalidRequest, "method not allowed"}
}
func invalidRequest() *apiError {
return &apiError{http.StatusBadRequest, errorCodeInvalidRequest, "invalid request"}
}
func unauthorized() *apiError {
return &apiError{http.StatusUnauthorized, errorCodeUnauthorized, "authentication required"}
}
func notFound() *apiError {
return &apiError{http.StatusNotFound, errorCodeNotFound, "resource not found"}
}
func internalError() *apiError {
return &apiError{http.StatusInternalServerError, errorCodeInternal, "internal server error"}
}
func unavailable() *apiError {
return &apiError{http.StatusServiceUnavailable, errorCodeUnavailable, "service unavailable"}
}
func writeError(w http.ResponseWriter, requestID string, err *apiError) {
writeJSON(w, err.status, map[string]any{"error": map[string]string{
"code": err.code, "message": err.message, "request_id": requestID,
}})
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
+300
View File
@@ -0,0 +1,300 @@
package httpapi
import (
"context"
"errors"
"net/http"
"regexp"
"strings"
"time"
"unicode/utf8"
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
)
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
func (s *Server) live(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
return nil
}
func (s *Server) readiness(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
if !s.ready.Load() {
return unavailable()
}
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
if err := s.database.Ping(ctx); err != nil {
return unavailable()
}
if err := s.sessions.Ping(ctx); err != nil {
return unavailable()
}
if err := s.objects.Ping(ctx); err != nil {
return unavailable()
}
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
return nil
}
func (s *Server) users(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodPost {
return methodNotAllowed(w, http.MethodPost)
}
var input struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
}
if err := readJSON(w, r, &input); err != nil {
return err
}
if !usernamePattern.MatchString(input.Username) || !validText(input.DisplayName, 100) || !validPassword(input.Password) {
return invalidRequest()
}
passwordHash, err := s.passwords.Hash(input.Password)
if err != nil {
return internalError()
}
user, err := s.userRepository.CreateUser(r.Context(), input.Username, input.DisplayName, passwordHash)
if errors.Is(err, model.ErrConflict) {
return &apiError{http.StatusConflict, errorCodeConflict, "username already exists"}
}
if err != nil {
return unavailable()
}
writeJSON(w, http.StatusCreated, user)
return nil
}
func validPassword(value string) bool {
length := utf8.RuneCountInString(value)
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && length >= 12 && length <= 128
}
func (s *Server) me(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
user, _, err := s.authenticate(r)
if err != nil {
return err
}
writeJSON(w, http.StatusOK, user)
return nil
}
func (s *Server) chats(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodPost && r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet+", "+http.MethodPost)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
if r.Method == http.MethodGet {
return s.listChats(w, r, user)
}
var input struct {
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
}
if err := readJSON(w, r, &input); err != nil {
return err
}
if !validText(input.Title, 100) || len(input.MemberIDs) < 1 || len(input.MemberIDs) > 100 {
return invalidRequest()
}
members := make(map[string]struct{}, len(input.MemberIDs))
for i, memberID := range input.MemberIDs {
canonical, valid := canonicalID(memberID)
if !valid {
return invalidRequest()
}
if _, duplicate := members[canonical]; duplicate {
return invalidRequest()
}
members[canonical] = struct{}{}
input.MemberIDs[i] = canonical
}
if _, included := members[user.ID]; !included {
return invalidRequest()
}
chat, err := s.chatRepository.CreateChat(r.Context(), input.Title, input.MemberIDs, user.ID)
if errors.Is(err, model.ErrInvalidMembers) {
return invalidRequest()
}
if err != nil {
return unavailable()
}
writeJSON(w, http.StatusCreated, chat)
return nil
}
func (s *Server) listChats(w http.ResponseWriter, r *http.Request, user User) *apiError {
limit, cursor, err := pageParams(r, "chat", user.ID)
if err != nil {
return err
}
items, hasNext, listErr := s.chatRepository.ListChats(r.Context(), user.ID, cursorPosition(cursor), limit)
if errors.Is(listErr, model.ErrInvalidCursor) {
return invalidRequest()
}
if listErr != nil {
return unavailable()
}
if items == nil {
items = []Chat{}
}
var next *string
if hasNext {
last := items[len(items)-1]
value := encodeCursor("chat", user.ID, last.CreatedAt, last.ID)
next = &value
}
writeJSON(w, http.StatusOK, struct {
Items []Chat `json:"items"`
NextCursor *string `json:"next_cursor"`
}{items, next})
return nil
}
func (s *Server) chat(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
chatID, valid := canonicalID(strings.Split(r.URL.Path, "/")[4])
if !valid {
return invalidRequest()
}
chat, err := s.chatRepository.ChatForUser(r.Context(), chatID, user.ID)
if errors.Is(err, model.ErrNotFound) {
return notFound()
}
if err != nil {
return unavailable()
}
writeJSON(w, http.StatusOK, chat)
return nil
}
func (s *Server) messages(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodPost && r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet+", "+http.MethodPost)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
chatID, valid := canonicalID(strings.Split(r.URL.Path, "/")[4])
if !valid {
return invalidRequest()
}
if r.Method == http.MethodGet {
return s.listMessages(w, r, user, chatID)
}
key, valid := idempotencyKey(r)
if !valid {
return invalidRequest()
}
var input createMessageRequest
if err := readJSON(w, r, &input); err != nil {
return err
}
text, attachmentIDs, valid := input.values()
if !valid || !validMessage(text, attachmentIDs) || !canonicalAttachmentIDs(attachmentIDs) {
return invalidRequest()
}
message, replay, err := s.messageRepository.CreateMessage(
r.Context(), chatID, user.ID, text, attachmentIDs, key, s.idempotencyTTL,
)
if errors.Is(err, model.ErrNotFound) {
return notFound()
}
if errors.Is(err, model.ErrIdempotencyConflict) {
return &apiError{http.StatusConflict, errorCodeConflict, "idempotency key conflicts with previous request"}
}
if err != nil {
return unavailable()
}
if replay {
s.metrics.replays.Inc()
}
writeJSON(w, http.StatusCreated, message)
return nil
}
func validMessage(text string, attachmentIDs []string) bool {
if !utf8.ValidString(text) || utf8.RuneCountInString(text) > 4000 {
return false
}
return len(attachmentIDs) > 0 || strings.TrimSpace(text) != ""
}
func canonicalAttachmentIDs(attachmentIDs []string) bool {
if len(attachmentIDs) > 10 {
return false
}
seen := make(map[string]struct{}, len(attachmentIDs))
for index, attachmentID := range attachmentIDs {
canonical, valid := canonicalID(attachmentID)
if !valid {
return false
}
if _, duplicate := seen[canonical]; duplicate {
return false
}
seen[canonical] = struct{}{}
attachmentIDs[index] = canonical
}
return true
}
func (s *Server) listMessages(w http.ResponseWriter, r *http.Request, user User, chatID string) *apiError {
limit, cursor, err := pageParams(r, "message", chatID)
if err != nil {
return err
}
items, hasNext, listErr := s.messageRepository.ListMessages(r.Context(), chatID, user.ID, cursorPosition(cursor), limit)
if errors.Is(listErr, model.ErrNotFound) {
return notFound()
}
if errors.Is(listErr, model.ErrInvalidCursor) {
return invalidRequest()
}
if listErr != nil {
return unavailable()
}
if items == nil {
items = []Message{}
}
var next *string
if hasNext {
last := items[len(items)-1]
value := encodeCursor("message", chatID, last.CreatedAt, last.ID)
next = &value
}
writeJSON(w, http.StatusOK, struct {
Items []Message `json:"items"`
NextCursor *string `json:"next_cursor"`
}{items, next})
return nil
}
func cursorPosition(cursor *pageCursor) *model.Position {
if cursor == nil {
return nil
}
return &model.Position{CreatedAt: cursor.Time, ID: cursor.ID}
}
@@ -0,0 +1,49 @@
package httpapi
import (
"context"
"time"
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/messenger/attachment"
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
)
type UserRepository interface {
CreateUser(context.Context, string, string, string) (model.User, error)
UserByID(context.Context, string) (model.User, error)
UserByUsername(context.Context, string) (model.UserCredentials, error)
}
type ChatRepository interface {
CreateChat(context.Context, string, []string, string) (model.Chat, error)
ChatForUser(context.Context, string, string) (model.Chat, error)
ListChats(context.Context, string, *model.Position, int) ([]model.Chat, bool, error)
}
type MessageRepository interface {
CreateMessage(context.Context, string, string, string, []string, string, time.Duration) (model.Message, bool, error)
ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error)
}
type AttachmentService interface {
Upload(context.Context, attachment.Upload) (model.Attachment, error)
Metadata(context.Context, string, string) (model.Attachment, error)
Content(context.Context, string, string, string) (attachment.Content, error)
}
type HealthChecker interface {
Ping(context.Context) error
}
type SessionStore interface {
HealthChecker
Create(context.Context, string, time.Duration) (string, time.Time, error)
UserID(context.Context, string) (string, error)
Delete(context.Context, string) error
}
type PasswordService interface {
Hash(string) (string, error)
Verify(string, string) (bool, error)
DummyHash() string
}
+119
View File
@@ -0,0 +1,119 @@
package httpapi
import (
"net/http"
"strconv"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
requestDurationBuckets = []float64{0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 20, 30}
uploadDurationBuckets = []float64{0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 20, 30, 60}
)
type metrics struct {
requests *prometheus.CounterVec
duration *prometheus.HistogramVec
inFlight prometheus.Gauge
replays prometheus.Counter
attachmentUploads *prometheus.CounterVec
attachmentDuration prometheus.Histogram
attachmentBytes prometheus.Counter
handler http.Handler
}
func newMetrics() *metrics {
registry := prometheus.NewRegistry()
result := &metrics{
requests: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "messenger",
Subsystem: "http",
Name: "requests_total",
Help: "Completed HTTP requests.",
}, []string{"method", "route", "status_class"}),
duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: "messenger",
Subsystem: "http",
Name: "request_duration_seconds",
Help: "HTTP request duration in seconds.",
Buckets: requestDurationBuckets,
}, []string{"method", "route"}),
inFlight: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: "messenger",
Subsystem: "http",
Name: "requests_in_flight",
Help: "HTTP requests currently being served.",
}),
replays: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: "messenger",
Subsystem: "http",
Name: "idempotency_replays_total",
Help: "Message requests served from an idempotency record.",
}),
attachmentUploads: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "messenger",
Name: "attachment_uploads_total",
Help: "Completed attachment uploads by result.",
}, []string{"result"}),
attachmentDuration: prometheus.NewHistogram(prometheus.HistogramOpts{
Namespace: "messenger",
Name: "attachment_upload_duration_seconds",
Help: "Attachment upload duration in seconds.",
Buckets: uploadDurationBuckets,
}),
attachmentBytes: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: "messenger",
Name: "attachment_upload_bytes_total",
Help: "Bytes accepted by successful attachment uploads.",
}),
}
registry.MustRegister(
result.requests,
result.duration,
result.inFlight,
result.replays,
result.attachmentUploads,
result.attachmentDuration,
result.attachmentBytes,
collectors.NewGoCollector(),
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
)
result.handler = promhttp.HandlerFor(registry, promhttp.HandlerOpts{})
return result
}
func (m *metrics) observe(r *http.Request, status int, started time.Time) {
route := routeTemplate(r.URL.Path)
m.requests.WithLabelValues(r.Method, route, strconv.Itoa(status/100)+"xx").Inc()
m.duration.WithLabelValues(r.Method, route).Observe(time.Since(started).Seconds())
}
func routeTemplate(path string) string {
switch path {
case "/health/live", "/health/ready", "/metrics", "/api/v1/users", "/api/v1/users/me",
"/api/v1/auth/sessions", "/api/v1/auth/sessions/current", "/api/v1/chats":
return path
}
parts := strings.Split(strings.Trim(path, "/"), "/")
if len(parts) == 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" {
return "/api/v1/chats/{chat_id}"
}
if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "messages" {
return "/api/v1/chats/{chat_id}/messages"
}
if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "attachments" {
return "/api/v1/chats/{chat_id}/attachments"
}
if len(parts) == 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" {
return "/api/v1/attachments/{attachment_id}"
}
if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" && parts[4] == "content" {
return "/api/v1/attachments/{attachment_id}/content"
}
return "unknown"
}
+30
View File
@@ -0,0 +1,30 @@
package httpapi
import (
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
"github.com/google/uuid"
)
type User = model.User
type Chat = model.Chat
type Message = model.Message
type Attachment = model.Attachment
func newID() (string, error) {
id, err := uuid.NewRandom()
if err != nil {
return "", err
}
return id.String(), nil
}
func canonicalID(value string) (string, bool) {
if len(value) != 36 {
return "", false
}
id, err := uuid.Parse(value)
if err != nil {
return "", false
}
return id.String(), true
}
+147
View File
@@ -0,0 +1,147 @@
package httpapi
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"io"
"mime"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
)
const maxRequestBytes = 1 << 20
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
type createMessageRequest struct {
Text json.RawMessage `json:"text"`
AttachmentIDs json.RawMessage `json:"attachment_ids"`
}
func (r createMessageRequest) values() (string, []string, bool) {
var text *string
if len(r.Text) == 0 || json.Unmarshal(r.Text, &text) != nil || text == nil {
return "", nil, false
}
if len(r.AttachmentIDs) == 0 {
return *text, nil, true
}
var attachmentIDs *[]string
if json.Unmarshal(r.AttachmentIDs, &attachmentIDs) != nil || attachmentIDs == nil {
return "", nil, false
}
return *text, *attachmentIDs, true
}
func readJSON(w http.ResponseWriter, r *http.Request, target any) *apiError {
mediaType, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || mediaType != "application/json" || (params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8")) {
return &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "expected application/json"}
}
r.Body = http.MaxBytesReader(w, r.Body, maxRequestBytes)
data, err := io.ReadAll(r.Body)
if err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
return &apiError{http.StatusRequestEntityTooLarge, errorCodePayloadTooLarge, "request body too large"}
}
return invalidRequest()
}
if !utf8.Valid(data) {
return invalidRequest()
}
var object map[string]json.RawMessage
if err := json.Unmarshal(data, &object); err != nil || object == nil {
return invalidRequest()
}
normalized, err := json.Marshal(object)
if err != nil {
return invalidRequest()
}
decoder := json.NewDecoder(bytes.NewReader(normalized))
decoder.DisallowUnknownFields()
if err := decoder.Decode(target); err != nil {
return invalidRequest()
}
return nil
}
func validText(value string, maxRunes int) bool {
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && utf8.RuneCountInString(value) <= maxRunes
}
func idempotencyKey(r *http.Request) (string, bool) {
values := r.Header.Values("Idempotency-Key")
if len(values) != 1 || !idempotencyKeyPattern.MatchString(values[0]) {
return "", false
}
return values[0], true
}
type pageCursor struct {
Kind string `json:"kind"`
Resource string `json:"resource"`
Time time.Time `json:"time"`
ID string `json:"id"`
}
func pageParams(r *http.Request, kind, resource string) (int, *pageCursor, *apiError) {
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
return 0, nil, invalidRequest()
}
for key := range query {
if key != "limit" && key != "cursor" {
return 0, nil, invalidRequest()
}
if len(query[key]) != 1 {
return 0, nil, invalidRequest()
}
}
limit := 50
if value, present := query["limit"]; present {
parsed, err := strconv.Atoi(value[0])
if err != nil || parsed < 1 || parsed > 100 {
return 0, nil, invalidRequest()
}
limit = parsed
}
if value, present := query["cursor"]; present {
cursor, valid := decodeCursor(value[0], kind, resource)
if !valid {
return 0, nil, invalidRequest()
}
return limit, cursor, nil
}
return limit, nil, nil
}
func encodeCursor(kind, resource string, createdAt time.Time, id string) string {
data, _ := json.Marshal(pageCursor{kind, resource, createdAt, id})
return base64.RawURLEncoding.EncodeToString(data)
}
func decodeCursor(value, kind, resource string) (*pageCursor, bool) {
data, err := base64.RawURLEncoding.DecodeString(value)
if err != nil {
return nil, false
}
var cursor pageCursor
if err := json.Unmarshal(data, &cursor); err != nil || cursor.Kind != kind || cursor.Resource != resource {
return nil, false
}
if cursor.Time.IsZero() {
return nil, false
}
if _, valid := canonicalID(cursor.ID); !valid {
return nil, false
}
return &cursor, true
}
+47
View File
@@ -0,0 +1,47 @@
package httpapi
import (
"net/http"
"strings"
)
type requestHandler func(http.ResponseWriter, *http.Request) *apiError
func (s *Server) route(w http.ResponseWriter, r *http.Request) *apiError {
var handler requestHandler
switch r.URL.Path {
case "/health/live":
handler = s.live
case "/health/ready":
handler = s.readiness
case "/metrics":
s.metrics.handler.ServeHTTP(w, r)
return nil
case "/api/v1/users":
handler = s.users
case "/api/v1/users/me":
handler = s.me
case "/api/v1/auth/sessions":
handler = s.createSession
case "/api/v1/auth/sessions/current":
handler = s.revokeSession
case "/api/v1/chats":
handler = s.chats
default:
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
if len(parts) == 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" {
handler = s.chat
} else if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "messages" {
handler = s.messages
} else if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "attachments" {
handler = s.uploadAttachment
} else if len(parts) == 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" {
handler = s.attachmentMetadata
} else if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" && parts[4] == "content" {
handler = s.attachmentContent
} else {
return notFound()
}
}
return handler(w, r)
}
+133
View File
@@ -0,0 +1,133 @@
package httpapi
import (
"context"
"log/slog"
"net/http"
"sync/atomic"
"time"
)
type Dependencies struct {
Users UserRepository
Chats ChatRepository
Messages MessageRepository
Attachments AttachmentService
Sessions SessionStore
Passwords PasswordService
Database HealthChecker
Objects HealthChecker
}
type Config struct {
SessionTTL time.Duration
IdempotencyTTL time.Duration
RequestTTL time.Duration
InstanceID string
SwaggerPort string
}
type Server struct {
userRepository UserRepository
chatRepository ChatRepository
messageRepository MessageRepository
attachments AttachmentService
sessions SessionStore
passwords PasswordService
database HealthChecker
objects HealthChecker
sessionTTL time.Duration
idempotencyTTL time.Duration
requestTTL time.Duration
instanceID string
logger *slog.Logger
swaggerPort string
metrics *metrics
ready atomic.Bool
}
type statusWriter struct {
http.ResponseWriter
status int
}
func (w *statusWriter) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
func NewServer(
logger *slog.Logger,
dependencies Dependencies,
config Config,
) *Server {
s := &Server{
userRepository: dependencies.Users, chatRepository: dependencies.Chats,
messageRepository: dependencies.Messages,
attachments: dependencies.Attachments, sessions: dependencies.Sessions,
passwords: dependencies.Passwords, database: dependencies.Database, objects: dependencies.Objects,
sessionTTL: config.SessionTTL, idempotencyTTL: config.IdempotencyTTL, requestTTL: config.RequestTTL,
instanceID: config.InstanceID, logger: logger, swaggerPort: config.SwaggerPort, metrics: newMetrics(),
}
s.ready.Store(true)
return s
}
func (s *Server) SetReady(ready bool) {
s.ready.Store(ready)
}
func (s *Server) Handler() http.Handler {
return http.HandlerFunc(s.serve)
}
func (s *Server) serve(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Instance-Id", s.instanceID)
requestID, err := newID()
if err != nil {
http.Error(w, "server unavailable", http.StatusServiceUnavailable)
return
}
w.Header().Set("X-Request-Id", requestID)
w.Header().Set("Cache-Control", "no-store")
wrapped := &statusWriter{ResponseWriter: w, status: http.StatusOK}
started := time.Now()
s.metrics.inFlight.Inc()
defer func() {
s.metrics.inFlight.Dec()
if recovered := recover(); recovered != nil {
s.logger.Error("request panic", "request_id", requestID, "method", r.Method, "path", r.URL.Path)
if wrapped.status == http.StatusOK {
writeError(wrapped, requestID, internalError())
}
}
s.metrics.observe(r, wrapped.status, started)
s.logger.Info("request", "request_id", requestID, "method", r.Method, "path", r.URL.Path, "status", wrapped.status, "duration_ms", time.Since(started).Milliseconds())
}()
if s.allowSwaggerOrigin(wrapped, r) && r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
wrapped.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
wrapped.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, Idempotency-Key")
wrapped.WriteHeader(http.StatusNoContent)
return
}
ctx, cancel := context.WithTimeout(r.Context(), s.requestTTL)
defer cancel()
r = r.WithContext(ctx)
if apiErr := s.route(wrapped, r); apiErr != nil {
if apiErr.status == http.StatusUnauthorized {
wrapped.Header().Set("WWW-Authenticate", authenticationChallenge(r))
}
writeError(wrapped, requestID, apiErr)
}
}
func (s *Server) allowSwaggerOrigin(w http.ResponseWriter, r *http.Request) bool {
origin := r.Header.Get("Origin")
if origin != "http://localhost:"+s.swaggerPort && origin != "http://127.0.0.1:"+s.swaggerPort {
return false
}
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Expose-Headers", "X-Request-Id, X-Instance-Id")
w.Header().Add("Vary", "Origin")
return true
}
+378
View File
@@ -0,0 +1,378 @@
package httpapi
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/stretchr/testify/suite"
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/messenger/attachment"
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
)
var errDependency = errors.New("dependency unavailable")
type MessengerSuite struct {
suite.Suite
logger *slog.Logger
}
func TestMessengerSuite(t *testing.T) {
suite.Run(t, new(MessengerSuite))
}
func (s *MessengerSuite) SetupTest() {
s.logger = slog.New(slog.NewTextHandler(io.Discard, nil))
}
type messengerStoreStub struct {
pingErr error
userByID model.User
userByIDErr error
credentials model.UserCredentials
credentialsErr error
message model.Message
messageReplay bool
messageErr error
}
func (s messengerStoreStub) Ping(context.Context) error { return s.pingErr }
func (messengerStoreStub) CreateUser(context.Context, string, string, string) (model.User, error) {
return model.User{}, nil
}
func (s messengerStoreStub) UserByID(context.Context, string) (model.User, error) {
return s.userByID, s.userByIDErr
}
func (s messengerStoreStub) UserByUsername(context.Context, string) (model.UserCredentials, error) {
return s.credentials, s.credentialsErr
}
func (messengerStoreStub) CreateChat(context.Context, string, []string, string) (model.Chat, error) {
return model.Chat{}, nil
}
func (messengerStoreStub) ChatForUser(context.Context, string, string) (model.Chat, error) {
return model.Chat{}, nil
}
func (messengerStoreStub) ListChats(context.Context, string, *model.Position, int) ([]model.Chat, bool, error) {
return nil, false, nil
}
func (s messengerStoreStub) CreateMessage(context.Context, string, string, string, []string, string, time.Duration) (model.Message, bool, error) {
return s.message, s.messageReplay, s.messageErr
}
func (messengerStoreStub) ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error) {
return nil, false, nil
}
type objectStoreStub struct {
pingErr error
}
func (s objectStoreStub) Ping(context.Context) error { return s.pingErr }
type attachmentServiceStub struct {
uploaded model.Attachment
err error
}
func (s attachmentServiceStub) Upload(context.Context, attachment.Upload) (model.Attachment, error) {
return s.uploaded, s.err
}
func (s attachmentServiceStub) Metadata(context.Context, string, string) (model.Attachment, error) {
return s.uploaded, s.err
}
func (s attachmentServiceStub) Content(context.Context, string, string, string) (attachment.Content, error) {
return attachment.Content{
Attachment: s.uploaded,
Variant: model.Variant{ContentType: s.uploaded.ContentType, SizeBytes: s.uploaded.SizeBytes},
Body: io.NopCloser(strings.NewReader("content")),
}, s.err
}
type sessionStub struct {
pingErr error
userID string
userIDErr error
}
func (s sessionStub) Ping(context.Context) error { return s.pingErr }
func (sessionStub) Create(context.Context, string, time.Duration) (string, time.Time, error) {
return "token", time.Now().Add(time.Hour), nil
}
func (s sessionStub) UserID(context.Context, string) (string, error) { return s.userID, s.userIDErr }
func (sessionStub) Delete(context.Context, string) error { return nil }
type passwordsStub struct {
verified bool
err error
}
func (passwordsStub) Hash(string) (string, error) { return "hash", nil }
func (passwordsStub) DummyHash() string { return "hash" }
func (s passwordsStub) Verify(string, string) (bool, error) {
return s.verified, s.err
}
func (s *MessengerSuite) TestReadinessReturnsUnavailableForDependencyFailure() {
t := s.T()
tests := []struct {
name string
store messengerStoreStub
sessions sessionStub
objects objectStoreStub
}{
{name: "postgres", store: messengerStoreStub{pingErr: errDependency}},
{name: "valkey", sessions: sessionStub{pingErr: errDependency}},
{name: "s3", objects: objectStoreStub{pingErr: errDependency}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
server := s.server(tt.store, tt.sessions, passwordsStub{}, tt.objects, attachmentServiceStub{})
response := serveRequest(server, http.MethodGet, "/health/ready", "")
if response.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable)
}
})
}
}
func (s *MessengerSuite) TestBusinessRequestReturnsUnavailableForDependencyFailure() {
t := s.T()
tests := []struct {
name string
store messengerStoreStub
sessions sessionStub
}{
{name: "valkey", sessions: sessionStub{userIDErr: errDependency}},
{name: "postgres", store: messengerStoreStub{userByIDErr: errDependency}, sessions: sessionStub{userID: "user-id"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
server := s.newTestServer(tt.store, tt.sessions, passwordsStub{})
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
request.Header.Set("Authorization", "Bearer valid-token")
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
if response.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable)
}
})
}
}
func (s *MessengerSuite) TestAuthenticationChallenges() {
t := s.T()
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
bearer := serveRequest(server, http.MethodGet, "/api/v1/users/me", "")
if bearer.Code != http.StatusUnauthorized || bearer.Header().Get("WWW-Authenticate") != `Bearer realm="messenger"` {
t.Fatalf("business challenge = %d %q", bearer.Code, bearer.Header().Get("WWW-Authenticate"))
}
store := messengerStoreStub{credentials: model.UserCredentials{PasswordHash: "hash"}}
server = s.newTestServer(store, sessionStub{}, passwordsStub{verified: false})
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
request.SetBasicAuth("user", "wrong-password")
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
if response.Code != http.StatusUnauthorized || response.Header().Get("WWW-Authenticate") != `Basic realm="messenger", charset="UTF-8"` {
t.Fatalf("session challenge = %d %q", response.Code, response.Header().Get("WWW-Authenticate"))
}
}
func (s *MessengerSuite) TestAttachmentContentAuthenticatesBeforeVariantValidation() {
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
response := serveRequest(
server,
http.MethodGet,
"/api/v1/attachments/00000000-0000-0000-0000-000000000001/content?variant=invalid",
"",
)
s.Equal(http.StatusUnauthorized, response.Code)
s.Equal(`Bearer realm="messenger"`, response.Header().Get("WWW-Authenticate"))
}
func (s *MessengerSuite) TestSessionCreationRejectsChunkedBody() {
t := s.T()
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", strings.NewReader("{}"))
request.ContentLength = -1
request.SetBasicAuth("user", "password")
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d", response.Code, http.StatusBadRequest)
}
}
func (s *MessengerSuite) TestRegistrationRejectsWhitespacePassword() {
t := s.T()
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
response := serveRequest(server, http.MethodPost, "/api/v1/users", `{"username":"student","display_name":"Student","password":" "}`)
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d", response.Code, http.StatusBadRequest)
}
}
func (s *MessengerSuite) TestInstanceHeaderIsSetOnSuccessAndError() {
t := s.T()
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
for _, response := range []*httptest.ResponseRecorder{
serveRequest(server, http.MethodGet, "/health/live", ""),
serveRequest(server, http.MethodGet, "/api/v1/users/me", ""),
} {
if value := response.Header().Get("X-Instance-Id"); value != "test-instance" {
t.Fatalf("X-Instance-Id = %q, want test-instance", value)
}
}
}
func (s *MessengerSuite) TestMessageCreationValidatesIdempotencyKey() {
t := s.T()
store := messengerStoreStub{userByID: model.User{ID: "user-id"}}
server := s.newTestServer(store, sessionStub{userID: "user-id"}, passwordsStub{})
tests := []struct {
name string
key string
}{
{name: "missing"},
{name: "invalid", key: "invalid key"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "/api/v1/chats/00000000-0000-0000-0000-000000000001/messages", strings.NewReader(`{"text":"message"}`))
request.Header.Set("Authorization", "Bearer valid-token")
request.Header.Set("Content-Type", "application/json")
if tt.key != "" {
request.Header.Set("Idempotency-Key", tt.key)
}
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d", response.Code, http.StatusBadRequest)
}
})
}
}
func (s *MessengerSuite) TestMessageCreationValidatesFieldPresenceAndTypes() {
store := messengerStoreStub{userByID: model.User{ID: "user-id"}}
server := s.newTestServer(store, sessionStub{userID: "user-id"}, passwordsStub{})
attachmentID := "00000000-0000-0000-0000-000000000002"
invalidBodies := []string{
`{"attachment_ids":["` + attachmentID + `"]}`,
`{"text":null,"attachment_ids":["` + attachmentID + `"]}`,
`{"text":"x","attachment_ids":null}`,
`{"text":1}`,
`{"text":"x","attachment_ids":{}}`,
}
for _, body := range invalidBodies {
response := createMessageRequestResponse(server, body)
s.Equal(http.StatusBadRequest, response.Code, body)
}
validBodies := []string{
`{"text":"message"}`,
`{"text":"message","attachment_ids":[]}`,
`{"text":"","attachment_ids":["` + attachmentID + `"]}`,
}
for _, body := range validBodies {
response := createMessageRequestResponse(server, body)
s.Equal(http.StatusCreated, response.Code, body)
}
}
func createMessageRequestResponse(server *Server, body string) *httptest.ResponseRecorder {
request := httptest.NewRequest(
http.MethodPost,
"/api/v1/chats/00000000-0000-0000-0000-000000000001/messages",
strings.NewReader(body),
)
request.Header.Set("Authorization", "Bearer valid-token")
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Idempotency-Key", "message-key")
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
return response
}
func (s *MessengerSuite) TestMessageCreationReturnsConflictForReusedKeyWithDifferentBody() {
t := s.T()
store := messengerStoreStub{
userByID: model.User{ID: "user-id"},
messageErr: fmt.Errorf("create message: %w", model.ErrIdempotencyConflict),
}
server := s.newTestServer(store, sessionStub{userID: "user-id"}, passwordsStub{})
request := httptest.NewRequest(http.MethodPost, "/api/v1/chats/00000000-0000-0000-0000-000000000001/messages", strings.NewReader(`{"text":"different"}`))
request.Header.Set("Authorization", "Bearer valid-token")
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Idempotency-Key", "same-key")
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
if response.Code != http.StatusConflict {
t.Fatalf("status = %d, want %d", response.Code, http.StatusConflict)
}
}
func (s *MessengerSuite) TestAttachmentFilenameValidation() {
for _, filename := range []string{"", " ", "../photo.png", "dir\\photo.png", "photo\x00.png", "photo\n.png"} {
_, valid := attachmentFilename(map[string][]string{"filename": {filename}})
s.False(valid, filename)
}
filename, valid := attachmentFilename(map[string][]string{"filename": {"фото.png"}})
s.True(valid)
s.Equal("фото.png", filename)
}
func (s *MessengerSuite) TestUploadRejectsMalformedQuery() {
store := messengerStoreStub{userByID: model.User{ID: "user-id"}}
server := s.newTestServer(store, sessionStub{userID: "user-id"}, passwordsStub{})
request := httptest.NewRequest(
http.MethodPost,
"/api/v1/chats/00000000-0000-0000-0000-000000000002/attachments?filename=photo.png&junk=%GG",
strings.NewReader("image"),
)
request.Header.Set("Authorization", "Bearer valid-token")
request.Header.Set("Content-Type", "image/png")
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
s.Equal(http.StatusBadRequest, response.Code)
}
func (s *MessengerSuite) newTestServer(store messengerStoreStub, sessions SessionStore, passwords PasswordService) *Server {
return s.server(store, sessions, passwords, objectStoreStub{}, attachmentServiceStub{})
}
func (s *MessengerSuite) server(
store messengerStoreStub,
sessions SessionStore,
passwords PasswordService,
objects objectStoreStub,
attachments AttachmentService,
) *Server {
return NewServer(s.logger, Dependencies{
Users: store, Chats: store, Messages: store, Attachments: attachments,
Sessions: sessions, Passwords: passwords, Database: store, Objects: objects,
}, Config{
SessionTTL: time.Hour, IdempotencyTTL: 24 * time.Hour, RequestTTL: time.Second,
InstanceID: "test-instance", SwaggerPort: "8081",
})
}
func serveRequest(server *Server, method, path, body string) *httptest.ResponseRecorder {
request := httptest.NewRequest(method, path, strings.NewReader(body))
if body != "" {
request.Header.Set("Content-Type", "application/json")
}
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
return response
}