forked from hiproz/minicdn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
peers.go
85 lines (73 loc) · 1.39 KB
/
peers.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
package main
import (
"errors"
"math/rand"
"sync"
"github.com/codeskyblue/groupcache"
"github.com/gorilla/websocket"
)
const defaultWSURL = "/_ws/"
var (
state = ServerState{
ActiveDownload: 0,
closed: false,
}
peerGroup = PeerGroup{
m: make(map[string]Peer, 10),
}
pool *groupcache.HTTPPool
)
type Peer struct {
Name string
Connection *websocket.Conn
ActiveDownload int
}
type PeerGroup struct {
sync.RWMutex
m map[string]Peer
}
func (sm *PeerGroup) AddPeer(name string, conn *websocket.Conn) {
sm.Lock()
defer sm.Unlock()
sm.m[name] = Peer{
Name: name,
Connection: conn,
}
}
func (sm *PeerGroup) Delete(name string) {
sm.Lock()
delete(sm.m, name)
sm.Unlock()
}
func (sm *PeerGroup) Keys() []string {
sm.RLock()
defer sm.RUnlock()
keys := []string{}
for key, _ := range sm.m {
keys = append(keys, key)
}
return keys
}
func (sm *PeerGroup) PeekPeer() (string, error) {
// FIXME(ssx): need to order by active download count
sm.RLock()
defer sm.RUnlock()
ridx := rand.Int()
keys := []string{}
for key, _ := range sm.m {
keys = append(keys, key)
}
if len(keys) == 0 {
return "", errors.New("Peer count zero")
}
return keys[ridx%len(keys)], nil
}
func (sm *PeerGroup) BroadcastJSON(v interface{}) error {
var err error
for _, s := range sm.m {
if err = s.Connection.WriteJSON(v); err != nil {
return err
}
}
return nil
}