Debian Codegraph @

storerouter.go

raw
1 package desync
2
3 import (
4 "strings"
5
6 "github.com/pkg/errors"
7 )
8
9 // StoreRouter is used to route requests to multiple stores. When a chunk is
10 // requested from the router, it'll query the first store and if that returns
11 // ChunkMissing, it'll move on to the next.
12 type StoreRouter struct {
13 Stores []Store
14 }
15
16 // NewStoreRouter returns an initialized router
17 func NewStoreRouter(stores ...Store) StoreRouter {
18 var l []Store
19 l = append(l, stores...)
20 return StoreRouter{l}
21 }
22
23 // GetChunk queries the available stores in order and moves to the next if
24 // it gets a ChunkMissing. Fails if any store returns a different error.
25 func (r StoreRouter) GetChunk(id ChunkID) (*Chunk, error) {
26 for _, s := range r.Stores {
27 chunk, err := s.GetChunk(id)
28 switch err.(type) {
29 case nil:
30 return chunk, nil
31 case ChunkMissing:
32 continue
33 default:
34 return nil, errors.Wrap(err, s.String())
35 }
36 }
37 return nil, ChunkMissing{id}
38 }
39
40 // HasChunk returns true if one of the containing stores has the chunk. It
41 // goes through the stores in order and returns as soon as the chunk is found.
42 func (r StoreRouter) HasChunk(id ChunkID) (bool, error) {
43 for _, s := range r.Stores {
44 hasChunk, err := s.HasChunk(id)
45 if err != nil {
46 return false, err
47 }
48 if hasChunk {
49 return true, nil
50 }
51 }
52 return false, nil
53 }
54
55 func (r StoreRouter) String() string {
56 var a []string
57 for _, s := range r.Stores {
58 a = append(a, s.String())
59 }
60 return strings.Join(a, ",")
61 }
62
63 // Close calls the Close() method on every store in the router. Returns
64 // only the first error encountered.
65 func (r StoreRouter) Close() error {
66 var sErr error
67 for _, s := range r.Stores {
68 if err := s.Close(); err != nil {
69 if sErr == nil {
70 sErr = err
71 }
72 }
73 }
74 return sErr
75 }