forked from mtusi2026/mtusi2026lab5
65 lines
1.4 KiB
Go
65 lines
1.4 KiB
Go
package pipeline
|
|
|
|
import (
|
|
"context"
|
|
"log/slog"
|
|
"time"
|
|
|
|
"highload/internal/repository/postgres"
|
|
"highload/internal/storage"
|
|
)
|
|
|
|
type Cleanup struct {
|
|
Repo *postgres.AttachmentRepository
|
|
Objects storage.ObjectCleanup
|
|
Grace time.Duration
|
|
Retention time.Duration
|
|
DryRun bool
|
|
}
|
|
|
|
func (c Cleanup) RunOnce(ctx context.Context) (int, error) {
|
|
policy := postgres.CleanupPolicy{Now: time.Now(), Grace: c.Grace, Retention: c.Retention, DryRun: c.DryRun}
|
|
removed := 0
|
|
for _, prefix := range []string{"staging/", "results/", "attachments/"} {
|
|
var token *string
|
|
for {
|
|
pageCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
objects, next, err := c.Objects.ListPage(pageCtx, token, prefix)
|
|
cancel()
|
|
if err != nil {
|
|
return removed, err
|
|
}
|
|
for _, obj := range objects {
|
|
eligible, err := c.Repo.CleanupObject(ctx, obj, policy, c.Objects.Delete)
|
|
if err != nil {
|
|
return removed, err
|
|
}
|
|
if eligible {
|
|
removed++
|
|
}
|
|
}
|
|
if next == nil {
|
|
break
|
|
}
|
|
token = next
|
|
}
|
|
}
|
|
return removed, nil
|
|
}
|
|
|
|
func (c Cleanup) Serve(ctx context.Context, period time.Duration) {
|
|
for ctx.Err() == nil {
|
|
count, err := c.RunOnce(ctx)
|
|
if err != nil && ctx.Err() == nil {
|
|
slog.Warn("cleanup pass failed", "error", err)
|
|
}
|
|
if count > 0 {
|
|
slog.Info("cleanup pass", "objects", count, "dry_run", c.DryRun)
|
|
}
|
|
select {
|
|
case <-ctx.Done():
|
|
case <-time.After(period):
|
|
}
|
|
}
|
|
}
|