forked from ipfs-inactive/bifrost-gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouting.go
174 lines (146 loc) · 3.91 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
package main
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"math/rand"
"net/http"
"strings"
"time"
"github.com/gogo/protobuf/proto"
"github.com/ipfs/boxo/ipns"
ipns_pb "github.com/ipfs/boxo/ipns/pb"
ic "github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/core/routing"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)
type proxyRouting struct {
kuboRPC []string
httpClient *http.Client
rand *rand.Rand
}
func newProxyRouting(kuboRPC []string, cdns *cachedDNS) routing.ValueStore {
s := rand.NewSource(time.Now().Unix())
rand := rand.New(s)
return &proxyRouting{
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 *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) {
return ps.fetch(ctx, k)
}
func (ps *proxyRouting) 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 *proxyRouting) fetch(ctx context.Context, key string) (rb []byte, err error) {
key = strings.TrimPrefix(key, "/ipns/")
id, err := peer.IDFromBytes([]byte(key))
if err != nil {
return nil, err
}
key = "/ipns/" + peer.ToCid(id).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
}
var entry ipns_pb.IpnsEntry
err = proto.Unmarshal(rb, &entry)
if err != nil {
return nil, err
}
pub, err := id.ExtractPublicKey()
if err != nil {
// Make sure it works with all those RSA that cannot be embedded into the
// Peer ID.
if len(entry.PubKey) > 0 {
pub, err = ic.UnmarshalPublicKey(entry.PubKey)
}
}
if err != nil {
return nil, err
}
err = ipns.Validate(pub, &entry)
if err != nil {
return nil, err
}
return rb, nil
}
func (ps *proxyRouting) getRandomKuboURL() string {
return ps.kuboRPC[ps.rand.Intn(len(ps.kuboRPC))]
}