Skip to content

Commit

Permalink
add mutex on download store
Browse files Browse the repository at this point in the history
  • Loading branch information
Romain committed Feb 2, 2017
1 parent 322de40 commit 2689490
Showing 1 changed file with 23 additions and 8 deletions.
31 changes: 23 additions & 8 deletions pkg/vfs/download_store.go
Expand Up @@ -2,6 +2,7 @@ package vfs

import (
"encoding/hex"
"sync"
"time"

"github.com/cozy/cozy-stack/pkg/crypto"
Expand All @@ -24,6 +25,7 @@ type fileRef struct {
const downloadStoreTTL = 1 * time.Hour
const downloadStoreCleanInterval = 1 * time.Hour

var storeStoreMutex = &sync.Mutex{}
var storeStore map[string]*memStore

func init() {
Expand Down Expand Up @@ -51,6 +53,8 @@ func cleanStore(s *memStore) {
}

func cleanDownloadStore() {
storeStoreMutex.Lock()
defer storeStoreMutex.Unlock()
for i, s := range storeStore {
cleanStore(s)
if len(s.Files) == 0 && len(s.Archives) == 0 {
Expand All @@ -61,21 +65,24 @@ func cleanDownloadStore() {

// GetStore returns the DownloadStore for the given Instance
func GetStore(domain string) DownloadStore {
storeStoreMutex.Lock()
defer storeStoreMutex.Unlock()
if storeStore == nil {
storeStore = make(map[string]*memStore)
}
store, ok := storeStore[domain]
if ok {
return store
}
storeStore[domain] = &memStore{
Archives: make(map[string]*Archive),
Files: make(map[string]*fileRef),
store, exists := storeStore[domain]
if !exists {
store = &memStore{
Archives: make(map[string]*Archive),
Files: make(map[string]*fileRef),
}
storeStore[domain] = store
}
return storeStore[domain]
return store
}

type memStore struct {
Mutex sync.Mutex
Archives map[string]*Archive
Files map[string]*fileRef
}
Expand All @@ -89,6 +96,8 @@ func (s *memStore) AddFile(f string) (string, error) {
Path: f,
ExpiresAt: time.Now().Add(downloadStoreTTL),
}
s.Mutex.Lock()
defer s.Mutex.Unlock()
cleanStore(s)
key := s.makeSecret()
s.Files[key] = fref
Expand All @@ -97,13 +106,17 @@ func (s *memStore) AddFile(f string) (string, error) {

func (s *memStore) AddArchive(a *Archive) (string, error) {
a.ExpiresAt = time.Now().Add(downloadStoreTTL)
s.Mutex.Lock()
defer s.Mutex.Unlock()
cleanStore(s)
key := s.makeSecret()
s.Archives[key] = a
return key, nil
}

func (s *memStore) GetFile(k string) (string, error) {
s.Mutex.Lock()
defer s.Mutex.Unlock()
f, ok := s.Files[k]
if !ok {
return "", nil
Expand All @@ -116,6 +129,8 @@ func (s *memStore) GetFile(k string) (string, error) {
}

func (s *memStore) GetArchive(k string) (*Archive, error) {
s.Mutex.Lock()
defer s.Mutex.Unlock()
a, ok := s.Archives[k]
if !ok {
return nil, nil
Expand Down

0 comments on commit 2689490

Please sign in to comment.