forked from mtusi2026/mtusi2026lab4
refactor: isolate attachment lifecycle
This commit is contained in:
@@ -0,0 +1,252 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"log/slog"
|
||||
"mime"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/sync/semaphore"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
ChatForUser(context.Context, string, string) (model.Chat, error)
|
||||
CreatePendingAttachment(context.Context, model.Attachment) (model.Attachment, error)
|
||||
MarkAttachmentReady(context.Context, string, string) (model.Attachment, error)
|
||||
DeletePendingAttachment(context.Context, string, string) error
|
||||
AttachmentByStorage(context.Context, string, string) (model.Attachment, error)
|
||||
AttachmentForUser(context.Context, string, string) (model.Attachment, 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
|
||||
}
|
||||
|
||||
type Upload struct {
|
||||
ChatID string
|
||||
OwnerID string
|
||||
Filename string
|
||||
ContentType string
|
||||
ContentLength int64
|
||||
Body io.Reader
|
||||
}
|
||||
|
||||
type Content struct {
|
||||
Attachment model.Attachment
|
||||
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.CleanupTimeout <= 0 {
|
||||
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()
|
||||
objectKey := "attachments/" + uuid.NewString() + "/original"
|
||||
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: objectKey, Status: model.AttachmentPending,
|
||||
})
|
||||
if err != nil {
|
||||
return model.Attachment{}, mapDependencyError(err)
|
||||
}
|
||||
if err := s.objects.Put(ctx, objectKey, contentType, data); err != nil {
|
||||
s.deletePending(pending.ID, objectKey)
|
||||
return model.Attachment{}, model.ErrUnavailable
|
||||
}
|
||||
attachment, err := s.repository.MarkAttachmentReady(ctx, pending.ID, objectKey)
|
||||
if err == nil {
|
||||
return attachment, nil
|
||||
}
|
||||
return s.resolveReadyOutcome(pending.ID, objectKey)
|
||||
}
|
||||
|
||||
func (s *Service) resolveReadyOutcome(attachmentID, objectKey string) (model.Attachment, error) {
|
||||
cleanupCtx, cancel := context.WithTimeout(context.Background(), s.config.CleanupTimeout)
|
||||
defer cancel()
|
||||
stored, err := s.repository.AttachmentByStorage(cleanupCtx, attachmentID, objectKey)
|
||||
if err == nil && stored.Status == model.AttachmentReady {
|
||||
return stored, nil
|
||||
}
|
||||
if err == nil && stored.Status == model.AttachmentPending {
|
||||
if deleteErr := s.objects.Delete(cleanupCtx, objectKey); deleteErr != nil {
|
||||
s.logger.Error("attachment compensation failed", "object_key", objectKey, "error", deleteErr)
|
||||
return model.Attachment{}, model.ErrUnavailable
|
||||
}
|
||||
if deleteErr := s.repository.DeletePendingAttachment(cleanupCtx, attachmentID, objectKey); deleteErr != nil {
|
||||
s.logger.Error("pending attachment cleanup failed", "attachment_id", attachmentID, "error", deleteErr)
|
||||
}
|
||||
return model.Attachment{}, model.ErrUnavailable
|
||||
}
|
||||
if errors.Is(err, model.ErrNotFound) {
|
||||
if deleteErr := s.objects.Delete(cleanupCtx, objectKey); deleteErr != nil {
|
||||
s.logger.Error("orphan attachment compensation failed", "object_key", objectKey, "error", deleteErr)
|
||||
}
|
||||
return model.Attachment{}, model.ErrUnavailable
|
||||
}
|
||||
s.logger.Error("attachment outcome is unknown", "attachment_id", attachmentID, "error", err)
|
||||
return model.Attachment{}, model.ErrUnavailable
|
||||
}
|
||||
|
||||
func (s *Service) deletePending(attachmentID, objectKey string) {
|
||||
cleanupCtx, cancel := context.WithTimeout(context.Background(), s.config.CleanupTimeout)
|
||||
defer cancel()
|
||||
if err := s.repository.DeletePendingAttachment(cleanupCtx, attachmentID, objectKey); 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 string) (Content, error) {
|
||||
attachment, err := s.Metadata(ctx, attachmentID, userID)
|
||||
if err != nil {
|
||||
return Content{}, err
|
||||
}
|
||||
body, err := s.objects.Get(ctx, attachment.ObjectKey)
|
||||
if err != nil {
|
||||
return Content{}, model.ErrUnavailable
|
||||
}
|
||||
return Content{Attachment: attachment, 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
|
||||
}
|
||||
pixels := int64(imageConfig.Width) * int64(imageConfig.Height)
|
||||
if imageConfig.Width < 1 || imageConfig.Height < 1 || pixels > s.config.MaxPixels {
|
||||
releaseBody()
|
||||
return nil, "", nil, model.ErrPayloadTooLarge
|
||||
}
|
||||
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,195 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"io"
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/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.AttachmentReady, result.Status)
|
||||
require.Equal(t, []string{"pending", "put", "ready"}, 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 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 TestUploadReturnsCommittedMetadataAfterAmbiguousReadyUpdate(t *testing.T) {
|
||||
data := pngFixture(t, 2, 2)
|
||||
repository := &repositoryStub{markErr: errors.New("connection lost"), lookupReady: true}
|
||||
objects := &objectStub{}
|
||||
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.AttachmentReady, result.Status)
|
||||
require.False(t, objects.deleted)
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
)
|
||||
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
|
||||
markErr error
|
||||
lookupReady bool
|
||||
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) MarkAttachmentReady(context.Context, string, string) (model.Attachment, error) {
|
||||
if s.markErr != nil {
|
||||
return model.Attachment{}, s.markErr
|
||||
}
|
||||
s.pending.Status = model.AttachmentReady
|
||||
s.record("ready")
|
||||
return s.pending, nil
|
||||
}
|
||||
|
||||
func (s *repositoryStub) DeletePendingAttachment(context.Context, string, string) error {
|
||||
s.pendingDeleted = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *repositoryStub) AttachmentByStorage(context.Context, string, string) (model.Attachment, error) {
|
||||
if s.lookupReady {
|
||||
s.pending.Status = model.AttachmentReady
|
||||
return s.pending, nil
|
||||
}
|
||||
return model.Attachment{}, model.ErrNotFound
|
||||
}
|
||||
|
||||
func (s *repositoryStub) AttachmentForUser(context.Context, string, string) (model.Attachment, error) {
|
||||
return s.pending, 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()
|
||||
}
|
||||
@@ -1,260 +0,0 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"golang.org/x/sync/semaphore"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/objectstore"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/postgres"
|
||||
)
|
||||
|
||||
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()
|
||||
}
|
||||
filename, valid := attachmentFilename(r.URL.Query())
|
||||
if !valid {
|
||||
return invalidRequest()
|
||||
}
|
||||
if _, err := s.messengerStore.ChatForUser(r.Context(), chatID, user.ID); errors.Is(err, postgres.ErrNotFound) {
|
||||
return notFound()
|
||||
} else if err != nil {
|
||||
result = "dependency_error"
|
||||
return unavailable()
|
||||
}
|
||||
data, contentType, readErr := readImage(w, r, s.maxUploadBytes, s.maxImagePixels, s.decodeMemory)
|
||||
if readErr != nil {
|
||||
return readErr
|
||||
}
|
||||
|
||||
attachmentID, err := newID()
|
||||
if err != nil {
|
||||
result = "dependency_error"
|
||||
return internalError()
|
||||
}
|
||||
objectID, err := newID()
|
||||
if err != nil {
|
||||
result = "dependency_error"
|
||||
return internalError()
|
||||
}
|
||||
objectKey := "attachments/" + objectID + "/original"
|
||||
if err := s.objects.Put(r.Context(), objectKey, contentType, data); err != nil {
|
||||
result = "dependency_error"
|
||||
return unavailable()
|
||||
}
|
||||
digest := sha256.Sum256(data)
|
||||
attachment, err := s.messengerStore.CreateAttachment(r.Context(), model.Attachment{
|
||||
ID: attachmentID, ChatID: chatID, OwnerID: user.ID, Filename: filename,
|
||||
ContentType: contentType, SizeBytes: int64(len(data)), SHA256: hex.EncodeToString(digest[:]), ObjectKey: objectKey,
|
||||
})
|
||||
if err != nil {
|
||||
result = "dependency_error"
|
||||
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), s.requestTTL)
|
||||
defer cancel()
|
||||
stored, lookupErr := s.messengerStore.AttachmentByStorage(cleanupCtx, attachmentID, objectKey)
|
||||
if lookupErr == nil {
|
||||
result = "success"
|
||||
s.metrics.attachmentBytes.Add(float64(len(data)))
|
||||
writeJSON(w, http.StatusCreated, stored)
|
||||
return nil
|
||||
}
|
||||
if !errors.Is(lookupErr, postgres.ErrNotFound) {
|
||||
s.logger.Error("attachment outcome is unknown", "attachment_id", attachmentID, "error", lookupErr)
|
||||
return unavailable()
|
||||
}
|
||||
if cleanupErr := s.objects.Delete(cleanupCtx, objectKey); cleanupErr != nil {
|
||||
s.logger.Error("attachment compensation failed", "object_key", objectKey, "error", cleanupErr)
|
||||
}
|
||||
if errors.Is(err, postgres.ErrNotFound) {
|
||||
return notFound()
|
||||
}
|
||||
return unavailable()
|
||||
}
|
||||
result = "success"
|
||||
s.metrics.attachmentBytes.Add(float64(len(data)))
|
||||
writeJSON(w, http.StatusCreated, attachment)
|
||||
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 readImage(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
maxBytes int64,
|
||||
maxPixels int64,
|
||||
decodeMemory *semaphore.Weighted,
|
||||
) ([]byte, string, *apiError) {
|
||||
mediaType, parameters, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil || len(parameters) != 0 || mediaType != "image/png" && mediaType != "image/jpeg" {
|
||||
return nil, "", &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "unsupported image type"}
|
||||
}
|
||||
if r.ContentLength > maxBytes {
|
||||
return nil, "", &apiError{http.StatusRequestEntityTooLarge, errorCodePayloadTooLarge, "image is too large"}
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
|
||||
data, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
var tooLarge *http.MaxBytesError
|
||||
if errors.As(err, &tooLarge) {
|
||||
return nil, "", &apiError{http.StatusRequestEntityTooLarge, errorCodePayloadTooLarge, "image is too large"}
|
||||
}
|
||||
return nil, "", invalidRequest()
|
||||
}
|
||||
if len(data) == 0 {
|
||||
return nil, "", &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "invalid image"}
|
||||
}
|
||||
detected := http.DetectContentType(data)
|
||||
if detected != mediaType {
|
||||
return nil, "", &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "content type does not match image"}
|
||||
}
|
||||
imageConfig, format, err := image.DecodeConfig(bytes.NewReader(data))
|
||||
if err != nil || imageContentType(format) != mediaType {
|
||||
return nil, "", &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "invalid image"}
|
||||
}
|
||||
pixels := int64(imageConfig.Width) * int64(imageConfig.Height)
|
||||
if imageConfig.Width < 1 || imageConfig.Height < 1 || pixels > maxPixels {
|
||||
return nil, "", &apiError{http.StatusRequestEntityTooLarge, errorCodePayloadTooLarge, "image dimensions are too large"}
|
||||
}
|
||||
decodeBytes := pixels*8 + int64(len(data))
|
||||
if !decodeMemory.TryAcquire(decodeBytes) {
|
||||
w.Header().Set("Retry-After", "1")
|
||||
return nil, "", &apiError{http.StatusTooManyRequests, errorCodeRateLimited, "image capacity is temporarily exhausted"}
|
||||
}
|
||||
defer decodeMemory.Release(decodeBytes)
|
||||
if _, format, err := image.Decode(bytes.NewReader(data)); err != nil || imageContentType(format) != mediaType {
|
||||
return nil, "", &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "invalid image"}
|
||||
}
|
||||
return data, mediaType, nil
|
||||
}
|
||||
|
||||
func imageContentType(format string) string {
|
||||
switch format {
|
||||
case "png":
|
||||
return "image/png"
|
||||
case "jpeg":
|
||||
return "image/jpeg"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
attachment, apiErr := s.attachmentForUser(r, user.ID)
|
||||
if apiErr != nil {
|
||||
return apiErr
|
||||
}
|
||||
writeJSON(w, http.StatusOK, attachment)
|
||||
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
|
||||
}
|
||||
if !originalVariant(r.URL.Query()) {
|
||||
return invalidRequest()
|
||||
}
|
||||
attachment, apiErr := s.attachmentForUser(r, user.ID)
|
||||
if apiErr != nil {
|
||||
return apiErr
|
||||
}
|
||||
content, err := s.objects.Get(r.Context(), attachment.ObjectKey)
|
||||
if errors.Is(err, objectstore.ErrNotFound) {
|
||||
return unavailable()
|
||||
}
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
defer func() { _ = content.Close() }()
|
||||
w.Header().Set("Content-Type", attachment.ContentType)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(attachment.SizeBytes, 10))
|
||||
w.Header().Set("Content-Disposition", mime.FormatMediaType("inline", map[string]string{"filename": attachment.Filename}))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if _, err := io.Copy(w, content); err != nil {
|
||||
s.logger.Warn("attachment download interrupted", "attachment_id", attachment.ID, "error", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func originalVariant(query url.Values) bool {
|
||||
if len(query) == 0 {
|
||||
return true
|
||||
}
|
||||
return len(query) == 1 && len(query["variant"]) == 1 && query["variant"][0] == "original"
|
||||
}
|
||||
|
||||
func (s *Server) attachmentForUser(r *http.Request, userID string) (Attachment, *apiError) {
|
||||
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
|
||||
attachmentID, valid := canonicalID(parts[3])
|
||||
if !valid {
|
||||
return Attachment{}, invalidRequest()
|
||||
}
|
||||
attachment, err := s.messengerStore.AttachmentForUser(r.Context(), attachmentID, userID)
|
||||
if errors.Is(err, postgres.ErrNotFound) {
|
||||
return Attachment{}, notFound()
|
||||
}
|
||||
if err != nil {
|
||||
return Attachment{}, unavailable()
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/messenger/attachment"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/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,
|
||||
})
|
||||
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.StatusCreated, 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)
|
||||
if err != nil || !originalVariant(query) {
|
||||
return invalidRequest()
|
||||
}
|
||||
attachmentID, apiErr := attachmentIDFromRequest(r)
|
||||
if apiErr != nil {
|
||||
return apiErr
|
||||
}
|
||||
content, err := s.attachments.Content(r.Context(), attachmentID, user.ID)
|
||||
if err != nil {
|
||||
return attachmentError(err)
|
||||
}
|
||||
defer func() { _ = content.Body.Close() }()
|
||||
w.Header().Set("Content-Type", content.Attachment.ContentType)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(content.Attachment.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 originalVariant(query url.Values) bool {
|
||||
if len(query) == 0 {
|
||||
return true
|
||||
}
|
||||
return len(query) == 1 && len(query["variant"]) == 1 && query["variant"][0] == "original"
|
||||
}
|
||||
|
||||
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"}
|
||||
default:
|
||||
return unavailable()
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package messenger
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
@@ -7,8 +7,6 @@ import (
|
||||
"strings"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/postgres"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/session"
|
||||
)
|
||||
|
||||
func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
@@ -23,8 +21,8 @@ func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError
|
||||
if !ok {
|
||||
return unauthorized()
|
||||
}
|
||||
credentials, err := s.messengerStore.UserByUsername(r.Context(), username)
|
||||
if errors.Is(err, postgres.ErrNotFound) {
|
||||
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()
|
||||
}
|
||||
@@ -69,7 +67,7 @@ func (s *Server) revokeSession(w http.ResponseWriter, r *http.Request) *apiError
|
||||
if authErr != nil {
|
||||
return authErr
|
||||
}
|
||||
if err := s.sessions.Delete(r.Context(), token); errors.Is(err, session.ErrNotFound) {
|
||||
if err := s.sessions.Delete(r.Context(), token); errors.Is(err, model.ErrSessionNotFound) {
|
||||
return unauthorized()
|
||||
} else if err != nil {
|
||||
return unavailable()
|
||||
@@ -88,14 +86,14 @@ func (s *Server) authenticate(r *http.Request) (User, string, *apiError) {
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
userID, err := s.sessions.UserID(r.Context(), token)
|
||||
if errors.Is(err, session.ErrNotFound) || errors.Is(err, session.ErrInvalidToken) {
|
||||
if errors.Is(err, model.ErrSessionNotFound) || errors.Is(err, model.ErrInvalidToken) {
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
if err != nil {
|
||||
return User{}, "", unavailable()
|
||||
}
|
||||
user, err := s.messengerStore.UserByID(r.Context(), userID)
|
||||
if errors.Is(err, postgres.ErrNotFound) {
|
||||
user, err := s.userRepository.UserByID(r.Context(), userID)
|
||||
if errors.Is(err, model.ErrNotFound) {
|
||||
_ = s.sessions.Delete(r.Context(), token)
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package messenger
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
@@ -1,4 +1,4 @@
|
||||
package messenger
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"unicode/utf8"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/postgres"
|
||||
)
|
||||
|
||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
@@ -32,7 +31,7 @@ func (s *Server) readiness(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
if err := s.messengerStore.Ping(ctx); err != nil {
|
||||
if err := s.database.Ping(ctx); err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
if err := s.sessions.Ping(ctx); err != nil {
|
||||
@@ -64,8 +63,8 @@ func (s *Server) users(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if err != nil {
|
||||
return internalError()
|
||||
}
|
||||
user, err := s.messengerStore.CreateUser(r.Context(), input.Username, input.DisplayName, passwordHash)
|
||||
if errors.Is(err, postgres.ErrConflict) {
|
||||
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 {
|
||||
@@ -128,8 +127,8 @@ func (s *Server) chats(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if _, included := members[user.ID]; !included {
|
||||
return invalidRequest()
|
||||
}
|
||||
chat, err := s.messengerStore.CreateChat(r.Context(), input.Title, input.MemberIDs, user.ID)
|
||||
if errors.Is(err, postgres.ErrInvalidMembers) {
|
||||
chat, err := s.chatRepository.CreateChat(r.Context(), input.Title, input.MemberIDs, user.ID)
|
||||
if errors.Is(err, model.ErrInvalidMembers) {
|
||||
return invalidRequest()
|
||||
}
|
||||
if err != nil {
|
||||
@@ -144,8 +143,8 @@ func (s *Server) listChats(w http.ResponseWriter, r *http.Request, user User) *a
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
items, hasNext, listErr := s.messengerStore.ListChats(r.Context(), user.ID, cursorPosition(cursor), limit)
|
||||
if errors.Is(listErr, postgres.ErrInvalidCursor) {
|
||||
items, hasNext, listErr := s.chatRepository.ListChats(r.Context(), user.ID, cursorPosition(cursor), limit)
|
||||
if errors.Is(listErr, model.ErrInvalidCursor) {
|
||||
return invalidRequest()
|
||||
}
|
||||
if listErr != nil {
|
||||
@@ -179,8 +178,8 @@ func (s *Server) chat(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if !valid {
|
||||
return invalidRequest()
|
||||
}
|
||||
chat, err := s.messengerStore.ChatForUser(r.Context(), chatID, user.ID)
|
||||
if errors.Is(err, postgres.ErrNotFound) {
|
||||
chat, err := s.chatRepository.ChatForUser(r.Context(), chatID, user.ID)
|
||||
if errors.Is(err, model.ErrNotFound) {
|
||||
return notFound()
|
||||
}
|
||||
if err != nil {
|
||||
@@ -219,13 +218,13 @@ func (s *Server) messages(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if !validMessage(input.Text, input.AttachmentIDs) || !canonicalAttachmentIDs(input.AttachmentIDs) {
|
||||
return invalidRequest()
|
||||
}
|
||||
message, replay, err := s.messengerStore.CreateMessage(
|
||||
message, replay, err := s.messageRepository.CreateMessage(
|
||||
r.Context(), chatID, user.ID, input.Text, input.AttachmentIDs, key, s.idempotencyTTL,
|
||||
)
|
||||
if errors.Is(err, postgres.ErrNotFound) {
|
||||
if errors.Is(err, model.ErrNotFound) {
|
||||
return notFound()
|
||||
}
|
||||
if errors.Is(err, postgres.ErrIdempotencyConflict) {
|
||||
if errors.Is(err, model.ErrIdempotencyConflict) {
|
||||
return &apiError{http.StatusConflict, errorCodeConflict, "idempotency key conflicts with previous request"}
|
||||
}
|
||||
if err != nil {
|
||||
@@ -269,11 +268,11 @@ func (s *Server) listMessages(w http.ResponseWriter, r *http.Request, user User,
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
items, hasNext, listErr := s.messengerStore.ListMessages(r.Context(), chatID, user.ID, cursorPosition(cursor), limit)
|
||||
if errors.Is(listErr, postgres.ErrNotFound) {
|
||||
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, postgres.ErrInvalidCursor) {
|
||||
if errors.Is(listErr, model.ErrInvalidCursor) {
|
||||
return invalidRequest()
|
||||
}
|
||||
if listErr != nil {
|
||||
+19
-14
@@ -1,37 +1,42 @@
|
||||
package messenger
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/messenger/attachment"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
|
||||
)
|
||||
|
||||
type MessengerStore interface {
|
||||
Ping(context.Context) error
|
||||
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)
|
||||
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)
|
||||
CreateAttachment(context.Context, model.Attachment) (model.Attachment, error)
|
||||
AttachmentByStorage(context.Context, string, string) (model.Attachment, error)
|
||||
AttachmentForUser(context.Context, string, string) (model.Attachment, error)
|
||||
}
|
||||
|
||||
type ObjectStore interface {
|
||||
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) (attachment.Content, error)
|
||||
}
|
||||
|
||||
type HealthChecker interface {
|
||||
Ping(context.Context) error
|
||||
Put(context.Context, string, string, []byte) error
|
||||
Get(context.Context, string) (io.ReadCloser, error)
|
||||
Delete(context.Context, string) error
|
||||
}
|
||||
|
||||
type SessionStore interface {
|
||||
Ping(context.Context) error
|
||||
HealthChecker
|
||||
Create(context.Context, string, time.Duration) (string, time.Time, error)
|
||||
UserID(context.Context, string) (string, error)
|
||||
Delete(context.Context, string) error
|
||||
@@ -1,4 +1,4 @@
|
||||
package messenger
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
@@ -1,4 +1,4 @@
|
||||
package messenger
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
|
||||
@@ -1,4 +1,4 @@
|
||||
package messenger
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@@ -1,4 +1,4 @@
|
||||
package messenger
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
@@ -1,4 +1,4 @@
|
||||
package messenger
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -6,26 +6,44 @@ import (
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sync/semaphore"
|
||||
)
|
||||
|
||||
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 {
|
||||
messengerStore MessengerStore
|
||||
sessions SessionStore
|
||||
passwords PasswordService
|
||||
objects ObjectStore
|
||||
sessionTTL time.Duration
|
||||
idempotencyTTL time.Duration
|
||||
requestTTL time.Duration
|
||||
instanceID string
|
||||
logger *slog.Logger
|
||||
swaggerPort string
|
||||
maxUploadBytes int64
|
||||
maxImagePixels int64
|
||||
decodeMemory *semaphore.Weighted
|
||||
metrics *metrics
|
||||
ready atomic.Bool
|
||||
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 {
|
||||
@@ -40,25 +58,16 @@ func (w *statusWriter) WriteHeader(status int) {
|
||||
|
||||
func NewServer(
|
||||
logger *slog.Logger,
|
||||
messages MessengerStore,
|
||||
sessions SessionStore,
|
||||
passwords PasswordService,
|
||||
objects ObjectStore,
|
||||
sessionTTL time.Duration,
|
||||
idempotencyTTL time.Duration,
|
||||
requestTTL time.Duration,
|
||||
instanceID string,
|
||||
swaggerPort string,
|
||||
maxUploadBytes int64,
|
||||
maxImagePixels int64,
|
||||
decodeMemoryBytes int64,
|
||||
dependencies Dependencies,
|
||||
config Config,
|
||||
) *Server {
|
||||
s := &Server{
|
||||
messengerStore: messages, sessions: sessions, passwords: passwords, objects: objects,
|
||||
sessionTTL: sessionTTL, idempotencyTTL: idempotencyTTL, requestTTL: requestTTL,
|
||||
instanceID: instanceID, logger: logger, swaggerPort: swaggerPort,
|
||||
maxUploadBytes: maxUploadBytes, maxImagePixels: maxImagePixels,
|
||||
decodeMemory: semaphore.NewWeighted(decodeMemoryBytes), metrics: newMetrics(),
|
||||
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
|
||||
@@ -1,13 +1,9 @@
|
||||
package messenger
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
@@ -17,10 +13,9 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
"golang.org/x/sync/semaphore"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/messenger/attachment"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/postgres"
|
||||
)
|
||||
|
||||
var errDependency = errors.New("dependency unavailable")
|
||||
@@ -39,19 +34,14 @@ func (s *MessengerSuite) SetupTest() {
|
||||
}
|
||||
|
||||
type messengerStoreStub struct {
|
||||
pingErr error
|
||||
userByID model.User
|
||||
userByIDErr error
|
||||
credentials model.UserCredentials
|
||||
credentialsErr error
|
||||
message model.Message
|
||||
messageReplay bool
|
||||
messageErr error
|
||||
attachment model.Attachment
|
||||
attachmentErr error
|
||||
storedAttachment model.Attachment
|
||||
storedAttachmentExists bool
|
||||
storedAttachmentErr error
|
||||
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 }
|
||||
@@ -79,50 +69,26 @@ func (s messengerStoreStub) CreateMessage(context.Context, string, string, strin
|
||||
func (messengerStoreStub) ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error) {
|
||||
return nil, false, nil
|
||||
}
|
||||
func (s messengerStoreStub) CreateAttachment(context.Context, model.Attachment) (model.Attachment, error) {
|
||||
return s.attachment, s.attachmentErr
|
||||
}
|
||||
func (s messengerStoreStub) AttachmentByStorage(context.Context, string, string) (model.Attachment, error) {
|
||||
if s.storedAttachmentErr != nil {
|
||||
return model.Attachment{}, s.storedAttachmentErr
|
||||
}
|
||||
if !s.storedAttachmentExists {
|
||||
return model.Attachment{}, postgres.ErrNotFound
|
||||
}
|
||||
return s.storedAttachment, nil
|
||||
}
|
||||
func (s messengerStoreStub) AttachmentForUser(context.Context, string, string) (model.Attachment, error) {
|
||||
return s.attachment, s.attachmentErr
|
||||
}
|
||||
|
||||
type objectStoreStub struct {
|
||||
pingErr error
|
||||
putErr error
|
||||
getData []byte
|
||||
getErr error
|
||||
deleteErr error
|
||||
putKey *string
|
||||
deletedKey *string
|
||||
pingErr error
|
||||
}
|
||||
|
||||
func (s objectStoreStub) Ping(context.Context) error { return s.pingErr }
|
||||
func (s objectStoreStub) Put(_ context.Context, key string, _ string, _ []byte) error {
|
||||
if s.putKey != nil {
|
||||
*s.putKey = key
|
||||
}
|
||||
return s.putErr
|
||||
|
||||
type attachmentServiceStub struct {
|
||||
uploaded model.Attachment
|
||||
err error
|
||||
}
|
||||
func (s objectStoreStub) Get(context.Context, string) (io.ReadCloser, error) {
|
||||
if s.getErr != nil {
|
||||
return nil, s.getErr
|
||||
}
|
||||
return io.NopCloser(bytes.NewReader(s.getData)), nil
|
||||
|
||||
func (s attachmentServiceStub) Upload(context.Context, attachment.Upload) (model.Attachment, error) {
|
||||
return s.uploaded, s.err
|
||||
}
|
||||
func (s objectStoreStub) Delete(_ context.Context, key string) error {
|
||||
if s.deletedKey != nil {
|
||||
*s.deletedKey = key
|
||||
}
|
||||
return s.deleteErr
|
||||
func (s attachmentServiceStub) Metadata(context.Context, string, string) (model.Attachment, error) {
|
||||
return s.uploaded, s.err
|
||||
}
|
||||
func (s attachmentServiceStub) Content(context.Context, string, string) (attachment.Content, error) {
|
||||
return attachment.Content{Attachment: s.uploaded, Body: io.NopCloser(strings.NewReader("content"))}, s.err
|
||||
}
|
||||
|
||||
type sessionStub struct {
|
||||
@@ -164,10 +130,7 @@ func (s *MessengerSuite) TestReadinessReturnsUnavailableForDependencyFailure() {
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
server := NewServer(
|
||||
s.logger, tt.store, tt.sessions, passwordsStub{}, tt.objects, time.Hour, 24*time.Hour,
|
||||
time.Second, "test-instance", "8081", 10*1024*1024, 40_000_000, 384*1024*1024,
|
||||
)
|
||||
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)
|
||||
@@ -300,7 +263,7 @@ func (s *MessengerSuite) TestMessageCreationReturnsConflictForReusedKeyWithDiffe
|
||||
t := s.T()
|
||||
store := messengerStoreStub{
|
||||
userByID: model.User{ID: "user-id"},
|
||||
messageErr: fmt.Errorf("create message: %w", postgres.ErrIdempotencyConflict),
|
||||
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"}`))
|
||||
@@ -314,52 +277,6 @@ func (s *MessengerSuite) TestMessageCreationReturnsConflictForReusedKeyWithDiffe
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestImageValidation() {
|
||||
data := testPNG(s.T(), 2, 2)
|
||||
tests := []struct {
|
||||
name string
|
||||
contentType string
|
||||
data []byte
|
||||
maxBytes int64
|
||||
maxPixels int64
|
||||
wantStatus int
|
||||
}{
|
||||
{name: "valid", contentType: "image/png", data: data, maxBytes: 1024, maxPixels: 4},
|
||||
{name: "spoofed MIME", contentType: "image/jpeg", data: data, maxBytes: 1024, maxPixels: 4, wantStatus: http.StatusUnsupportedMediaType},
|
||||
{name: "too many pixels", contentType: "image/png", data: data, maxBytes: 1024, maxPixels: 3, wantStatus: http.StatusRequestEntityTooLarge},
|
||||
{name: "too many bytes", contentType: "image/png", data: data, maxBytes: int64(len(data) - 1), maxPixels: 4, wantStatus: http.StatusRequestEntityTooLarge},
|
||||
{name: "damaged", contentType: "image/png", data: data[:16], maxBytes: 1024, maxPixels: 4, wantStatus: http.StatusUnsupportedMediaType},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
s.Run(tt.name, func() {
|
||||
request := httptest.NewRequest(http.MethodPost, "/upload", bytes.NewReader(tt.data))
|
||||
request.Header.Set("Content-Type", tt.contentType)
|
||||
response := httptest.NewRecorder()
|
||||
actual, _, apiErr := readImage(
|
||||
response, request, tt.maxBytes, tt.maxPixels, semaphore.NewWeighted(384*1024*1024),
|
||||
)
|
||||
if tt.wantStatus == 0 {
|
||||
s.Require().Nil(apiErr)
|
||||
s.Equal(tt.data, actual)
|
||||
return
|
||||
}
|
||||
s.Require().NotNil(apiErr)
|
||||
s.Equal(tt.wantStatus, apiErr.status)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestImageValidationLimitsConcurrentDecodeMemory() {
|
||||
data := testPNG(s.T(), 2, 2)
|
||||
request := httptest.NewRequest(http.MethodPost, "/upload", bytes.NewReader(data))
|
||||
request.Header.Set("Content-Type", "image/png")
|
||||
response := httptest.NewRecorder()
|
||||
_, _, apiErr := readImage(response, request, 1024, 4, semaphore.NewWeighted(1))
|
||||
s.Require().NotNil(apiErr)
|
||||
s.Equal(http.StatusTooManyRequests, apiErr.status)
|
||||
s.Equal("1", response.Header().Get("Retry-After"))
|
||||
}
|
||||
|
||||
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}})
|
||||
@@ -370,79 +287,39 @@ func (s *MessengerSuite) TestAttachmentFilenameValidation() {
|
||||
s.Equal("фото.png", filename)
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestUploadCompensatesObjectWhenMetadataWriteFails() {
|
||||
var putKey, deletedKey string
|
||||
store := messengerStoreStub{
|
||||
userByID: model.User{ID: "00000000-0000-0000-0000-000000000001"},
|
||||
attachmentErr: errDependency,
|
||||
}
|
||||
objects := objectStoreStub{putKey: &putKey, deletedKey: &deletedKey}
|
||||
server := NewServer(
|
||||
s.logger, store, sessionStub{userID: store.userByID.ID}, passwordsStub{}, objects,
|
||||
time.Hour, 24*time.Hour, time.Second, "test-instance", "8081", 10*1024*1024, 40_000_000, 384*1024*1024,
|
||||
)
|
||||
data := testPNG(s.T(), 2, 2)
|
||||
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",
|
||||
bytes.NewReader(data),
|
||||
"/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.StatusServiceUnavailable, response.Code)
|
||||
s.NotEmpty(putKey)
|
||||
s.Equal(putKey, deletedKey)
|
||||
s.Equal(http.StatusBadRequest, response.Code)
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestUploadKeepsObjectWhenMetadataCommitSucceeded() {
|
||||
var deletedKey string
|
||||
stored := model.Attachment{
|
||||
ID: "00000000-0000-0000-0000-000000000003",
|
||||
ChatID: "00000000-0000-0000-0000-000000000002",
|
||||
OwnerID: "00000000-0000-0000-0000-000000000001",
|
||||
Filename: "photo.png", ContentType: "image/png", SizeBytes: 1, SHA256: strings.Repeat("0", 64),
|
||||
Status: "ready", Variants: []model.Variant{}, CreatedAt: time.Now(), UpdatedAt: time.Now(),
|
||||
}
|
||||
store := messengerStoreStub{
|
||||
userByID: model.User{ID: stored.OwnerID}, attachmentErr: errDependency,
|
||||
storedAttachment: stored, storedAttachmentExists: true,
|
||||
}
|
||||
server := NewServer(
|
||||
s.logger, store, sessionStub{userID: stored.OwnerID}, passwordsStub{}, objectStoreStub{deletedKey: &deletedKey},
|
||||
time.Hour, 24*time.Hour, time.Second, "test-instance", "8081", 10*1024*1024, 40_000_000, 384*1024*1024,
|
||||
)
|
||||
data := testPNG(s.T(), 2, 2)
|
||||
request := httptest.NewRequest(
|
||||
http.MethodPost,
|
||||
"/api/v1/chats/00000000-0000-0000-0000-000000000002/attachments?filename=photo.png",
|
||||
bytes.NewReader(data),
|
||||
)
|
||||
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.StatusCreated, response.Code)
|
||||
s.Empty(deletedKey)
|
||||
func (s *MessengerSuite) newTestServer(store messengerStoreStub, sessions SessionStore, passwords PasswordService) *Server {
|
||||
return s.server(store, sessions, passwords, objectStoreStub{}, attachmentServiceStub{})
|
||||
}
|
||||
|
||||
func testPNG(t *testing.T, width, height int) []byte {
|
||||
t.Helper()
|
||||
var data bytes.Buffer
|
||||
imageData := image.NewRGBA(image.Rect(0, 0, width, height))
|
||||
imageData.Set(0, 0, color.White)
|
||||
if err := png.Encode(&data, imageData); err != nil {
|
||||
t.Fatalf("encode PNG: %v", err)
|
||||
}
|
||||
return data.Bytes()
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) newTestServer(messages MessengerStore, sessions SessionStore, passwords PasswordService) *Server {
|
||||
return NewServer(
|
||||
s.logger, messages, sessions, passwords, objectStoreStub{}, time.Hour, 24*time.Hour,
|
||||
time.Second, "test-instance", "8081", 10*1024*1024, 40_000_000, 384*1024*1024,
|
||||
)
|
||||
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 {
|
||||
Reference in New Issue
Block a user