This repository has been archived by the owner on Jun 20, 2024. It is now read-only.
generated from ipfs/ipfs-repository-template
-
Notifications
You must be signed in to change notification settings - Fork 20
/
routing.go
280 lines (231 loc) · 6.43 KB
/
routing.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
package main
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"math/rand"
"net/http"
"strings"
"time"
"github.com/ipfs/boxo/ipns"
"github.com/libp2p/go-libp2p/core/routing"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)
type rpcProxyRouting struct {
kuboRPC []string
httpClient *http.Client
rand *rand.Rand
}
func newRPCProxyRouting(kuboRPC []string, cdns *cachedDNS) routing.ValueStore {
s := rand.NewSource(time.Now().Unix())
rand := rand.New(s)
return &rpcProxyRouting{
kuboRPC: kuboRPC,
httpClient: &http.Client{
Transport: otelhttp.NewTransport(&customTransport{
// Roundtripper with increased defaults than http.Transport such that retrieving
// multiple lookups concurrently is fast.
RoundTripper: &http.Transport{
MaxIdleConns: 1000,
MaxConnsPerHost: 100,
MaxIdleConnsPerHost: 100,
IdleConnTimeout: 90 * time.Second,
DialContext: cdns.dialWithCachedDNS,
ForceAttemptHTTP2: true,
},
}),
},
rand: rand,
}
}
func (ps *rpcProxyRouting) PutValue(context.Context, string, []byte, ...routing.Option) error {
return routing.ErrNotSupported
}
func (ps *rpcProxyRouting) GetValue(ctx context.Context, k string, opts ...routing.Option) ([]byte, error) {
return ps.fetch(ctx, k)
}
func (ps *rpcProxyRouting) SearchValue(ctx context.Context, k string, opts ...routing.Option) (<-chan []byte, error) {
if !strings.HasPrefix(k, "/ipns/") {
return nil, routing.ErrNotSupported
}
ch := make(chan []byte)
go func() {
v, err := ps.fetch(ctx, k)
if err != nil {
close(ch)
} else {
ch <- v
close(ch)
}
}()
return ch, nil
}
func (ps *rpcProxyRouting) fetch(ctx context.Context, key string) (rb []byte, err error) {
name, err := ipns.NameFromRoutingKey([]byte(key))
if err != nil {
return nil, err
}
key = "/ipns/" + name.String()
urlStr := fmt.Sprintf("%s/api/v0/dht/get?arg=%s", ps.getRandomKuboURL(), key)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, urlStr, nil)
if err != nil {
return nil, err
}
goLog.Debugw("routing proxy fetch", "key", key, "from", req.URL.String())
defer func() {
if err != nil {
goLog.Debugw("routing proxy fetch error", "key", key, "from", req.URL.String(), "error", err.Error())
}
}()
resp, err := ps.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Read at most 10 KiB (max size of IPNS record).
rb, err = io.ReadAll(io.LimitReader(resp.Body, 10240))
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("routing/get RPC returned unexpected status: %s, body: %q", resp.Status, string(rb))
}
parts := bytes.Split(bytes.TrimSpace(rb), []byte("\n"))
var b64 string
for _, part := range parts {
var evt routing.QueryEvent
err = json.Unmarshal(part, &evt)
if err != nil {
return nil, fmt.Errorf("routing/get RPC response cannot be parsed: %w", err)
}
if evt.Type == routing.Value {
b64 = evt.Extra
break
}
}
if b64 == "" {
return nil, errors.New("routing/get RPC returned no value")
}
rb, err = base64.StdEncoding.DecodeString(b64)
if err != nil {
return nil, err
}
entry, err := ipns.UnmarshalRecord(rb)
if err != nil {
return nil, err
}
err = ipns.ValidateWithName(entry, name)
if err != nil {
return nil, err
}
return rb, nil
}
func (ps *rpcProxyRouting) getRandomKuboURL() string {
return ps.kuboRPC[ps.rand.Intn(len(ps.kuboRPC))]
}
type proxyRouting struct {
ipnsRecordGateways []string
httpClient *http.Client
rand *rand.Rand
}
func newProxyRouting(ipnsRecordGateways []string, cdns *cachedDNS) routing.ValueStore {
s := rand.NewSource(time.Now().Unix())
rand := rand.New(s)
return &proxyRouting{
ipnsRecordGateways: ipnsRecordGateways,
httpClient: &http.Client{
Transport: otelhttp.NewTransport(&customTransport{
// RoundTripper with increased defaults than http.Transport such that retrieving
// multiple lookups concurrently is fast.
RoundTripper: &http.Transport{
MaxIdleConns: 1000,
MaxConnsPerHost: 100,
MaxIdleConnsPerHost: 100,
IdleConnTimeout: 90 * time.Second,
DialContext: cdns.dialWithCachedDNS,
ForceAttemptHTTP2: true,
},
}),
},
rand: rand,
}
}
func (ps *proxyRouting) PutValue(context.Context, string, []byte, ...routing.Option) error {
return routing.ErrNotSupported
}
func (ps *proxyRouting) GetValue(ctx context.Context, k string, opts ...routing.Option) ([]byte, error) {
if !strings.HasPrefix(k, "/ipns/") {
return nil, routing.ErrNotSupported
}
name, err := ipns.NameFromRoutingKey([]byte(k))
if err != nil {
return nil, err
}
return ps.fetch(ctx, name)
}
func (ps *proxyRouting) SearchValue(ctx context.Context, k string, opts ...routing.Option) (<-chan []byte, error) {
if !strings.HasPrefix(k, "/ipns/") {
return nil, routing.ErrNotSupported
}
name, err := ipns.NameFromRoutingKey([]byte(k))
if err != nil {
return nil, err
}
ch := make(chan []byte)
go func() {
v, err := ps.fetch(ctx, name)
if err != nil {
close(ch)
} else {
ch <- v
close(ch)
}
}()
return ch, nil
}
func (ps *proxyRouting) fetch(ctx context.Context, name ipns.Name) ([]byte, error) {
urlStr := fmt.Sprintf("%s/ipns/%s", ps.getRandomGatewayURL(), name.String())
req, err := http.NewRequestWithContext(ctx, http.MethodGet, urlStr, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/vnd.ipfs.ipns-record")
goLog.Debugw("routing proxy fetch", "key", name.String(), "from", req.URL.String())
defer func() {
if err != nil {
goLog.Debugw("routing proxy fetch error", "key", name.String(), "from", req.URL.String(), "error", err.Error())
}
}()
resp, err := ps.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status from remote gateway: %s", resp.Status)
}
rb, err := io.ReadAll(io.LimitReader(resp.Body, int64(ipns.MaxRecordSize)))
if err != nil {
return nil, err
}
rec, err := ipns.UnmarshalRecord(rb)
if err != nil {
return nil, err
}
err = ipns.ValidateWithName(rec, name)
if err != nil {
return nil, err
}
return rb, nil
}
func (ps *proxyRouting) getRandomGatewayURL() string {
return strings.TrimSuffix(ps.ipnsRecordGateways[ps.rand.Intn(len(ps.ipnsRecordGateways))], "/")
}