fix(metadata): wait for the aggregation worker before closing the store

This commit is contained in:
2026-11-23 14:26:35 +00:00
parent a84f080b79
commit fe2d9f8b3a
4 changed files with 87 additions and 3 deletions
+15 -2
View File
@@ -1,6 +1,7 @@
package gormstore
import (
"sync"
"time"
"github.com/rs/zerolog/log"
@@ -17,6 +18,8 @@ type AggregationWorker struct {
stopChan chan struct{}
ticker *time.Ticker
now func() time.Time // nil means time.Now
wg sync.WaitGroup
stopOnce sync.Once
}
// NewAggregationWorker creates a new aggregation worker
@@ -36,6 +39,15 @@ func (w *AggregationWorker) clock() time.Time {
return time.Now()
}
// StartAsync runs Start in a goroutine that Stop waits for.
func (w *AggregationWorker) StartAsync() {
w.wg.Add(1)
go func() {
defer w.wg.Done()
w.Start()
}()
}
// Start begins the aggregation worker
func (w *AggregationWorker) Start() {
log.Info().Msg("Starting aggregation worker")
@@ -68,9 +80,10 @@ func (w *AggregationWorker) Start() {
}
}
// Stop stops the aggregation worker
// Stop stops the aggregation worker and waits for a started one to exit. Safe to call repeatedly.
func (w *AggregationWorker) Stop() {
close(w.stopChan)
w.stopOnce.Do(func() { close(w.stopChan) })
w.wg.Wait()
}
// AggregateHourly aggregates download events into hourly stats
+13
View File
@@ -0,0 +1,13 @@
package gormstore
import "testing"
func TestCloseIsIdempotent(t *testing.T) {
store := openFileStore(t, true)
if err := store.Close(); err != nil {
t.Fatalf("first Close: %v", err)
}
if err := store.Close(); err != nil {
t.Fatalf("second Close: %v", err)
}
}
+1 -1
View File
@@ -128,7 +128,7 @@ func NewV2(cfg Config) (*GORMStoreV2, error) {
// Start aggregation worker (skip for in-memory databases used in tests)
if !strings.Contains(cfg.DSN, ":memory:") {
store.aggregationWorker = NewAggregationWorker(db)
go store.aggregationWorker.Start()
store.aggregationWorker.StartAsync()
} else {
// For tests: create worker but don't start it
store.aggregationWorker = NewAggregationWorker(db)