Files

165 lines
4.8 KiB
Go

package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"highload/internal/config"
"highload/internal/database"
"highload/internal/database/sqlc"
"highload/internal/repository/postgres"
"highload/internal/service"
"highload/internal/storage/s3"
"log/slog"
"os"
"os/signal"
"syscall"
"time"
"github.com/jackc/pgx/v5/pgconn"
)
type cleanupConfig struct {
once bool
dryRun bool
gracePeriod time.Duration
interval time.Duration
passTimeout time.Duration
reconcile bool
restoreID string
backupFile string
}
func main() {
var cfg cleanupConfig
flag.BoolVar(&cfg.once, "once", false, "Run once and exit")
flag.BoolVar(&cfg.dryRun, "dry-run", true, "Do not actually delete files")
flag.DurationVar(&cfg.gracePeriod, "grace-period", 10*time.Minute, "Grace period for old files")
flag.DurationVar(&cfg.interval, "interval", 5*time.Minute, "Interval between runs")
flag.DurationVar(&cfg.passTimeout, "pass-timeout", 2*time.Minute, "Timeout for a single pass")
flag.BoolVar(&cfg.reconcile, "reconcile", false, "Scan both stores once and print JSON observations")
flag.StringVar(&cfg.restoreID, "restore-id", "", "Restore the missing original for this attachment ID")
flag.StringVar(&cfg.backupFile, "backup-file", "", "Path to the original backup used for restore")
flag.Parse()
if cfg.gracePeriod <= 0 || cfg.interval <= 0 || cfg.passTimeout <= 0 {
slog.Error("all duration flags must be positive")
os.Exit(1)
}
if (cfg.restoreID == "") != (cfg.backupFile == "") || (cfg.reconcile && cfg.restoreID != "") {
slog.Error("use -reconcile alone, or supply both -restore-id and -backup-file")
os.Exit(1)
}
if err := run(cfg); err != nil {
slog.Error("attachment cleanup failed", "error", err)
os.Exit(1)
}
}
func run(cfg cleanupConfig) error {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
databaseURL, s3Config, err := config.LoadAttachmentCleanup()
if err != nil {
return fmt.Errorf("load cleanup configuration: %w", err)
}
startupCtx, cancelStartup := context.WithTimeout(ctx, 10*time.Second)
defer cancelStartup()
pool, err := database.NewPostgres(startupCtx, databaseURL)
if err != nil {
var configErr *pgconn.ParseConfigError
if errors.As(err, &configErr) {
return errors.New("invalid PostgreSQL connection string")
}
return fmt.Errorf("connect to PostgreSQL: %w", err)
}
defer pool.Close()
s3Storage, err := s3.NewStorage(startupCtx, &s3Config)
if err != nil {
return fmt.Errorf("create S3 client: %w", err)
}
cancelStartup()
attachmentRepo := postgres.NewAttachmentRepository(sqlc.New(pool), pool)
options := &service.AttachmentCleanupOptions{
GracePeriod: cfg.gracePeriod,
DryRun: cfg.dryRun,
ListTimeout: 5 * time.Second,
}
attachmentCleanupService := service.NewAttachmentCleanupService(attachmentRepo, s3Storage, options)
if cfg.reconcile || cfg.restoreID != "" {
passCtx, cancel := context.WithTimeout(ctx, cfg.passTimeout)
defer cancel()
reconciler := service.NewAttachmentReconciler(attachmentRepo, s3Storage, *options)
start := time.Now()
report := struct {
DryRun bool `json:"dry_run"`
DurationMS int64 `json:"duration_ms"`
Complete bool `json:"complete"`
Orphans *service.OrphanReport `json:"orphan_scan,omitempty"`
Missing *service.MissingReport `json:"missing_scan,omitempty"`
Restore string `json:"restore,omitempty"`
}{DryRun: cfg.dryRun}
var actionErr error
if cfg.reconcile {
missing, err := reconciler.ScanMissing(passCtx)
report.Missing = &missing
actionErr = err
if err == nil {
orphans, err := attachmentCleanupService.ScanOrphans(passCtx)
report.Orphans = &orphans
actionErr = err
}
} else {
file, err := os.Open(cfg.backupFile)
if err != nil {
return fmt.Errorf("open backup original: %w", err)
}
defer file.Close()
report.Restore, actionErr = reconciler.Restore(passCtx, cfg.restoreID, file)
}
report.DurationMS = time.Since(start).Milliseconds()
report.Complete = actionErr == nil
return errors.Join(actionErr, json.NewEncoder(os.Stdout).Encode(report))
}
runPass := func() error {
passCtx, cancelPass := context.WithTimeout(ctx, cfg.passTimeout)
defer cancelPass()
return attachmentCleanupService.RunOnce(passCtx)
}
if cfg.once {
return runPass()
}
if err := runPass(); err != nil && ctx.Err() == nil {
slog.Error("attachment cleanup pass failed", "error", err)
}
ticker := time.NewTicker(cfg.interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return nil
case <-ticker.C:
if ctx.Err() != nil {
return nil
}
if err := runPass(); err != nil && ctx.Err() == nil {
slog.Error("attachment cleanup pass failed", "error", err)
}
}
}
}