Skip to content

Commit

Permalink
Fix potential data races (#82)
Browse files Browse the repository at this point in the history
  • Loading branch information
streamer45 authored Jan 9, 2023
1 parent 8e39357 commit dbc7c31
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
5 changes: 3 additions & 2 deletions service/audit.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,13 @@ func (s *Service) httpAudit(handler string, data *httpData, w http.ResponseWrite
}

func reqAuditFields(req *http.Request) []mlog.Field {
delete(req.Header, "Authorization")
hdr := req.Header.Clone()
delete(hdr, "Authorization")
fields := []mlog.Field{
mlog.String("remoteAddr", req.RemoteAddr),
mlog.String("method", req.Method),
mlog.String("url", req.URL.String()),
mlog.Any("header", req.Header),
mlog.Any("header", hdr),
mlog.String("host", req.Host),
}
return fields
Expand Down
18 changes: 16 additions & 2 deletions service/store/bitcask.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ func (s *bitcaskStore) Set(key, value string) error {
return ErrEmptyKey
}

s.mut.Lock()
defer s.mut.Unlock()

err := s.db.Put([]byte(key), []byte(value))
if err != nil {
return fmt.Errorf("failed to set key: %w", err)
Expand All @@ -47,12 +50,13 @@ func (s *bitcaskStore) Set(key, value string) error {
}

func (s *bitcaskStore) Put(key, value string) error {
s.mut.Lock()
defer s.mut.Unlock()
if key == "" {
return ErrEmptyKey
}

s.mut.Lock()
defer s.mut.Unlock()

if s.db.Has([]byte(key)) {
return ErrConflict
}
Expand All @@ -73,6 +77,10 @@ func (s *bitcaskStore) Get(key string) (string, error) {
if key == "" {
return "", ErrEmptyKey
}

s.mut.RLock()
defer s.mut.RUnlock()

val, err := s.db.Get([]byte(key))
if errors.Is(err, bitcask.ErrKeyNotFound) {
return "", ErrNotFound
Expand All @@ -87,6 +95,9 @@ func (s *bitcaskStore) Delete(key string) error {
return ErrEmptyKey
}

s.mut.Lock()
defer s.mut.Unlock()

err := s.db.Delete([]byte(key))
if err != nil {
return fmt.Errorf("failed to delete key: %w", err)
Expand All @@ -100,6 +111,9 @@ func (s *bitcaskStore) Delete(key string) error {
}

func (s *bitcaskStore) Close() error {
s.mut.Lock()
defer s.mut.Unlock()

err := s.db.Close()
if err != nil {
return fmt.Errorf("failed to close store: %w", err)
Expand Down

0 comments on commit dbc7c31

Please sign in to comment.