From 5b8733f8ec59df3e22d5fba4d1e3e6f92977587b Mon Sep 17 00:00:00 2001 From: Guilhem Fanton Date: Thu, 23 Aug 2018 18:48:43 +0200 Subject: [PATCH] fix(store): Fix store concurrency --- helpers/helpers.go | 49 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 37 insertions(+), 12 deletions(-) diff --git a/helpers/helpers.go b/helpers/helpers.go index 0367deee..fd6ea999 100644 --- a/helpers/helpers.go +++ b/helpers/helpers.go @@ -6,6 +6,7 @@ import ( "reflect" "regexp" "strings" + "sync" "text/template" "github.com/Masterminds/sprig" @@ -22,13 +23,6 @@ var ( registry *ggdescriptor.Registry // some helpers need access to registry ) -// Utility to store some vars across multiple scope -var store = make(map[string]interface{}) - -func SetRegistry(reg *ggdescriptor.Registry) { - registry = reg -} - var ProtoHelpersFuncMap = template.FuncMap{ "string": func(i interface { String() string @@ -166,19 +160,50 @@ var ProtoHelpersFuncMap = template.FuncMap{ var pathMap map[interface{}]*descriptor.SourceCodeInfo_Location -func setStore(key string, i interface{}) string { - store[key] = i - return "" +var store = newStore() + +// Utility to store some vars across multiple scope +type globalStore struct { + store map[string]interface{} + mu sync.Mutex +} + +func newStore() *globalStore { + return &globalStore{ + store: make(map[string]interface{}), + } } -func getStore(s string) interface{} { - if v, ok := store[s]; ok { +func (s *globalStore) getData(key string) interface{} { + s.mu.Lock() + defer s.mu.Unlock() + + if v, ok := s.store[key]; ok { return v } return false } +func (s *globalStore) setData(key string, o interface{}) { + s.mu.Lock() + s.store[key] = o + s.mu.Unlock() +} + +func setStore(key string, o interface{}) string { + store.setData(key, o) + return "" +} + +func getStore(key string) interface{} { + return store.getData(key) +} + +func SetRegistry(reg *ggdescriptor.Registry) { + registry = reg +} + func InitPathMap(file *descriptor.FileDescriptorProto) { pathMap = make(map[interface{}]*descriptor.SourceCodeInfo_Location) addToPathMap(file.GetSourceCodeInfo(), file, []int32{})