peerdata.go 785 Bytes
Newer Older
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
package sessionpeermanager

import (
	"time"

	"github.com/ipfs/go-cid"
)

const (
	newLatencyWeight = 0.5
)

type peerData struct {
	hasLatency bool
	latency    time.Duration
	lt         *latencyTracker
}

func newPeerData() *peerData {
	return &peerData{
		hasLatency: false,
		lt:         newLatencyTracker(),
		latency:    0,
	}
}

func (pd *peerData) AdjustLatency(k cid.Cid, hasFallbackLatency bool, fallbackLatency time.Duration) {

	latency, hasLatency := pd.lt.RecordResponse(k)
	if !hasLatency {
		latency, hasLatency = fallbackLatency, hasFallbackLatency
	}
	if hasLatency {
		if pd.hasLatency {
			pd.latency = time.Duration(float64(pd.latency)*(1.0-newLatencyWeight) + float64(latency)*newLatencyWeight)
		} else {
			pd.latency = latency
			pd.hasLatency = true
		}
	}
}