From 5dc839696b83d5e29eea654efdee474f111c52d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Mierzwa?= Date: Tue, 7 Jul 2020 21:10:17 +0100 Subject: [PATCH] fix(backend): avoid race conditions when generating label colors --- internal/transform/colors.go | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/internal/transform/colors.go b/internal/transform/colors.go index 80e571f52..f11662ddf 100644 --- a/internal/transform/colors.go +++ b/internal/transform/colors.go @@ -2,8 +2,10 @@ package transform import ( "crypto/sha1" + "image/color" "io" "math/rand" + "sync" "github.com/prymitive/karma/internal/config" "github.com/prymitive/karma/internal/models" @@ -15,6 +17,8 @@ import ( log "github.com/sirupsen/logrus" ) +var lock sync.RWMutex + func labelToSeed(key string, val string) int64 { h := sha1.New() @@ -35,6 +39,13 @@ func labelToSeed(key string, val string) int64 { return seed } +func colorFromKeyVal(key, val string) color.Color { + lock.Lock() + defer lock.Unlock() + rand.Seed(labelToSeed(key, val)) + return randomcolor.New(randomcolor.Random, randomcolor.LIGHT) +} + func rgbToBrightness(r, g, b uint8) int32 { return ((int32(r) * 299) + (int32(g) * 587) + (int32(b) * 114)) / 1000 } @@ -88,8 +99,7 @@ func ColorLabel(colorStore models.LabelsColorMap, key string, val string) { colorStore[key] = make(map[string]models.LabelColors) } if _, found := colorStore[key][val]; !found { - rand.Seed(labelToSeed(key, val)) - color := randomcolor.New(randomcolor.Random, randomcolor.LIGHT) + color := colorFromKeyVal(key, val) red, green, blue, alpha := color.RGBA() bc := models.Color{ Red: uint8(red >> 8),