Sorting before termination of uploads

This fix is in limitedstore/limitedstore.go, to intelligently terminate
existing file uploads. The store.uploads map is sorted, and
then analysed to remove the bigger existing uploads first.
This commit is contained in:
anirudt 2015-11-21 09:02:48 +05:30
parent 7c7c49f786
commit 06be13f200
1 changed files with 27 additions and 1 deletions

View File

@ -14,6 +14,7 @@ package limitedstore
import ( import (
"github.com/tus/tusd" "github.com/tus/tusd"
"sync" "sync"
"sort"
) )
type LimitedStore struct { type LimitedStore struct {
@ -26,6 +27,19 @@ type LimitedStore struct {
mutex *sync.Mutex mutex *sync.Mutex
} }
// Pair structure to perform map-sorting
type Pair struct {
key string
value int64
}
type Pairlist []Pair
func (p Pairlist) Len() int { return len(p) }
func (p Pairlist) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p Pairlist) Less(i, j int) bool { return p[i].value < p[j].value }
// Create a new limited store with the given size as the maximum storage size // Create a new limited store with the given size as the maximum storage size
func New(storeSize int64, dataStore tusd.DataStore) *LimitedStore { func New(storeSize int64, dataStore tusd.DataStore) *LimitedStore {
return &LimitedStore{ return &LimitedStore{
@ -82,8 +96,19 @@ func (store *LimitedStore) ensureSpace(size int64) error {
// Enough space is available to store the new upload // Enough space is available to store the new upload
return nil return nil
} }
sorted_uploads := make(Pairlist, len(store.uploads))
i := 0
for u,h := range store.uploads {
sorted_uploads[i] = Pair{u, h}
i++
}
sort.Sort(sorted_uploads)
for id, _ := range store.uploads { // Reverse traversal through the
// uploads in terms of size, biggest upload first
j := len(store.uploads)
for j >= 0 {
id := sorted_uploads[j].key
if err := store.terminate(id); err != nil { if err := store.terminate(id); err != nil {
return err return err
} }
@ -92,6 +117,7 @@ func (store *LimitedStore) ensureSpace(size int64) error {
// Enough space has been freed to store the new upload // Enough space has been freed to store the new upload
return nil return nil
} }
j--
} }
return nil return nil