forked from mtusi2026/mtusi2026lab4
ЛР4: S3-вложения, приватный bucket и согласованность хранилищ (трек 2)
This commit is contained in:
@@ -0,0 +1,357 @@
|
||||
// Command reconciler is the track-2 consistency tool for the two stores.
|
||||
//
|
||||
// It compares PostgreSQL attachment rows with the objects under the private
|
||||
// bucket prefix and reports:
|
||||
// - ready row + object -> ok
|
||||
// - ready row without object -> missing_object (report only: bytes
|
||||
// cannot be invented or safely replaced; the operator must restore them)
|
||||
// - pending row + object -> stale upload intent after the grace
|
||||
// period; the object and the row are both removed
|
||||
// - pending row without object -> stale upload intent; the row is removed
|
||||
// - object without a row -> orphan object; removed only after grace
|
||||
//
|
||||
// Fresh objects and rows are never touched: the grace period protects an
|
||||
// upload that is between its S3 PUT and its PostgreSQL COMMIT, and the
|
||||
// reconciler re-checks the database immediately before every delete.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"mtusi.ru/messenger-lab4/internal/config"
|
||||
"mtusi.ru/messenger-lab4/internal/objectstore"
|
||||
"mtusi.ru/messenger-lab4/internal/store"
|
||||
)
|
||||
|
||||
type item struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
ObjectKey string `json:"object_key"`
|
||||
Status string `json:"status,omitempty"`
|
||||
AgeSeconds int64 `json:"age_seconds"`
|
||||
ObjectPresent bool `json:"object_present,omitempty"`
|
||||
}
|
||||
|
||||
type report struct {
|
||||
GeneratedAt string `json:"generated_at"`
|
||||
Mode string `json:"mode"`
|
||||
Bucket string `json:"bucket"`
|
||||
Prefix string `json:"prefix"`
|
||||
GraceSeconds int64 `json:"grace_seconds"`
|
||||
Database dbCounts `json:"database"`
|
||||
ObjectStore s3Counts `json:"object_store"`
|
||||
Findings findings `json:"findings"`
|
||||
Actions actions `json:"actions"`
|
||||
Timing timing `json:"timing"`
|
||||
}
|
||||
|
||||
type dbCounts struct {
|
||||
Rows int `json:"rows"`
|
||||
Ready int `json:"ready"`
|
||||
Pending int `json:"pending"`
|
||||
}
|
||||
|
||||
type s3Counts struct {
|
||||
Objects int `json:"objects"`
|
||||
}
|
||||
|
||||
type findings struct {
|
||||
OK int `json:"ok"`
|
||||
OrphanObjects []item `json:"orphan_objects"`
|
||||
ProtectedObjects []item `json:"protected_recent_objects"`
|
||||
MissingObjects []item `json:"missing_objects"`
|
||||
StalePending []item `json:"stale_pending"`
|
||||
ProtectedPending []item `json:"protected_pending"`
|
||||
}
|
||||
|
||||
type actions struct {
|
||||
PlannedDeletes []string `json:"planned_deletes,omitempty"`
|
||||
DeletedObjects []string `json:"deleted_objects"`
|
||||
DeletedPendingRows []string `json:"deleted_pending_rows"`
|
||||
Skipped []string `json:"skipped"`
|
||||
UnresolvedMissing []string `json:"unresolved_missing"`
|
||||
Errors []string `json:"errors"`
|
||||
}
|
||||
|
||||
type timing struct {
|
||||
DBScanMS int64 `json:"db_scan_ms"`
|
||||
S3ListMS int64 `json:"s3_list_ms"`
|
||||
TotalMS int64 `json:"total_ms"`
|
||||
DBRows int `json:"db_rows"`
|
||||
S3Objects int `json:"s3_objects"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
apply := flag.Bool("apply", false, "perform safe deletions; without it the run is a read-only dry run")
|
||||
prefix := flag.String("prefix", "attachments/", "bucket prefix owned by the application")
|
||||
output := flag.String("output", "", "optional path for the JSON report")
|
||||
defaultGrace := time.Hour
|
||||
if raw := os.Getenv("RECONCILE_GRACE_SECONDS"); raw != "" {
|
||||
seconds, err := strconv.Atoi(raw)
|
||||
if err != nil || seconds < 1 {
|
||||
fmt.Fprintln(os.Stderr, "reconciler: RECONCILE_GRACE_SECONDS must be a positive integer")
|
||||
os.Exit(2)
|
||||
}
|
||||
defaultGrace = time.Duration(seconds) * time.Second
|
||||
}
|
||||
grace := flag.Duration("grace", defaultGrace, "minimum age before an orphan object or pending upload intent may be removed")
|
||||
flag.Parse()
|
||||
if *grace < time.Second {
|
||||
fmt.Fprintln(os.Stderr, "reconciler: -grace must be at least 1s")
|
||||
os.Exit(2)
|
||||
}
|
||||
if *prefix == "" || *prefix == "/" {
|
||||
fmt.Fprintln(os.Stderr, "reconciler: -prefix must be a non-empty application prefix")
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
cfg, err := config.LoadTool()
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "reconciler: configuration error:", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
repository, err := store.Open(context.Background(), cfg.DatabaseURL, store.Options{
|
||||
MaxConns: 4,
|
||||
MinConns: 0,
|
||||
ConnectTimeout: cfg.DBConnectTimeout,
|
||||
StatementTimeout: cfg.DBStatementTimeout,
|
||||
QueryTimeout: cfg.QueryTimeout,
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "reconciler: database configuration error:", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
defer repository.Close()
|
||||
objects, err := objectstore.Open(objectstore.Config{
|
||||
Endpoint: cfg.S3Endpoint,
|
||||
Region: cfg.S3Region,
|
||||
Bucket: cfg.S3Bucket,
|
||||
AccessKey: cfg.S3AccessKey,
|
||||
SecretKey: cfg.S3SecretKey,
|
||||
Timeout: cfg.S3Timeout,
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "reconciler: object store configuration error:", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
started := time.Now().UTC()
|
||||
result := report{
|
||||
GeneratedAt: started.Format(time.RFC3339Nano),
|
||||
Mode: "dry-run",
|
||||
Bucket: cfg.S3Bucket,
|
||||
Prefix: *prefix,
|
||||
GraceSeconds: int64(grace.Seconds()),
|
||||
}
|
||||
if *apply {
|
||||
result.Mode = "apply"
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
dbStarted := time.Now()
|
||||
rows, err := repository.ListAttachmentsForReconcile(ctx)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "reconciler: database scan failed:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
result.Timing.DBScanMS = time.Since(dbStarted).Milliseconds()
|
||||
result.Timing.DBRows = len(rows)
|
||||
result.Database.Rows = len(rows)
|
||||
|
||||
s3Started := time.Now()
|
||||
stored, err := objects.List(ctx, *prefix)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "reconciler: object store scan failed:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
result.Timing.S3ListMS = time.Since(s3Started).Milliseconds()
|
||||
result.Timing.S3Objects = len(stored)
|
||||
result.ObjectStore.Objects = len(stored)
|
||||
|
||||
now := time.Now().UTC()
|
||||
dbByKey := make(map[string]store.ReconcileAttachment, len(rows))
|
||||
for _, row := range rows {
|
||||
dbByKey[row.ObjectKey] = row
|
||||
switch row.Status {
|
||||
case "ready":
|
||||
result.Database.Ready++
|
||||
case "pending":
|
||||
result.Database.Pending++
|
||||
}
|
||||
}
|
||||
objectByKey := make(map[string]objectstore.ObjectInfo, len(stored))
|
||||
for _, object := range stored {
|
||||
objectByKey[object.Key] = object
|
||||
}
|
||||
|
||||
// Objects with no metadata row: candidate orphans, unless still fresh.
|
||||
for _, object := range stored {
|
||||
if _, known := dbByKey[object.Key]; known {
|
||||
continue
|
||||
}
|
||||
age := ageSeconds(now, object.LastModified)
|
||||
if object.LastModified.IsZero() || age < int64(grace.Seconds()) {
|
||||
result.Findings.ProtectedObjects = append(result.Findings.ProtectedObjects, item{
|
||||
ObjectKey: object.Key, AgeSeconds: age,
|
||||
})
|
||||
continue
|
||||
}
|
||||
result.Findings.OrphanObjects = append(result.Findings.OrphanObjects, item{
|
||||
ObjectKey: object.Key, AgeSeconds: age,
|
||||
})
|
||||
}
|
||||
|
||||
// Metadata rows: ready rows must have an object; pending rows are internal
|
||||
// upload intents and are cleaned only after the grace period.
|
||||
for _, row := range rows {
|
||||
_, exists := objectByKey[row.ObjectKey]
|
||||
age := ageSeconds(now, row.UpdatedAt)
|
||||
switch row.Status {
|
||||
case "ready":
|
||||
if exists {
|
||||
result.Findings.OK++
|
||||
} else {
|
||||
result.Findings.MissingObjects = append(result.Findings.MissingObjects, item{
|
||||
ID: row.ID, ObjectKey: row.ObjectKey, Status: row.Status, AgeSeconds: age,
|
||||
})
|
||||
}
|
||||
case "pending":
|
||||
if age >= int64(grace.Seconds()) {
|
||||
result.Findings.StalePending = append(result.Findings.StalePending, item{
|
||||
ID: row.ID, ObjectKey: row.ObjectKey, Status: row.Status,
|
||||
AgeSeconds: age, ObjectPresent: exists,
|
||||
})
|
||||
} else {
|
||||
result.Findings.ProtectedPending = append(result.Findings.ProtectedPending, item{
|
||||
ID: row.ID, ObjectKey: row.ObjectKey, Status: row.Status,
|
||||
AgeSeconds: age, ObjectPresent: exists,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
sortFindings(&result.Findings)
|
||||
|
||||
if *apply {
|
||||
applyActions(ctx, repository, objects, result.Findings.OrphanObjects, result.Findings.StalePending, *grace, &result.Actions)
|
||||
} else {
|
||||
for _, orphan := range result.Findings.OrphanObjects {
|
||||
result.Actions.PlannedDeletes = append(result.Actions.PlannedDeletes, orphan.ObjectKey)
|
||||
}
|
||||
for _, pending := range result.Findings.StalePending {
|
||||
result.Actions.PlannedDeletes = append(result.Actions.PlannedDeletes, pending.ObjectKey)
|
||||
}
|
||||
}
|
||||
for _, missing := range result.Findings.MissingObjects {
|
||||
result.Actions.UnresolvedMissing = append(result.Actions.UnresolvedMissing, missing.ID)
|
||||
}
|
||||
result.Timing.TotalMS = time.Since(started).Milliseconds()
|
||||
|
||||
encoded, err := json.MarshalIndent(result, "", " ")
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "reconciler: encode report failed:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Println(string(encoded))
|
||||
if *output != "" {
|
||||
if err := os.WriteFile(*output, append(encoded, '\n'), 0o644); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "reconciler: write report failed:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
if len(result.Actions.Errors) > 0 {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// applyActions performs the two safe mutations. Broken ready metadata is never
|
||||
// deleted: automatic deletion would destroy the only record of a user's file
|
||||
// and could hide data loss. Each mutation re-reads the database first.
|
||||
func applyActions(ctx context.Context, repository *store.Store, objects *objectstore.Store, orphans, stale []item, grace time.Duration, result *actions) {
|
||||
for _, orphan := range orphans {
|
||||
stillReferenced, err := repository.AttachmentByObjectKey(ctx, orphan.ObjectKey)
|
||||
if err != nil {
|
||||
result.Errors = append(result.Errors, "recheck "+orphan.ObjectKey+": "+err.Error())
|
||||
continue
|
||||
}
|
||||
if stillReferenced {
|
||||
result.Skipped = append(result.Skipped, orphan.ObjectKey)
|
||||
continue
|
||||
}
|
||||
if err := objects.Remove(ctx, orphan.ObjectKey); err != nil {
|
||||
result.Errors = append(result.Errors, "delete "+orphan.ObjectKey+": "+err.Error())
|
||||
continue
|
||||
}
|
||||
result.DeletedObjects = append(result.DeletedObjects, orphan.ObjectKey)
|
||||
}
|
||||
for _, pending := range stale {
|
||||
status, key, updatedAt, err := repository.AttachmentState(ctx, pending.ID)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
result.Skipped = append(result.Skipped, pending.ObjectKey)
|
||||
continue
|
||||
}
|
||||
result.Errors = append(result.Errors, "recheck "+pending.ID+": "+err.Error())
|
||||
continue
|
||||
}
|
||||
if status != "pending" {
|
||||
result.Skipped = append(result.Skipped, pending.ObjectKey)
|
||||
continue
|
||||
}
|
||||
if time.Since(updatedAt) < grace {
|
||||
// Defensive: the snapshot said stale, but the row is fresh now
|
||||
// (a retried upload may have updated it). Never delete it.
|
||||
result.Skipped = append(result.Skipped, pending.ObjectKey)
|
||||
continue
|
||||
}
|
||||
// Delete the intent row first, then the object. The reverse order has
|
||||
// a race: a concurrent MarkAttachmentReady could promote the row
|
||||
// between Remove and DELETE, leaving a ready row whose bytes are gone.
|
||||
// With this order a crash after the row delete leaves an orphan object
|
||||
// that the next run removes after the grace period.
|
||||
deleted, err := repository.DeleteAttachmentIfPending(ctx, pending.ID)
|
||||
if err != nil {
|
||||
result.Errors = append(result.Errors, "delete row "+pending.ID+": "+err.Error())
|
||||
continue
|
||||
}
|
||||
if !deleted {
|
||||
result.Skipped = append(result.Skipped, pending.ObjectKey)
|
||||
continue
|
||||
}
|
||||
result.DeletedPendingRows = append(result.DeletedPendingRows, pending.ID)
|
||||
if !pending.ObjectPresent {
|
||||
continue
|
||||
}
|
||||
if err := objects.Remove(ctx, key); err != nil {
|
||||
result.Errors = append(result.Errors, "delete orphaned object after row "+key+": "+err.Error())
|
||||
continue
|
||||
}
|
||||
result.DeletedObjects = append(result.DeletedObjects, key)
|
||||
}
|
||||
}
|
||||
|
||||
func ageSeconds(now, then time.Time) int64 {
|
||||
if then.IsZero() {
|
||||
return -1
|
||||
}
|
||||
age := now.Sub(then)
|
||||
if age < 0 {
|
||||
return 0
|
||||
}
|
||||
return int64(age.Seconds())
|
||||
}
|
||||
|
||||
func sortFindings(value *findings) {
|
||||
sort.Slice(value.OrphanObjects, func(i, j int) bool { return value.OrphanObjects[i].ObjectKey < value.OrphanObjects[j].ObjectKey })
|
||||
sort.Slice(value.ProtectedObjects, func(i, j int) bool { return value.ProtectedObjects[i].ObjectKey < value.ProtectedObjects[j].ObjectKey })
|
||||
sort.Slice(value.MissingObjects, func(i, j int) bool { return value.MissingObjects[i].ObjectKey < value.MissingObjects[j].ObjectKey })
|
||||
sort.Slice(value.StalePending, func(i, j int) bool { return value.StalePending[i].ObjectKey < value.StalePending[j].ObjectKey })
|
||||
sort.Slice(value.ProtectedPending, func(i, j int) bool { return value.ProtectedPending[i].ObjectKey < value.ProtectedPending[j].ObjectKey })
|
||||
}
|
||||
Reference in New Issue
Block a user