forked from mtusi2026/mtusi2026lab4
feat(reconcile): add attachment consistency reconciler
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
FROM golang:1.27.1 AS build
|
||||
WORKDIR /src
|
||||
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
COPY . .
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -o /out/reconcile ./cmd/reconcile
|
||||
|
||||
FROM gcr.io/distroless/static-debian12:nonroot
|
||||
WORKDIR /app
|
||||
COPY --from=build /out/reconcile .
|
||||
|
||||
ENTRYPOINT ["/app/reconcile"]
|
||||
@@ -0,0 +1,133 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
|
||||
"mtusi2026-messenger/internal/config"
|
||||
"mtusi2026-messenger/internal/db"
|
||||
"mtusi2026-messenger/internal/postgres"
|
||||
"mtusi2026-messenger/internal/reconcile"
|
||||
s3store "mtusi2026-messenger/internal/s3"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := run(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "reconcile:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run() error {
|
||||
if err := godotenv.Load(); err != nil && !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
|
||||
dryRun := flag.Bool("dry-run", true, "report findings without changing PostgreSQL or S3")
|
||||
grace := flag.Duration("grace", reconcile.DefaultGrace, "minimum age before an object or row may be repaired")
|
||||
maxDeletes := flag.Int("max-deletes", reconcile.DefaultMaxDeletes, "maximum destructive repairs per run")
|
||||
asJSON := flag.Bool("json", false, "print the report as JSON")
|
||||
flag.Parse()
|
||||
|
||||
cfg := config.Load()
|
||||
log := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: cfg.Logging.Level}))
|
||||
|
||||
databaseURL, err := cfg.Database.URL()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
pool, err := postgres.New(ctx, databaseURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
s3Client, err := s3store.New(ctx, cfg.S3, log)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
reconciler := reconcile.New(s3Client, db.New(pool), log)
|
||||
|
||||
report, err := reconciler.Run(ctx, reconcile.Options{
|
||||
DryRun: *dryRun,
|
||||
Grace: *grace,
|
||||
MaxDeletes: *maxDeletes,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if *asJSON {
|
||||
encoder := json.NewEncoder(os.Stdout)
|
||||
encoder.SetIndent("", " ")
|
||||
if err := encoder.Encode(report); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
printReport(report)
|
||||
}
|
||||
|
||||
if len(report.Errors) > 0 {
|
||||
return fmt.Errorf("completed with %d errors", len(report.Errors))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func printReport(report reconcile.Report) {
|
||||
fmt.Printf("dry_run=%t duration_ms=%d\n", report.DryRun, report.DurationMS)
|
||||
fmt.Printf(
|
||||
"scanned objects=%d rows=%d list_pages=%d\n",
|
||||
report.ScannedObjects,
|
||||
report.ScannedRows,
|
||||
report.ListPages,
|
||||
)
|
||||
fmt.Printf(
|
||||
"found orphan_objects=%d missing_attachments=%d stale_uploads=%d corrupt_objects=%d\n",
|
||||
len(report.OrphanObjects),
|
||||
len(report.MissingAttachments),
|
||||
len(report.StaleUploads),
|
||||
len(report.CorruptObjects),
|
||||
)
|
||||
fmt.Printf(
|
||||
"skipped fresh=%d referenced=%d inactive=%d\n",
|
||||
report.SkippedFresh,
|
||||
report.SkippedReferenced,
|
||||
report.SkippedInactive,
|
||||
)
|
||||
fmt.Printf(
|
||||
"changes deleted_objects=%d deleted_rows=%d marked_failed=%d\n",
|
||||
report.DeletedObjects,
|
||||
report.DeletedRows,
|
||||
report.MarkedFailed,
|
||||
)
|
||||
|
||||
for _, key := range report.OrphanObjects {
|
||||
fmt.Printf("orphan_object %s\n", key)
|
||||
}
|
||||
for _, key := range report.CorruptObjects {
|
||||
fmt.Printf("corrupt_object %s\n", key)
|
||||
}
|
||||
for _, id := range report.MissingAttachments {
|
||||
fmt.Printf("missing_attachment %s\n", id)
|
||||
}
|
||||
for _, id := range report.StaleUploads {
|
||||
fmt.Printf("stale_upload %s\n", id)
|
||||
}
|
||||
for _, message := range report.Errors {
|
||||
fmt.Printf("error %s\n", message)
|
||||
}
|
||||
}
|
||||
@@ -153,6 +153,27 @@ services:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
|
||||
reconcile:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.reconcile
|
||||
image: mtusi-messenger-reconcile:lab4
|
||||
profiles: ["tools"]
|
||||
env_file:
|
||||
- .env
|
||||
secrets:
|
||||
- database_url
|
||||
- s3_access_key_id
|
||||
- s3_secret_access_key
|
||||
- s3_bootstrap_access_key_id
|
||||
- s3_bootstrap_secret_access_key
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.25"
|
||||
memory: 64M
|
||||
restart: "no"
|
||||
|
||||
secrets:
|
||||
postgres_password:
|
||||
file: ./secrets/postgres_password.txt
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
package reconcile
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026-messenger/internal/db"
|
||||
s3store "mtusi2026-messenger/internal/s3"
|
||||
)
|
||||
|
||||
const (
|
||||
Prefix = "chats/"
|
||||
DefaultGrace = time.Hour
|
||||
DefaultMaxDeletes = 100
|
||||
ErrorCodeObjectMissing = "object_missing"
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
DryRun bool
|
||||
Grace time.Duration
|
||||
MaxDeletes int
|
||||
}
|
||||
|
||||
type Report struct {
|
||||
ScannedObjects int `json:"scanned_objects"`
|
||||
ScannedRows int `json:"scanned_rows"`
|
||||
ListPages int `json:"list_pages"`
|
||||
OrphanObjects []string `json:"orphan_objects"`
|
||||
MissingAttachments []uuid.UUID `json:"missing_attachments"`
|
||||
StaleUploads []uuid.UUID `json:"stale_uploads"`
|
||||
CorruptObjects []string `json:"corrupt_objects"`
|
||||
SkippedFresh int `json:"skipped_fresh"`
|
||||
SkippedReferenced int `json:"skipped_referenced"`
|
||||
SkippedInactive int `json:"skipped_inactive"`
|
||||
DeletedObjects int `json:"deleted_objects"`
|
||||
DeletedRows int `json:"deleted_rows"`
|
||||
MarkedFailed int `json:"marked_failed"`
|
||||
DryRun bool `json:"dry_run"`
|
||||
Errors []string `json:"errors"`
|
||||
DurationMS int64 `json:"duration_ms"`
|
||||
}
|
||||
|
||||
type ObjectClient interface {
|
||||
ListAll(ctx context.Context, prefix string) (s3store.ListResult, error)
|
||||
DeleteAdmin(ctx context.Context, key string) error
|
||||
}
|
||||
|
||||
type AttachmentQueries interface {
|
||||
ListAttachmentsForReconcile(ctx context.Context) ([]db.ListAttachmentsForReconcileRow, error)
|
||||
DeleteQueuedAttachment(ctx context.Context, id uuid.UUID) (int64, error)
|
||||
MarkAttachmentFailedIfReady(ctx context.Context, arg db.MarkAttachmentFailedIfReadyParams) (int64, error)
|
||||
}
|
||||
|
||||
type Reconciler struct {
|
||||
q AttachmentQueries
|
||||
store ObjectClient
|
||||
log *slog.Logger
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
type plan struct {
|
||||
orphans []s3store.ObjectInfo
|
||||
staleUploads []db.ListAttachmentsForReconcileRow
|
||||
missing []db.ListAttachmentsForReconcileRow
|
||||
corrupt []s3store.ObjectInfo
|
||||
skippedFresh int
|
||||
skippedReferenced int
|
||||
skippedInactive int
|
||||
}
|
||||
|
||||
func New(store ObjectClient, queries AttachmentQueries, log *slog.Logger) *Reconciler {
|
||||
if log == nil {
|
||||
log = slog.Default()
|
||||
}
|
||||
|
||||
return &Reconciler{
|
||||
store: store,
|
||||
q: queries,
|
||||
log: log,
|
||||
now: time.Now,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Reconciler) Run(ctx context.Context, opts Options) (Report, error) {
|
||||
opts = opts.withDefaults()
|
||||
started := r.now()
|
||||
|
||||
report := Report{
|
||||
OrphanObjects: []string{},
|
||||
MissingAttachments: []uuid.UUID{},
|
||||
StaleUploads: []uuid.UUID{},
|
||||
CorruptObjects: []string{},
|
||||
DryRun: opts.DryRun,
|
||||
Errors: []string{},
|
||||
}
|
||||
|
||||
listed, err := r.store.ListAll(ctx, Prefix)
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
|
||||
rows, err := r.q.ListAttachmentsForReconcile(ctx)
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
|
||||
report.ScannedObjects = len(listed.Objects)
|
||||
report.ScannedRows = len(rows)
|
||||
report.ListPages = listed.Pages
|
||||
|
||||
p := buildPlan(listed.Objects, rows, started, opts.Grace)
|
||||
|
||||
for _, obj := range p.orphans {
|
||||
report.OrphanObjects = append(report.OrphanObjects, obj.Key)
|
||||
}
|
||||
for _, obj := range p.corrupt {
|
||||
report.CorruptObjects = append(report.CorruptObjects, obj.Key)
|
||||
}
|
||||
for _, row := range p.staleUploads {
|
||||
report.StaleUploads = append(report.StaleUploads, row.ID)
|
||||
}
|
||||
for _, row := range p.missing {
|
||||
report.MissingAttachments = append(report.MissingAttachments, row.ID)
|
||||
}
|
||||
|
||||
report.SkippedFresh = p.skippedFresh
|
||||
report.SkippedReferenced = p.skippedReferenced
|
||||
report.SkippedInactive = p.skippedInactive
|
||||
|
||||
if !opts.DryRun {
|
||||
r.apply(ctx, opts, p, &report)
|
||||
}
|
||||
|
||||
report.DurationMS = r.now().Sub(started).Milliseconds()
|
||||
|
||||
r.log.Info(
|
||||
"attachment reconcile finished",
|
||||
"dry_run", opts.DryRun,
|
||||
"scanned_objects", report.ScannedObjects,
|
||||
"scanned_rows", report.ScannedRows,
|
||||
"list_pages", report.ListPages,
|
||||
"orphan_objects", len(report.OrphanObjects),
|
||||
"missing_attachments", len(report.MissingAttachments),
|
||||
"stale_uploads", len(report.StaleUploads),
|
||||
"corrupt_objects", len(report.CorruptObjects),
|
||||
"deleted_objects", report.DeletedObjects,
|
||||
"deleted_rows", report.DeletedRows,
|
||||
"marked_failed", report.MarkedFailed,
|
||||
"errors", len(report.Errors),
|
||||
)
|
||||
|
||||
return report, nil
|
||||
}
|
||||
|
||||
func (o Options) withDefaults() Options {
|
||||
if o.Grace <= 0 {
|
||||
o.Grace = DefaultGrace
|
||||
}
|
||||
if o.MaxDeletes <= 0 {
|
||||
o.MaxDeletes = DefaultMaxDeletes
|
||||
}
|
||||
|
||||
return o
|
||||
}
|
||||
|
||||
func buildPlan(
|
||||
objects []s3store.ObjectInfo,
|
||||
rows []db.ListAttachmentsForReconcileRow,
|
||||
now time.Time,
|
||||
grace time.Duration,
|
||||
) plan {
|
||||
var p plan
|
||||
|
||||
byKey := make(map[string]s3store.ObjectInfo, len(objects))
|
||||
for _, obj := range objects {
|
||||
byKey[obj.Key] = obj
|
||||
}
|
||||
|
||||
for _, row := range rows {
|
||||
obj, exists := byKey[row.S3Key]
|
||||
if exists {
|
||||
delete(byKey, row.S3Key)
|
||||
}
|
||||
|
||||
switch row.Status {
|
||||
case db.AttachmentStatusQueued:
|
||||
if now.Sub(row.CreatedAt) < grace {
|
||||
p.skippedFresh++
|
||||
continue
|
||||
}
|
||||
if row.Referenced {
|
||||
p.skippedReferenced++
|
||||
continue
|
||||
}
|
||||
p.staleUploads = append(p.staleUploads, row)
|
||||
case db.AttachmentStatusReady:
|
||||
if !exists {
|
||||
p.missing = append(p.missing, row)
|
||||
continue
|
||||
}
|
||||
if obj.Size != int64(row.SizeBytes) {
|
||||
p.corrupt = append(p.corrupt, obj)
|
||||
}
|
||||
default:
|
||||
if exists {
|
||||
p.skippedInactive++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, obj := range byKey {
|
||||
if now.Sub(obj.LastModified) < grace {
|
||||
p.skippedFresh++
|
||||
continue
|
||||
}
|
||||
p.orphans = append(p.orphans, obj)
|
||||
}
|
||||
|
||||
sort.Slice(p.orphans, func(i, j int) bool {
|
||||
return p.orphans[i].Key < p.orphans[j].Key
|
||||
})
|
||||
sort.Slice(p.corrupt, func(i, j int) bool {
|
||||
return p.corrupt[i].Key < p.corrupt[j].Key
|
||||
})
|
||||
sort.Slice(p.staleUploads, func(i, j int) bool {
|
||||
return p.staleUploads[i].ID.String() < p.staleUploads[j].ID.String()
|
||||
})
|
||||
sort.Slice(p.missing, func(i, j int) bool {
|
||||
return p.missing[i].ID.String() < p.missing[j].ID.String()
|
||||
})
|
||||
|
||||
return p
|
||||
}
|
||||
|
||||
func (r *Reconciler) apply(ctx context.Context, opts Options, p plan, report *Report) {
|
||||
deletes := 0
|
||||
|
||||
for _, row := range p.staleUploads {
|
||||
if deletes >= opts.MaxDeletes {
|
||||
report.Errors = append(report.Errors, "max deletes reached")
|
||||
break
|
||||
}
|
||||
|
||||
removed, err := r.q.DeleteQueuedAttachment(ctx, row.ID)
|
||||
if err != nil {
|
||||
report.Errors = append(report.Errors, fmt.Sprintf("delete row %s: %v", row.ID, err))
|
||||
continue
|
||||
}
|
||||
if removed == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
deletes++
|
||||
report.DeletedRows++
|
||||
|
||||
if err := r.store.DeleteAdmin(ctx, row.S3Key); err != nil {
|
||||
report.Errors = append(report.Errors, fmt.Sprintf("delete object %s: %v", row.S3Key, err))
|
||||
continue
|
||||
}
|
||||
report.DeletedObjects++
|
||||
}
|
||||
|
||||
for _, obj := range p.orphans {
|
||||
if deletes >= opts.MaxDeletes {
|
||||
report.Errors = append(report.Errors, "max deletes reached")
|
||||
break
|
||||
}
|
||||
|
||||
if err := r.store.DeleteAdmin(ctx, obj.Key); err != nil {
|
||||
report.Errors = append(report.Errors, fmt.Sprintf("delete object %s: %v", obj.Key, err))
|
||||
continue
|
||||
}
|
||||
|
||||
deletes++
|
||||
report.DeletedObjects++
|
||||
}
|
||||
|
||||
for _, row := range p.missing {
|
||||
marked, err := r.q.MarkAttachmentFailedIfReady(ctx, db.MarkAttachmentFailedIfReadyParams{
|
||||
ID: row.ID,
|
||||
ErrorCode: ErrorCodeObjectMissing,
|
||||
})
|
||||
if err != nil {
|
||||
report.Errors = append(report.Errors, fmt.Sprintf("mark failed %s: %v", row.ID, err))
|
||||
continue
|
||||
}
|
||||
|
||||
report.MarkedFailed += int(marked)
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http"
|
||||
@@ -24,6 +25,7 @@ var (
|
||||
ErrObjectNotFound = errors.New("object not found")
|
||||
ErrPutObject = errors.New("put object")
|
||||
ErrGetObject = errors.New("get object")
|
||||
ErrListObjects = errors.New("list objects")
|
||||
ErrDeleteObject = errors.New("delete object")
|
||||
)
|
||||
|
||||
@@ -34,6 +36,17 @@ type Client struct {
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
type ObjectInfo struct {
|
||||
Key string
|
||||
Size int64
|
||||
LastModified time.Time
|
||||
}
|
||||
|
||||
type ListResult struct {
|
||||
Objects []ObjectInfo
|
||||
Pages int
|
||||
}
|
||||
|
||||
func New(ctx context.Context, cfg appconfig.S3Config, log *slog.Logger) (*Client, error) {
|
||||
apiAccessKey, err := cfg.APIAccessKey()
|
||||
if err != nil {
|
||||
@@ -144,6 +157,35 @@ func (c *Client) Get(ctx context.Context, key string) (*awss3.GetObjectOutput, e
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *Client) ListAll(ctx context.Context, prefix string) (ListResult, error) {
|
||||
result := ListResult{Objects: []ObjectInfo{}}
|
||||
|
||||
paginator := awss3.NewListObjectsV2Paginator(c.bootstrap, &awss3.ListObjectsV2Input{
|
||||
Bucket: aws.String(c.bucket),
|
||||
Prefix: aws.String(prefix),
|
||||
})
|
||||
|
||||
for paginator.HasMorePages() {
|
||||
page, err := paginator.NextPage(ctx)
|
||||
if err != nil {
|
||||
c.log.Error("list objects", "bucket", c.bucket, "prefix", prefix, "error", err)
|
||||
return ListResult{}, ErrListObjects
|
||||
}
|
||||
|
||||
result.Pages++
|
||||
|
||||
for _, obj := range page.Contents {
|
||||
result.Objects = append(result.Objects, ObjectInfo{
|
||||
Key: aws.ToString(obj.Key),
|
||||
Size: aws.ToInt64(obj.Size),
|
||||
LastModified: aws.ToTime(obj.LastModified),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *Client) DeleteAdmin(ctx context.Context, key string) error {
|
||||
_, err := c.bootstrap.DeleteObject(ctx, &awss3.DeleteObjectInput{
|
||||
Bucket: aws.String(c.bucket),
|
||||
|
||||
+6
-1
@@ -6,14 +6,16 @@ LOAD_ARGS = $(if $(LOAD_WORKERS),-workers=$(LOAD_WORKERS),) \
|
||||
REPLICA ?= 1
|
||||
ACTION ?= stop-one.sh
|
||||
ACTION_AT ?= 10s
|
||||
DRY_RUN ?= true
|
||||
|
||||
.PHONY: help-go contract-go race-go load-go failure-go load-action-go
|
||||
.PHONY: help-go contract-go race-go load-go failure-go load-action-go reconcile
|
||||
|
||||
help-go:
|
||||
@echo "contract-go: contract tests"
|
||||
@echo "race-go: concurrency tests (-race)"
|
||||
@echo "load-go: load test"
|
||||
@echo "failure-go: dependency failure tests (stops redis/postgres containers)"
|
||||
@echo "reconcile: attachment audit; DRY_RUN=false to repair"
|
||||
|
||||
contract-go:
|
||||
go test -tags=contract ./student-tests/... -v -args -base-url=$(BASE_URL)
|
||||
@@ -33,3 +35,6 @@ load-action-go:
|
||||
-replica=$(REPLICA) \
|
||||
-action=$(CURDIR)/scripts/$(ACTION) \
|
||||
-action-at=$(ACTION_AT)
|
||||
|
||||
reconcile:
|
||||
docker compose --env-file .env run --rm --no-deps reconcile -dry-run=$(DRY_RUN)
|
||||
|
||||
Reference in New Issue
Block a user