package peerstore

import (
	
	

	
)

// LatencyEWMASmoothing governs the decay of the EWMA (the speed
// at which it changes). This must be a normalized (0-1) value.
// 1 is 100% change, 0 is no change.
var LatencyEWMASmoothing = 0.1

type metrics struct {
	mutex  sync.RWMutex
	latmap map[peer.ID]time.Duration
}

func () *metrics {
	return &metrics{
		latmap: make(map[peer.ID]time.Duration),
	}
}

// RecordLatency records a new latency measurement
func ( *metrics) ( peer.ID,  time.Duration) {
	 := float64()
	 := LatencyEWMASmoothing
	if  > 1 ||  < 0 {
		 = 0.1 // ignore the knob. it's broken. look, it jiggles.
	}

	.mutex.Lock()
	,  := .latmap[]
	 := float64()
	if ! {
		.latmap[] =  // when no data, just take it as the mean.
	} else {
		 = ((1.0 - ) * ) + ( * )
		.latmap[] = time.Duration()
	}
	.mutex.Unlock()
}

// LatencyEWMA returns an exponentially-weighted moving avg.
// of all measurements of a peer's latency.
func ( *metrics) ( peer.ID) time.Duration {
	.mutex.RLock()
	defer .mutex.RUnlock()
	return .latmap[]
}

func ( *metrics) ( peer.ID) {
	.mutex.Lock()
	delete(.latmap, )
	.mutex.Unlock()
}