master
go 51 lines 908 Bytes
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package pinger
4
5 import (
6 "sync"
7 "time"
8 )
9
10 type hostState struct {
11 ewma float64
12 sma []float64
13 }
14
15 type stateStore struct {
16 mu sync.Mutex
17 byHost map[string]*hostState
18 }
19
20 func newStateStore() *stateStore {
21 return &stateStore{
22 byHost: make(map[string]*hostState),
23 }
24 }
25
26 func (s *stateStore) update(host string, current time.Duration, cfg AnalysisConfig) (time.Duration, time.Duration) {
27 s.mu.Lock()
28 defer s.mu.Unlock()
29
30 st, ok := s.byHost[host]
31 if !ok {
32 st = &hostState{}
33 s.byHost[host] = st
34 }
35
36 curr := float64(current)
37 alpha := 1.0 / float64(cfg.JitterEWMASamples)
38 st.ewma = alpha*curr + (1-alpha)*st.ewma
39
40 st.sma = append(st.sma, curr)
41 if len(st.sma) > cfg.JitterSMAWindow {
42 st.sma = st.sma[1:]
43 }
44
45 var sum float64
46 for _, v := range st.sma {
47 sum += v
48 }
49
50 return time.Duration(st.ewma), time.Duration(sum / float64(len(st.sma)))
51 }