diff --git a/pkg/cache/cache.go b/pkg/cache/cache.go index 4e4ed34..bc05449 100644 --- a/pkg/cache/cache.go +++ b/pkg/cache/cache.go @@ -44,6 +44,8 @@ type Manager struct { analytics AnalyticsInterface broadcaster events.Broadcaster stopCh chan struct{} + bgCtx context.Context // cancelled by Close; parent of background scans + bgCancel context.CancelFunc sf singleflight.Group config Config cleanupWG sync.WaitGroup @@ -175,7 +177,10 @@ func New(storage storage.StorageBackend, metadata metadata.MetadataStore, scanne config.MaxPackageSize = 2 * 1024 * 1024 * 1024 // 2GB default } + bgCtx, bgCancel := context.WithCancel(context.Background()) manager := &Manager{ + bgCtx: bgCtx, + bgCancel: bgCancel, storage: storage, metadata: metadata, scanner: scanner, @@ -616,7 +621,7 @@ func (m *Manager) store(ctx context.Context, registry, name, version string, dat } go func() { - scanCtx := context.Background() + scanCtx := m.bgCtx var filePath string var cleanupFunc func() @@ -826,6 +831,7 @@ func (m *Manager) Close() error { // Stop cleanup worker (idempotent via sync.Once). m.closeOnce.Do(func() { + m.bgCancel() close(m.stopCh) m.cleanupWG.Wait() }) diff --git a/pkg/cache/scan_shutdown_test.go b/pkg/cache/scan_shutdown_test.go new file mode 100644 index 0000000..149048a --- /dev/null +++ b/pkg/cache/scan_shutdown_test.go @@ -0,0 +1,48 @@ +package cache + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +// blockingScanner holds the scan open until its context ends. +type blockingScanner struct { + started chan struct{} + done chan error +} + +func (s *blockingScanner) Enabled() bool { return true } +func (s *blockingScanner) ScanPackage(ctx context.Context, _, _, _, _ string) error { + close(s.started) + <-ctx.Done() + s.done <- ctx.Err() + return ctx.Err() +} +func (s *blockingScanner) CheckVulnerabilities(context.Context, string, string, string) (bool, string, error) { + return false, "", nil +} + +// Close must cancel an in-flight background scan instead of leaking it. +func TestClose_CancelsBackgroundScan(t *testing.T) { + sc := &blockingScanner{started: make(chan struct{}), done: make(chan error, 1)} + manager := newMissManager(t, sc, Config{ScanWaitTimeout: 50 * time.Millisecond}) + + _, err := manager.Get(context.Background(), "npm", "lodash", "4.17.21", fetchLodash) + require.NoError(t, err) + select { + case <-sc.started: + case <-time.After(2 * time.Second): + t.Fatal("scan did not start") + } + + require.NoError(t, manager.Close()) + select { + case err := <-sc.done: + require.ErrorIs(t, err, context.Canceled) + case <-time.After(2 * time.Second): + t.Fatal("background scan still running after Close") + } +}