forked from mtusi2026/mtusi2026lab5
324 lines
7.9 KiB
Go
324 lines
7.9 KiB
Go
package reconcile
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log/slog"
|
|
"sort"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"mtusi2026-messenger/internal/db"
|
|
s3store "mtusi2026-messenger/internal/s3"
|
|
)
|
|
|
|
const (
|
|
Prefix = "chats/"
|
|
StagingPrefix = "staging/"
|
|
DefaultStagingRetention = 24 * time.Hour
|
|
DefaultGrace = time.Hour
|
|
DefaultMaxDeletes = 100
|
|
ErrorCodeObjectMissing = "object_missing"
|
|
)
|
|
|
|
type Options struct {
|
|
DryRun bool
|
|
Grace time.Duration
|
|
MaxDeletes int
|
|
StagingRetention time.Duration
|
|
}
|
|
|
|
type Report struct {
|
|
ScannedObjects int `json:"scanned_objects"`
|
|
ScannedRows int `json:"scanned_rows"`
|
|
ListPages int `json:"list_pages"`
|
|
StagingObjects []string `json:"staging_objects"`
|
|
OrphanObjects []string `json:"orphan_objects"`
|
|
MissingAttachments []uuid.UUID `json:"missing_attachments"`
|
|
CorruptObjects []string `json:"corrupt_objects"`
|
|
SkippedFresh int `json:"skipped_fresh"`
|
|
SkippedInactive int `json:"skipped_inactive"`
|
|
DeletedObjects int `json:"deleted_objects"`
|
|
MarkedFailed int `json:"marked_failed"`
|
|
DryRun bool `json:"dry_run"`
|
|
Errors []string `json:"errors"`
|
|
DurationMS int64 `json:"duration_ms"`
|
|
}
|
|
|
|
type ObjectClient interface {
|
|
ListAll(ctx context.Context, prefix string) (s3store.ListResult, error)
|
|
DeleteAdmin(ctx context.Context, key string) error
|
|
}
|
|
|
|
type txBeginner interface {
|
|
Begin(ctx context.Context) (pgx.Tx, error)
|
|
}
|
|
|
|
type AttachmentQueries interface {
|
|
LockAttachmentByStagingKey(ctx context.Context, stagingKey string) (db.Attachment, error)
|
|
ClearAttachmentStagingKey(ctx context.Context, id uuid.UUID) error
|
|
ListAttachmentsForReconcile(ctx context.Context) ([]db.ListAttachmentsForReconcileRow, error)
|
|
MarkAttachmentFailedIfReady(ctx context.Context, arg db.MarkAttachmentFailedIfReadyParams) (int64, error)
|
|
}
|
|
|
|
type Reconciler struct {
|
|
pool txBeginner
|
|
q AttachmentQueries
|
|
withTx func(pgx.Tx) AttachmentQueries
|
|
store ObjectClient
|
|
log *slog.Logger
|
|
now func() time.Time
|
|
}
|
|
|
|
type plan struct {
|
|
orphans []s3store.ObjectInfo
|
|
staging []s3store.ObjectInfo
|
|
missing []db.ListAttachmentsForReconcileRow
|
|
corrupt []s3store.ObjectInfo
|
|
skippedFresh int
|
|
skippedInactive int
|
|
}
|
|
|
|
func New(
|
|
pool *pgxpool.Pool,
|
|
store ObjectClient,
|
|
queries *db.Queries,
|
|
log *slog.Logger,
|
|
) *Reconciler {
|
|
if log == nil {
|
|
log = slog.Default()
|
|
}
|
|
|
|
return &Reconciler{
|
|
pool: pool,
|
|
withTx: func(tx pgx.Tx) AttachmentQueries {
|
|
return queries.WithTx(tx)
|
|
},
|
|
store: store,
|
|
q: queries,
|
|
log: log,
|
|
now: time.Now,
|
|
}
|
|
}
|
|
|
|
func (r *Reconciler) Run(ctx context.Context, opts Options) (Report, error) {
|
|
opts = opts.withDefaults()
|
|
started := r.now()
|
|
|
|
report := Report{
|
|
OrphanObjects: []string{},
|
|
StagingObjects: []string{},
|
|
MissingAttachments: []uuid.UUID{},
|
|
CorruptObjects: []string{},
|
|
DryRun: opts.DryRun,
|
|
Errors: []string{},
|
|
}
|
|
|
|
listed, err := r.store.ListAll(ctx, Prefix)
|
|
if err != nil {
|
|
return report, err
|
|
}
|
|
|
|
staging, err := r.store.ListAll(ctx, StagingPrefix)
|
|
if err != nil {
|
|
return report, err
|
|
}
|
|
|
|
rows, err := r.q.ListAttachmentsForReconcile(ctx)
|
|
if err != nil {
|
|
return report, err
|
|
}
|
|
|
|
report.ScannedObjects = len(listed.Objects) + len(staging.Objects)
|
|
report.ScannedRows = len(rows)
|
|
report.ListPages = listed.Pages + staging.Pages
|
|
|
|
p := buildPlan(listed.Objects, staging.Objects, rows, started, opts)
|
|
|
|
for _, obj := range p.orphans {
|
|
report.OrphanObjects = append(report.OrphanObjects, obj.Key)
|
|
}
|
|
for _, obj := range p.staging {
|
|
report.StagingObjects = append(report.StagingObjects, obj.Key)
|
|
}
|
|
for _, obj := range p.corrupt {
|
|
report.CorruptObjects = append(report.CorruptObjects, obj.Key)
|
|
}
|
|
for _, row := range p.missing {
|
|
report.MissingAttachments = append(report.MissingAttachments, row.ID)
|
|
}
|
|
|
|
report.SkippedFresh = p.skippedFresh
|
|
report.SkippedInactive = p.skippedInactive
|
|
|
|
if !opts.DryRun {
|
|
r.apply(ctx, opts, p, &report)
|
|
}
|
|
|
|
report.DurationMS = r.now().Sub(started).Milliseconds()
|
|
|
|
r.log.Info(
|
|
"attachment reconcile finished",
|
|
"dry_run", opts.DryRun,
|
|
"scanned_objects", report.ScannedObjects,
|
|
"scanned_rows", report.ScannedRows,
|
|
"list_pages", report.ListPages,
|
|
"orphan_objects", len(report.OrphanObjects),
|
|
"staging_objects", len(report.StagingObjects),
|
|
"missing_attachments", len(report.MissingAttachments),
|
|
"corrupt_objects", len(report.CorruptObjects),
|
|
"deleted_objects", report.DeletedObjects,
|
|
"marked_failed", report.MarkedFailed,
|
|
"errors", len(report.Errors),
|
|
)
|
|
|
|
return report, nil
|
|
}
|
|
|
|
func (o Options) withDefaults() Options {
|
|
if o.Grace <= 0 {
|
|
o.Grace = DefaultGrace
|
|
}
|
|
if o.MaxDeletes <= 0 {
|
|
o.MaxDeletes = DefaultMaxDeletes
|
|
}
|
|
|
|
if o.StagingRetention <= 0 {
|
|
o.StagingRetention = DefaultStagingRetention
|
|
}
|
|
|
|
return o
|
|
}
|
|
|
|
func buildPlan(
|
|
objects []s3store.ObjectInfo,
|
|
staging []s3store.ObjectInfo,
|
|
rows []db.ListAttachmentsForReconcileRow,
|
|
now time.Time,
|
|
opts Options,
|
|
) plan {
|
|
var p plan
|
|
|
|
byKey := make(map[string]s3store.ObjectInfo, len(objects))
|
|
for _, obj := range objects {
|
|
byKey[obj.Key] = obj
|
|
}
|
|
|
|
byStagingKey := make(map[string]db.ListAttachmentsForReconcileRow, len(rows))
|
|
for _, row := range rows {
|
|
if row.StagingKey != nil {
|
|
byStagingKey[*row.StagingKey] = row
|
|
}
|
|
|
|
obj, exists := byKey[row.S3Key]
|
|
if exists {
|
|
delete(byKey, row.S3Key)
|
|
}
|
|
|
|
switch row.Status {
|
|
case db.AttachmentStatusQueued:
|
|
p.skippedInactive++
|
|
case db.AttachmentStatusReady:
|
|
if !exists {
|
|
p.missing = append(p.missing, row)
|
|
continue
|
|
}
|
|
if obj.Size != int64(row.SizeBytes) {
|
|
p.corrupt = append(p.corrupt, obj)
|
|
}
|
|
default:
|
|
if exists {
|
|
p.skippedInactive++
|
|
}
|
|
}
|
|
}
|
|
|
|
for _, obj := range byKey {
|
|
if now.Sub(obj.LastModified) < opts.Grace {
|
|
p.skippedFresh++
|
|
continue
|
|
}
|
|
p.orphans = append(p.orphans, obj)
|
|
}
|
|
|
|
for _, obj := range staging {
|
|
retainedSince := obj.LastModified
|
|
if row, exists := byStagingKey[obj.Key]; exists {
|
|
if row.Status != db.AttachmentStatusReady && row.Status != db.AttachmentStatusFailed {
|
|
p.skippedInactive++
|
|
continue
|
|
}
|
|
|
|
retainedSince = row.UpdatedAt
|
|
}
|
|
|
|
if now.Sub(retainedSince) < opts.StagingRetention {
|
|
p.skippedFresh++
|
|
continue
|
|
}
|
|
|
|
p.staging = append(p.staging, obj)
|
|
}
|
|
|
|
sort.Slice(p.staging, func(i, j int) bool {
|
|
return p.staging[i].Key < p.staging[j].Key
|
|
})
|
|
sort.Slice(p.orphans, func(i, j int) bool {
|
|
return p.orphans[i].Key < p.orphans[j].Key
|
|
})
|
|
sort.Slice(p.corrupt, func(i, j int) bool {
|
|
return p.corrupt[i].Key < p.corrupt[j].Key
|
|
})
|
|
sort.Slice(p.missing, func(i, j int) bool {
|
|
return p.missing[i].ID.String() < p.missing[j].ID.String()
|
|
})
|
|
|
|
return p
|
|
}
|
|
|
|
func (r *Reconciler) apply(ctx context.Context, opts Options, p plan, report *Report) {
|
|
deletes := 0
|
|
|
|
for _, obj := range p.orphans {
|
|
if deletes >= opts.MaxDeletes {
|
|
report.Errors = append(report.Errors, "max deletes reached")
|
|
break
|
|
}
|
|
|
|
if err := r.store.DeleteAdmin(ctx, obj.Key); err != nil {
|
|
report.Errors = append(report.Errors, fmt.Sprintf("delete object %s: %v", obj.Key, err))
|
|
continue
|
|
}
|
|
|
|
deletes++
|
|
report.DeletedObjects++
|
|
}
|
|
|
|
for _, row := range p.missing {
|
|
marked, err := r.q.MarkAttachmentFailedIfReady(ctx, db.MarkAttachmentFailedIfReadyParams{
|
|
ID: row.ID,
|
|
ErrorCode: ErrorCodeObjectMissing,
|
|
})
|
|
if err != nil {
|
|
report.Errors = append(report.Errors, fmt.Sprintf("mark failed %s: %v", row.ID, err))
|
|
continue
|
|
}
|
|
|
|
report.MarkedFailed += int(marked)
|
|
}
|
|
|
|
for _, obj := range p.staging {
|
|
if report.DeletedObjects >= opts.MaxDeletes {
|
|
report.Errors = append(report.Errors, "max deletes reached")
|
|
break
|
|
}
|
|
|
|
if err := r.cleanupStagingObject(ctx, obj, opts, report); err != nil {
|
|
report.Errors = append(report.Errors, fmt.Sprintf("cleanup staging %s: %v", obj.Key, err))
|
|
}
|
|
}
|
|
}
|