mirror of
https://github.com/prymitive/karma
synced 2026-05-05 03:16:51 +00:00
fix(backend): avoid race conditions when generating label colors
This commit is contained in:
committed by
Łukasz Mierzwa
parent
8fe1484c97
commit
5dc839696b
@@ -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),
|
||||
|
||||
Reference in New Issue
Block a user