ЛР 5 — асинхронная обработка и версии pipeline
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
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):
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user