forked from mtusi2026/mtusi2026lab4
310 lines
8.5 KiB
Go
310 lines
8.5 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"os"
|
|
"os/signal"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"github.com/minio/minio-go/v7"
|
|
)
|
|
|
|
type reconcileReport struct {
|
|
Apply bool `json:"apply"`
|
|
GraceSeconds int `json:"grace_seconds"`
|
|
Cutoff string `json:"cutoff"`
|
|
Objects int `json:"objects_scanned"`
|
|
Rows int `json:"metadata_scanned"`
|
|
Orphans int `json:"old_orphans"`
|
|
Fresh int `json:"fresh_protected"`
|
|
Used int `json:"metadata_protected"`
|
|
Busy int `json:"active_protected"`
|
|
Missing int `json:"missing"`
|
|
Recovered int `json:"recovered"`
|
|
Deleted int `json:"deleted"`
|
|
Marked int `json:"marked_unavailable"`
|
|
Cleared int `json:"cleared_unavailable"`
|
|
HeadRequests int `json:"head_requests"`
|
|
GetRequests int `json:"get_requests"`
|
|
VerifiedBytes int64 `json:"verified_bytes"`
|
|
ElapsedMS int64 `json:"elapsed_ms"`
|
|
Complete bool `json:"complete"`
|
|
}
|
|
|
|
func absentObject(err error) bool {
|
|
e := minio.ToErrorResponse(err)
|
|
return e.Code == "NoSuchKey" || e.Code == "NoSuchObject" || (e.StatusCode == 404 && e.Code == "NotFound")
|
|
}
|
|
|
|
// Same per-key lock as upload/message creation. Re-check PostgreSQL and HEAD
|
|
// after locking; a stale LIST snapshot can never authorize a deletion alone.
|
|
func (a *App) reconcileObject(ctx context.Context, key string, cutoff time.Time, apply bool, r *reconcileReport) error {
|
|
id := strings.TrimPrefix(key, "original/")
|
|
normalized, err := normalizeID(id)
|
|
if err != nil || id != normalized || key != "original/"+id {
|
|
return nil
|
|
}
|
|
tx, err := a.db.Begin(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer rollbackAttachment(tx)
|
|
var locked bool
|
|
if err = tx.QueryRow(ctx, "SELECT pg_try_advisory_xact_lock(hashtextextended($1,0))", "attachment:"+id).Scan(&locked); err != nil {
|
|
return err
|
|
}
|
|
if !locked {
|
|
r.Busy++
|
|
return nil
|
|
}
|
|
var exists bool
|
|
if err = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM attachments WHERE object_key=$1)", key).Scan(&exists); err != nil {
|
|
return err
|
|
}
|
|
if exists {
|
|
r.Used++
|
|
return nil
|
|
}
|
|
r.HeadRequests++
|
|
info, err := a.s3.StatObject(ctx, a.bucket, key, minio.StatObjectOptions{})
|
|
if absentObject(err) {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !info.LastModified.Before(cutoff) {
|
|
r.Fresh++
|
|
return nil
|
|
}
|
|
r.Orphans++
|
|
if apply {
|
|
if err = a.s3.RemoveObject(ctx, a.bucket, key, minio.RemoveObjectOptions{}); err != nil {
|
|
return err
|
|
}
|
|
r.Deleted++
|
|
}
|
|
return tx.Commit(ctx)
|
|
}
|
|
|
|
type attachmentRecord struct {
|
|
id, key, checksum string
|
|
size int64
|
|
created time.Time
|
|
missing *time.Time
|
|
}
|
|
|
|
func (a *App) reconcileMetadata(ctx context.Context, row attachmentRecord, cutoff time.Time, apply bool, r *reconcileReport) error {
|
|
tx, err := a.db.Begin(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer rollbackAttachment(tx)
|
|
var locked bool
|
|
if err = tx.QueryRow(ctx, "SELECT pg_try_advisory_xact_lock(hashtextextended($1,0))", "attachment:"+row.id).Scan(&locked); err != nil {
|
|
return err
|
|
}
|
|
if !locked {
|
|
r.Busy++
|
|
return nil
|
|
}
|
|
// Refresh after acquiring the lock, rather than acting on the page snapshot.
|
|
err = tx.QueryRow(ctx, "SELECT object_key,sha256,size_bytes,created_at,missing_since FROM attachments WHERE id=$1", row.id).Scan(&row.key, &row.checksum, &row.size, &row.created, &row.missing)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !row.created.Before(cutoff) {
|
|
r.Fresh++
|
|
return nil
|
|
}
|
|
r.HeadRequests++
|
|
info, err := a.s3.StatObject(ctx, a.bucket, row.key, minio.StatObjectOptions{})
|
|
if err != nil && !absentObject(err) {
|
|
return err
|
|
}
|
|
if absentObject(err) {
|
|
r.Missing++
|
|
// Keep metadata and message references: lost bytes cannot be reconstructed.
|
|
if apply && row.missing == nil {
|
|
if _, err = tx.Exec(ctx, "UPDATE attachments SET missing_since=clock_timestamp(),updated_at=clock_timestamp() WHERE id=$1", row.id); err != nil {
|
|
return err
|
|
}
|
|
r.Marked++
|
|
}
|
|
} else if row.missing != nil {
|
|
if info.Size != row.size {
|
|
return fmt.Errorf("restored object has wrong size")
|
|
}
|
|
object, e := a.s3.GetObject(ctx, a.bucket, row.key, minio.GetObjectOptions{})
|
|
if e != nil {
|
|
return e
|
|
}
|
|
r.GetRequests++
|
|
hash := sha256.New()
|
|
n, e := io.Copy(hash, io.LimitReader(object, row.size+1))
|
|
object.Close()
|
|
r.VerifiedBytes += n
|
|
if e != nil {
|
|
return e
|
|
}
|
|
if n != row.size || hex.EncodeToString(hash.Sum(nil)) != row.checksum {
|
|
return fmt.Errorf("restored object has wrong checksum")
|
|
}
|
|
r.Recovered++
|
|
if apply {
|
|
if _, err = tx.Exec(ctx, "UPDATE attachments SET missing_since=NULL,updated_at=clock_timestamp() WHERE id=$1", row.id); err != nil {
|
|
return err
|
|
}
|
|
r.Cleared++
|
|
}
|
|
} else if info.Size != row.size {
|
|
return fmt.Errorf("stored object has wrong size")
|
|
}
|
|
return tx.Commit(ctx)
|
|
}
|
|
|
|
func (a *App) reconcile(ctx context.Context, apply bool, grace int) (reconcileReport, error) {
|
|
started := time.Now()
|
|
r := reconcileReport{Apply: apply, GraceSeconds: grace}
|
|
var now time.Time
|
|
if err := a.db.QueryRow(ctx, "SELECT clock_timestamp()").Scan(&now); err != nil {
|
|
return r, err
|
|
}
|
|
cutoff := now.Add(-time.Duration(grace) * time.Second)
|
|
r.Cutoff = stamp(cutoff)
|
|
listing, cancel := context.WithCancel(ctx)
|
|
defer cancel()
|
|
for object := range a.s3.ListObjects(listing, a.bucket, minio.ListObjectsOptions{Prefix: "original/", Recursive: true, MaxKeys: 1000}) {
|
|
if object.Err != nil {
|
|
return r, object.Err
|
|
}
|
|
r.Objects++
|
|
itemCtx, done := context.WithTimeout(ctx, 15*time.Second)
|
|
err := a.reconcileObject(itemCtx, object.Key, cutoff, apply, &r)
|
|
done()
|
|
if err != nil {
|
|
return r, err
|
|
}
|
|
}
|
|
last := "00000000-0000-0000-0000-000000000000"
|
|
for {
|
|
rows, err := a.db.Query(ctx, "SELECT id::text FROM attachments WHERE id>$1 ORDER BY id LIMIT 256", last)
|
|
if err != nil {
|
|
return r, err
|
|
}
|
|
page := []attachmentRecord{}
|
|
for rows.Next() {
|
|
var x attachmentRecord
|
|
if err = rows.Scan(&x.id); err != nil {
|
|
rows.Close()
|
|
return r, err
|
|
}
|
|
page = append(page, x)
|
|
}
|
|
err = rows.Err()
|
|
rows.Close()
|
|
if err != nil {
|
|
return r, err
|
|
}
|
|
for _, x := range page {
|
|
r.Rows++
|
|
last = x.id
|
|
itemCtx, done := context.WithTimeout(ctx, 15*time.Second)
|
|
err = a.reconcileMetadata(itemCtx, x, cutoff, apply, &r)
|
|
done()
|
|
if err != nil {
|
|
return r, err
|
|
}
|
|
}
|
|
if len(page) < 256 {
|
|
break
|
|
}
|
|
}
|
|
r.ElapsedMS = time.Since(started).Milliseconds()
|
|
r.Complete = true
|
|
return r, nil
|
|
}
|
|
|
|
func runReconcile() error {
|
|
return reconcileCommand(context.Background(), os.Args[2:])
|
|
}
|
|
|
|
func reconcileCommand(parent context.Context, args []string) error {
|
|
flags := flag.NewFlagSet("reconcile", flag.ContinueOnError)
|
|
apply := flags.Bool("apply", false, "apply changes (default is read-only dry-run)")
|
|
grace := flags.Int("grace-seconds", 3600, "minimum object/metadata age, at least 60 seconds")
|
|
if err := flags.Parse(args); err != nil {
|
|
return err
|
|
}
|
|
if *grace < 60 || flags.NArg() != 0 {
|
|
return errors.New("grace must be >=60 seconds; no positional arguments")
|
|
}
|
|
uri, err := secretFile("DATABASE_URL_FILE")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
cfg, err := pgxpool.ParseConfig(uri)
|
|
if err != nil {
|
|
return errors.New("invalid database configuration")
|
|
}
|
|
cfg.MaxConns = 2
|
|
cfg.ConnConfig.ConnectTimeout = 2 * time.Second
|
|
cfg.ConnConfig.RuntimeParams["statement_timeout"] = "5000"
|
|
cfg.ConnConfig.RuntimeParams["lock_timeout"] = "1000"
|
|
ctx, cancel := context.WithTimeout(parent, 10*time.Minute)
|
|
defer cancel()
|
|
db, err := pgxpool.NewWithConfig(ctx, cfg)
|
|
if err != nil {
|
|
return errors.New("database setup failed")
|
|
}
|
|
defer db.Close()
|
|
s3, bucket, err := s3Client()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
a := App{db: db, s3: s3, bucket: bucket}
|
|
report, err := a.reconcile(ctx, *apply, *grace)
|
|
if e := json.NewEncoder(os.Stdout).Encode(report); e != nil {
|
|
return e
|
|
}
|
|
if err != nil {
|
|
return errors.New("reconciliation interrupted; inspect dependencies and rerun (no missing inference on network errors)")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func reconcileLoop() error {
|
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
|
defer stop()
|
|
for {
|
|
// Each bounded scan closes its resources and emits aggregate statistics.
|
|
// The background cleanup uses a one-hour grace period.
|
|
err := reconcileCommand(ctx, []string{"--apply"})
|
|
if err != nil {
|
|
slog.Warn("reconciliation failed; will retry")
|
|
}
|
|
timer := time.NewTimer(15 * time.Minute)
|
|
select {
|
|
case <-ctx.Done():
|
|
timer.Stop()
|
|
return nil
|
|
case <-timer.C:
|
|
}
|
|
}
|
|
}
|