Files

167 lines
4.1 KiB
Go

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
}