forked from mtusi2026/mtusi2026lab5
61 lines
1.1 KiB
Go
61 lines
1.1 KiB
Go
package reconcile
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
"mtusi2026-messenger/internal/db"
|
|
s3store "mtusi2026-messenger/internal/s3"
|
|
)
|
|
|
|
func (r *Reconciler) cleanupStagingObject(
|
|
ctx context.Context,
|
|
obj s3store.ObjectInfo,
|
|
opts Options,
|
|
report *Report,
|
|
) error {
|
|
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
defer cancel()
|
|
|
|
tx, err := r.pool.Begin(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback(context.Background())
|
|
|
|
q := r.withTx(tx)
|
|
row, err := q.LockAttachmentByStagingKey(ctx, obj.Key)
|
|
orphan := errors.Is(err, pgx.ErrNoRows)
|
|
if err != nil && !orphan {
|
|
return err
|
|
}
|
|
|
|
if !orphan {
|
|
if row.Status != db.AttachmentStatusReady && row.Status != db.AttachmentStatusFailed {
|
|
report.SkippedInactive++
|
|
return nil
|
|
}
|
|
|
|
if r.now().Sub(row.UpdatedAt) < opts.StagingRetention {
|
|
report.SkippedFresh++
|
|
return nil
|
|
}
|
|
}
|
|
|
|
if err := r.store.DeleteAdmin(ctx, obj.Key); err != nil {
|
|
return err
|
|
}
|
|
report.DeletedObjects++
|
|
|
|
if !orphan {
|
|
if err := q.ClearAttachmentStagingKey(ctx, row.ID); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
return tx.Commit(ctx)
|
|
}
|