Implement lab4 private S3 attachments, safe reconciliation and defense guide
This commit is contained in:
@@ -0,0 +1,158 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/minio/minio-go/v7"
|
||||
)
|
||||
|
||||
type ReconcileResult struct {
|
||||
DryRun bool `json:"dry_run"`
|
||||
GraceSeconds int `json:"grace_seconds"`
|
||||
Scanned int `json:"scanned"`
|
||||
Orphans int `json:"orphans"`
|
||||
Missing int `json:"missing"`
|
||||
StaleIntents int `json:"stale_intents"`
|
||||
Fresh int `json:"fresh_protected"`
|
||||
Referenced int `json:"referenced_protected"`
|
||||
DeletedObjects int `json:"deleted_objects"`
|
||||
DeletedMetadata int `json:"deleted_metadata"`
|
||||
ClearedIntents int `json:"cleared_intents"`
|
||||
DurationMS int64 `json:"duration_ms"`
|
||||
}
|
||||
|
||||
func Reconcile(db *pgxpool.Pool, o *ObjectStore, args []string) error {
|
||||
flags := flag.NewFlagSet("reconcile", flag.ContinueOnError)
|
||||
apply := flags.Bool("apply", false, "apply safe deletions; default dry-run")
|
||||
grace := flags.Int("grace-seconds", 3600, "minimum age (>=60s, greater than upload deadline)")
|
||||
if e := flags.Parse(args); e != nil {
|
||||
return e
|
||||
}
|
||||
if *grace < 60 {
|
||||
return fmt.Errorf("grace must be at least 60 seconds")
|
||||
}
|
||||
start := time.Now()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
|
||||
defer cancel()
|
||||
result := ReconcileResult{DryRun: !*apply, GraceSeconds: *grace}
|
||||
// Snapshot is only an inventory. Every candidate is rechecked under the SAME
|
||||
// per-object transaction lock as upload; current rows and HEAD decide removal.
|
||||
keys := map[string]bool{}
|
||||
for object := range o.Client.ListObjects(ctx, o.Bucket, minio.ListObjectsOptions{Prefix: "originals/", Recursive: true}) {
|
||||
if object.Err != nil {
|
||||
return fmt.Errorf("S3 list failed")
|
||||
}
|
||||
keys[object.Key] = true
|
||||
}
|
||||
rows, e := db.Query(ctx, "SELECT object_key FROM attachments UNION SELECT object_key FROM upload_intents")
|
||||
if e != nil {
|
||||
return fmt.Errorf("inventory failed")
|
||||
}
|
||||
for rows.Next() {
|
||||
var key string
|
||||
if e = rows.Scan(&key); e != nil {
|
||||
rows.Close()
|
||||
return e
|
||||
}
|
||||
keys[key] = true
|
||||
}
|
||||
e = rows.Err()
|
||||
rows.Close()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
for key := range keys {
|
||||
result.Scanned++
|
||||
tx, e := db.Begin(ctx)
|
||||
if e != nil {
|
||||
return fmt.Errorf("reconcile transaction failed")
|
||||
}
|
||||
err := func() error {
|
||||
defer tx.Rollback(context.Background())
|
||||
if _, e = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1,4))", key); e != nil {
|
||||
return e
|
||||
}
|
||||
var id string
|
||||
var metadataTime time.Time
|
||||
// Lock against concurrent message attachment linkage/deletion.
|
||||
rows, e := tx.Query(ctx, "SELECT id::text,created_at FROM attachments WHERE object_key=$1 FOR UPDATE", key)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
hasMetadata := rows.Next()
|
||||
if hasMetadata {
|
||||
e = rows.Scan(&id, &metadataTime)
|
||||
}
|
||||
rows.Close()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
var intentAge bool
|
||||
if e = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM upload_intents WHERE object_key=$1 AND created_at<=clock_timestamp()-make_interval(secs=>$2))", key, *grace).Scan(&intentAge); e != nil {
|
||||
return e
|
||||
}
|
||||
var freshIntent bool
|
||||
if e = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM upload_intents WHERE object_key=$1 AND created_at>clock_timestamp()-make_interval(secs=>$2))", key, *grace).Scan(&freshIntent); e != nil {
|
||||
return e
|
||||
}
|
||||
info, headErr := o.Client.StatObject(ctx, o.Bucket, key, minio.StatObjectOptions{})
|
||||
exists := headErr == nil
|
||||
if headErr != nil {
|
||||
code := minio.ToErrorResponse(headErr).Code
|
||||
if code != "NoSuchKey" && code != "NoSuchObject" && code != "NotFound" {
|
||||
return fmt.Errorf("HEAD failed; no repair attempted")
|
||||
}
|
||||
}
|
||||
fresh := freshIntent || (exists && time.Since(info.LastModified) < time.Duration(*grace)*time.Second) || (hasMetadata && time.Since(metadataTime) < time.Duration(*grace)*time.Second)
|
||||
if fresh {
|
||||
result.Fresh++
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
if !hasMetadata && exists {
|
||||
result.Orphans++
|
||||
if *apply {
|
||||
if e = o.Client.RemoveObject(ctx, o.Bucket, key, minio.RemoveObjectOptions{}); e != nil {
|
||||
return e
|
||||
}
|
||||
result.DeletedObjects++
|
||||
}
|
||||
}
|
||||
if hasMetadata && !exists {
|
||||
result.Missing++
|
||||
var referenced bool
|
||||
if e = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM message_attachments WHERE attachment_id=$1)", id).Scan(&referenced); e != nil {
|
||||
return e
|
||||
}
|
||||
if referenced {
|
||||
result.Referenced++
|
||||
} else if *apply {
|
||||
if _, e = tx.Exec(ctx, "DELETE FROM attachments WHERE id=$1", id); e != nil {
|
||||
return e
|
||||
}
|
||||
result.DeletedMetadata++
|
||||
}
|
||||
}
|
||||
if intentAge {
|
||||
result.StaleIntents++
|
||||
if *apply {
|
||||
if _, e = tx.Exec(ctx, "DELETE FROM upload_intents WHERE object_key=$1", key); e != nil {
|
||||
return e
|
||||
}
|
||||
result.ClearedIntents++
|
||||
}
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}()
|
||||
if err != nil {
|
||||
return fmt.Errorf("reconcile failed safely: %w", err)
|
||||
}
|
||||
}
|
||||
result.DurationMS = time.Since(start).Milliseconds()
|
||||
return json.NewEncoder(os.Stdout).Encode(result)
|
||||
}
|
||||
Reference in New Issue
Block a user