-
Notifications
You must be signed in to change notification settings - Fork 44
/
storerouter.go
77 lines (69 loc) · 1.73 KB
/
storerouter.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
69
70
71
72
73
74
75
76
77
package desync
import (
"strings"
"github.com/pkg/errors"
)
// StoreRouter is used to route requests to multiple stores. When a chunk is
// requested from the router, it'll query the first store and if that returns
// ChunkMissing, it'll move on to the next.
type StoreRouter struct {
Stores []Store
}
// NewStoreRouter returns an initialized router
func NewStoreRouter(stores ...Store) StoreRouter {
var l []Store
for _, s := range stores {
l = append(l, s)
}
return StoreRouter{l}
}
// GetChunk queries the available stores in order and moves to the next if
// it gets a ChunkMissing. Fails if any store returns a different error.
func (r StoreRouter) GetChunk(id ChunkID) (*Chunk, error) {
for _, s := range r.Stores {
chunk, err := s.GetChunk(id)
switch err.(type) {
case nil:
return chunk, nil
case ChunkMissing:
continue
default:
return nil, errors.Wrap(err, s.String())
}
}
return nil, ChunkMissing{id}
}
// HasChunk returns true if one of the containing stores has the chunk. It
// goes through the stores in order and returns as soon as the chunk is found.
func (r StoreRouter) HasChunk(id ChunkID) (bool, error) {
for _, s := range r.Stores {
hasChunk, err := s.HasChunk(id)
if err != nil {
return false, err
}
if hasChunk {
return true, nil
}
}
return false, nil
}
func (r StoreRouter) String() string {
var a []string
for _, s := range r.Stores {
a = append(a, s.String())
}
return strings.Join(a, ",")
}
// Close calls the Close() method on every store in the router. Returns
// only the first error encountered.
func (r StoreRouter) Close() error {
var sErr error
for _, s := range r.Stores {
if err := s.Close(); err != nil {
if sErr == nil {
sErr = err
}
}
}
return sErr
}