| 1 |
package desync |
| 2 |
|
| 3 |
import ( |
| 4 |
"sync" |
| 5 |
|
| 6 |
"github.com/pkg/errors" |
| 7 |
) |
| 8 |
|
| 9 |
var _ Store = &SwapStore{} |
| 10 |
var _ WriteStore = &SwapWriteStore{} |
| 11 |
|
| 12 |
// SwapStore wraps another store and provides the ability to swap out the underlying |
| 13 |
// store with another one while under load. Typically used to reload config for |
| 14 |
// long-running processes, perhaps reloading a store config file on SIGHUP and |
| 15 |
// updating the store on-the-fly without restart. |
| 16 |
type SwapStore struct { |
| 17 |
s Store |
| 18 |
|
| 19 |
mu sync.RWMutex |
| 20 |
} |
| 21 |
|
| 22 |
// SwapWriteStore does the same as SwapStore but implements WriteStore as well. |
| 23 |
type SwapWriteStore struct { |
| 24 |
SwapStore |
| 25 |
} |
| 26 |
|
| 27 |
// NewSwapStore creates an instance of a swap store wrapper that allows replacing |
| 28 |
// the wrapped store at runtime. |
| 29 |
func NewSwapStore(s Store) *SwapStore { |
| 30 |
return &SwapStore{s: s} |
| 31 |
} |
| 32 |
|
| 33 |
// NewSwapWriteStore initializes as new instance of a swap store that supports |
| 34 |
// writing and swapping at runtime. |
| 35 |
func NewSwapWriteStore(s Store) *SwapWriteStore { |
| 36 |
return &SwapWriteStore{SwapStore{s: s}} |
| 37 |
} |
| 38 |
|
| 39 |
// GetChunk reads and returns one (compressed!) chunk from the store |
| 40 |
func (s *SwapStore) GetChunk(id ChunkID) (*Chunk, error) { |
| 41 |
s.mu.RLock() |
| 42 |
defer s.mu.RUnlock() |
| 43 |
return s.s.GetChunk(id) |
| 44 |
} |
| 45 |
|
| 46 |
// HasChunk returns true if the chunk is in the store |
| 47 |
func (s *SwapStore) HasChunk(id ChunkID) (bool, error) { |
| 48 |
s.mu.RLock() |
| 49 |
defer s.mu.RUnlock() |
| 50 |
return s.s.HasChunk(id) |
| 51 |
} |
| 52 |
|
| 53 |
func (s *SwapStore) String() string { |
| 54 |
s.mu.RLock() |
| 55 |
defer s.mu.RUnlock() |
| 56 |
return s.s.String() |
| 57 |
} |
| 58 |
|
| 59 |
// Close the store. NOP operation, needed to implement Store interface. |
| 60 |
func (s *SwapStore) Close() error { |
| 61 |
s.mu.RLock() |
| 62 |
defer s.mu.RUnlock() |
| 63 |
return s.s.Close() |
| 64 |
} |
| 65 |
|
| 66 |
// Close the store. NOP operation, needed to implement Store interface. |
| 67 |
func (s *SwapStore) Swap(new Store) error { |
| 68 |
s.mu.Lock() |
| 69 |
defer s.mu.Unlock() |
| 70 |
_, oldWritable := s.s.(WriteStore) |
| 71 |
_, newWritable := new.(WriteStore) |
| 72 |
if oldWritable && !newWritable { |
| 73 |
return errors.New("a writable store can only be updated with another writable one") |
| 74 |
} |
| 75 |
s.s.Close() // Close the old store |
| 76 |
s.s = new |
| 77 |
return nil |
| 78 |
} |
| 79 |
|
| 80 |
// StoreChunk adds a new chunk to the store |
| 81 |
func (s *SwapWriteStore) StoreChunk(chunk *Chunk) error { |
| 82 |
s.mu.RLock() |
| 83 |
defer s.mu.RUnlock() |
| 84 |
return s.s.(WriteStore).StoreChunk(chunk) |
| 85 |
} |