From 662f5155b983a79ee07e5c21baa4179a35f868ef Mon Sep 17 00:00:00 2001 From: Denis Arh Date: Mon, 4 Apr 2022 16:50:29 +0200 Subject: [PATCH] Address data race in pkg/healtcheck --- pkg/healthcheck/check.go | 10 +++++++++- pkg/healthcheck/check_test.go | 14 ++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/pkg/healthcheck/check.go b/pkg/healthcheck/check.go index 1fbe94a28..307eeec2b 100644 --- a/pkg/healthcheck/check.go +++ b/pkg/healthcheck/check.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "strings" + "sync" ) type ( @@ -28,6 +29,7 @@ type ( results []*result checks struct { + l sync.RWMutex cc []*check } ) @@ -50,10 +52,16 @@ func New() *checks { // Add appends new check func (c *checks) Add(fn checkFn, label string, description ...string) { + c.l.Lock() + defer c.l.Unlock() + c.cc = append(c.cc, &check{fn, &Meta{Label: label, Description: strings.Join(description, "")}}) } -func (c checks) Run(ctx context.Context) results { +func (c *checks) Run(ctx context.Context) results { + c.l.RLock() + defer c.l.RUnlock() + var rr = make([]*result, len(c.cc)) for i, c := range c.cc { diff --git a/pkg/healthcheck/check_test.go b/pkg/healthcheck/check_test.go index ab133dc98..81a1a6051 100644 --- a/pkg/healthcheck/check_test.go +++ b/pkg/healthcheck/check_test.go @@ -66,3 +66,17 @@ func Test_Healthy(t *testing.T) { }) } } + +// tested with +// go test -count 10 -race -run Test_DataRace ./pkg/healthcheck/... +func Test_DataRace(t *testing.T) { + hc := New() + + go func() { + hc.Add(func(ctx context.Context) error { return nil }, "hc1") + hc.Add(func(ctx context.Context) error { return nil }, "hc2") + hc.Add(func(ctx context.Context) error { return nil }, "hc3") + }() + go hc.Run(context.Background()) + +}