diff options
| author | Paul Buetow <paul@buetow.org> | 2026-05-01 22:42:18 +0300 |
|---|---|---|
| committer | Paul Buetow <paul@buetow.org> | 2026-05-01 22:42:18 +0300 |
| commit | 36bf8b9f1f1adf99aebd5dea37ff8cf6f3e847cd (patch) | |
| tree | 3a7e363ee6f57dc4c54adc6651e487938025e824 | |
| parent | 6b33ed2dc614c51627d20c83df5310d776983555 (diff) | |
fix(gc): pass cancellable context to GCWorker.run() to avoid goroutine leak (#5)
Replace context.Background() inside GCWorker.run() with a cancellable
context created in Start() and cancelled in Stop().
This fixes the goroutine leak risk identified in 100-go-mistakes #62.
Files changed:
- internal/service/gc.go
| -rw-r--r-- | internal/service/gc.go | 17 |
1 files changed, 13 insertions, 4 deletions
diff --git a/internal/service/gc.go b/internal/service/gc.go index 9cb07d5..f95b12a 100644 --- a/internal/service/gc.go +++ b/internal/service/gc.go @@ -25,6 +25,8 @@ type GCWorker struct { stopOnce sync.Once wg sync.WaitGroup mediaRoot string + ctx context.Context + cancel context.CancelFunc } // NewGCWorker creates a GCWorker. Use WithAge and WithInterval to customise. @@ -54,6 +56,7 @@ func (w *GCWorker) WithInterval(interval time.Duration) *GCWorker { // Start launches the GC goroutine. func (w *GCWorker) Start() { + w.ctx, w.cancel = context.WithCancel(context.Background()) w.ticker = time.NewTicker(w.interval) w.wg.Add(1) go func() { @@ -61,7 +64,7 @@ func (w *GCWorker) Start() { for { select { case <-w.ticker.C: - w.run() + w.run(w.ctx) case <-w.stopCh: return } @@ -76,13 +79,15 @@ func (w *GCWorker) Stop() { if w.ticker != nil { w.ticker.Stop() } + if w.cancel != nil { + w.cancel() + } close(w.stopCh) }) w.wg.Wait() } -func (w *GCWorker) run() { - ctx := context.Background() +func (w *GCWorker) run(ctx context.Context) { items, err := w.store.ListDeletedMedia(ctx) if err != nil { if w.logger != nil { @@ -129,6 +134,10 @@ func (w *GCWorker) RunOnce() error { if w.interval == 0 { return fmt.Errorf("worker not started") } - w.run() + ctx := w.ctx + if ctx == nil { + ctx = context.Background() + } + w.run(ctx) return nil } |
