forked from application-research/estuary
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathranking.go
114 lines (93 loc) · 2.4 KB
/
ranking.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package main
import (
"sort"
"time"
"github.com/filecoin-project/go-address"
)
const minerListTTL = time.Minute
func (cm *ContentManager) sortedMinerList() ([]address.Address, []*minerDealStats, error) {
cm.minerLk.Lock()
defer cm.minerLk.Unlock()
if time.Since(cm.lastComputed) < minerListTTL {
return cm.sortedMiners, cm.rawData, nil
}
sml, err := cm.computeSortedMinerList()
if err != nil {
return nil, nil, err
}
sortedAddrs := make([]address.Address, 0, len(sml))
for _, m := range sml {
sus, err := cm.minerIsSuspended(m.Miner)
if err != nil {
return nil, nil, err
}
if !sus {
sortedAddrs = append(sortedAddrs, m.Miner)
}
}
cm.rawData = sml
cm.lastComputed = time.Now()
cm.sortedMiners = sortedAddrs
return sortedAddrs, sml, nil
}
func (cm *ContentManager) minerIsSuspended(m address.Address) (bool, error) {
var miner storageMiner
if err := cm.DB.Find(&miner, "address = ?", m.String()).Error; err != nil {
return false, err
}
return miner.Suspended, nil
}
type minerDealStats struct {
Miner address.Address `json:"miner"`
TotalDeals int `json:"totalDeals"`
ConfirmedDeals int `json:"confirmedDeals"`
FailedDeals int `json:"failedDeals"`
DealFaults int `json:"dealFaults"`
}
func (mds *minerDealStats) SuccessRatio() float64 {
return float64(mds.ConfirmedDeals) / float64(mds.TotalDeals)
}
// The comparison function that decides 'miner X is better than miner Y'
func (mds *minerDealStats) Better(o *minerDealStats) bool {
return mds.SuccessRatio() > o.SuccessRatio()
}
func (cm *ContentManager) computeSortedMinerList() ([]*minerDealStats, error) {
var deals []contentDeal
if err := cm.DB.Find(&deals).Error; err != nil {
return nil, err
}
stats := make(map[address.Address]*minerDealStats)
for _, d := range deals {
maddr, err := d.MinerAddr()
if err != nil {
return nil, err
}
st, ok := stats[maddr]
if !ok {
st = &minerDealStats{
Miner: maddr,
}
stats[maddr] = st
}
st.TotalDeals++
if d.DealID > 0 {
if d.Failed {
st.DealFaults++
} else {
st.ConfirmedDeals++
}
} else if d.Failed {
st.FailedDeals++
} else {
// in progress
}
}
minerStatsArr := make([]*minerDealStats, 0, len(stats))
for _, st := range stats {
minerStatsArr = append(minerStatsArr, st)
}
sort.Slice(minerStatsArr, func(i, j int) bool {
return minerStatsArr[i].Better(minerStatsArr[j])
})
return minerStatsArr, nil
}