Skip to content
Snippets Groups Projects
Commit 197ca0ea authored by gjahn's avatar gjahn
Browse files

Make ephemeral store concurrency-safe

Fore more information see https://go.dev/blog/maps#concurrency
parent 7b35b477
No related branches found
No related tags found
No related merge requests found
...@@ -2,17 +2,20 @@ package state ...@@ -2,17 +2,20 @@ package state
import ( import (
"errors" "errors"
"sync"
) )
type Ephemeral struct { type Ephemeral struct {
store map[ string ] *Item store map[ string ] Item
mux sync.Mutex
} }
func NewEphemeralStore() *Ephemeral { func NewEphemeralStore() *Ephemeral {
return &Ephemeral{ return &Ephemeral{
store: map[ string ] *Item {}, store: map[ string ] Item {},
mux: sync.Mutex{},
} }
} }
...@@ -23,7 +26,11 @@ func ( e *Ephemeral ) Add( i *Item ) error { ...@@ -23,7 +26,11 @@ func ( e *Ephemeral ) Add( i *Item ) error {
} }
name := i.Name() name := i.Name()
e.mux.Lock()
e.store[ name ] = i e.store[ name ] = i
e.mux.Unlock()
return nil return nil
} }
...@@ -33,7 +40,10 @@ func ( e *Ephemeral ) Remove( name string ) error { ...@@ -33,7 +40,10 @@ func ( e *Ephemeral ) Remove( name string ) error {
return errors.New( "ephemeral storage not available" ) return errors.New( "ephemeral storage not available" )
} }
e.mux.Lock()
delete( e.store, name ) delete( e.store, name )
e.mux.Unlock()
return nil return nil
} }
...@@ -43,7 +53,10 @@ func ( e *Ephemeral ) Fetch( name string ) ( *Item, error ) { ...@@ -43,7 +53,10 @@ func ( e *Ephemeral ) Fetch( name string ) ( *Item, error ) {
return nil, errors.New( "ephemeral storage not available" ) return nil, errors.New( "ephemeral storage not available" )
} }
e.mux.Lock()
item, found := e.store[ name ] item, found := e.store[ name ]
e.mux.Unlock()
if !found { if !found {
return nil, nil return nil, nil
} }
...@@ -56,10 +69,13 @@ func ( e *Ephemeral ) Show() ( []string, error ) { ...@@ -56,10 +69,13 @@ func ( e *Ephemeral ) Show() ( []string, error ) {
return nil, errors.New( "ephemeral storage not available" ) return nil, errors.New( "ephemeral storage not available" )
} }
e.mux.Lock()
names := make( []string, 0, len( e.store ) ) names := make( []string, 0, len( e.store ) )
for k := range e.store { for k := range e.store {
names = append( names, k ) names = append( names, k )
} }
e.mux.Unlock()
return names, nil return names, nil
} }
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment