From 5d95719653946dc827a565110be52946cde0147a Mon Sep 17 00:00:00 2001 From: Pete Steyert-Woods Date: Tue, 9 Apr 2024 12:56:40 +0100 Subject: [PATCH] Fix race condition in pgxstore cleanup - Run this test with the race detector on --- pgxstore/pgxstore.go | 2 +- pgxstore/pgxstore_test.go | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/pgxstore/pgxstore.go b/pgxstore/pgxstore.go index 65fe8d0..5d2db88 100644 --- a/pgxstore/pgxstore.go +++ b/pgxstore/pgxstore.go @@ -28,6 +28,7 @@ func New(pool *pgxpool.Pool) *PostgresStore { func NewWithCleanupInterval(pool *pgxpool.Pool, cleanupInterval time.Duration) *PostgresStore { p := &PostgresStore{pool: pool} if cleanupInterval > 0 { + p.stopCleanup = make(chan bool) go p.startCleanup(cleanupInterval) } return p @@ -99,7 +100,6 @@ func (p *PostgresStore) All() (map[string][]byte, error) { } func (p *PostgresStore) startCleanup(interval time.Duration) { - p.stopCleanup = make(chan bool) ticker := time.NewTicker(interval) for { select { diff --git a/pgxstore/pgxstore_test.go b/pgxstore/pgxstore_test.go index 047ead0..e2565d1 100644 --- a/pgxstore/pgxstore_test.go +++ b/pgxstore/pgxstore_test.go @@ -5,6 +5,7 @@ import ( "context" "os" "reflect" + "strconv" "testing" "time" @@ -241,6 +242,26 @@ func TestCleanup(t *testing.T) { } } +func TestStopCleanup(t *testing.T) { + ctx := context.Background() + + dsn := os.Getenv("SCS_POSTGRES_TEST_DSN") + pool, err := pgxpool.New(ctx, dsn) + if err != nil { + t.Fatal(err) + } + defer pool.Close() + + for i := 0; i < 100; i++ { + t.Run(strconv.Itoa(i), func(t *testing.T) { + t.Parallel() + p := New(pool) + time.Sleep(100 * time.Millisecond) + defer p.StopCleanup() + }) + } +} + func TestStopNilCleanup(t *testing.T) { dsn := os.Getenv("SCS_POSTGRES_TEST_DSN") pool, err := pgxpool.New(context.Background(), dsn)