feat(rescan): limit rescans to active packages and run them in parallel

security.rescan_active_window skips packages not requested within the
window. security.rescan_concurrency runs a bounded pool of scans per
cycle. The cycle summary reports skips by reason. Both options default
to the previous behaviour.
This commit is contained in:
2026-11-23 19:26:10 +00:00
parent d6044cdd2e
commit 41f8369c43
5 changed files with 241 additions and 109 deletions
+166 -94
View File
@@ -3,6 +3,7 @@ package scanner
import (
"context"
"sync"
"sync/atomic"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
@@ -16,16 +17,41 @@ type RescanWorker struct {
stopCh chan struct{}
stopOnce sync.Once
interval time.Duration
activeWindow time.Duration
concurrency int
}
// RescanOption tunes a RescanWorker.
type RescanOption func(*RescanWorker)
// WithActiveWindow skips packages not accessed within window (0 = scan all).
func WithActiveWindow(window time.Duration) RescanOption {
return func(w *RescanWorker) { w.activeWindow = window }
}
// WithConcurrency sets the scans run in parallel within a cycle; values below 1 mean 1.
func WithConcurrency(n int) RescanOption {
return func(w *RescanWorker) {
if n < 1 {
n = 1
}
w.concurrency = n
}
}
// NewRescanWorker creates a new rescan worker
func NewRescanWorker(manager *Manager, metadataStore metadata.MetadataStore, interval time.Duration) *RescanWorker {
return &RescanWorker{
func NewRescanWorker(manager *Manager, metadataStore metadata.MetadataStore, interval time.Duration, opts ...RescanOption) *RescanWorker {
w := &RescanWorker{
manager: manager,
metadataStore: metadataStore,
interval: interval,
concurrency: 1,
stopCh: make(chan struct{}),
}
for _, opt := range opts {
opt(w)
}
return w
}
// Start begins the periodic re-scanning process
@@ -70,115 +96,161 @@ func (w *RescanWorker) Stop() {
})
}
// rescanCounts tallies one rescan cycle; workers update it concurrently.
type rescanCounts struct {
scanned atomic.Int64
failed atomic.Int64
skipMetadata atomic.Int64
skipIdle atomic.Int64
skipFresh atomic.Int64
skipNoSource atomic.Int64
}
// rescanPackages re-scans packages that need updating
func (w *RescanWorker) rescanPackages(ctx context.Context) {
log.Info().Msg("Starting package rescan cycle - checking all packages for scan status")
// Get all packages
packages, err := w.metadataStore.ListPackages(ctx, &metadata.ListOptions{})
if err != nil {
log.Error().Err(err).Msg("Failed to list packages for rescan")
return
}
scanned := 0
skipped := 0
failed := 0
for _, pkg := range packages {
// Metadata pages and Go .mod/.info rows are not scannable artifacts.
if metadata.IsMetadataEntry(pkg.Registry, pkg.Name, pkg.Version) {
skipped++
continue
}
// Check if package needs rescanning
needsRescan, err := w.needsRescan(ctx, pkg)
if err != nil {
log.Error().
Err(err).
Str("package", pkg.Name).
Str("version", pkg.Version).
Msg("Failed to check rescan status")
failed++
continue
}
if !needsRescan {
log.Debug().
Str("package", pkg.Name).
Str("version", pkg.Version).
Bool("security_scanned", pkg.SecurityScanned).
Msg("Package does not need rescanning, skipping")
skipped++
continue
}
log.Info().
Str("registry", pkg.Registry).
Str("package", pkg.Name).
Str("version", pkg.Version).
Msg("Package needs rescanning")
if pkg.StorageKey == "" {
log.Warn().
Str("registry", pkg.Registry).
Str("package", pkg.Name).
Str("version", pkg.Version).
Msg("Package has no storage key, skipping rescan")
failed++
continue
}
source := w.manager.currentFileSource()
if source == nil {
log.Debug().
Str("registry", pkg.Registry).
Str("package", pkg.Name).
Str("version", pkg.Version).
Msg("No file source configured, skipping rescan")
skipped++
continue
}
filePath, cleanup, err := source(ctx, pkg.Registry, pkg.Name, pkg.Version)
if err != nil {
log.Warn().
Err(err).
Str("registry", pkg.Registry).
Str("package", pkg.Name).
Str("version", pkg.Version).
Str("storage_key", pkg.StorageKey).
Msg("Failed to read package file, skipping rescan")
failed++
continue
}
// Perform the actual scan
err = w.manager.ScanPackage(ctx, pkg.Registry, pkg.Name, pkg.Version, filePath)
cleanup()
if err != nil {
log.Error().
Err(err).
Str("registry", pkg.Registry).
Str("package", pkg.Name).
Str("version", pkg.Version).
Msg("Failed to rescan package")
failed++
continue
}
scanned++
var counts rescanCounts
jobs := make(chan *metadata.Package)
var wg sync.WaitGroup
for i := 0; i < w.concurrency; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for pkg := range jobs {
w.rescanOne(ctx, pkg, &counts)
}
}()
}
dispatch:
for _, pkg := range packages {
if metadata.IsMetadataEntry(pkg.Registry, pkg.Name, pkg.Version) {
counts.skipMetadata.Add(1)
continue
}
if w.idle(pkg) {
counts.skipIdle.Add(1)
continue
}
select {
case jobs <- pkg:
case <-ctx.Done():
break dispatch
case <-w.stopCh:
break dispatch
}
}
close(jobs)
wg.Wait()
log.Info().
Int("total", len(packages)).
Int("scanned", scanned).
Int("skipped", skipped).
Int("failed", failed).
Int64("scanned", counts.scanned.Load()).
Int64("failed", counts.failed.Load()).
Int64("skipped_metadata", counts.skipMetadata.Load()).
Int64("skipped_idle", counts.skipIdle.Load()).
Int64("skipped_fresh", counts.skipFresh.Load()).
Int64("skipped_no_source", counts.skipNoSource.Load()).
Int("concurrency", w.concurrency).
Dur("active_window", w.activeWindow).
Msg("Rescan cycle completed")
}
// idle reports whether a package was last served longer ago than the active window.
// A zero LastAccessed is unknown, so the package is scanned.
func (w *RescanWorker) idle(pkg *metadata.Package) bool {
if w.activeWindow <= 0 || pkg.LastAccessed.IsZero() {
return false
}
return time.Since(pkg.LastAccessed) > w.activeWindow
}
// rescanOne scans a single package when its result is missing or stale.
func (w *RescanWorker) rescanOne(ctx context.Context, pkg *metadata.Package, counts *rescanCounts) {
needsRescan, err := w.needsRescan(ctx, pkg)
if err != nil {
log.Error().
Err(err).
Str("package", pkg.Name).
Str("version", pkg.Version).
Msg("Failed to check rescan status")
counts.failed.Add(1)
return
}
if !needsRescan {
log.Debug().
Str("package", pkg.Name).
Str("version", pkg.Version).
Bool("security_scanned", pkg.SecurityScanned).
Msg("Package does not need rescanning, skipping")
counts.skipFresh.Add(1)
return
}
log.Info().
Str("registry", pkg.Registry).
Str("package", pkg.Name).
Str("version", pkg.Version).
Msg("Package needs rescanning")
if pkg.StorageKey == "" {
log.Warn().
Str("registry", pkg.Registry).
Str("package", pkg.Name).
Str("version", pkg.Version).
Msg("Package has no storage key, skipping rescan")
counts.failed.Add(1)
return
}
source := w.manager.currentFileSource()
if source == nil {
log.Debug().
Str("registry", pkg.Registry).
Str("package", pkg.Name).
Str("version", pkg.Version).
Msg("No file source configured, skipping rescan")
counts.skipNoSource.Add(1)
return
}
filePath, cleanup, err := source(ctx, pkg.Registry, pkg.Name, pkg.Version)
if err != nil {
log.Warn().
Err(err).
Str("registry", pkg.Registry).
Str("package", pkg.Name).
Str("version", pkg.Version).
Str("storage_key", pkg.StorageKey).
Msg("Failed to read package file, skipping rescan")
counts.failed.Add(1)
return
}
err = w.manager.ScanPackage(ctx, pkg.Registry, pkg.Name, pkg.Version, filePath)
cleanup()
if err != nil {
log.Error().
Err(err).
Str("registry", pkg.Registry).
Str("package", pkg.Name).
Str("version", pkg.Version).
Msg("Failed to rescan package")
counts.failed.Add(1)
return
}
counts.scanned.Add(1)
}
// needsRescan checks if a package needs to be rescanned
func (w *RescanWorker) needsRescan(ctx context.Context, pkg *metadata.Package) (bool, error) {
// Get latest scan result
+55 -2
View File
@@ -9,6 +9,7 @@ import (
hoardererrors "github.com/lukaszraczylo/gohoarder/pkg/errors"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// rescanStore serves a fixed package list and keeps saved scan results.
@@ -76,7 +77,7 @@ func pkgRow(registry, name, version string, lastAccessed time.Time) *metadata.Pa
}
}
func runRescan(t *testing.T, pkgs []*metadata.Package) map[string]int {
func runRescan(t *testing.T, pkgs []*metadata.Package, opts ...RescanOption) map[string]int {
t.Helper()
store := &rescanStore{results: map[string]*metadata.ScanResult{}, packages: pkgs}
mgr := newTestManager(t, store)
@@ -85,7 +86,7 @@ func runRescan(t *testing.T, pkgs []*metadata.Package) map[string]int {
mgr.SetFileSource(func(context.Context, string, string, string) (string, func(), error) {
return "/tmp/dummy", func() {}, nil
})
NewRescanWorker(mgr, store, time.Hour).rescanPackages(context.Background())
NewRescanWorker(mgr, store, time.Hour, opts...).rescanPackages(context.Background())
return cs.snapshot()
}
@@ -106,3 +107,55 @@ func TestRescanSkipsMetadataEntries(t *testing.T) {
scanKey("npm", "weird.mod", "1.0.0"): 1,
}, got)
}
func TestRescanActiveWindow(t *testing.T) {
now := time.Now()
pkgs := []*metadata.Package{
pkgRow("npm", "hot", "1.0.0", now.Add(-time.Hour)),
pkgRow("npm", "cold", "1.0.0", now.Add(-72*time.Hour)),
pkgRow("npm", "unknown", "1.0.0", time.Time{}),
}
tests := []struct {
name string
want []string
window time.Duration
}{
{"window off scans everything", []string{"hot", "cold", "unknown"}, 0},
{"window skips idle only", []string{"hot", "unknown"}, 24 * time.Hour},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := runRescan(t, pkgs, WithActiveWindow(tt.window))
want := map[string]int{}
for _, n := range tt.want {
want[scanKey("npm", n, "1.0.0")] = 1
}
assert.Equal(t, want, got)
})
}
}
func TestRescanConcurrencyScansEachOnce(t *testing.T) {
now := time.Now()
var pkgs []*metadata.Package
want := map[string]int{}
for i := 0; i < 40; i++ {
name := string(rune('a'+i%26)) + string(rune('a'+i/26))
pkgs = append(pkgs, pkgRow("npm", name, "1.0.0", now))
want[scanKey("npm", name, "1.0.0")] = 1
}
pkgs = append(pkgs, pkgRow("go", "m/@v/v1.mod", "v1", now))
for _, n := range []int{-2, 0, 1, 3, 8} {
got := runRescan(t, pkgs, WithConcurrency(n))
require.Equal(t, want, got, "concurrency %d", n)
}
}
func TestRescanConcurrencyFloor(t *testing.T) {
for _, n := range []int{-1, 0} {
w := NewRescanWorker(nil, nil, time.Hour, WithConcurrency(n))
assert.Equal(t, 1, w.concurrency)
}
assert.Equal(t, 1, NewRescanWorker(nil, nil, time.Hour).concurrency)
}