Skip to content
File

Blob: spec/rpc/rpc.go

go217 lines
1package rpc
2 
3import (
4 "context"
5 "encoding/binary"
6 "fmt"
7 "io"
8 "net"
9 "net/http"
10 "strconv"
11 "strings"
12 "sync"
13 "time"
14 
15 "go.miragespace.co/specter/spec/protocol"
16 "go.miragespace.co/specter/spec/transport"
17 "go.miragespace.co/specter/timing"
18 "go.miragespace.co/specter/util/ratecounter"
19 
20 pool "github.com/libp2p/go-buffer-pool"
21 "github.com/twitchtv/twirp"
22)
23 
24const (
25 // uint32
26 LengthSize = 4
27)
28 
29var builderPool = sync.Pool{
30 New: func() any {
31 return &strings.Builder{}
32 },
33}
34 
35type ChordClient interface {
36 protocol.VNodeService
37 protocol.KVService
38 RatePer(interval time.Duration) float64
39}
40 
41type TunnelClient interface {
42 protocol.TunnelService
43 protocol.KeylessService
44}
45 
46// StreamDialer adapts an overlay stream to an HTTP transport. The request
47// context selects the peer; baseCtx bounds the dial lifetime because net/http
48// detaches its dial context from the request's cancellation and deadline.
49func StreamDialer(baseCtx context.Context, transport transport.Transport, kind protocol.Stream_Type) func(reqCtx context.Context, _, _ string) (net.Conn, error) {
50 return func(reqCtx context.Context, _, _ string) (net.Conn, error) {
51 peer := GetNode(reqCtx)
52 if peer == nil {
53 return nil, fmt.Errorf("node not found in context")
54 }
55 return transport.DialStream(baseCtx, peer, kind)
56 }
57}
58 
59// DynamicChordClient returns a rpc client suitable for both VNodeService and KVService, with the destination
60// set per call dynamically according to the destination in context. Use WithNode(ctx, node) at call site to dynamically dispatch.
61func DynamicChordClient(baseContext context.Context, chordTransport transport.Transport) ChordClient {
62 outboundRate := ratecounter.New(time.Second, time.Second*5)
63 
64 injector := &twirp.ClientHooks{
65 RequestPrepared: func(ctx context.Context, r *http.Request) (context.Context, error) {
66 peer := GetNode(ctx)
67 if peer == nil {
68 return nil, fmt.Errorf("node not found in context")
69 }
70 SerializeContextHeader(ctx, r.Header)
71 
72 // needed to override dialer instead of using http://chord as key
73 sb := builderPool.Get().(*strings.Builder)
74 defer builderPool.Put(sb)
75 defer sb.Reset()
76 sb.WriteString(strconv.FormatUint(peer.GetId(), 10))
77 sb.WriteString(".")
78 sb.WriteString(peer.GetAddress())
79 r.URL.Host = sb.String()
80 
81 outboundRate.Increment()
82 return ctx, nil
83 },
84 }
85 
86 // default to http client pooling
87 t := http.DefaultTransport.(*http.Transport).Clone()
88 t.MaxConnsPerHost = 50
89 t.MaxIdleConnsPerHost = 5
90 t.DisableCompression = true
91 t.IdleConnTimeout = timing.RPCIdleTimeout
92 t.DialTLSContext = StreamDialer(baseContext, chordTransport, protocol.Stream_RPC)
93 c := &http.Client{
94 Transport: t,
95 }
96 // disable in testing
97 if disable, ok := baseContext.Value(contextDisablePoolKey).(bool); ok && disable {
98 t.DisableKeepAlives = true
99 t.MaxConnsPerHost = -1
100 }
101 
102 return &struct {
103 protocol.VNodeService
104 protocol.KVService
105 *ratecounter.Rate
106 }{
107 VNodeService: protocol.NewVNodeServiceProtobufClient("https://chord", c, twirp.WithClientHooks(injector)),
108 KVService: protocol.NewKVServiceProtobufClient("https://chord", c, twirp.WithClientHooks(injector)),
109 Rate: outboundRate,
110 }
111}
112 
113// DynamicTunnelClient returns a rpc client suitable for TunnelService, with the destination set per call dynamically
114// according to the destination in context. Use WithNode(ctx, node) at call site to dynamically dispatch. Optionally,
115// use WithClientToken(ctx, token) to include client token.
116func DynamicTunnelClient(baseContext context.Context, tunnelTransport transport.Transport) TunnelClient {
117 injector := &twirp.ClientHooks{
118 RequestPrepared: func(ctx context.Context, r *http.Request) (context.Context, error) {
119 peer := GetNode(ctx)
120 if peer == nil {
121 return nil, fmt.Errorf("peer not found in context")
122 }
123 r.URL.Host = peer.GetAddress() // needed to override dialer instead of using http://tunnel as key
124 return ctx, nil
125 },
126 }
127 
128 // default to http client pooling
129 t := http.DefaultTransport.(*http.Transport).Clone()
130 t.MaxConnsPerHost = 10
131 t.MaxIdleConnsPerHost = 1
132 t.DisableCompression = true
133 t.IdleConnTimeout = timing.RPCIdleTimeout
134 t.DialTLSContext = StreamDialer(baseContext, tunnelTransport, protocol.Stream_RPC)
135 c := &http.Client{
136 Transport: t,
137 }
138 // disable in testing
139 if disable, ok := baseContext.Value(contextDisablePoolKey).(bool); ok && disable {
140 t.DisableKeepAlives = true
141 t.MaxConnsPerHost = -1
142 }
143 
144 return &struct {
145 protocol.TunnelService
146 protocol.KeylessService
147 }{
148 TunnelService: protocol.NewTunnelServiceProtobufClient("https://tunnel", c, twirp.WithClientHooks(injector)),
149 KeylessService: protocol.NewKeylessServiceProtobufClient("https://tunnel", c, twirp.WithClientHooks(injector)),
150 }
151}
152 
153func receive(stream io.Reader, rr VTMarshaler, checker func(size uint32) bool) error {
154 var sb [LengthSize]byte
155 
156 n, err := io.ReadFull(stream, sb[:])
157 if err != nil {
158 return fmt.Errorf("reading RPC message buffer size: %w", err)
159 }
160 if n != LengthSize {
161 return fmt.Errorf("expected %d bytes to be read but %d bytes was read", LengthSize, n)
162 }
163 
164 ms := binary.BigEndian.Uint32(sb[:])
165 if !checker(ms) {
166 return fmt.Errorf("RPC message is too large")
167 }
168 
169 mb := pool.Get(int(ms))
170 defer pool.Put(mb)
171 
172 n, err = io.ReadFull(stream, mb)
173 if err != nil {
174 return fmt.Errorf("reading RPC message: %w", err)
175 }
176 if ms != uint32(n) {
177 return fmt.Errorf("expected %d bytes to be read but %d bytes was read", ms, n)
178 }
179 
180 return rr.UnmarshalVT(mb)
181}
182 
183func BoundedReceive(stream io.Reader, rr VTMarshaler, max uint32) error {
184 return receive(stream, rr, func(size uint32) bool {
185 return size <= max
186 })
187}
188 
189func Receive(stream io.Reader, rr VTMarshaler) error {
190 return receive(stream, rr, func(size uint32) bool {
191 return true
192 })
193}
194 
195func Send(stream io.Writer, rr VTMarshaler) error {
196 l := rr.SizeVT()
197 mb := pool.Get(LengthSize + l)
198 defer pool.Put(mb)
199 
200 binary.BigEndian.PutUint32(mb[0:LengthSize], uint32(l))
201 
202 _, err := rr.MarshalToSizedBufferVT(mb[LengthSize:])
203 if err != nil {
204 return fmt.Errorf("encoding outbound RPC message: %w", err)
205 }
206 
207 n, err := stream.Write(mb)
208 if err != nil {
209 return fmt.Errorf("sending RPC message: %w", err)
210 }
211 if n != LengthSize+l {
212 return fmt.Errorf("expected %d bytes sent but %d bytes was sent", l, n)
213 }
214 
215 return nil
216}