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
package kcpstore
import (
"context"
"errors"
"sync"
)
func definitive(err error) bool {
switch {
case err == nil:
return true
case errors.Is(err, ErrNoPath):
return true
case IsNotFound(err):
return true
}
return false
}
type PathCache struct {
store *Store
mu sync.Mutex
byID map[string]string
}
func NewPathCache(store *Store) *PathCache {
return &PathCache{store: store, byID: map[string]string{}}
}
func (c *PathCache) Lookup(ctx context.Context, logicalCluster string) string {
c.mu.Lock()
if path, seen := c.byID[logicalCluster]; seen {
c.mu.Unlock()
return path
}
c.mu.Unlock()
path := ""
if c.store != nil {
resolved, err := c.store.ClusterPath(ctx, logicalCluster)
if !definitive(err) {
return ""
}
path = resolved
}
c.mu.Lock()
c.byID[logicalCluster] = path
c.mu.Unlock()
return path
}
func (c *PathCache) Forget(logicalCluster string) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.byID, logicalCluster)
}
func (c *PathCache) Len() int {
c.mu.Lock()
defer c.mu.Unlock()
return len(c.byID)
}