-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
77 lines (65 loc) · 1.23 KB
/
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
66
67
68
69
70
71
72
73
74
75
76
77
package server
import (
"crypto/sha1"
"fmt"
"k8s.io/apimachinery/pkg/util/json"
"k8s.io/klog/v2"
"sync"
"time"
)
type Cache struct {
Mementos []Memento
lock sync.Mutex
}
func NewCache() *Cache {
return &Cache{
Mementos: make([]Memento, 0),
lock: sync.Mutex{},
}
}
func (c *Cache) update(data interface{}) {
c.lock.Lock()
var m *Memento
if l := len(c.Mementos); l > 0 {
m = c.Mementos[len(c.Mementos)-1].Clone()
} else {
m = NewMemento()
}
switch data.(type) {
case []Route:
m.Routes = data.([]Route)
m.SetHash()
case Route:
m.Routes = append(m.Routes, data.(Route))
klog.Infof("route added %v", data)
}
//TODO: does not do []Route currently individual route.
c.Mementos = append(c.Mementos, *m)
c.lock.Unlock()
}
type Memento struct {
Routes []Route
Hash string
DateCreated time.Time
}
func NewMemento() *Memento {
m := &Memento{
Routes: make([]Route, 0),
Hash: "",
DateCreated: time.Now(),
}
m.SetHash()
return m
}
func (m *Memento) SetHash() {
data, _ := json.Marshal(m.Routes)
m.Hash = fmt.Sprintf("%x", sha1.Sum(data))
}
func (m *Memento) Clone() *Memento {
d := Memento{
Routes: m.Routes,
DateCreated: time.Now(),
}
d.SetHash()
return &d
}