-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
delegated.go
332 lines (280 loc) · 8.46 KB
/
delegated.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
package routing
import (
"context"
"encoding/base64"
"errors"
"fmt"
"net/http"
drclient "github.com/ipfs/boxo/routing/http/client"
"github.com/ipfs/boxo/routing/http/contentrouter"
"github.com/ipfs/go-datastore"
logging "github.com/ipfs/go-log"
version "github.com/ipfs/kubo"
"github.com/ipfs/kubo/config"
dht "github.com/libp2p/go-libp2p-kad-dht"
"github.com/libp2p/go-libp2p-kad-dht/dual"
"github.com/libp2p/go-libp2p-kad-dht/fullrt"
record "github.com/libp2p/go-libp2p-record"
routinghelpers "github.com/libp2p/go-libp2p-routing-helpers"
ic "github.com/libp2p/go-libp2p/core/crypto"
host "github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/core/routing"
ma "github.com/multiformats/go-multiaddr"
"go.opencensus.io/stats/view"
)
var log = logging.Logger("routing/delegated")
func Parse(routers config.Routers, methods config.Methods, extraDHT *ExtraDHTParams, extraHTTP *ExtraHTTPParams) (routing.Routing, error) {
if err := methods.Check(); err != nil {
return nil, err
}
createdRouters := make(map[string]routing.Routing)
finalRouter := &Composer{}
// Create all needed routers from method names
for mn, m := range methods {
router, err := parse(make(map[string]bool), createdRouters, m.RouterName, routers, extraDHT, extraHTTP)
if err != nil {
return nil, err
}
switch mn {
case config.MethodNamePutIPNS:
finalRouter.PutValueRouter = router
case config.MethodNameGetIPNS:
finalRouter.GetValueRouter = router
case config.MethodNameFindPeers:
finalRouter.FindPeersRouter = router
case config.MethodNameFindProviders:
finalRouter.FindProvidersRouter = router
case config.MethodNameProvide:
finalRouter.ProvideRouter = router
}
log.Info("using method ", mn, " with router ", m.RouterName)
}
return finalRouter, nil
}
func parse(visited map[string]bool,
createdRouters map[string]routing.Routing,
routerName string,
routersCfg config.Routers,
extraDHT *ExtraDHTParams,
extraHTTP *ExtraHTTPParams,
) (routing.Routing, error) {
// check if we already created it
r, ok := createdRouters[routerName]
if ok {
return r, nil
}
// check if we are in a dep loop
if visited[routerName] {
return nil, fmt.Errorf("dependency loop creating router with name %q", routerName)
}
// set node as visited
visited[routerName] = true
cfg, ok := routersCfg[routerName]
if !ok {
return nil, fmt.Errorf("config for router with name %q not found", routerName)
}
var router routing.Routing
var err error
switch cfg.Type {
case config.RouterTypeHTTP:
router, err = httpRoutingFromConfig(cfg.Router, extraHTTP)
case config.RouterTypeDHT:
router, err = dhtRoutingFromConfig(cfg.Router, extraDHT)
case config.RouterTypeParallel:
crp := cfg.Parameters.(*config.ComposableRouterParams)
var pr []*routinghelpers.ParallelRouter
for _, cr := range crp.Routers {
ri, err := parse(visited, createdRouters, cr.RouterName, routersCfg, extraDHT, extraHTTP)
if err != nil {
return nil, err
}
pr = append(pr, &routinghelpers.ParallelRouter{
Router: ri,
IgnoreError: cr.IgnoreErrors,
DoNotWaitForSearchValue: true,
Timeout: cr.Timeout.Duration,
ExecuteAfter: cr.ExecuteAfter.WithDefault(0),
})
}
router = routinghelpers.NewComposableParallel(pr)
case config.RouterTypeSequential:
crp := cfg.Parameters.(*config.ComposableRouterParams)
var sr []*routinghelpers.SequentialRouter
for _, cr := range crp.Routers {
ri, err := parse(visited, createdRouters, cr.RouterName, routersCfg, extraDHT, extraHTTP)
if err != nil {
return nil, err
}
sr = append(sr, &routinghelpers.SequentialRouter{
Router: ri,
IgnoreError: cr.IgnoreErrors,
Timeout: cr.Timeout.Duration,
})
}
router = routinghelpers.NewComposableSequential(sr)
default:
return nil, fmt.Errorf("unknown router type %q", cfg.Type)
}
if err != nil {
return nil, err
}
createdRouters[routerName] = router
log.Info("created router ", routerName, " with params ", cfg.Parameters)
return router, nil
}
type ExtraHTTPParams struct {
PeerID string
Addrs []string
PrivKeyB64 string
}
func ConstructHTTPRouter(endpoint string, peerID string, addrs []string, privKey string) (routing.Routing, error) {
return httpRoutingFromConfig(
config.Router{
Type: "http",
Parameters: &config.HTTPRouterParams{
Endpoint: endpoint,
},
},
&ExtraHTTPParams{
PeerID: peerID,
Addrs: addrs,
PrivKeyB64: privKey,
},
)
}
func httpRoutingFromConfig(conf config.Router, extraHTTP *ExtraHTTPParams) (routing.Routing, error) {
params := conf.Parameters.(*config.HTTPRouterParams)
if params.Endpoint == "" {
return nil, NewParamNeededErr("Endpoint", conf.Type)
}
params.FillDefaults()
// Increase per-host connection pool since we are making lots of concurrent requests.
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.MaxIdleConns = 500
transport.MaxIdleConnsPerHost = 100
delegateHTTPClient := &http.Client{
Transport: &drclient.ResponseBodyLimitedTransport{
RoundTripper: transport,
LimitBytes: 1 << 20,
},
}
key, err := decodePrivKey(extraHTTP.PrivKeyB64)
if err != nil {
return nil, err
}
addrInfo, err := createAddrInfo(extraHTTP.PeerID, extraHTTP.Addrs)
if err != nil {
return nil, err
}
cli, err := drclient.New(
params.Endpoint,
drclient.WithHTTPClient(delegateHTTPClient),
drclient.WithIdentity(key),
drclient.WithProviderInfo(addrInfo.ID, addrInfo.Addrs),
drclient.WithUserAgent(version.GetUserAgentVersion()),
)
if err != nil {
return nil, err
}
cr := contentrouter.NewContentRoutingClient(
cli,
contentrouter.WithMaxProvideBatchSize(params.MaxProvideBatchSize),
contentrouter.WithMaxProvideConcurrency(params.MaxProvideConcurrency),
)
err = view.Register(drclient.OpenCensusViews...)
if err != nil {
return nil, fmt.Errorf("registering HTTP delegated routing views: %w", err)
}
return &httpRoutingWrapper{
ContentRouting: cr,
PeerRouting: cr,
ValueStore: cr,
ProvideManyRouter: cr,
}, nil
}
func decodePrivKey(keyB64 string) (ic.PrivKey, error) {
pk, err := base64.StdEncoding.DecodeString(keyB64)
if err != nil {
return nil, err
}
return ic.UnmarshalPrivateKey(pk)
}
func createAddrInfo(peerID string, addrs []string) (peer.AddrInfo, error) {
pID, err := peer.Decode(peerID)
if err != nil {
return peer.AddrInfo{}, err
}
var mas []ma.Multiaddr
for _, a := range addrs {
m, err := ma.NewMultiaddr(a)
if err != nil {
return peer.AddrInfo{}, err
}
mas = append(mas, m)
}
return peer.AddrInfo{
ID: pID,
Addrs: mas,
}, nil
}
type ExtraDHTParams struct {
BootstrapPeers []peer.AddrInfo
Host host.Host
Validator record.Validator
Datastore datastore.Batching
Context context.Context
}
func dhtRoutingFromConfig(conf config.Router, extra *ExtraDHTParams) (routing.Routing, error) {
params, ok := conf.Parameters.(*config.DHTRouterParams)
if !ok {
return nil, errors.New("incorrect params for DHT router")
}
if params.AcceleratedDHTClient {
return createFullRT(extra)
}
var mode dht.ModeOpt
switch params.Mode {
case config.DHTModeAuto:
mode = dht.ModeAuto
case config.DHTModeClient:
mode = dht.ModeClient
case config.DHTModeServer:
mode = dht.ModeServer
default:
return nil, fmt.Errorf("invalid DHT mode: %q", params.Mode)
}
return createDHT(extra, params.PublicIPNetwork, mode)
}
func createDHT(params *ExtraDHTParams, public bool, mode dht.ModeOpt) (routing.Routing, error) {
var opts []dht.Option
if public {
opts = append(opts, dht.QueryFilter(dht.PublicQueryFilter),
dht.RoutingTableFilter(dht.PublicRoutingTableFilter),
dht.RoutingTablePeerDiversityFilter(dht.NewRTPeerDiversityFilter(params.Host, 2, 3)))
} else {
opts = append(opts, dht.ProtocolExtension(dual.LanExtension),
dht.QueryFilter(dht.PrivateQueryFilter),
dht.RoutingTableFilter(dht.PrivateRoutingTableFilter))
}
opts = append(opts,
dht.Concurrency(10),
dht.Mode(mode),
dht.Datastore(params.Datastore),
dht.Validator(params.Validator),
dht.BootstrapPeers(params.BootstrapPeers...))
return dht.New(
params.Context, params.Host, opts...,
)
}
func createFullRT(params *ExtraDHTParams) (routing.Routing, error) {
return fullrt.NewFullRT(params.Host,
dht.DefaultPrefix,
fullrt.DHTOption(
dht.Validator(params.Validator),
dht.Datastore(params.Datastore),
dht.BootstrapPeers(params.BootstrapPeers...),
dht.BucketSize(20),
),
)
}