/
host_manager.go
62 lines (53 loc) · 1.5 KB
/
host_manager.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
package upload
import (
"github.com/bittorrent/go-btfs/core/commands/storage/contracts"
guardpb "github.com/bittorrent/go-btfs-common/protos/guard"
"github.com/bittorrent/go-btfs-common/protos/node"
config "github.com/bittorrent/go-btfs-config"
"github.com/ipfs/go-datastore"
)
type ICount interface {
Count(ds datastore.Datastore, peerId string, status guardpb.Contract_ContractState) (int, error)
}
type Count struct{}
type HostManager struct {
low int
high int
threshold int64
count ICount
}
func NewHostManager(cfg *config.Config) *HostManager {
return &HostManager{
low: cfg.UI.Host.ContractManager.LowWater,
high: cfg.UI.Host.ContractManager.HighWater,
threshold: cfg.UI.Host.ContractManager.Threshold,
count: &Count{},
}
}
func (h *HostManager) AcceptContract(ds datastore.Datastore, peerId string, shardSize int64) (bool, error) {
count, err := h.count.Count(ds, peerId, guardpb.Contract_READY_CHALLENGE)
if err != nil {
log.Debug("err", err)
return true, nil
}
if count <= h.low {
return true, nil
} else if count >= h.high {
return false, nil
} else {
return shardSize <= h.threshold, nil
}
}
func (h *Count) Count(ds datastore.Datastore, peerId string, status guardpb.Contract_ContractState) (int, error) {
contracts, err := contracts.ListContracts(ds, peerId, node.ContractStat_HOST.String())
if err != nil {
return 0, err
}
c := 0
for i := 0; i < len(contracts); i++ {
if contracts[i].Status == status {
c++
}
}
return c, nil
}