Files
mtusi2026lab5/cmd/reconcile/main.go
T

101 lines
2.8 KiB
Go

// Command reconcile reports attachment inconsistencies as JSON lines. Mutations
// require --apply; --deep also streams referenced objects to verify SHA256.
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"os"
"os/signal"
"syscall"
"time"
"messenger/internal/attachment"
"messenger/internal/platform/config"
"messenger/internal/platform/postgres"
"messenger/internal/platform/s3store"
)
func main() {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
code := run(ctx, os.Args[1:], os.Stdout, os.Stderr)
stop()
os.Exit(code)
}
func run(ctx context.Context, args []string, out, errOut io.Writer) int {
flags := flag.NewFlagSet("reconcile", flag.ContinueOnError)
flags.SetOutput(errOut)
apply := flags.Bool("apply", false, "apply repairs (default: read-only dry run)")
deep := flags.Bool("deep", false, "stream referenced objects and verify SHA256 and size")
grace := flags.Duration("grace", time.Hour, "minimum file/object age; must be at least 2m")
if err := flags.Parse(args); err != nil {
if errors.Is(err, flag.ErrHelp) {
return 0
}
return 2
}
if flags.NArg() != 0 || *grace < 2*time.Minute {
fmt.Fprintln(errOut, "reconcile: no positional arguments allowed; --grace must be at least 2m")
return 2
}
databaseURL, err := config.LoadDatabaseURL(os.LookupEnv)
if err != nil {
fmt.Fprintln(errOut, "configuration error:", err)
return 2
}
// Compose mounts the reconciler identity at the standard credential paths.
s3Config, err := config.LoadS3(os.LookupEnv)
if err != nil {
fmt.Fprintln(errOut, "configuration error:", err)
return 2
}
blobs, err := s3store.New(s3Config)
if err != nil {
fmt.Fprintln(errOut, "configuration error:", err)
return 2
}
db, err := postgres.NewPool(ctx, databaseURL, 10)
if err != nil {
fmt.Fprintln(errOut, "reconcile:", err)
return 1
}
defer db.Close()
r, err := attachment.NewReconcilerWithRetention(db, blobs, *grace, s3Config.StagingRetention)
if err != nil {
fmt.Fprintln(errOut, "reconcile:", err)
return 2
}
// A broken output stream cancels the scan so repairs cannot continue after
// the caller loses the audit trail. Print partial statistics on scan errors.
scanCtx, cancel := context.WithCancel(ctx)
defer cancel()
encoder := json.NewEncoder(out)
var outputErr error
options := attachment.ReconcileOptions{Apply: *apply, Deep: *deep}
stats, runErr := r.Run(scanCtx, options, func(f attachment.Finding) {
if outputErr == nil {
outputErr = encoder.Encode(f)
if outputErr != nil {
cancel()
}
}
})
if outputErr == nil {
outputErr = encoder.Encode(stats)
}
if outputErr != nil {
fmt.Fprintln(errOut, "reconcile output:", outputErr)
return 1
}
if runErr != nil {
fmt.Fprintln(errOut, "reconcile:", runErr)
return 1
}
return 0
}