forked from ipfs/boxo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
centralized_server.go
91 lines (74 loc) · 1.86 KB
/
centralized_server.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
package mockrouting
import (
"context"
"math/rand"
"sync"
"time"
"github.com/ipfs/go-cid"
ds "github.com/ipfs/go-datastore"
dssync "github.com/ipfs/go-datastore/sync"
tnet "github.com/libp2p/go-libp2p-testing/net"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/littlespeechless/boxo/routing/offline"
)
// server is the mockrouting.Client's private interface to the routing server
type server interface {
Announce(peer.AddrInfo, cid.Cid) error
Providers(cid.Cid) []peer.AddrInfo
Server
}
// s is an implementation of the private server interface
type s struct {
delayConf DelayConfig
lock sync.RWMutex
providers map[string]map[peer.ID]providerRecord
}
type providerRecord struct {
Peer peer.AddrInfo
Created time.Time
}
func (rs *s) Announce(p peer.AddrInfo, c cid.Cid) error {
rs.lock.Lock()
defer rs.lock.Unlock()
k := c.KeyString()
_, ok := rs.providers[k]
if !ok {
rs.providers[k] = make(map[peer.ID]providerRecord)
}
rs.providers[k][p.ID] = providerRecord{
Created: time.Now(),
Peer: p,
}
return nil
}
func (rs *s) Providers(c cid.Cid) []peer.AddrInfo {
rs.delayConf.Query.Wait() // before locking
rs.lock.RLock()
defer rs.lock.RUnlock()
k := c.KeyString()
var ret []peer.AddrInfo
records, ok := rs.providers[k]
if !ok {
return ret
}
for _, r := range records {
if time.Since(r.Created) > rs.delayConf.ValueVisibility.Get() {
ret = append(ret, r.Peer)
}
}
for i := range ret {
j := rand.Intn(i + 1)
ret[i], ret[j] = ret[j], ret[i]
}
return ret
}
func (rs *s) Client(p tnet.Identity) Client {
return rs.ClientWithDatastore(context.Background(), p, dssync.MutexWrap(ds.NewMapDatastore()))
}
func (rs *s) ClientWithDatastore(_ context.Context, p tnet.Identity, datastore ds.Datastore) Client {
return &client{
peer: p,
vs: offline.NewOfflineRouter(datastore, MockValidator{}),
server: rs,
}
}