forked from mtusi2026/mtusi2026lab6
feat: add bounded observability and verified SLO incident alerts
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
package media
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ObjectInfo describes an immutable object without its contents.
|
||||
type ObjectInfo struct {
|
||||
// Key is the server-assigned private coordinate.
|
||||
Key string
|
||||
// ModifiedAt determines eligibility for a grace-protected scan.
|
||||
ModifiedAt time.Time
|
||||
}
|
||||
|
||||
// OrphanMetadata checks all reservations, not only published files.
|
||||
type OrphanMetadata interface {
|
||||
// HasObject reports whether any state references the key.
|
||||
HasObject(context.Context, string) (bool, error)
|
||||
}
|
||||
|
||||
// OrphanObjects supports resumable listing and single-object cleanup.
|
||||
type OrphanObjects interface {
|
||||
// List returns a bounded lexicographic page after the given key.
|
||||
List(context.Context, string) ([]ObjectInfo, error)
|
||||
// Remove deletes an explicitly identified unreferenced key.
|
||||
Remove(context.Context, string) error
|
||||
}
|
||||
|
||||
// OrphanResult reports one page of a safe S3-to-database reconciliation.
|
||||
type OrphanResult struct {
|
||||
// Scanned counts objects examined.
|
||||
Scanned int `json:"scanned"`
|
||||
// Orphans counts old objects with no metadata reservation.
|
||||
Orphans int `json:"orphans"`
|
||||
// Removed counts applied removals.
|
||||
Removed int `json:"removed"`
|
||||
// Next resumes the lexicographic scan.
|
||||
Next string `json:"next"`
|
||||
}
|
||||
|
||||
// ReconcileOrphans protects fresh and referenced objects, and defaults to dry-run at the CLI.
|
||||
func ReconcileOrphans(ctx context.Context, metadata OrphanMetadata, objects OrphanObjects, after string, grace time.Duration, apply bool) (OrphanResult, error) {
|
||||
var result OrphanResult
|
||||
if grace < time.Hour {
|
||||
return result, fmt.Errorf("reconciliation grace must be at least one hour")
|
||||
}
|
||||
entries, err := objects.List(ctx, after)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
cutoff := time.Now().UTC().Add(-grace)
|
||||
for _, entry := range entries {
|
||||
result.Scanned++
|
||||
result.Next = entry.Key
|
||||
if entry.ModifiedAt.IsZero() || entry.ModifiedAt.After(cutoff) {
|
||||
continue
|
||||
}
|
||||
referenced, err := metadata.HasObject(ctx, entry.Key)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
if referenced {
|
||||
continue
|
||||
}
|
||||
result.Orphans++
|
||||
if apply {
|
||||
if err := objects.Remove(ctx, entry.Key); err != nil {
|
||||
return result, err
|
||||
}
|
||||
result.Removed++
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package media
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
)
|
||||
|
||||
// Inventory supports bounded, resumable scans and guarded state transitions.
|
||||
type Inventory interface {
|
||||
// Scan returns the next at most limit metadata records by ID.
|
||||
Scan(context.Context, uuid.UUID, int) ([]dto.Attachment, error)
|
||||
// Reclaim deletes only an old unfinished unreferenced reservation after claiming it.
|
||||
Reclaim(context.Context, uuid.UUID, time.Time, bool) (bool, error)
|
||||
// MarkMissing preserves metadata and references when an original disappears.
|
||||
MarkMissing(context.Context, uuid.UUID, bool) error
|
||||
}
|
||||
|
||||
// ObjectInventory exposes bounded inspection and explicit removal.
|
||||
type ObjectInventory interface {
|
||||
// Exists distinguishes absence from infrastructure failure.
|
||||
Exists(context.Context, string) (bool, error)
|
||||
// Remove deletes a single immutable object key.
|
||||
Remove(context.Context, string) error
|
||||
}
|
||||
|
||||
// ReconcileResult records observations and the continuation cursor without file contents.
|
||||
type ReconcileResult struct {
|
||||
// Scanned counts inspected metadata rows.
|
||||
Scanned int `json:"scanned"`
|
||||
// Missing counts published originals absent from S3.
|
||||
Missing int `json:"missing"`
|
||||
// Abandoned counts old incomplete reservations eligible for cleanup.
|
||||
Abandoned int `json:"abandoned"`
|
||||
// Changed counts successful applied repairs, zero for dry run.
|
||||
Changed int `json:"changed"`
|
||||
// Next continues scanning without retaining the full database in RAM.
|
||||
Next uuid.UUID `json:"next"`
|
||||
}
|
||||
|
||||
// Reconcile inspects at most 1000 records and protects active uploads with a one-hour minimum grace.
|
||||
func Reconcile(ctx context.Context, metadata Inventory, objects ObjectInventory, after uuid.UUID, grace time.Duration, apply bool) (ReconcileResult, error) {
|
||||
var result ReconcileResult
|
||||
if grace < time.Hour {
|
||||
return result, fmt.Errorf("reconciliation grace must be at least one hour")
|
||||
}
|
||||
records, err := metadata.Scan(ctx, after, 1000)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
cutoff := time.Now().UTC().Add(-grace)
|
||||
for _, a := range records {
|
||||
result.Scanned++
|
||||
result.Next = a.ID
|
||||
if a.Status == "queued" || a.Status == "processing" || a.Status == "failed" || a.CreatedAt.After(cutoff) {
|
||||
continue
|
||||
}
|
||||
exists, err := objects.Exists(ctx, a.ObjectKey)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
switch {
|
||||
case a.Status == "uploading" || a.Status == "deleting":
|
||||
result.Abandoned++
|
||||
if !apply {
|
||||
continue
|
||||
}
|
||||
claimed, err := metadata.Reclaim(ctx, a.ID, cutoff, false)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
if !claimed {
|
||||
continue
|
||||
}
|
||||
if err := objects.Remove(ctx, a.ObjectKey); err != nil {
|
||||
return result, err
|
||||
}
|
||||
if _, err := metadata.Reclaim(ctx, a.ID, cutoff, true); err != nil {
|
||||
return result, err
|
||||
}
|
||||
result.Changed++
|
||||
case !exists:
|
||||
result.Missing++
|
||||
if apply && a.Status != "missing" {
|
||||
if err := metadata.MarkMissing(ctx, a.ID, true); err != nil {
|
||||
return result, err
|
||||
}
|
||||
result.Changed++
|
||||
}
|
||||
case a.Status == "missing" && apply:
|
||||
if err := metadata.MarkMissing(ctx, a.ID, false); err != nil {
|
||||
return result, err
|
||||
}
|
||||
result.Changed++
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package media
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
)
|
||||
|
||||
type reconciliationFixture struct {
|
||||
records []dto.Attachment
|
||||
entries []ObjectInfo
|
||||
exists bool
|
||||
referenced bool
|
||||
claim bool
|
||||
scanErr error
|
||||
existsErr error
|
||||
claimErr error
|
||||
finishErr error
|
||||
removeErr error
|
||||
markErr error
|
||||
listErr error
|
||||
referenceErr error
|
||||
removed int
|
||||
}
|
||||
|
||||
// Scan returns an independent bounded fixture page.
|
||||
func (f *reconciliationFixture) Scan(context.Context, uuid.UUID, int) ([]dto.Attachment, error) {
|
||||
return f.records, f.scanErr
|
||||
}
|
||||
|
||||
// Reclaim injects failures at the claim or finish boundary independently.
|
||||
func (f *reconciliationFixture) Reclaim(_ context.Context, _ uuid.UUID, _ time.Time, finish bool) (bool, error) {
|
||||
if finish {
|
||||
return f.claim, f.finishErr
|
||||
}
|
||||
return f.claim, f.claimErr
|
||||
}
|
||||
|
||||
// MarkMissing models availability-state persistence without deleting metadata.
|
||||
func (f *reconciliationFixture) MarkMissing(context.Context, uuid.UUID, bool) error {
|
||||
return f.markErr
|
||||
}
|
||||
|
||||
// Exists returns an explicit existence or infrastructure-failure outcome.
|
||||
func (f *reconciliationFixture) Exists(context.Context, string) (bool, error) {
|
||||
return f.exists, f.existsErr
|
||||
}
|
||||
|
||||
// Remove counts applied side effects for dry-run and referenced-object assertions.
|
||||
func (f *reconciliationFixture) Remove(context.Context, string) error {
|
||||
f.removed++
|
||||
return f.removeErr
|
||||
}
|
||||
|
||||
// List supplies object timestamps independently of database state.
|
||||
func (f *reconciliationFixture) List(context.Context, string) ([]ObjectInfo, error) {
|
||||
return f.entries, f.listErr
|
||||
}
|
||||
|
||||
// HasObject includes reservations so active uploads remain protected.
|
||||
func (f *reconciliationFixture) HasObject(context.Context, string) (bool, error) {
|
||||
return f.referenced, f.referenceErr
|
||||
}
|
||||
|
||||
// TestReconciliationSafety exercises interrupted cleanup, age protection and missing-object repair.
|
||||
func TestReconciliationSafety(t *testing.T) {
|
||||
fault := errors.New("dependency failure")
|
||||
old := time.Now().Add(-2 * time.Hour)
|
||||
cases := []struct {
|
||||
name string
|
||||
fixture reconciliationFixture
|
||||
status string
|
||||
created time.Time
|
||||
apply bool
|
||||
wantErr bool
|
||||
changed int
|
||||
}{
|
||||
{name: "fresh", created: time.Now(), apply: true},
|
||||
{name: "scan failure", fixture: reconciliationFixture{scanErr: fault}, wantErr: true},
|
||||
{name: "head failure", fixture: reconciliationFixture{existsErr: fault}, wantErr: true},
|
||||
{name: "dry abandoned", status: "uploading"},
|
||||
{name: "abandoned applied", status: "uploading", apply: true, fixture: reconciliationFixture{claim: true}, changed: 1},
|
||||
{name: "claimed by another", status: "uploading", apply: true},
|
||||
{name: "claim failure", status: "uploading", apply: true, fixture: reconciliationFixture{claimErr: fault}, wantErr: true},
|
||||
{name: "delete failure", status: "deleting", apply: true, fixture: reconciliationFixture{claim: true, removeErr: fault}, wantErr: true},
|
||||
{name: "finish failure", status: "deleting", apply: true, fixture: reconciliationFixture{claim: true, finishErr: fault}, wantErr: true},
|
||||
{name: "missing dry", status: "ready"},
|
||||
{name: "missing applied", status: "ready", apply: true, changed: 1},
|
||||
{name: "mark failure", status: "ready", apply: true, fixture: reconciliationFixture{markErr: fault}, wantErr: true},
|
||||
{name: "missing repeat", status: "missing", apply: true},
|
||||
{name: "restored", status: "missing", apply: true, fixture: reconciliationFixture{exists: true}, changed: 1},
|
||||
{name: "restore failure", status: "missing", apply: true, fixture: reconciliationFixture{exists: true, markErr: fault}, wantErr: true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := tc.fixture
|
||||
created := tc.created
|
||||
if created.IsZero() {
|
||||
created = old
|
||||
}
|
||||
f.records = []dto.Attachment{{ID: uuid.New(), Status: tc.status, CreatedAt: created, ObjectKey: "original/test"}}
|
||||
result, err := Reconcile(t.Context(), &f, &f, uuid.Nil, time.Hour, tc.apply)
|
||||
if (err != nil) != tc.wantErr || result.Changed != tc.changed {
|
||||
t.Fatalf("result=%+v error=%v", result, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestOrphanSafety rejects deleting fresh, reserved and unknown-age objects.
|
||||
func TestOrphanSafety(t *testing.T) {
|
||||
fault := errors.New("dependency failure")
|
||||
cases := []struct {
|
||||
name string
|
||||
fixture reconciliationFixture
|
||||
fresh bool
|
||||
apply bool
|
||||
wantErr bool
|
||||
removed int
|
||||
}{
|
||||
{name: "fresh", fresh: true, apply: true},
|
||||
{name: "referenced", fixture: reconciliationFixture{referenced: true}, apply: true},
|
||||
{name: "dry run"},
|
||||
{name: "remove", apply: true, removed: 1},
|
||||
{name: "list failure", fixture: reconciliationFixture{listErr: fault}, wantErr: true},
|
||||
{name: "metadata failure", fixture: reconciliationFixture{referenceErr: fault}, wantErr: true},
|
||||
{name: "remove failure", fixture: reconciliationFixture{removeErr: fault}, apply: true, wantErr: true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := tc.fixture
|
||||
modified := time.Now().Add(-2 * time.Hour)
|
||||
if tc.fresh {
|
||||
modified = time.Now()
|
||||
}
|
||||
f.entries = []ObjectInfo{{Key: "original/test", ModifiedAt: modified}}
|
||||
result, err := ReconcileOrphans(t.Context(), &f, &f, "", time.Hour, tc.apply)
|
||||
if (err != nil) != tc.wantErr || result.Removed != tc.removed {
|
||||
t.Fatalf("result=%+v error=%v", result, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestGraceCannotBeDisabled rejects unsafe cleanup windows at both scan entrypoints.
|
||||
func TestGraceCannotBeDisabled(t *testing.T) {
|
||||
f := &reconciliationFixture{}
|
||||
if _, err := Reconcile(t.Context(), f, f, uuid.Nil, time.Second, true); err == nil {
|
||||
t.Fatal("unsafe metadata grace accepted")
|
||||
}
|
||||
if _, err := ReconcileOrphans(t.Context(), f, f, "", time.Second, true); err == nil {
|
||||
t.Fatal("unsafe object grace accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package media
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ReconcileMetadata combines bounded database inventory operations for the operator workflow.
|
||||
type ReconcileMetadata interface {
|
||||
Inventory
|
||||
OrphanMetadata
|
||||
}
|
||||
|
||||
// ReconcileObjects combines object inspection and listing for the operator workflow.
|
||||
type ReconcileObjects interface {
|
||||
ObjectInventory
|
||||
OrphanObjects
|
||||
}
|
||||
|
||||
// RunReconciliation emits one bounded result per page and stops on any uncertain dependency outcome.
|
||||
func RunReconciliation(ctx context.Context, metadata ReconcileMetadata, objects ReconcileObjects, output io.Writer, apply bool) error {
|
||||
encoder := json.NewEncoder(output)
|
||||
after := uuid.Nil
|
||||
for {
|
||||
result, err := Reconcile(ctx, metadata, objects, after, time.Hour, apply)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := encoder.Encode(result); err != nil {
|
||||
return err
|
||||
}
|
||||
if result.Scanned < 1000 {
|
||||
break
|
||||
}
|
||||
after = result.Next
|
||||
}
|
||||
key := ""
|
||||
for {
|
||||
result, err := ReconcileOrphans(ctx, metadata, objects, key, time.Hour, apply)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := encoder.Encode(result); err != nil {
|
||||
return err
|
||||
}
|
||||
if result.Scanned < 1000 {
|
||||
return nil
|
||||
}
|
||||
key = result.Next
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package media
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
)
|
||||
|
||||
type pagedFixture struct {
|
||||
reconciliationFixture
|
||||
metadataPage int
|
||||
objectPage int
|
||||
}
|
||||
|
||||
// Scan returns one full fresh page followed by an empty continuation.
|
||||
func (f *pagedFixture) Scan(context.Context, uuid.UUID, int) ([]dto.Attachment, error) {
|
||||
f.metadataPage++
|
||||
if f.metadataPage > 1 {
|
||||
return nil, nil
|
||||
}
|
||||
records := make([]dto.Attachment, 1000)
|
||||
for i := range records {
|
||||
records[i] = dto.Attachment{ID: uuid.New(), CreatedAt: time.Now()}
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
|
||||
// List returns one full fresh page followed by an empty continuation.
|
||||
func (f *pagedFixture) List(context.Context, string) ([]ObjectInfo, error) {
|
||||
f.objectPage++
|
||||
if f.objectPage > 1 {
|
||||
return nil, nil
|
||||
}
|
||||
records := make([]ObjectInfo, 1000)
|
||||
for i := range records {
|
||||
records[i] = ObjectInfo{Key: uuid.NewString(), ModifiedAt: time.Now()}
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
|
||||
type failingWriter struct {
|
||||
successful int
|
||||
}
|
||||
|
||||
// Write injects a broken report sink after a fixed number of complete pages.
|
||||
func (f *failingWriter) Write(data []byte) (int, error) {
|
||||
if f.successful == 0 {
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
f.successful--
|
||||
return len(data), nil
|
||||
}
|
||||
|
||||
// TestReconciliationPagination proves both inventories advance beyond a full page.
|
||||
func TestReconciliationPagination(t *testing.T) {
|
||||
f := &pagedFixture{}
|
||||
if err := RunReconciliation(t.Context(), f, f, io.Discard, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f.metadataPage != 2 || f.objectPage != 2 {
|
||||
t.Fatalf("pages: metadata=%d objects=%d", f.metadataPage, f.objectPage)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReconciliationStopsOnFailures prevents misleading successful reports after lost evidence or dependencies.
|
||||
func TestReconciliationStopsOnFailures(t *testing.T) {
|
||||
fault := errors.New("dependency failure")
|
||||
cases := []struct {
|
||||
name string
|
||||
fixture reconciliationFixture
|
||||
writer io.Writer
|
||||
}{
|
||||
{"metadata", reconciliationFixture{scanErr: fault}, io.Discard},
|
||||
{"objects", reconciliationFixture{listErr: fault}, io.Discard},
|
||||
{"first report", reconciliationFixture{}, &failingWriter{}},
|
||||
{"second report", reconciliationFixture{}, &failingWriter{successful: 1}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := tc.fixture
|
||||
if err := RunReconciliation(t.Context(), &f, &f, tc.writer, false); err == nil {
|
||||
t.Fatal("failed run reported success")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
// Package media implements attachment authorization and the S3 publication protocol.
|
||||
package media
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
)
|
||||
|
||||
// Metadata persists reservations before object creation.
|
||||
type Metadata interface {
|
||||
// Reserve inserts an uploading reservation.
|
||||
Reserve(context.Context, dto.Attachment) error
|
||||
// QueueAttachment atomically exposes queued metadata and durable processing intent.
|
||||
QueueAttachment(context.Context, uuid.UUID) (dto.Attachment, error)
|
||||
// Attachment retrieves metadata by a validated ID.
|
||||
Attachment(context.Context, uuid.UUID) (dto.Attachment, error)
|
||||
}
|
||||
|
||||
// Objects exposes private object operations without a concrete S3 client.
|
||||
type Objects interface {
|
||||
// Put uploads a known bounded length without a multipart buffer.
|
||||
Put(context.Context, string, string, io.Reader, int64) error
|
||||
// Get opens an original stream; the caller closes it.
|
||||
Get(context.Context, string) (io.ReadCloser, error)
|
||||
}
|
||||
|
||||
// Chats authorizes access using the existing business service.
|
||||
type Chats interface {
|
||||
// ChatsGetByID checks the caller and membership.
|
||||
ChatsGetByID(context.Context, string, string) (dto.ChatDTO, error)
|
||||
}
|
||||
|
||||
// Service coordinates bounded validation and durable publication.
|
||||
type Service struct {
|
||||
metadata Metadata
|
||||
objects Objects
|
||||
chats Chats
|
||||
slots chan struct{}
|
||||
}
|
||||
|
||||
// New validates required dependencies and caps simultaneous image decoding.
|
||||
func New(metadata Metadata, objects Objects, chats Chats) (*Service, error) {
|
||||
if metadata == nil || objects == nil || chats == nil {
|
||||
return nil, fmt.Errorf("attachment dependencies are required")
|
||||
}
|
||||
return &Service{metadata: metadata, objects: objects, chats: chats, slots: make(chan struct{}, 2)}, nil
|
||||
}
|
||||
|
||||
// Upload validates access and original bytes before reserving and publishing.
|
||||
func (s *Service) Upload(ctx context.Context, user, chat, filename, contentType string, body []byte) (dto.Attachment, error) {
|
||||
scope, err := s.chats.ChatsGetByID(ctx, user, chat)
|
||||
if err != nil {
|
||||
return dto.Attachment{}, err
|
||||
}
|
||||
select {
|
||||
case s.slots <- struct{}{}:
|
||||
defer func() {
|
||||
<-s.slots
|
||||
}()
|
||||
default:
|
||||
return dto.Attachment{}, service.ErrUnavailable
|
||||
}
|
||||
if err := validateImage(filename, contentType, body); err != nil {
|
||||
return dto.Attachment{}, err
|
||||
}
|
||||
owner, err := uuid.Parse(user)
|
||||
if err != nil {
|
||||
return dto.Attachment{}, service.ErrUnauthorized
|
||||
}
|
||||
sum := sha256.Sum256(body)
|
||||
id := uuid.New()
|
||||
now := time.Now().UTC()
|
||||
attachment := dto.Attachment{
|
||||
ID: id,
|
||||
ChatID: scope.ID,
|
||||
OwnerID: owner,
|
||||
Filename: filename,
|
||||
ContentType: contentType,
|
||||
SizeBytes: int64(len(body)),
|
||||
SHA256: hex.EncodeToString(sum[:]),
|
||||
Status: "uploading",
|
||||
ObjectKey: "staging/" + id.String(),
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
if err := s.metadata.Reserve(ctx, attachment); err != nil {
|
||||
return dto.Attachment{}, err
|
||||
}
|
||||
if err := s.objects.Put(ctx, attachment.ObjectKey, contentType, bytes.NewReader(body), attachment.SizeBytes); err != nil {
|
||||
return dto.Attachment{}, service.ErrUnavailable
|
||||
}
|
||||
// A lost COMMIT acknowledgement must never trigger deletion of a possibly published object.
|
||||
return s.metadata.QueueAttachment(ctx, id)
|
||||
}
|
||||
|
||||
// Get authorizes metadata access without exposing private object coordinates.
|
||||
func (s *Service) Get(ctx context.Context, user, rawID string) (dto.Attachment, error) {
|
||||
id, err := uuid.Parse(rawID)
|
||||
if err != nil {
|
||||
return dto.Attachment{}, service.ErrInvalid
|
||||
}
|
||||
attachment, err := s.metadata.Attachment(ctx, id)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
return dto.Attachment{}, service.ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return dto.Attachment{}, err
|
||||
}
|
||||
if _, err := s.chats.ChatsGetByID(ctx, user, attachment.ChatID.String()); err != nil {
|
||||
return dto.Attachment{}, err
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
// Download validates access and variant before opening the original stream.
|
||||
func (s *Service) Download(ctx context.Context, user, id, variant string) (dto.Attachment, io.ReadCloser, error) {
|
||||
attachment, err := s.Get(ctx, user, id)
|
||||
if err != nil {
|
||||
return dto.Attachment{}, nil, err
|
||||
}
|
||||
if attachment.Status != "ready" {
|
||||
return dto.Attachment{}, nil, service.ErrConflict
|
||||
}
|
||||
if variant != "" && variant != "original" {
|
||||
found := false
|
||||
for _, candidate := range attachment.Variants {
|
||||
if candidate.Name == variant {
|
||||
attachment.ObjectKey = candidate.ObjectKey
|
||||
attachment.ContentType = candidate.ContentType
|
||||
attachment.SizeBytes = candidate.SizeBytes
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return dto.Attachment{}, nil, service.ErrNotFound
|
||||
}
|
||||
}
|
||||
reader, err := s.objects.Get(ctx, attachment.ObjectKey)
|
||||
if err != nil {
|
||||
return dto.Attachment{}, nil, service.ErrUnavailable
|
||||
}
|
||||
return attachment, reader, nil
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
package media
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
|
||||
)
|
||||
|
||||
type mediaFixture struct {
|
||||
attachment dto.Attachment
|
||||
body []byte
|
||||
authorizeErr error
|
||||
reserveErr error
|
||||
publishErr error
|
||||
getErr error
|
||||
objectErr error
|
||||
}
|
||||
|
||||
// ChatsGetByID models a single authorization outcome for one scenario.
|
||||
func (f *mediaFixture) ChatsGetByID(_ context.Context, _, chat string) (dto.ChatDTO, error) {
|
||||
id, _ := uuid.Parse(chat)
|
||||
return dto.ChatDTO{ID: id}, f.authorizeErr
|
||||
}
|
||||
|
||||
// Reserve records durable intent before a test object can be written.
|
||||
func (f *mediaFixture) Reserve(_ context.Context, a dto.Attachment) error {
|
||||
f.attachment = a
|
||||
return f.reserveErr
|
||||
}
|
||||
|
||||
// QueueAttachment models an acknowledged or uncertain database commit.
|
||||
func (f *mediaFixture) QueueAttachment(_ context.Context, _ uuid.UUID) (dto.Attachment, error) {
|
||||
f.attachment.Status = "queued"
|
||||
return f.attachment, f.publishErr
|
||||
}
|
||||
|
||||
// Attachment returns fixture metadata without bypassing service authorization.
|
||||
func (f *mediaFixture) Attachment(_ context.Context, _ uuid.UUID) (dto.Attachment, error) {
|
||||
return f.attachment, f.getErr
|
||||
}
|
||||
|
||||
// Put captures exact original bytes or injects an object failure.
|
||||
func (f *mediaFixture) Put(_ context.Context, _, _ string, r io.Reader, _ int64) error {
|
||||
if f.objectErr != nil {
|
||||
return f.objectErr
|
||||
}
|
||||
var err error
|
||||
f.body, err = io.ReadAll(r)
|
||||
return err
|
||||
}
|
||||
|
||||
// Get returns a separate read cursor over the captured original.
|
||||
func (f *mediaFixture) Get(_ context.Context, _ string) (io.ReadCloser, error) {
|
||||
return io.NopCloser(bytes.NewReader(f.body)), f.objectErr
|
||||
}
|
||||
|
||||
// mediaService constructs an independent service with explicit fixture dependencies.
|
||||
func mediaService(t *testing.T, f *mediaFixture) *Service {
|
||||
t.Helper()
|
||||
s, err := New(f, f, f)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// TestUploadPublication verifies exact bytes and durable publication ordering.
|
||||
func TestUploadPublication(t *testing.T) {
|
||||
f := &mediaFixture{}
|
||||
s := mediaService(t, f)
|
||||
original := imageBytes(t)
|
||||
a, err := s.Upload(t.Context(), uuid.NewString(), uuid.NewString(), "a.png", "image/png", original)
|
||||
if err != nil || a.Status != "queued" || a.SizeBytes != int64(len(original)) || len(a.SHA256) != 64 || !bytes.Equal(f.body, original) {
|
||||
t.Fatalf("upload result: %+v %v", a, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUploadRejectsUnauthorized verifies authorization precedes object creation.
|
||||
func TestUploadRejectsUnauthorized(t *testing.T) {
|
||||
f := &mediaFixture{authorizeErr: service.ErrNotFound}
|
||||
s := mediaService(t, f)
|
||||
_, err := s.Upload(t.Context(), uuid.NewString(), uuid.NewString(), "a.png", "image/png", imageBytes(t))
|
||||
if !errors.Is(err, service.ErrNotFound) || f.body != nil {
|
||||
t.Fatalf("unauthorized upload: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUploadDependencyFailures verifies failed operations are not acknowledged as ready.
|
||||
func TestUploadDependencyFailures(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
fixture mediaFixture
|
||||
}{
|
||||
{name: "reserve", fixture: mediaFixture{reserveErr: service.ErrUnavailable}},
|
||||
{name: "put", fixture: mediaFixture{objectErr: service.ErrUnavailable}},
|
||||
{name: "commit acknowledgement", fixture: mediaFixture{publishErr: service.ErrUnavailable}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := tc.fixture
|
||||
s := mediaService(t, &f)
|
||||
_, err := s.Upload(t.Context(), uuid.NewString(), uuid.NewString(), "a.png", "image/png", imageBytes(t))
|
||||
if !errors.Is(err, service.ErrUnavailable) {
|
||||
t.Fatalf("error=%v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestUploadConcurrencyBound verifies decoding cannot create an unbounded queue.
|
||||
func TestUploadConcurrencyBound(t *testing.T) {
|
||||
s := mediaService(t, &mediaFixture{})
|
||||
s.slots <- struct{}{}
|
||||
s.slots <- struct{}{}
|
||||
_, err := s.Upload(t.Context(), uuid.NewString(), uuid.NewString(), "a.png", "image/png", imageBytes(t))
|
||||
if !errors.Is(err, service.ErrUnavailable) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetAttachment checks metadata authorization and intermediate state handling.
|
||||
func TestGetAttachment(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
fixture mediaFixture
|
||||
id string
|
||||
want error
|
||||
}{
|
||||
{name: "invalid id", id: "bad", want: service.ErrInvalid},
|
||||
{name: "missing", id: uuid.NewString(), fixture: mediaFixture{getErr: store.ErrNotFound}, want: service.ErrNotFound},
|
||||
{name: "database unavailable", id: uuid.NewString(), fixture: mediaFixture{getErr: service.ErrUnavailable}, want: service.ErrUnavailable},
|
||||
{name: "foreign", id: uuid.NewString(), fixture: mediaFixture{authorizeErr: service.ErrNotFound}, want: service.ErrNotFound},
|
||||
{name: "unfinished", id: uuid.NewString(), fixture: mediaFixture{attachment: dto.Attachment{Status: "queued"}}},
|
||||
{name: "ready", id: uuid.NewString(), fixture: mediaFixture{attachment: dto.Attachment{Status: "ready"}}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := tc.fixture
|
||||
s := mediaService(t, &f)
|
||||
_, err := s.Get(t.Context(), uuid.NewString(), tc.id)
|
||||
if !errors.Is(err, tc.want) {
|
||||
t.Fatalf("got %v want %v", err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestDownloadOriginal checks byte identity through an independently authorized read.
|
||||
func TestDownloadOriginal(t *testing.T) {
|
||||
f := &mediaFixture{attachment: dto.Attachment{Status: "ready"}, body: imageBytes(t)}
|
||||
s := mediaService(t, f)
|
||||
_, reader, err := s.Download(t.Context(), uuid.NewString(), uuid.NewString(), "original")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := io.ReadAll(reader)
|
||||
if closeErr := reader.Close(); closeErr != nil {
|
||||
t.Fatal(closeErr)
|
||||
}
|
||||
if err != nil || !bytes.Equal(got, f.body) {
|
||||
t.Fatalf("download: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMediaRequiresDependencies rejects incomplete service composition.
|
||||
func TestMediaRequiresDependencies(t *testing.T) {
|
||||
if _, err := New(nil, nil, nil); err == nil {
|
||||
t.Fatal("missing dependencies accepted")
|
||||
}
|
||||
}
|
||||
|
||||
// TestUploadRejectsInvalidOriginal never reserves invalid file metadata.
|
||||
func TestUploadRejectsInvalidOriginal(t *testing.T) {
|
||||
f := &mediaFixture{}
|
||||
s := mediaService(t, f)
|
||||
_, err := s.Upload(t.Context(), uuid.NewString(), uuid.NewString(), "a.png", "image/png", []byte("invalid"))
|
||||
if !errors.Is(err, service.ErrMedia) || f.attachment.ID != uuid.Nil {
|
||||
t.Fatalf("invalid bytes persisted: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUploadRejectsMalformedOwner does not persist an invalid authenticated identity.
|
||||
func TestUploadRejectsMalformedOwner(t *testing.T) {
|
||||
f := &mediaFixture{}
|
||||
s := mediaService(t, f)
|
||||
_, err := s.Upload(t.Context(), "bad", uuid.NewString(), "a.png", "image/png", imageBytes(t))
|
||||
if !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDownloadFailures keeps authorization, variant and dependency failures distinct.
|
||||
func TestDownloadFailures(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
fixture mediaFixture
|
||||
variant string
|
||||
want error
|
||||
}{
|
||||
{name: "foreign", fixture: mediaFixture{authorizeErr: service.ErrNotFound}, want: service.ErrNotFound},
|
||||
{name: "variant missing", fixture: mediaFixture{attachment: dto.Attachment{Status: "ready"}}, variant: "thumbnail", want: service.ErrNotFound},
|
||||
{name: "S3 unavailable", fixture: mediaFixture{attachment: dto.Attachment{Status: "ready"}, objectErr: service.ErrUnavailable}, want: service.ErrUnavailable},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := tc.fixture
|
||||
s := mediaService(t, &f)
|
||||
_, reader, err := s.Download(t.Context(), uuid.NewString(), uuid.NewString(), tc.variant)
|
||||
if reader != nil {
|
||||
_ = reader.Close()
|
||||
}
|
||||
if !errors.Is(err, tc.want) {
|
||||
t.Fatalf("got %v want %v", err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package media
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
|
||||
// Register the only accepted original image decoders.
|
||||
_ "image/jpeg"
|
||||
// Register PNG for content validation before storage.
|
||||
_ "image/png"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
)
|
||||
|
||||
const maxImageBytes = 10 << 20
|
||||
const maxImagePixels = 40_000_000
|
||||
|
||||
// validateImage checks encoded size, display name, actual format and complete decoding.
|
||||
func validateImage(filename, mime string, body []byte) error {
|
||||
if len(body) > maxImageBytes {
|
||||
return service.ErrTooLarge
|
||||
}
|
||||
if !utf8.ValidString(filename) || strings.TrimSpace(filename) == "" || utf8.RuneCountInString(filename) > 255 {
|
||||
return service.ErrInvalid
|
||||
}
|
||||
for _, r := range filename {
|
||||
if r == '/' || r == '\\' || unicode.IsControl(r) {
|
||||
return service.ErrInvalid
|
||||
}
|
||||
}
|
||||
if mime != "image/png" && mime != "image/jpeg" {
|
||||
return service.ErrMedia
|
||||
}
|
||||
dimensions, format, err := image.DecodeConfig(bytes.NewReader(body))
|
||||
if err != nil || "image/"+format != mime {
|
||||
return service.ErrMedia
|
||||
}
|
||||
if dimensions.Width < 1 || dimensions.Height < 1 || int64(dimensions.Width)*int64(dimensions.Height) > maxImagePixels {
|
||||
return service.ErrTooLarge
|
||||
}
|
||||
if _, _, err := image.Decode(bytes.NewReader(body)); err != nil {
|
||||
return service.ErrMedia
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package media
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"hash/crc32"
|
||||
"image"
|
||||
"image/png"
|
||||
"testing"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
)
|
||||
|
||||
// imageBytes creates a valid independent synthetic PNG fixture.
|
||||
func imageBytes(t *testing.T) []byte {
|
||||
t.Helper()
|
||||
var output bytes.Buffer
|
||||
if err := png.Encode(&output, image.NewRGBA(image.Rect(0, 0, 3, 2))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return output.Bytes()
|
||||
}
|
||||
|
||||
// TestValidateImage checks file-level rejection independently of persistence.
|
||||
func TestValidateImage(t *testing.T) {
|
||||
valid := imageBytes(t)
|
||||
cases := []struct {
|
||||
name string
|
||||
filename string
|
||||
mime string
|
||||
body []byte
|
||||
want error
|
||||
}{
|
||||
{"valid", "test.png", "image/png", valid, nil},
|
||||
{"traversal", "../test.png", "image/png", valid, service.ErrInvalid},
|
||||
{"backslash", "a\\b", "image/png", valid, service.ErrInvalid},
|
||||
{"control", "a\n", "image/png", valid, service.ErrInvalid},
|
||||
{"empty name", "", "image/png", valid, service.ErrInvalid},
|
||||
{"mime mismatch", "a.jpg", "image/jpeg", valid, service.ErrMedia},
|
||||
{"unsupported", "a.png", "text/plain", valid, service.ErrMedia},
|
||||
{"corrupt header", "a.png", "image/png", []byte("bad"), service.ErrMedia},
|
||||
{"truncated payload", "a.png", "image/png", valid[:len(valid)-12], service.ErrMedia},
|
||||
{"encoded limit", "a.png", "image/png", make([]byte, maxImageBytes+1), service.ErrTooLarge},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := validateImage(tc.filename, tc.mime, tc.body)
|
||||
if !errors.Is(err, tc.want) {
|
||||
t.Fatalf("got %v want %v", err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestPixelLimitPrecedesDecode rejects a valid PNG header before allocating a huge pixel buffer.
|
||||
func TestPixelLimitPrecedesDecode(t *testing.T) {
|
||||
body := append([]byte{}, imageBytes(t)...)
|
||||
binary.BigEndian.PutUint32(body[16:20], 10000)
|
||||
binary.BigEndian.PutUint32(body[20:24], 10000)
|
||||
binary.BigEndian.PutUint32(body[29:33], crc32.ChecksumIEEE(body[12:29]))
|
||||
if err := validateImage("huge.png", "image/png", body); !errors.Is(err, service.ErrTooLarge) {
|
||||
t.Fatalf("pixel limit: %v", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user