Files
mtusi2026lab4/internal/attachment/reconcile.go
T
2026-10-28 22:41:10 +03:00

223 lines
6.7 KiB
Go

package attachment
import (
"context"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/minio/minio-go/v7"
)
type Summary struct {
Apply bool `json:"apply"`
GraceSeconds float64 `json:"grace_seconds"`
ObjectsScanned int `json:"objects_scanned"`
MetadataScanned int `json:"metadata_scanned"`
BytesScanned int64 `json:"bytes_scanned"`
ListRequestsEstimate int `json:"list_requests_estimate"`
StatRequests int `json:"stat_requests"`
DBQueries int `json:"db_queries"`
Orphans int `json:"orphans"`
Missing int `json:"missing"`
FreshSkipped int `json:"fresh_skipped"`
LockedSkipped int `json:"locked_skipped"`
ReferencedMissing int `json:"referenced_missing"`
Deleted int `json:"deleted"`
MarkedFailed int `json:"marked_failed"`
DurationMS int64 `json:"duration_ms"`
Actions []Action `json:"actions"`
}
type Action struct {
Kind string `json:"kind"`
Key string `json:"key"`
Applied bool `json:"applied"`
}
// Reconcile scans a fixed cutoff and rechecks each candidate while holding the
// same transaction-scoped advisory lock as upload. Metadata, including message
// references, is never deleted. Missing originals become failed tombstones.
func (s *Service) Reconcile(ctx context.Context, apply bool, grace time.Duration) (result Summary, err error) {
started := time.Now()
result = Summary{Apply: apply, GraceSeconds: grace.Seconds(), Actions: []Action{}}
defer func() { result.DurationMS = time.Since(started).Milliseconds() }()
if grace < MinimumGrace {
return result, fmt.Errorf("grace must be at least %s (upload timeout %s)", MinimumGrace, UploadTimeout)
}
cutoff := started.Add(-grace)
for obj := range s.Store.Client.ListObjects(ctx, s.Store.Bucket, minio.ListObjectsOptions{Prefix: "original/", Recursive: true, MaxKeys: 1000}) {
if obj.Err != nil {
return result, fmt.Errorf("S3 listing failed")
}
result.ObjectsScanned++
result.BytesScanned += obj.Size
if result.ObjectsScanned%1000 == 1 {
result.ListRequestsEstimate++
}
if !obj.LastModified.Before(cutoff) {
result.FreshSkipped++
continue
}
err = s.reconcileObject(ctx, obj.Key, cutoff, apply, &result)
if err != nil {
return result, err
}
}
// Bounded keyset pages avoid retaining the entire bucket or a DB cursor while
// making per-object transactions. A later run picks up concurrent new rows.
last := "00000000-0000-0000-0000-000000000000"
for {
result.DBQueries++
rows, e := s.Pool.Query(ctx, `SELECT id::text,object_key,created_at,status FROM attachments WHERE id>$1 ORDER BY id LIMIT 100`, last)
if e != nil {
return result, fmt.Errorf("metadata scan failed")
}
type metadata struct {
id, key, status string
created time.Time
}
page := []metadata{}
for rows.Next() {
var m metadata
if e = rows.Scan(&m.id, &m.key, &m.created, &m.status); e != nil {
rows.Close()
return result, e
}
page = append(page, m)
}
e = rows.Err()
rows.Close()
if e != nil {
return result, e
}
if len(page) == 0 {
break
}
for _, m := range page {
last = m.id
result.MetadataScanned++
if m.status != "ready" {
continue
}
if !m.created.Before(cutoff) {
result.FreshSkipped++
continue
}
if e = s.reconcileMetadata(ctx, m.id, m.key, cutoff, apply, &result); e != nil {
return result, e
}
}
}
if ctx.Err() != nil {
return result, ctx.Err()
}
return result, nil
}
func (s *Service) locked(ctx context.Context, key string, r *Summary) (pgx.Tx, bool, error) {
tx, err := s.Pool.Begin(ctx)
if err != nil {
return nil, false, fmt.Errorf("DB unavailable")
}
var locked bool
r.DBQueries++
if err = tx.QueryRow(ctx, `SELECT pg_try_advisory_xact_lock(hashtextextended($1,0))`, key).Scan(&locked); err != nil {
tx.Rollback(context.Background())
return nil, false, fmt.Errorf("lock failed")
}
if !locked {
r.LockedSkipped++
tx.Rollback(context.Background())
return nil, false, nil
}
return tx, true, nil
}
func (s *Service) reconcileObject(ctx context.Context, key string, cutoff time.Time, apply bool, r *Summary) error {
tx, ok, err := s.locked(ctx, key, r)
if err != nil || !ok {
return err
}
defer tx.Rollback(context.Background())
var exists bool
r.DBQueries++
if err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM attachments WHERE object_key=$1)`, key).Scan(&exists); err != nil {
return fmt.Errorf("metadata recheck failed")
}
if exists {
return nil
}
r.StatRequests++
obj, err := s.Store.Client.StatObject(ctx, s.Store.Bucket, key, minio.StatObjectOptions{})
if IsMissing(err) {
return nil
}
if err != nil {
return fmt.Errorf("object recheck failed")
}
if !obj.LastModified.Before(cutoff) {
r.FreshSkipped++
return nil
}
r.Orphans++
if apply {
if err = s.Store.Client.RemoveObject(ctx, s.Store.Bucket, key, minio.RemoveObjectOptions{}); err != nil {
return fmt.Errorf("orphan deletion failed")
}
r.Deleted++
}
if len(r.Actions) < 100 {
r.Actions = append(r.Actions, Action{Kind: "orphan", Key: key, Applied: apply})
}
return nil
}
func (s *Service) reconcileMetadata(ctx context.Context, id, key string, cutoff time.Time, apply bool, r *Summary) error {
tx, ok, err := s.locked(ctx, key, r)
if err != nil || !ok {
return err
}
defer tx.Rollback(context.Background())
var created time.Time
var status string
r.DBQueries++
err = tx.QueryRow(ctx, `SELECT created_at,status FROM attachments WHERE id=$1 FOR UPDATE`, id).Scan(&created, &status)
if err == pgx.ErrNoRows {
return nil
}
if err != nil {
return fmt.Errorf("metadata recheck failed")
}
if status != "ready" || !created.Before(cutoff) {
return nil
}
r.StatRequests++
_, err = s.Store.Client.StatObject(ctx, s.Store.Bucket, key, minio.StatObjectOptions{})
if err == nil {
return nil
}
if !IsMissing(err) {
return fmt.Errorf("object stat failed (no mutation)")
}
var referenced bool
r.DBQueries++
if err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM messages WHERE $1::uuid=ANY(attachment_ids))`, id).Scan(&referenced); err != nil {
return fmt.Errorf("reference check failed")
}
r.Missing++
if referenced {
r.ReferencedMissing++
}
if apply {
r.DBQueries++
if _, err = tx.Exec(ctx, `UPDATE attachments SET status='failed',error_code='original_missing' WHERE id=$1 AND status='ready'`, id); err != nil {
return fmt.Errorf("mark missing failed")
}
if err = tx.Commit(ctx); err != nil {
return fmt.Errorf("commit missing failed")
}
r.MarkedFailed++
}
if len(r.Actions) < 100 {
r.Actions = append(r.Actions, Action{Kind: "missing", Key: key, Applied: apply})
}
return nil
}