forked from mtusi2026/mtusi2026lab6
Prepare verified laboratory 6 implementation and evidence
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
package usecase
|
||||
|
||||
import (
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/port"
|
||||
"backend/internal/domain/repository"
|
||||
"context"
|
||||
"github.com/google/uuid"
|
||||
"io"
|
||||
)
|
||||
|
||||
type Attachments struct {
|
||||
repo repository.AsyncAttachments
|
||||
messenger *Messenger
|
||||
objects port.Objects
|
||||
}
|
||||
|
||||
func NewAttachments(r repository.AsyncAttachments, m *Messenger, o port.Objects) *Attachments {
|
||||
return &Attachments{r, m, o}
|
||||
}
|
||||
func ObjectKey(id uuid.UUID) string { return "originals/" + id.String() }
|
||||
func (a *Attachments) Upload(ctx context.Context, caller, chat uuid.UUID, name, mime, sha string, size int64, body io.Reader) (model.Attachment, error) {
|
||||
if _, e := a.messenger.GetChat(ctx, caller, chat); e != nil {
|
||||
return model.Attachment{}, e
|
||||
}
|
||||
row, e := a.repo.ReserveAttachment(ctx, model.Attachment{ID: uuid.New(), ChatID: chat, OwnerID: caller, Filename: name, ContentType: mime, SHA256: sha, SizeBytes: size})
|
||||
if e != nil {
|
||||
return model.Attachment{}, e
|
||||
}
|
||||
if e = a.objects.Put(ctx, "staging/"+row.ID.String(), body, size, mime); e != nil {
|
||||
return model.Attachment{}, model.ErrUnavailable
|
||||
}
|
||||
carrier := model.TraceFrom(ctx)
|
||||
return a.repo.QueueAttachment(ctx, row, carrier.Traceparent, carrier.Tracestate)
|
||||
}
|
||||
func (a *Attachments) Get(ctx context.Context, caller, id uuid.UUID) (model.Attachment, error) {
|
||||
row, e := a.repo.GetAttachment(ctx, id)
|
||||
if e != nil {
|
||||
return model.Attachment{}, e
|
||||
}
|
||||
if _, e = a.messenger.GetChat(ctx, caller, row.ChatID); e != nil {
|
||||
return model.Attachment{}, e
|
||||
}
|
||||
return row, nil
|
||||
}
|
||||
func (a *Attachments) Content(ctx context.Context, caller, id uuid.UUID, variant string) (model.Attachment, io.ReadCloser, error) {
|
||||
row, e := a.Get(ctx, caller, id)
|
||||
if e != nil {
|
||||
return row, nil, e
|
||||
}
|
||||
if row.Status != "ready" {
|
||||
return row, nil, model.ErrConflict
|
||||
}
|
||||
key := ObjectKey(id)
|
||||
if variant != "original" {
|
||||
found := false
|
||||
for _, v := range row.Variants {
|
||||
if v.Name == variant {
|
||||
found = true
|
||||
key = VariantKey(id, row.PipelineVersion, variant)
|
||||
row.SizeBytes = v.SizeBytes
|
||||
row.ContentType = v.ContentType
|
||||
row.SHA256 = v.SHA256
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return row, nil, model.ErrNotFound
|
||||
}
|
||||
}
|
||||
info, e := a.objects.Stat(ctx, key)
|
||||
if e != nil || info.Size != row.SizeBytes {
|
||||
return row, nil, model.ErrUnavailable
|
||||
}
|
||||
r, e := a.objects.Get(ctx, key)
|
||||
if e != nil {
|
||||
return row, nil, model.ErrUnavailable
|
||||
}
|
||||
return row, r, nil
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package usecase
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/port"
|
||||
)
|
||||
|
||||
type Auth struct {
|
||||
sessions port.Sessions
|
||||
passwords port.Passwords
|
||||
messenger *Messenger
|
||||
ttl time.Duration
|
||||
now func() time.Time
|
||||
}
|
||||
type Session struct {
|
||||
Token string
|
||||
ExpiresAt time.Time
|
||||
User model.User
|
||||
}
|
||||
|
||||
func NewAuth(s port.Sessions, p port.Passwords, m *Messenger, ttl time.Duration, now func() time.Time) *Auth {
|
||||
return &Auth{s, p, m, ttl, now}
|
||||
}
|
||||
func (a *Auth) Register(ctx context.Context, username, name, password string) (model.User, error) {
|
||||
if n := utf8.RuneCountInString(password); n < 12 || n > 128 || !utf8.ValidString(password) {
|
||||
return model.User{}, &model.ValidationError{Message: "password: 12–128 Unicode characters"}
|
||||
}
|
||||
draft, err := model.NewUserDraft(username, name)
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
hash, err := a.passwords.Hash(password)
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
draft.PasswordHash = hash
|
||||
return a.messenger.repo.CreateUser(ctx, draft)
|
||||
}
|
||||
func (a *Auth) Login(ctx context.Context, username, password string) (Session, error) {
|
||||
id, hash, err := a.sessions.Credentials(ctx, username)
|
||||
if err != nil {
|
||||
return Session{}, err
|
||||
}
|
||||
if !a.passwords.Verify(password, hash) {
|
||||
return Session{}, model.ErrUnauthorized
|
||||
}
|
||||
user, err := a.messenger.repo.GetUser(ctx, id)
|
||||
if err != nil {
|
||||
return Session{}, err
|
||||
}
|
||||
raw := make([]byte, 32)
|
||||
if _, err = rand.Read(raw); err != nil {
|
||||
return Session{}, err
|
||||
}
|
||||
token := base64.RawURLEncoding.EncodeToString(raw)
|
||||
expires := a.now().UTC().Add(a.ttl)
|
||||
if err = a.sessions.CreateSession(ctx, TokenHash(token), id, expires); err != nil {
|
||||
return Session{}, err
|
||||
}
|
||||
return Session{token, expires, user}, nil
|
||||
}
|
||||
func TokenHash(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
func (a *Auth) Authenticate(ctx context.Context, token string) (model.User, error) {
|
||||
if len(token) != 43 {
|
||||
return model.User{}, model.ErrUnauthorized
|
||||
}
|
||||
id, err := a.sessions.AuthenticateSession(ctx, TokenHash(token))
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
return a.messenger.repo.GetUser(ctx, id)
|
||||
}
|
||||
func (a *Auth) Logout(ctx context.Context, token string) error {
|
||||
return a.sessions.RevokeSession(ctx, TokenHash(token))
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package usecase
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/repository"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const chatsCursorScope = "chats"
|
||||
|
||||
// Page — страница списка; NextCursor == nil, если следующей записи нет.
|
||||
type Page[T any] struct {
|
||||
Items []T
|
||||
NextCursor *string
|
||||
}
|
||||
|
||||
type Messenger struct {
|
||||
repo repository.Repository
|
||||
}
|
||||
|
||||
func NewMessenger(repo repository.Repository) *Messenger {
|
||||
return &Messenger{repo: repo}
|
||||
}
|
||||
|
||||
func (m *Messenger) CreateChat(ctx context.Context, caller uuid.UUID, title string, memberIDs []uuid.UUID) (model.Chat, error) {
|
||||
draft, err := model.NewChatDraft(caller, title, memberIDs)
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
return m.repo.CreateChat(ctx, draft)
|
||||
}
|
||||
|
||||
func (m *Messenger) ListChats(ctx context.Context, caller uuid.UUID, limit *int, cursor *string) (Page[model.Chat], error) {
|
||||
q, err := model.NewPageQuery(limit, cursor, chatsCursorScope)
|
||||
if err != nil {
|
||||
return Page[model.Chat]{}, err
|
||||
}
|
||||
chats, more, err := m.repo.ListChats(ctx, caller, q)
|
||||
if err != nil {
|
||||
return Page[model.Chat]{}, err
|
||||
}
|
||||
return newPage(chats, more, chatsCursorScope, model.Chat.Position), nil
|
||||
}
|
||||
|
||||
// GetChat отдаёт чат только участнику; постороннему — ErrNotFound, чтобы не
|
||||
// раскрывать существование чужого чата.
|
||||
func (m *Messenger) GetChat(ctx context.Context, caller, chatID uuid.UUID) (model.Chat, error) {
|
||||
chat, err := m.repo.GetChat(ctx, chatID)
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
if !chat.HasMember(caller) {
|
||||
return model.Chat{}, model.ErrNotFound
|
||||
}
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
// SendMessage сначала проверяет доступ, затем тело: посторонний получает 404
|
||||
// даже на невалидное сообщение. Проверка членства и запись не атомарны, но
|
||||
// участники чата неизменяемы, а чаты не удаляются, поэтому гонки здесь нет.
|
||||
func (m *Messenger) SendMessage(ctx context.Context, caller, chatID uuid.UUID, text, key string, attachments []uuid.UUID) (model.Message, error) {
|
||||
if _, err := m.GetChat(ctx, caller, chatID); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
draft, err := model.NewMessageDraft(chatID, caller, text, attachments)
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
draft, err = model.WithKey(draft, key)
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
return m.repo.CreateMessage(ctx, draft)
|
||||
}
|
||||
|
||||
func (m *Messenger) ListMessages(ctx context.Context, caller, chatID uuid.UUID, limit *int, cursor *string) (Page[model.Message], error) {
|
||||
if _, err := m.GetChat(ctx, caller, chatID); err != nil {
|
||||
return Page[model.Message]{}, err
|
||||
}
|
||||
scope := "messages:" + chatID.String()
|
||||
q, err := model.NewPageQuery(limit, cursor, scope)
|
||||
if err != nil {
|
||||
return Page[model.Message]{}, err
|
||||
}
|
||||
messages, more, err := m.repo.ListMessages(ctx, chatID, q)
|
||||
if err != nil {
|
||||
return Page[model.Message]{}, err
|
||||
}
|
||||
return newPage(messages, more, scope, model.Message.Position), nil
|
||||
}
|
||||
|
||||
func newPage[T any](items []T, more bool, scope string, position func(T) model.Position) Page[T] {
|
||||
page := Page[T]{Items: items}
|
||||
if more && len(items) > 0 {
|
||||
next := model.EncodeCursor(scope, position(items[len(items)-1]))
|
||||
page.NextCursor = &next
|
||||
}
|
||||
return page
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package usecase
|
||||
|
||||
import (
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/port"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/google/uuid"
|
||||
"io"
|
||||
"math/rand/v2"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Pipeline struct {
|
||||
store port.PipelineStore
|
||||
objects port.Objects
|
||||
transform port.Transformer
|
||||
MaxAttempts int32
|
||||
Fault func(string) error
|
||||
OnResult func(context.Context, model.Job, string, time.Duration)
|
||||
}
|
||||
|
||||
func NewPipeline(s port.PipelineStore, o port.Objects, t port.Transformer, max int32) *Pipeline {
|
||||
return &Pipeline{store: s, objects: o, transform: t, MaxAttempts: max, Fault: func(string) error { return nil }}
|
||||
}
|
||||
func VariantKey(id uuid.UUID, version int32, name string) string {
|
||||
return fmt.Sprintf("variants/%s/v%d/%s", id, version, name)
|
||||
}
|
||||
func (p *Pipeline) Process(ctx context.Context, j model.Job) error {
|
||||
lease := uuid.New()
|
||||
owned, a, ok, e := p.store.AcquireJob(ctx, j, lease, 30*time.Second)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if !ok {
|
||||
return p.Cleanup(ctx)
|
||||
}
|
||||
j = owned
|
||||
started := time.Now()
|
||||
outcome := "retry"
|
||||
if j.Attempt >= p.MaxAttempts {
|
||||
outcome = "failed"
|
||||
}
|
||||
reported := false
|
||||
defer func() {
|
||||
if !reported && p.OnResult != nil {
|
||||
p.OnResult(ctx, j, outcome, time.Since(started))
|
||||
}
|
||||
}()
|
||||
if j.Attempt > p.MaxAttempts {
|
||||
return p.store.RetryJob(ctx, j, lease, "retry_exhausted", 0, true)
|
||||
}
|
||||
// Reprocessing uses the immutable original after staging was safely removed.
|
||||
key := "staging/" + a.ID.String()
|
||||
r, e := p.objects.Get(ctx, key)
|
||||
if errors.Is(e, model.ErrNotFound) {
|
||||
r, e = p.objects.Get(ctx, ObjectKey(a.ID))
|
||||
}
|
||||
if e != nil {
|
||||
return p.retry(ctx, j, lease, e)
|
||||
}
|
||||
original, e := io.ReadAll(io.LimitReader(r, model.MaxImageBytes+1))
|
||||
_ = r.Close()
|
||||
if e != nil || int64(len(original)) != a.SizeBytes {
|
||||
return p.retry(ctx, j, lease, model.ErrUnavailable)
|
||||
}
|
||||
sum := sha256.Sum256(original)
|
||||
if hex.EncodeToString(sum[:]) != a.SHA256 {
|
||||
outcome = "failed"
|
||||
return p.retry(ctx, j, lease, model.ErrInvalidImage)
|
||||
}
|
||||
if e = p.objects.Put(ctx, ObjectKey(a.ID), bytes.NewReader(original), a.SizeBytes, a.ContentType); e != nil {
|
||||
return p.retry(ctx, j, lease, e)
|
||||
}
|
||||
if e = p.Fault("after_original"); e != nil {
|
||||
return e
|
||||
}
|
||||
variants, e := p.transform.Transform(ctx, bytes.NewReader(original))
|
||||
if e != nil {
|
||||
if errors.Is(e, model.ErrInvalidImage) {
|
||||
outcome = "failed"
|
||||
}
|
||||
return p.retry(ctx, j, lease, e)
|
||||
}
|
||||
result := make([]model.Variant, 0, len(variants))
|
||||
for _, v := range variants {
|
||||
if e = p.objects.Put(ctx, VariantKey(a.ID, j.PipelineVersion, v.Metadata.Name), bytes.NewReader(v.Bytes), int64(len(v.Bytes)), v.Metadata.ContentType); e != nil {
|
||||
return p.retry(ctx, j, lease, e)
|
||||
}
|
||||
result = append(result, v.Metadata)
|
||||
}
|
||||
if e = p.Fault("after_objects"); e != nil {
|
||||
return e
|
||||
}
|
||||
ok, e = p.store.CompleteJob(ctx, j, lease, result)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if !ok {
|
||||
outcome = "stale"
|
||||
return nil
|
||||
}
|
||||
outcome = "ready"
|
||||
if p.OnResult != nil {
|
||||
p.OnResult(ctx, j, outcome, time.Since(started))
|
||||
}
|
||||
reported = true
|
||||
if e = p.Fault("after_commit"); e != nil {
|
||||
return e
|
||||
}
|
||||
return p.Cleanup(ctx)
|
||||
}
|
||||
func (p *Pipeline) retry(ctx context.Context, j model.Job, lease uuid.UUID, cause error) error {
|
||||
failed := j.Attempt >= p.MaxAttempts
|
||||
code := "processing_failed"
|
||||
if failed {
|
||||
code = "retry_exhausted"
|
||||
}
|
||||
if errors.Is(cause, model.ErrInvalidImage) {
|
||||
failed = true
|
||||
code = "invalid_image"
|
||||
}
|
||||
delay := time.Duration((1<<min(j.Attempt, 5))*100+rand.IntN(100)) * time.Millisecond
|
||||
if e := p.store.RetryJob(ctx, j, lease, code, delay, failed); e != nil {
|
||||
return e
|
||||
}
|
||||
// This delivery has durably recorded its retry/failed effect. Ack it; the
|
||||
// transactional outbox schedules the next attempt instead of retaining a PEL entry.
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Pipeline) Cleanup(ctx context.Context) error {
|
||||
rows, e := p.store.StagingCleanup(ctx)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
for _, a := range rows {
|
||||
if a.Status == "ready" {
|
||||
info, e := p.objects.Stat(ctx, ObjectKey(a.ID))
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if info.Size != a.SizeBytes {
|
||||
return model.ErrUnavailable
|
||||
}
|
||||
}
|
||||
if e = p.objects.Remove(ctx, "staging/"+a.ID.String()); e != nil {
|
||||
return e
|
||||
}
|
||||
if e = p.store.StagingCleaned(ctx, a.ID); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package usecase
|
||||
|
||||
import (
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/port"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"github.com/google/uuid"
|
||||
"io"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type pipelineStoreFixture struct {
|
||||
failed bool
|
||||
code string
|
||||
complete bool
|
||||
a model.Attachment
|
||||
cleaned int
|
||||
}
|
||||
|
||||
func (f *pipelineStoreFixture) PendingJobs(context.Context) ([]model.Job, error) { return nil, nil }
|
||||
func (f *pipelineStoreFixture) Published(context.Context, uuid.UUID) error { return nil }
|
||||
func (f *pipelineStoreFixture) AcquireJob(_ context.Context, j model.Job, _ uuid.UUID, _ time.Duration) (model.Job, model.Attachment, bool, error) {
|
||||
j.Attempt = 1
|
||||
return j, f.a, !f.complete, nil
|
||||
}
|
||||
func (f *pipelineStoreFixture) CompleteJob(context.Context, model.Job, uuid.UUID, []model.Variant) (bool, error) {
|
||||
f.complete = true
|
||||
f.a.Status = "ready"
|
||||
return true, nil
|
||||
}
|
||||
func (f *pipelineStoreFixture) RetryJob(_ context.Context, _ model.Job, _ uuid.UUID, code string, _ time.Duration, failed bool) error {
|
||||
f.failed = failed
|
||||
f.code = code
|
||||
return nil
|
||||
}
|
||||
func (f *pipelineStoreFixture) ReplayJob(context.Context, uuid.UUID) (bool, error) { return false, nil }
|
||||
func (f *pipelineStoreFixture) AdvancePipeline(context.Context, uuid.UUID) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
func (f *pipelineStoreFixture) StagingCleanup(context.Context) ([]model.Attachment, error) {
|
||||
if f.complete && f.cleaned == 0 {
|
||||
return []model.Attachment{f.a}, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
func (f *pipelineStoreFixture) StagingCleaned(context.Context, uuid.UUID) error {
|
||||
f.cleaned++
|
||||
return nil
|
||||
}
|
||||
|
||||
type pipelineObjectsFixture struct {
|
||||
content []byte
|
||||
removeErr error
|
||||
removed int
|
||||
}
|
||||
|
||||
func (f *pipelineObjectsFixture) Get(context.Context, string) (io.ReadCloser, error) {
|
||||
return io.NopCloser(bytes.NewReader(f.content)), nil
|
||||
}
|
||||
func (f *pipelineObjectsFixture) Put(context.Context, string, io.Reader, int64, string) error {
|
||||
return nil
|
||||
}
|
||||
func (f *pipelineObjectsFixture) Stat(context.Context, string) (port.Object, error) {
|
||||
return port.Object{Size: int64(len(f.content))}, nil
|
||||
}
|
||||
func (f *pipelineObjectsFixture) Remove(context.Context, string) error {
|
||||
if f.removeErr != nil {
|
||||
return f.removeErr
|
||||
}
|
||||
f.removed++
|
||||
return nil
|
||||
}
|
||||
func (f *pipelineObjectsFixture) List(context.Context, string) ([]port.Object, bool, error) {
|
||||
return nil, false, nil
|
||||
}
|
||||
func (f *pipelineObjectsFixture) Ready(context.Context) error { return nil }
|
||||
|
||||
type transformFixture struct{ err error }
|
||||
|
||||
func (f transformFixture) Transform(context.Context, io.Reader) ([]port.ProcessedVariant, error) {
|
||||
return nil, f.err
|
||||
}
|
||||
func TestInfrastructureTransformFailureIsRetried(t *testing.T) {
|
||||
raw := []byte("valid durable bytes")
|
||||
sum := sha256.Sum256(raw)
|
||||
f := &pipelineStoreFixture{a: model.Attachment{ID: uuid.New(), SizeBytes: int64(len(raw)), SHA256: hex.EncodeToString(sum[:])}}
|
||||
for _, failure := range []error{syscall.ENOSPC, errors.New("convert executable unavailable")} {
|
||||
p := NewPipeline(f, &pipelineObjectsFixture{content: raw}, transformFixture{failure}, 5)
|
||||
if e := p.Process(context.Background(), model.Job{ID: uuid.New(), PipelineVersion: 1}); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if f.failed || f.code != "processing_failed" {
|
||||
t.Fatalf("temporary transform infrastructure failure became permanent: failed=%t code=%s", f.failed, f.code)
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestCompletedDeliveryRecoversStagingCleanupAfterCrash(t *testing.T) {
|
||||
raw := []byte("immutable original")
|
||||
sum := sha256.Sum256(raw)
|
||||
store := &pipelineStoreFixture{a: model.Attachment{ID: uuid.New(), SizeBytes: int64(len(raw)), SHA256: hex.EncodeToString(sum[:])}}
|
||||
objects := &pipelineObjectsFixture{content: raw}
|
||||
p := NewPipeline(store, objects, transformFixture{}, 5)
|
||||
p.Fault = func(point string) error {
|
||||
if point == "after_commit" {
|
||||
return errors.New("worker crash")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
j := model.Job{ID: uuid.New(), PipelineVersion: 1}
|
||||
if e := p.Process(context.Background(), j); e == nil {
|
||||
t.Fatal("crash was not injected")
|
||||
}
|
||||
if objects.removed != 0 {
|
||||
t.Fatal("staging removed before simulated crash")
|
||||
}
|
||||
p = NewPipeline(store, objects, transformFixture{}, 5)
|
||||
if e := p.Process(context.Background(), j); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if objects.removed != 1 || store.cleaned != 1 || store.a.Status != "ready" {
|
||||
t.Fatalf("completed redelivery did not recover cleanup: removed=%d durable_cleaned=%d status=%s", objects.removed, store.cleaned, store.a.Status)
|
||||
}
|
||||
if e := p.Process(context.Background(), j); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if objects.removed != 1 {
|
||||
t.Fatal("completed cleanup was repeated")
|
||||
}
|
||||
}
|
||||
|
||||
type blockedCleanupObjects struct {
|
||||
*pipelineObjectsFixture
|
||||
entered, release chan struct{}
|
||||
}
|
||||
|
||||
func (f *blockedCleanupObjects) Remove(ctx context.Context, key string) error {
|
||||
close(f.entered)
|
||||
select {
|
||||
case <-f.release:
|
||||
return f.pipelineObjectsFixture.Remove(ctx, key)
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
func TestReadyTelemetryPublishedBeforeSlowStagingCleanup(t *testing.T) {
|
||||
raw := []byte("immutable original")
|
||||
sum := sha256.Sum256(raw)
|
||||
store := &pipelineStoreFixture{a: model.Attachment{ID: uuid.New(), SizeBytes: int64(len(raw)), SHA256: hex.EncodeToString(sum[:])}}
|
||||
objects := &blockedCleanupObjects{pipelineObjectsFixture: &pipelineObjectsFixture{content: raw}, entered: make(chan struct{}), release: make(chan struct{})}
|
||||
p := NewPipeline(store, objects, transformFixture{}, 5)
|
||||
events := make(chan string, 2)
|
||||
p.OnResult = func(_ context.Context, _ model.Job, outcome string, _ time.Duration) { events <- outcome }
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- p.Process(ctx, model.Job{ID: uuid.New(), PipelineVersion: 1, CreatedAt: time.Now()}) }()
|
||||
select {
|
||||
case <-objects.entered:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("cleanup was not reached")
|
||||
}
|
||||
reported := 0
|
||||
select {
|
||||
case outcome := <-events:
|
||||
reported++
|
||||
if outcome != "ready" {
|
||||
t.Error("wrong published outcome")
|
||||
}
|
||||
default:
|
||||
t.Error("ready telemetry was delayed until staging cleanup")
|
||||
}
|
||||
close(objects.release)
|
||||
if e := <-done; e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
select {
|
||||
case <-events:
|
||||
reported++
|
||||
default:
|
||||
}
|
||||
if reported != 1 {
|
||||
t.Error("ready attempt emitted an incorrect event count")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package usecase
|
||||
|
||||
import (
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/port"
|
||||
"backend/internal/domain/repository"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"github.com/google/uuid"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ReconcileReport struct {
|
||||
Metadata, Objects, Orphans, Missing, Recovered, Fresh, Deleted, Changed int
|
||||
PipelineSkipped int
|
||||
NextMetadata, NextObject string
|
||||
}
|
||||
type Reconciler struct {
|
||||
repo repository.AttachmentRepository
|
||||
objects port.Objects
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewReconciler(repo repository.AttachmentRepository, objects port.Objects, now func() time.Time) *Reconciler {
|
||||
return &Reconciler{repo, objects, now}
|
||||
}
|
||||
func (r *Reconciler) Run(ctx context.Context, after uuid.UUID, objectAfter string, grace time.Duration, apply bool) (report ReconcileReport, runErr error) {
|
||||
report = ReconcileReport{}
|
||||
defer func() {
|
||||
if runErr != nil {
|
||||
report.NextMetadata = ""
|
||||
report.NextObject = ""
|
||||
}
|
||||
}()
|
||||
if grace < time.Minute {
|
||||
return report, &model.ValidationError{Message: "reconciliation grace must be at least 60 seconds"}
|
||||
}
|
||||
now := r.now().UTC()
|
||||
old := func(t time.Time) bool { age := now.Sub(t); return !t.IsZero() && age >= grace && age >= 0 }
|
||||
rows, more, e := r.repo.ReconcileAttachments(ctx, after)
|
||||
if e != nil {
|
||||
return report, e
|
||||
}
|
||||
for _, a := range rows {
|
||||
report.Metadata++
|
||||
if more {
|
||||
report.NextMetadata = a.ID.String()
|
||||
}
|
||||
if !old(a.CreatedAt) {
|
||||
report.Fresh++
|
||||
continue
|
||||
}
|
||||
// Only the fenced pipeline can publish versioned results. The legacy
|
||||
// reconciler knows nothing about required variants, retries or outbox jobs.
|
||||
if a.PipelineVersion > 0 {
|
||||
report.PipelineSkipped++
|
||||
continue
|
||||
}
|
||||
info, e := r.objects.Stat(ctx, ObjectKey(a.ID))
|
||||
target := a.Status
|
||||
if errors.Is(e, model.ErrNotFound) {
|
||||
switch a.Status {
|
||||
case "ready":
|
||||
report.Missing++
|
||||
target = "missing"
|
||||
case "uploading":
|
||||
report.Missing++
|
||||
target = "abandoned"
|
||||
}
|
||||
} else if e != nil {
|
||||
return report, e
|
||||
} else if a.Status != "ready" {
|
||||
valid := false
|
||||
if info.Size == a.SizeBytes {
|
||||
body, err := r.objects.Get(ctx, ObjectKey(a.ID))
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
hash := sha256.New()
|
||||
n, err := io.Copy(hash, io.LimitReader(body, a.SizeBytes+1))
|
||||
_ = body.Close()
|
||||
if err != nil {
|
||||
return report, model.ErrUnavailable
|
||||
}
|
||||
valid = n == a.SizeBytes && hex.EncodeToString(hash.Sum(nil)) == a.SHA256
|
||||
}
|
||||
if valid {
|
||||
report.Recovered++
|
||||
target = "ready"
|
||||
} else {
|
||||
report.Missing++
|
||||
target = "missing"
|
||||
}
|
||||
} else if info.Size != a.SizeBytes {
|
||||
report.Missing++
|
||||
target = "missing"
|
||||
}
|
||||
if apply && target != a.Status {
|
||||
changed, e := r.repo.SetAttachmentStatus(ctx, a.ID, a.Status, target)
|
||||
if e != nil {
|
||||
return report, e
|
||||
}
|
||||
if changed {
|
||||
report.Changed++
|
||||
}
|
||||
}
|
||||
}
|
||||
objects, more, e := r.objects.List(ctx, objectAfter)
|
||||
if e != nil {
|
||||
return report, e
|
||||
}
|
||||
for _, o := range objects {
|
||||
report.Objects++
|
||||
if more {
|
||||
report.NextObject = o.Key
|
||||
}
|
||||
if !old(o.Modified) {
|
||||
report.Fresh++
|
||||
continue
|
||||
}
|
||||
raw, ok := strings.CutPrefix(o.Key, "originals/")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
id, e := uuid.Parse(raw)
|
||||
if e != nil || ObjectKey(id) != o.Key {
|
||||
continue
|
||||
}
|
||||
if _, e = r.repo.GetAttachment(ctx, id); e == nil {
|
||||
continue
|
||||
} else if !errors.Is(e, model.ErrNotFound) {
|
||||
return report, e
|
||||
}
|
||||
report.Orphans++
|
||||
if !apply {
|
||||
continue
|
||||
}
|
||||
fresh, e := r.objects.Stat(ctx, o.Key)
|
||||
if errors.Is(e, model.ErrNotFound) {
|
||||
continue
|
||||
}
|
||||
if e != nil {
|
||||
return report, e
|
||||
}
|
||||
if fresh.ETag != o.ETag || fresh.Size != o.Size || !fresh.Modified.Equal(o.Modified) || !old(fresh.Modified) {
|
||||
report.Fresh++
|
||||
continue
|
||||
}
|
||||
if _, e = r.repo.GetAttachment(ctx, id); e == nil {
|
||||
continue
|
||||
} else if !errors.Is(e, model.ErrNotFound) {
|
||||
return report, e
|
||||
}
|
||||
// Object keys are random UUIDs, immutable and never reused by the upload API.
|
||||
// An absent metadata row cannot later adopt an old inventory key.
|
||||
if e = r.objects.Remove(ctx, o.Key); e != nil {
|
||||
return report, e
|
||||
}
|
||||
report.Deleted++
|
||||
}
|
||||
return report, nil
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package usecase
|
||||
|
||||
import (
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/port"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"github.com/google/uuid"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestReconcilerCannotPublishVersionedPipelineResult(t *testing.T) {
|
||||
for _, status := range []string{"uploading", "queued", "processing", "failed", "ready"} {
|
||||
t.Run(status, func(t *testing.T) {
|
||||
id := uuid.New()
|
||||
raw := []byte("only original survived worker crash")
|
||||
sum := sha256.Sum256(raw)
|
||||
repo := &fixtureRepo{rows: map[uuid.UUID]model.Attachment{id: {ID: id, Status: status, PipelineVersion: 1, SizeBytes: int64(len(raw)), SHA256: hex.EncodeToString(sum[:]), CreatedAt: fixedNow.Add(-2 * time.Minute)}}}
|
||||
objects := &fixtureObjects{items: map[string]port.Object{ObjectKey(id): {Key: ObjectKey(id), Size: int64(len(raw)), Modified: fixedNow.Add(-2 * time.Minute)}}, content: raw}
|
||||
report, e := NewReconciler(repo, objects, func() time.Time { return fixedNow }).Run(context.Background(), uuid.Nil, "", time.Minute, true)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if repo.rows[id].Status != status || report.Recovered != 0 || report.Changed != 0 {
|
||||
t.Fatalf("pipeline state was changed by legacy reconciler: status %s -> %s, report %+v", status, repo.rows[id].Status, report)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package usecase
|
||||
|
||||
import (
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/port"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"github.com/google/uuid"
|
||||
"io"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type fixtureRepo struct {
|
||||
rows map[uuid.UUID]model.Attachment
|
||||
failure error
|
||||
more bool
|
||||
}
|
||||
|
||||
func (f *fixtureRepo) ReserveAttachment(context.Context, model.Attachment) (model.Attachment, error) {
|
||||
panic("not used")
|
||||
}
|
||||
func (f *fixtureRepo) GetAttachment(_ context.Context, id uuid.UUID) (model.Attachment, error) {
|
||||
if f.failure != nil {
|
||||
return model.Attachment{}, f.failure
|
||||
}
|
||||
a, ok := f.rows[id]
|
||||
if !ok {
|
||||
return a, model.ErrNotFound
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
func (f *fixtureRepo) SetAttachmentStatus(_ context.Context, id uuid.UUID, from, to string) (bool, error) {
|
||||
a := f.rows[id]
|
||||
if a.Status != from {
|
||||
return false, nil
|
||||
}
|
||||
a.Status = to
|
||||
f.rows[id] = a
|
||||
return true, nil
|
||||
}
|
||||
func (f *fixtureRepo) ReconcileAttachments(context.Context, uuid.UUID) ([]model.Attachment, bool, error) {
|
||||
out := []model.Attachment{}
|
||||
for _, a := range f.rows {
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, f.more, f.failure
|
||||
}
|
||||
|
||||
type fixtureObjects struct {
|
||||
items map[string]port.Object
|
||||
content []byte
|
||||
failure error
|
||||
removed int
|
||||
changed bool
|
||||
}
|
||||
|
||||
func (f *fixtureObjects) Put(context.Context, string, io.Reader, int64, string) error {
|
||||
panic("not used")
|
||||
}
|
||||
func (f *fixtureObjects) Get(context.Context, string) (io.ReadCloser, error) {
|
||||
return io.NopCloser(bytes.NewReader(f.content)), f.failure
|
||||
}
|
||||
func (f *fixtureObjects) Stat(_ context.Context, key string) (port.Object, error) {
|
||||
if f.failure != nil {
|
||||
return port.Object{}, f.failure
|
||||
}
|
||||
o, ok := f.items[key]
|
||||
if !ok {
|
||||
return o, model.ErrNotFound
|
||||
}
|
||||
if f.changed {
|
||||
o.ETag = "changed"
|
||||
}
|
||||
return o, nil
|
||||
}
|
||||
func (f *fixtureObjects) Remove(_ context.Context, key string) error {
|
||||
delete(f.items, key)
|
||||
f.removed++
|
||||
return nil
|
||||
}
|
||||
func (f *fixtureObjects) List(context.Context, string) ([]port.Object, bool, error) {
|
||||
out := []port.Object{}
|
||||
for _, o := range f.items {
|
||||
out = append(out, o)
|
||||
}
|
||||
return out, false, f.failure
|
||||
}
|
||||
|
||||
var fixedNow = time.Date(2026, 11, 12, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
func TestOrphanCleanupHonorsGraceAndDryRun(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
age time.Duration
|
||||
apply, used, changed bool
|
||||
wantDeleted int
|
||||
}{
|
||||
{name: "old dry run", age: 2 * time.Minute},
|
||||
{name: "old apply", age: 2 * time.Minute, apply: true, wantDeleted: 1},
|
||||
{name: "fresh protected", age: 10 * time.Second, apply: true},
|
||||
{name: "future timestamp protected", age: -time.Minute, apply: true},
|
||||
{name: "referenced protected", age: 2 * time.Minute, apply: true, used: true},
|
||||
{name: "changed inventory protected", age: 2 * time.Minute, apply: true, changed: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
id := uuid.MustParse("00000000-0000-0000-0000-000000000001")
|
||||
key := ObjectKey(id)
|
||||
repo := &fixtureRepo{rows: map[uuid.UUID]model.Attachment{}}
|
||||
if tc.used {
|
||||
repo.rows[id] = model.Attachment{ID: id, Status: "ready", CreatedAt: fixedNow}
|
||||
}
|
||||
objects := &fixtureObjects{items: map[string]port.Object{key: {Key: key, ETag: "original", Modified: fixedNow.Add(-tc.age)}}, changed: tc.changed}
|
||||
report, e := NewReconciler(repo, objects, func() time.Time { return fixedNow }).Run(context.Background(), uuid.Nil, "", time.Minute, tc.apply)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if objects.removed != tc.wantDeleted {
|
||||
t.Fatalf("deleted %d, want %d; report=%+v", objects.removed, tc.wantDeleted, report)
|
||||
}
|
||||
if tc.wantDeleted > 0 {
|
||||
_, e = NewReconciler(repo, objects, func() time.Time { return fixedNow }).Run(context.Background(), uuid.Nil, "", time.Minute, true)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if objects.removed != 1 {
|
||||
t.Fatal("second run deleted something twice")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestMissingAndPendingMetadataRepair(t *testing.T) {
|
||||
for _, status := range []string{"ready", "uploading", "missing"} {
|
||||
t.Run(status, func(t *testing.T) {
|
||||
id := uuid.New()
|
||||
raw := []byte("original bytes")
|
||||
sum := sha256.Sum256(raw)
|
||||
repo := &fixtureRepo{rows: map[uuid.UUID]model.Attachment{id: {ID: id, Status: status, CreatedAt: fixedNow.Add(-2 * time.Minute), UpdatedAt: fixedNow.Add(-2 * time.Minute), SizeBytes: int64(len(raw)), SHA256: hex.EncodeToString(sum[:])}}}
|
||||
objects := &fixtureObjects{items: map[string]port.Object{}, content: raw}
|
||||
want := "missing"
|
||||
if status != "ready" {
|
||||
objects.items[ObjectKey(id)] = port.Object{Key: ObjectKey(id), Size: int64(len(raw)), Modified: fixedNow.Add(-2 * time.Minute)}
|
||||
want = "ready"
|
||||
}
|
||||
_, e := NewReconciler(repo, objects, func() time.Time { return fixedNow }).Run(context.Background(), uuid.Nil, "", time.Minute, true)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if got := repo.rows[id].Status; got != want {
|
||||
t.Fatalf("status %s, want %s", got, want)
|
||||
}
|
||||
if objects.removed != 0 {
|
||||
t.Fatal("metadata repair removed original")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestDependencyFailureNeverDeletes(t *testing.T) {
|
||||
repo := &fixtureRepo{rows: map[uuid.UUID]model.Attachment{}, failure: model.ErrUnavailable}
|
||||
objects := &fixtureObjects{items: map[string]port.Object{}}
|
||||
_, e := NewReconciler(repo, objects, func() time.Time { return fixedNow }).Run(context.Background(), uuid.Nil, "", time.Minute, true)
|
||||
if !errors.Is(e, model.ErrUnavailable) {
|
||||
t.Fatalf("expected dependency error, got %v", e)
|
||||
}
|
||||
if objects.removed != 0 {
|
||||
t.Fatal("deleted during failed inventory")
|
||||
}
|
||||
}
|
||||
func TestFailureDoesNotReturnCursorPastFailedRecord(t *testing.T) {
|
||||
id := uuid.New()
|
||||
repo := &fixtureRepo{rows: map[uuid.UUID]model.Attachment{id: {ID: id, Status: "ready", CreatedAt: fixedNow.Add(-2 * time.Minute)}}, more: true}
|
||||
objects := &fixtureObjects{failure: model.ErrUnavailable}
|
||||
report, err := NewReconciler(repo, objects, func() time.Time { return fixedNow }).Run(context.Background(), uuid.Nil, "", time.Minute, true)
|
||||
if !errors.Is(err, model.ErrUnavailable) {
|
||||
t.Fatalf("expected failure, got %v", err)
|
||||
}
|
||||
if report.NextMetadata != "" || report.NextObject != "" {
|
||||
t.Fatal("failed inventory must restart rather than skip the failed item")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user