Debian Codegraph @

chunkstorage.go

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