forked from gazette/core
-
Notifications
You must be signed in to change notification settings - Fork 2
/
route_cache.go
65 lines (56 loc) · 1.46 KB
/
route_cache.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
package client
import (
"context"
"time"
pb "github.com/LiveRamp/gazette/v2/pkg/protocol"
"github.com/hashicorp/golang-lru"
)
// RouteCache caches observed Routes for JournalSpecs (and consumer
// ShardSpecs, or any other allocator.Item)
type RouteCache struct {
cache lru.Cache
ttl time.Duration
}
// NewRouteCache returns a RouteCache of the given size (which must be > 0)
// and caching Duration.
func NewRouteCache(size int, ttl time.Duration) *RouteCache {
var cache, err = lru.New(size)
if err != nil {
panic(err.Error()) // Only errors on size <= 0.
}
return &RouteCache{
cache: *cache,
ttl: ttl,
}
}
// UpdateRoute caches the provided Route for |item|, or invalidates it if |route| is nil.
func (rc *RouteCache) UpdateRoute(item string, route *pb.Route) {
if route == nil {
rc.cache.Remove(item)
} else {
var cr = cachedRoute{
route: *route,
at: timeNow(),
}
rc.cache.Add(item, cr)
}
}
// Route queries for a cached Route of |item|.
func (rc *RouteCache) Route(ctx context.Context, item string) pb.Route {
if v, ok := rc.cache.Get(item); ok {
// If the TTL has elapsed, treat as a cache miss and remove.
if cr := v.(cachedRoute); cr.at.Add(rc.ttl).Before(timeNow()) {
rc.cache.Remove(item)
} else {
return cr.route
}
}
return pb.Route{Primary: -1}
}
// IsNoopRouter returns false.
func (rc *RouteCache) IsNoopRouter() bool { return false }
type cachedRoute struct {
route pb.Route
at time.Time
}
var timeNow = time.Now