Files
mtusi2026lab4-implementation/internal/reconcile/reconcile.go
T

108 lines
2.9 KiB
Go

package reconcile
import (
"sort"
"strings"
"time"
"uuid"
)
type Object struct {
Key string
Size int64
LastModified time.Time
}
type Metadata struct {
ID uuid.UUID
ObjectKey string
ChatID uuid.UUID
CreatedAt time.Time
}
type Orphan struct {
Key string `json:"key"`
SizeBytes int64 `json:"size_bytes"`
LastModified string `json:"last_modified"`
AgeSeconds int64 `json:"age_seconds"`
}
type Missing struct {
ID string `json:"id"`
ObjectKey string `json:"object_key"`
ChatID string `json:"chat_id"`
CreatedAt string `json:"created_at"`
Referenced bool `json:"referenced_by_message"`
}
type Report struct {
Prefix string `json:"prefix"`
GraceSeconds int64 `json:"grace_seconds"`
DryRun bool `json:"dry_run"`
ScannedObjects int `json:"scanned_objects"`
ScannedRows int `json:"scanned_rows"`
Truncated bool `json:"truncated"`
Orphans []Orphan `json:"orphans"`
Missing []Missing `json:"missing"`
DeletedObjects int `json:"deleted_objects"`
DeletedMetadata int `json:"deleted_metadata"`
RetainedMissing int `json:"retained_missing"`
DeleteFailures int `json:"delete_failures"`
S3Requests int64 `json:"s3_requests"`
DBQueries int `json:"db_queries"`
DurationMS int64 `json:"duration_ms"`
ObjectsPerSecond float64 `json:"objects_per_second"`
}
func Plan(objects []Object, rows []Metadata, referenced map[uuid.UUID]bool, prefix string, now time.Time, grace time.Duration) ([]Orphan, []Missing) {
known := make(map[string]struct{}, len(rows))
existing := make(map[string]struct{}, len(objects))
for _, row := range rows {
known[row.ObjectKey] = struct{}{}
}
for _, object := range objects {
existing[object.Key] = struct{}{}
}
orphans := make([]Orphan, 0)
for _, object := range objects {
if !strings.HasPrefix(object.Key, prefix) {
continue
}
if _, ok := known[object.Key]; ok {
continue
}
age := now.Sub(object.LastModified)
if age < grace {
continue
}
orphans = append(orphans, Orphan{
Key: object.Key,
SizeBytes: object.Size,
LastModified: object.LastModified.UTC().Format(time.RFC3339),
AgeSeconds: int64(age.Seconds()),
})
}
missing := make([]Missing, 0)
for _, row := range rows {
if !strings.HasPrefix(row.ObjectKey, prefix) {
continue
}
if _, ok := existing[row.ObjectKey]; ok {
continue
}
missing = append(missing, Missing{
ID: row.ID.String(),
ObjectKey: row.ObjectKey,
ChatID: row.ChatID.String(),
CreatedAt: row.CreatedAt.UTC().Format(time.RFC3339),
Referenced: referenced[row.ID],
})
}
sort.Slice(orphans, func(i, j int) bool { return orphans[i].Key < orphans[j].Key })
sort.Slice(missing, func(i, j int) bool { return missing[i].ObjectKey < missing[j].ObjectKey })
return orphans, missing
}