-
Notifications
You must be signed in to change notification settings - Fork 1
/
strat_adaptive.go
59 lines (44 loc) · 1.35 KB
/
strat_adaptive.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
package server
import (
"log"
"math"
"sync"
"time"
"github.com/golang/protobuf/proto"
"github.com/hashicorp/terraform/helper/hashcode"
)
type adaptiveStrategy struct {
alpha float64
lastModification time.Time
responseHash int
lastEstimation time.Duration
mux sync.Mutex
}
// compile-time check that we adhere to interface
var _ estimationStrategy = (*adaptiveStrategy)(nil)
func (strat *adaptiveStrategy) initialize() {
log.Printf("Using Adaptive TTL strategy with alpha=%f", strat.alpha)
strat.lastModification = time.Now()
strat.responseHash = 11
strat.lastEstimation = 0
}
func (strat *adaptiveStrategy) update(timestamp time.Time, reply proto.Message) {
incomingHash := hashcode.String(reply.String())
strat.mux.Lock()
if incomingHash != strat.responseHash {
strat.lastModification = timestamp
strat.responseHash = incomingHash
}
strat.mux.Unlock()
}
func (strat *adaptiveStrategy) determineInterval() time.Duration {
bounded := math.Max(strat.lastEstimation.Seconds()/2.0, defaultInterval.Seconds())
return time.Duration(bounded) * time.Second
}
func (strat *adaptiveStrategy) determineEstimation() time.Duration {
estimatedTTL := float64(time.Now().Sub(strat.lastModification).Nanoseconds()) * strat.alpha
strat.mux.Lock()
strat.lastEstimation = time.Duration(int64(estimatedTTL))
strat.mux.Unlock()
return strat.lastEstimation
}