fix(cache): cancel background scans when the manager closes

This commit is contained in:
2026-11-23 01:15:19 +00:00
parent 380b3b9d1c
commit 1d0363b247
2 changed files with 55 additions and 1 deletions
+7 -1
View File
@@ -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()
})
+48
View File
@@ -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")
}
}