-
Notifications
You must be signed in to change notification settings - Fork 44
/
chunkstorage.go
68 lines (58 loc) · 1.89 KB
/
chunkstorage.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package desync
import (
"sync"
)
// ChunkStorage stores chunks in a writable store. It can be safely used by multiple goroutines and
// contains an internal cache of what chunks have been store previously.
type ChunkStorage struct {
sync.Mutex
ws WriteStore
processed map[ChunkID]struct{}
}
// NewChunkStorage initializes a ChunkStorage object.
func NewChunkStorage(ws WriteStore) *ChunkStorage {
s := &ChunkStorage{
ws: ws,
processed: make(map[ChunkID]struct{}),
}
return s
}
// Mark a chunk in the in-memory cache as having been processed and returns true
// if it was already marked, and is therefore presumably already stored.
func (s *ChunkStorage) markProcessed(id ChunkID) bool {
s.Lock()
defer s.Unlock()
_, ok := s.processed[id]
s.processed[id] = struct{}{}
return ok
}
// Unmark a chunk in the in-memory cache. This is used if a chunk is first
// marked as processed, but then actually fails to be stored. Unmarking the
// makes it eligible to be re-tried again in case of errors.
func (s *ChunkStorage) unmarkProcessed(id ChunkID) {
s.Lock()
defer s.Unlock()
delete(s.processed, id)
}
// StoreChunk stores a single chunk in a synchronous manner.
func (s *ChunkStorage) StoreChunk(chunk *Chunk) (err error) {
// Mark this chunk as done so no other goroutine will attempt to store it
// at the same time. If this is the first time this chunk is marked, it'll
// return false and we need to continue processing/storing the chunk below.
if s.markProcessed(chunk.ID()) {
return nil
}
// Skip this chunk if the store already has it
if hasChunk, err := s.ws.HasChunk(chunk.ID()); err != nil || hasChunk {
return err
}
// The chunk was marked as "processed" above. If there's a problem to actually
// store it, we need to unmark it again.
defer func() {
if err != nil {
s.unmarkProcessed(chunk.ID())
}
}()
// Store the compressed chunk
return s.ws.StoreChunk(chunk)
}