Files
lincodex/labd/internal/reaper/reaper.go
T

51 lines
1.4 KiB
Go

// Package reaper runs the periodic work that makes lab deletion
// guaranteed: it ends labs at their timers, retries unfinished deletions,
// and removes LXD objects that no lab record owns.
package reaper
import (
"context"
"log/slog"
"time"
)
// Target is the lab manager.
type Target interface {
// Sweep ends expired labs and retries pending deletions.
Sweep(ctx context.Context)
// Reconcile deletes orphaned LXD objects.
Reconcile(ctx context.Context) error
}
// Config holds the intervals of the reaper.
type Config struct {
SweepInterval time.Duration
ReconcileInterval time.Duration
}
// Run sweeps every SweepInterval and reconciles every ReconcileInterval until
// ctx ends. The first sweep runs at once; the caller reconciles once before
// it serves. A failed reconciliation is logged and retried on schedule;
// reconciled reports each outcome, for readiness.
func Run(ctx context.Context, target Target, cfg Config, reconciled func(error), logger *slog.Logger) {
sweep := time.NewTicker(cfg.SweepInterval)
defer sweep.Stop()
reconcile := time.NewTicker(cfg.ReconcileInterval)
defer reconcile.Stop()
target.Sweep(ctx)
for {
select {
case <-ctx.Done():
return
case <-sweep.C:
target.Sweep(ctx)
case <-reconcile.C:
err := target.Reconcile(ctx)
if err != nil && ctx.Err() == nil {
logger.WarnContext(ctx, "lab reconciliation failed; retrying on schedule", slog.String("error", err.Error()))
}
reconciled(err)
}
}
}