-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathrpc.go
429 lines (338 loc) · 8.93 KB
/
rpc.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
package muxrpc // import "go.cryptoscope.co/muxrpc"
import (
"context"
"encoding/json"
"net"
"sync"
"github.com/pkg/errors"
"go.cryptoscope.co/luigi"
"go.cryptoscope.co/muxrpc/codec"
)
var (
_ Endpoint = (*rpc)(nil)
_ Server = (*rpc)(nil)
)
// rpc implements an Endpoint, but also implements Server
type rpc struct {
remote net.Addr
// pkr is the Sink and Source of the network connection
pkr Packer
// reqs is the map we keep, tracking all requests
reqs map[int32]*Request
rLock sync.Mutex
// highest is the highest request id we already allocated
highest int32
root Handler
// terminated indicates that the rpc session is being terminated
terminated bool
tLock sync.Mutex
}
// Handler allows handling connections.
// When a connection is established, HandleConnect is called.
// When we are being called, HandleCall is called.
type Handler interface {
HandleCall(ctx context.Context, req *Request, edp Endpoint)
HandleConnect(ctx context.Context, edp Endpoint)
}
const bufSize = 5
// Handle handles the connection of the packer using the specified handler.
func Handle(pkr Packer, handler Handler) Endpoint {
var raddr net.Addr
if pkr, ok := pkr.(*packer); ok {
if ra, ok := pkr.c.(interface{ RemoteAddr() net.Addr }); ok {
raddr = ra.RemoteAddr()
}
}
return handle(pkr, handler, raddr)
}
// HandleWithRemote also sets the remote address the endpoint is connected to
// TODO: better passing through packer maybe?!
func HandleWithRemote(pkr Packer, handler Handler, addr net.Addr) Endpoint {
return handle(pkr, handler, addr)
}
func handle(pkr Packer, handler Handler, remote net.Addr) Endpoint {
r := &rpc{
remote: remote,
pkr: pkr,
reqs: make(map[int32]*Request),
root: handler,
}
go handler.HandleConnect(context.Background(), r)
return r
}
// Async does an aync call on the remote.
func (r *rpc) Async(ctx context.Context, tipe interface{}, method Method, args ...interface{}) (interface{}, error) {
inSrc, inSink := luigi.NewPipe(luigi.WithBuffer(bufSize))
req := &Request{
Type: "async",
Stream: NewStream(inSrc, r.pkr, 0, false, false),
in: inSink,
Method: method,
Args: args,
tipe: tipe,
}
err := r.Do(ctx, req)
if err != nil {
return nil, errors.Wrap(err, "error sending request")
}
v, err := req.Stream.Next(ctx)
return v, errors.Wrap(err, "error reading response from request source")
}
// Source does a source call on the remote.
func (r *rpc) Source(ctx context.Context, tipe interface{}, method Method, args ...interface{}) (luigi.Source, error) {
inSrc, inSink := luigi.NewPipe(luigi.WithBuffer(bufSize))
req := &Request{
Type: "source",
Stream: NewStream(inSrc, r.pkr, 0, true, false),
in: inSink,
Method: method,
Args: args,
tipe: tipe,
}
err := r.Do(ctx, req)
if err != nil {
return nil, errors.Wrap(err, "error sending request")
}
return req.Stream, nil
}
// Sink does a sink call on the remote.
func (r *rpc) Sink(ctx context.Context, method Method, args ...interface{}) (luigi.Sink, error) {
inSrc, inSink := luigi.NewPipe(luigi.WithBuffer(bufSize))
req := &Request{
Type: "sink",
Stream: NewStream(inSrc, r.pkr, 0, false, true),
in: inSink,
Method: method,
Args: args,
}
err := r.Do(ctx, req)
if err != nil {
return nil, errors.Wrap(err, "error sending request")
}
return req.Stream, nil
}
// Duplex does a duplex call on the remote.
func (r *rpc) Duplex(ctx context.Context, tipe interface{}, method Method, args ...interface{}) (luigi.Source, luigi.Sink, error) {
inSrc, inSink := luigi.NewPipe(luigi.WithBuffer(bufSize))
req := &Request{
Type: "duplex",
Stream: NewStream(inSrc, r.pkr, 0, true, true),
in: inSink,
Method: method,
Args: args,
tipe: tipe,
}
err := r.Do(ctx, req)
if err != nil {
return nil, nil, errors.Wrap(err, "error sending request")
}
return req.Stream, req.Stream, nil
}
// Terminate ends the RPC session
func (r *rpc) Terminate() error {
r.tLock.Lock()
defer r.tLock.Unlock()
r.terminated = true
return r.pkr.Close()
}
func (r *rpc) finish(ctx context.Context, reqID int32) error {
req := r.reqs[reqID]
delete(r.reqs, reqID)
isStream := req.Type.Flags() != 0
err := r.pkr.Pour(ctx, newEndOkayPacket(reqID, isStream))
return errors.Wrap(err, "error pouring done message")
}
// Do executes a generic call
func (r *rpc) Do(ctx context.Context, req *Request) error {
var (
pkt codec.Packet
err error
)
if req.Args == nil {
req.Args = []interface{}{}
}
func() {
r.rLock.Lock()
defer r.rLock.Unlock()
pkt.Flag = pkt.Flag.Set(codec.FlagJSON)
pkt.Flag = pkt.Flag.Set(req.Type.Flags())
pkt.Body, err = json.Marshal(req)
pkt.Req = r.highest + 1
r.highest = pkt.Req
r.reqs[pkt.Req] = req
req.Stream.WithReq(pkt.Req)
req.Stream.WithType(req.tipe)
req.pkt = &pkt
}()
if err != nil {
return err
}
return r.pkr.Pour(ctx, &pkt)
}
// ParseRequest parses the first packet of a stream and parses the contained request
func (r *rpc) ParseRequest(pkt *codec.Packet) (*Request, error) {
var req Request
if !pkt.Flag.Get(codec.FlagJSON) {
return nil, errors.New("expected JSON flag")
}
if pkt.Req >= 0 {
// request numbers should have been inverted by now
return nil, errors.New("expected negative request id")
}
err := json.Unmarshal(pkt.Body, &req)
if err != nil {
return nil, errors.Wrap(err, "error decoding packet")
}
req.pkt = pkt
inSrc, inSink := luigi.NewPipe(luigi.WithBuffer(bufSize))
var inStream, outStream bool
if pkt.Flag.Get(codec.FlagStream) {
switch req.Type {
case "duplex":
inStream, outStream = true, true
case "source":
inStream, outStream = false, true
case "sink":
inStream, outStream = true, false
default:
return nil, errors.Errorf("unhandled request type: %q", req.Type)
}
}
req.Stream = NewStream(inSrc, r.pkr, pkt.Req, inStream, outStream)
req.in = inSink
return &req, nil
}
func isTrue(data []byte) bool {
return len(data) == 4 &&
data[0] == 't' &&
data[1] == 'r' &&
data[2] == 'u' &&
data[3] == 'e'
}
// fetchRequest returns the request from the reqs map or, if it's not there yet, builds a new one.
func (r *rpc) fetchRequest(ctx context.Context, pkt *codec.Packet) (*Request, bool, error) {
var err error
r.rLock.Lock()
defer r.rLock.Unlock()
// get request from map, otherwise make new one
req, ok := r.reqs[pkt.Req]
if !ok {
req, err = r.ParseRequest(pkt)
if err != nil {
return nil, false, errors.Wrap(err, "error parsing request")
}
r.reqs[pkt.Req] = req
go r.root.HandleCall(ctx, req, r)
}
return req, !ok, nil
}
type Server interface {
Remote() net.Addr
Serve(context.Context) error
}
// Serve handles the RPC session
func (r *rpc) Serve(ctx context.Context) (err error) {
defer r.pkr.Close()
for {
var vpkt interface{}
// read next packet from connection
doRet := func() bool {
vpkt, err = r.pkr.Next(ctx)
r.tLock.Lock()
defer r.tLock.Unlock()
if luigi.IsEOS(err) {
err = nil
return true
}
if err != nil {
if r.terminated {
err = nil
return true
}
err = errors.Wrap(err, "error reading from packer source")
return true
}
return false
}()
if doRet {
return err
}
pkt := vpkt.(*codec.Packet)
if pkt.Flag.Get(codec.FlagEndErr) {
getReq := func(req int32) (*Request, bool) {
r.rLock.Lock()
defer r.rLock.Unlock()
r, ok := r.reqs[req]
return r, ok
}
if req, ok := getReq(pkt.Req); ok {
err := func() error {
r.rLock.Lock()
defer r.rLock.Unlock()
if isTrue(pkt.Body) {
err = req.in.Close()
if err != nil {
return errors.Wrap(err, "error closing pipe sink")
}
err = req.Stream.Close()
if err != nil {
return errors.Wrap(err, "error closing stream")
}
} else {
e, err := parseError(pkt.Body)
if err != nil {
return errors.Wrap(err, "error parsing error packet")
}
err = req.in.(luigi.ErrorCloser).CloseWithError(e)
if err != nil {
return errors.Wrap(err, "error closing pipe sink with error")
}
}
delete(r.reqs, pkt.Req)
return nil
}()
if err != nil {
return err
}
continue
}
}
req, isNew, err := r.fetchRequest(ctx, pkt)
if err != nil {
return errors.Wrap(err, "error getting request")
}
if isNew {
continue
}
// localize defer
err = func() error {
err := req.in.Pour(ctx, pkt)
return errors.Wrap(err, "error pouring data to handler")
}()
if err != nil {
return err
}
}
}
func (r *rpc) Remote() net.Addr {
return r.remote
}
type CallError struct {
Name string `json:"name"`
Message string `json:"message"`
Stack string `json:"stack"`
}
func (e *CallError) Error() string {
return e.Message
}
func parseError(data []byte) (*CallError, error) {
var e CallError
err := json.Unmarshal(data, &e)
if err != nil {
return nil, errors.Wrap(err, "error unmarshaling error packet")
}
if e.Name != "Error" {
return nil, errors.New(`name is not "Error"`)
}
return &e, nil
}