This repository has been archived by the owner on Jan 21, 2022. It is now read-only.
/
freshness.go
68 lines (55 loc) · 1.75 KB
/
freshness.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
package store
import (
"encoding/json"
"time"
"github.com/cloudfoundry/hm9000/models"
"github.com/cloudfoundry/storeadapter"
)
func (store *RealStore) BumpActualFreshness(timestamp time.Time) error {
return store.bumpFreshness(store.SchemaRoot()+store.config.ActualFreshnessKey, store.config.ActualFreshnessTTL(), timestamp)
}
func (store *RealStore) RevokeActualFreshness() error {
return store.adapter.Delete(store.SchemaRoot() + store.config.ActualFreshnessKey)
}
func (store *RealStore) bumpFreshness(key string, ttl uint64, timestamp time.Time) error {
var jsonTimestamp []byte
oldTimestamp, err := store.adapter.Get(key)
if err == nil {
jsonTimestamp = oldTimestamp.Value
} else {
jsonTimestamp, _ = json.Marshal(models.FreshnessTimestamp{Timestamp: timestamp.Unix()})
}
return store.adapter.SetMulti([]storeadapter.StoreNode{
{
Key: key,
Value: jsonTimestamp,
TTL: ttl,
},
})
}
func (store *RealStore) IsActualStateFresh(currentTime time.Time) (bool, error) {
node, err := store.adapter.Get(store.SchemaRoot() + store.config.ActualFreshnessKey)
if err != nil {
if storeErr, ok := err.(storeadapter.Error); ok && storeErr.Type() == storeadapter.ErrorKeyNotFound {
return false, nil
}
return false, err
}
freshnessTimestamp := models.FreshnessTimestamp{}
err = json.Unmarshal(node.Value, &freshnessTimestamp)
if err != nil {
return false, err
}
isUpToDate := currentTime.Sub(time.Unix(freshnessTimestamp.Timestamp, 0)) >= time.Duration(store.config.ActualFreshnessTTL())*time.Second
return isUpToDate, nil
}
func (store *RealStore) VerifyFreshness(time time.Time) error {
actualFresh, err := store.IsActualStateFresh(time)
if err != nil {
return err
}
if !actualFresh {
return ActualIsNotFreshError
}
return nil
}