forked from capnproto/go-capnp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpc.go
1573 lines (1387 loc) · 41.8 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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package rpc implements the Cap'n Proto RPC protocol.
package rpc // import "capnproto.org/go/capnp/v3/rpc"
import (
"context"
"errors"
"fmt"
"sync"
"time"
"golang.org/x/sync/errgroup"
"capnproto.org/go/capnp/v3"
"capnproto.org/go/capnp/v3/exc"
"capnproto.org/go/capnp/v3/exp/mpsc"
"capnproto.org/go/capnp/v3/internal/syncutil"
"capnproto.org/go/capnp/v3/rpc/transport"
rpccp "capnproto.org/go/capnp/v3/std/capnp/rpc"
)
/*
At a high level, Conn manages three resources:
1) The connection's state: the tables
2) The transport's outbound stream
3) The transport's inbound stream
Each of these resources require mutually exclusive access. Complexity
ensues because there are two primary actors contending for these
resources: the local vat (sometimes referred to as the application) and
the remote vat. In this implementation, the remote vat is represented
by a goroutine that is solely responsible for the inbound stream. This
is referred to as the receive goroutine. The local vat accesses the
Conn via objects created by the Conn, and may do so from many different
goroutines. However, the Conn will largely serialize operations coming
from the local vat. Similarly, outbound messages are enqueued on 'sendq',
and processed by a single goroutine.
Conn protects the connection state with a simple mutex: Conn.mu. This
mutex must not be held while performing operations that take
indeterminate time or are provided by the application. This reduces
contention, but more importantly, prevents deadlocks. An application-
provided operation can (and commonly will) call back into the Conn.
The receive goroutine, being the only goroutine that receives messages
from the transport, can receive from the transport without additional
synchronization. One intentional side effect of this arrangement is
that during processing of a message, no other messages will be received.
This provides backpressure to the remote vat as well as simplifying some
message processing. However, it is essential that the receive goroutine
never block while processing a message. In other words, the receive
goroutine may only block when waiting for an incoming message.
Some advice for those working on this code:
Many functions are verbose; resist the urge to shorten them. There's
a lot more going on in this code than in most code, and many steps
require complicated invariants. Only extract common functionality if
the preconditions are simple.
As much as possible, ensure that when a function returns, the goroutine
is holding (or not holding) the same set of locks as when it started.
Try to push lock acquisition as high up in the call stack as you can.
This makes it easy to see and avoid extraneous lock transitions, which
is a common source of errors and/or inefficiencies.
*/
// A Conn is a connection to another Cap'n Proto vat.
// It is safe to use from multiple goroutines.
type Conn struct {
bootstrap capnp.Client
er errReporter
abortTimeout time.Duration
// bgctx is a Context that is canceled when shutdown starts. Note
// that it's parent is context.Background(), so we can rely on this
// being the *only* time it will be canceled.
bgctx context.Context
// tasks block shutdown.
tasks sync.WaitGroup
closed chan struct{} // closed when shutdown() returns
// The underlying transport. Only the reader & writer goroutines
// may do IO, but any thread may call NewMessage().
transport Transport
sender mpsc.Queue[asyncSend]
// lk contains all the fields that need to be protected by a mutex
// this makes it easy to tell at call sites whether you should or
// should not be holding the lock.
lk struct {
sync.Mutex // protects all the fields in lk.
closing bool // used to make shutdown() idempotent
bgcancel context.CancelFunc // bgcancel cancels bgctx.
// Tables
questions []*question
questionID idgen
answers map[answerID]*answer
exports []*expent
exportID idgen
imports map[importID]*impent
embargoes []*embargo
embargoID idgen
}
}
// Options specifies optional parameters for creating a Conn.
type Options struct {
// BootstrapClient is the capability that will be returned to the
// remote peer when receiving a Bootstrap message. NewConn "steals"
// this reference: it will release the client when the connection is
// closed.
BootstrapClient capnp.Client
// ErrorReporter will be called upon when errors occur while the Conn
// is receiving messages from the remote vat.
ErrorReporter ErrorReporter
// AbortTimeout specifies how long to block on sending an abort message
// before closing the transport. If zero, then a reasonably short
// timeout is used.
AbortTimeout time.Duration
}
// ErrorReporter can receive errors from a Conn. ReportError should be quick
// to return and should not use the Conn that it is attached to.
type ErrorReporter interface {
ReportError(error)
}
// NewConn creates a new connection that communicates on a given transport.
//
// Closing the connection will close the transport and release the bootstrap
// client provided in opts.
//
// If opts == nil, sensible defaults are used. See Options for more info.
//
// Once a connection is created, it will immediately start receiving
// requests from the transport.
func NewConn(t Transport, opts *Options) *Conn {
ctx, cancel := context.WithCancel(context.Background())
// We use an errgroup to link the lifetime of background tasks
// to each other.
g, ctx := errgroup.WithContext(ctx)
c := &Conn{
transport: t,
closed: make(chan struct{}),
bgctx: ctx,
sender: *mpsc.New[asyncSend](),
}
c.lk.bgcancel = cancel
c.lk.answers = make(map[answerID]*answer)
c.lk.imports = make(map[importID]*impent)
if opts != nil {
c.bootstrap = opts.BootstrapClient
c.er = errReporter{opts.ErrorReporter}
c.abortTimeout = opts.AbortTimeout
}
if c.abortTimeout == 0 {
c.abortTimeout = 100 * time.Millisecond
}
// start background tasks
g.Go(c.backgroundTask(c.send))
g.Go(c.backgroundTask(c.receive))
// monitor background tasks
go func() {
err := g.Wait()
// Treat context.Canceled as a success indicator.
// Do not report or send an abort message.
if errors.Is(err, context.Canceled) {
err = nil
}
c.er.ReportError(err) // ignores nil errors
c.lk.Lock()
defer c.lk.Unlock()
if err = c.shutdown(err); err != nil {
c.er.ReportError(err)
}
}()
return c
}
func (c *Conn) backgroundTask(f func() error) func() error {
c.tasks.Add(1)
return func() (err error) {
defer c.tasks.Done()
// backgroundTask MUST return a non-nil error in order to signal
// other tasks to stop. The context.Canceled will be treated as
// a success indicator by the caller.
if err = f(); err == nil {
err = context.Canceled
}
return err
}
}
// Bootstrap returns the remote vat's bootstrap interface. This creates
// a new client that the caller is responsible for releasing.
func (c *Conn) Bootstrap(ctx context.Context) (bc capnp.Client) {
c.lk.Lock()
defer c.lk.Unlock()
// Start a background task to prevent the conn from shutting down
// while sending the bootstrap message.
if !c.startTask() {
return capnp.ErrorClient(rpcerr.Disconnectedf("connection closed"))
}
defer c.tasks.Done()
bootCtx, cancel := context.WithCancel(ctx)
q := c.newQuestion(capnp.Method{})
bc, q.bootstrapPromise = capnp.NewPromisedClient(bootstrapClient{
c: q.p.Answer().Client().AddRef(),
cancel: cancel,
})
c.sendMessage(ctx, func(m rpccp.Message) error {
boot, err := m.NewBootstrap()
if err == nil {
boot.SetQuestionId(uint32(q.id))
}
return err
}, func(err error) {
if err != nil {
syncutil.With(&c.lk, func() {
c.lk.questions[q.id] = nil
})
q.bootstrapPromise.Reject(exc.Annotate("rpc", "bootstrap", err))
syncutil.With(&c.lk, func() {
c.lk.questionID.remove(uint32(q.id))
})
return
}
c.tasks.Add(1)
go func() {
defer c.tasks.Done()
q.handleCancel(bootCtx)
}()
})
return
}
type bootstrapClient struct {
c capnp.Client
cancel context.CancelFunc
}
func (bc bootstrapClient) Send(ctx context.Context, s capnp.Send) (*capnp.Answer, capnp.ReleaseFunc) {
return bc.c.SendCall(ctx, s)
}
func (bc bootstrapClient) Recv(ctx context.Context, r capnp.Recv) capnp.PipelineCaller {
return bc.c.RecvCall(ctx, r)
}
func (bc bootstrapClient) Brand() capnp.Brand {
return bc.c.State().Brand
}
func (bc bootstrapClient) Shutdown() {
bc.cancel()
bc.c.Release()
}
// Close sends an abort to the remote vat and closes the underlying
// transport.
func (c *Conn) Close() error {
c.lk.Lock()
defer func() {
c.lk.Unlock()
<-c.closed
}()
return c.shutdown(exc.Exception{ // NOTE: omit "rpc" prefix
Type: exc.Failed,
Cause: ErrConnClosed,
})
}
// Done returns a channel that is closed after the connection is
// shut down.
func (c *Conn) Done() <-chan struct{} {
return c.closed
}
// shutdown tears down the connection and transport, optionally sending
// an abort message before closing. The caller MUST be hold c.lk.
func (c *Conn) shutdown(abortErr error) (err error) {
if !c.lk.closing {
c.lk.closing = true
c.lk.bgcancel()
readyForClose := make(chan struct{})
go func() {
defer close(c.closed)
select {
case <-readyForClose:
case <-time.After(c.abortTimeout):
}
if err = c.transport.Close(); err != nil {
err = rpcerr.Failedf("close transport: %w", err)
}
}()
c.stopTasks()
syncutil.Without(&c.lk, c.drainQueue)
c.release()
c.abort(abortErr)
close(readyForClose)
<-c.closed
}
return
}
// Stop all tasks and prevent new tasks from being started.
// Called by 'shutdown'. Callers MUST hold c.lk.
func (c *Conn) stopTasks() {
for _, a := range c.lk.answers {
if a != nil && a.cancel != nil {
a.cancel()
}
}
// Wait for work to stop.
c.lk.Unlock()
defer c.lk.Lock()
c.tasks.Wait()
}
// caller MUST NOT hold c.lk
func (c *Conn) drainQueue() {
for {
pending, ok := c.sender.TryRecv()
if !ok {
break
}
pending.Abort(ErrConnClosed)
}
}
// Clear all tables, releasing exported clients and unfinished answers.
// Called by 'shutdown'. Caller MUST hold c.lk.
func (c *Conn) release() {
exports := c.lk.exports
embargoes := c.lk.embargoes
answers := c.lk.answers
questions := c.lk.questions
c.lk.imports = nil
c.lk.exports = nil
c.lk.embargoes = nil
c.lk.questions = nil
c.lk.answers = nil
c.lk.Unlock()
defer c.lk.Lock()
c.releaseBootstrap()
c.releaseExports(exports)
c.liftEmbargoes(embargoes)
c.releaseAnswers(answers)
c.releaseQuestions(questions)
}
func (c *Conn) releaseBootstrap() {
c.bootstrap.Release()
c.bootstrap = capnp.Client{}
}
func (c *Conn) releaseExports(exports []*expent) {
for _, e := range exports {
if e != nil {
metadata := e.client.State().Metadata
syncutil.With(metadata, func() {
c.clearExportID(metadata)
})
e.client.Release()
}
}
}
func (c *Conn) liftEmbargoes(embargoes []*embargo) {
for _, e := range embargoes {
if e != nil {
e.lift()
}
}
}
func (c *Conn) releaseAnswers(answers map[answerID]*answer) {
for _, a := range answers {
if a != nil && a.msgReleaser != nil {
a.msgReleaser.Decr()
}
}
}
func (c *Conn) releaseQuestions(questions []*question) {
for _, q := range questions {
canceled := q != nil && q.flags&finished != 0
if !canceled {
// Only reject the question if it isn't already flagged
// as finished; otherwise it was rejected when the finished
// flag was set.
q.Reject(ExcClosed)
}
}
}
// If abortErr != nil, send abort message. IO and alloc errors are ignored.
// Called by 'shutdown'. Callers MUST hold c.lk.
func (c *Conn) abort(abortErr error) {
// send abort message?
if abortErr != nil {
c.lk.Unlock()
defer c.lk.Lock()
outMsg, err := c.transport.NewMessage()
if err != nil {
return
}
defer outMsg.Release()
// configure & send abort message
if abort, err := outMsg.Message.NewAbort(); err == nil {
abort.SetType(rpccp.Exception_Type(exc.TypeOf(abortErr)))
if err = abort.SetReason(abortErr.Error()); err == nil {
outMsg.Send()
}
}
}
}
func (c *Conn) send() error {
for {
async, err := c.sender.Recv(c.bgctx)
if err != nil {
return err
}
async.Send()
}
}
// receive receives and dispatches messages coming from c.transport. receive
// runs in a background goroutine.
//
// After receive returns, the connection is shut down. If receive
// returns a non-nil error, it is sent to the remove vat as an abort.
func (c *Conn) receive() error {
ctx := c.bgctx
incoming := make(chan incomingMessage)
// We delegate actual IO to a separate goroutine, so we can always be responsive to the
// context:
go reader(ctx, incoming, c.transport)
for {
var (
recv rpccp.Message
release capnp.ReleaseFunc
err error
)
select {
case <-ctx.Done():
return ctx.Err()
case in := <-incoming:
recv = in.Message
release = in.Release
err = in.err
}
if err != nil {
return err
}
switch recv.Which() {
case rpccp.Message_Which_unimplemented:
// no-op for now to avoid feedback loop
case rpccp.Message_Which_abort:
defer release()
e, err := recv.Abort()
if err != nil {
c.er.ReportError(fmt.Errorf("read abort: %w", err))
return nil
}
reason, err := e.Reason()
if err != nil {
c.er.ReportError(fmt.Errorf("read abort: reason: %w", err))
return nil
}
c.er.ReportError(exc.New(exc.Type(e.Type()), "rpc", "remote abort: "+reason))
return nil
case rpccp.Message_Which_bootstrap:
bootstrap, err := recv.Bootstrap()
if err != nil {
release()
c.er.ReportError(fmt.Errorf("read bootstrap: %w", err))
continue
}
qid := answerID(bootstrap.QuestionId())
release()
if err := c.handleBootstrap(ctx, qid); err != nil {
return err
}
case rpccp.Message_Which_call:
call, err := recv.Call()
if err != nil {
release()
c.er.ReportError(fmt.Errorf("read call: %w", err))
continue
}
if err := c.handleCall(ctx, call, release); err != nil {
return err
}
case rpccp.Message_Which_return:
ret, err := recv.Return()
if err != nil {
release()
c.er.ReportError(fmt.Errorf("read return: %w", err))
continue
}
if err := c.handleReturn(ctx, ret, release); err != nil {
return err
}
case rpccp.Message_Which_finish:
fin, err := recv.Finish()
if err != nil {
release()
c.er.ReportError(fmt.Errorf("read finish: %w", err))
continue
}
qid := answerID(fin.QuestionId())
releaseResultCaps := fin.ReleaseResultCaps()
release()
if err := c.handleFinish(ctx, qid, releaseResultCaps); err != nil {
return err
}
case rpccp.Message_Which_release:
rel, err := recv.Release()
if err != nil {
release()
c.er.ReportError(fmt.Errorf("read release: %w", err))
continue
}
id := exportID(rel.Id())
count := rel.ReferenceCount()
release()
if err := c.handleRelease(ctx, id, count); err != nil {
return err
}
case rpccp.Message_Which_disembargo:
d, err := recv.Disembargo()
if err != nil {
release()
c.er.ReportError(fmt.Errorf("read disembargo: %w", err))
continue
}
err = c.handleDisembargo(ctx, d, release)
if err != nil {
return err
}
default:
c.er.ReportError(fmt.Errorf("unknown message type %v from remote", recv.Which()))
c.sendMessage(ctx, func(m rpccp.Message) error {
defer release()
if err := m.SetUnimplemented(recv); err != nil {
return rpcerr.Annotatef(err, "send unimplemented")
}
return nil
}, nil)
}
}
}
func (c *Conn) handleBootstrap(ctx context.Context, id answerID) error {
rl := &releaseList{}
defer rl.Release()
c.lk.Lock()
defer c.lk.Unlock()
if c.lk.answers[id] != nil {
return rpcerr.Failedf("incoming bootstrap: answer ID %d reused", id)
}
var (
err error
ans = answer{c: c, id: id}
)
syncutil.Without(&c.lk, func() {
ans.ret, ans.sendMsg, ans.msgReleaser, err = c.newReturn()
if err == nil {
ans.ret.SetAnswerId(uint32(id))
ans.ret.SetReleaseParamCaps(false)
}
})
if err != nil {
err = rpcerr.Annotate(err, "incoming bootstrap")
c.lk.answers[id] = errorAnswer(c, id, err)
c.er.ReportError(err)
return nil
}
c.lk.answers[id] = &ans
if !c.bootstrap.IsValid() {
ans.sendException(rl, exc.New(exc.Failed, "", "vat does not expose a public/bootstrap interface"))
return nil
}
if err := ans.setBootstrap(c.bootstrap.AddRef()); err != nil {
ans.sendException(rl, err)
return nil
}
err = ans.sendReturn(rl)
if err != nil {
// Answer cannot possibly encounter a Finish, since we still
// haven't returned to receive().
panic(err)
}
return nil
}
func (c *Conn) handleCall(ctx context.Context, call rpccp.Call, releaseCall capnp.ReleaseFunc) error {
rl := &releaseList{}
defer rl.Release()
id := answerID(call.QuestionId())
// TODO(3rd-party handshake): support sending results to 3rd party vat
if call.SendResultsTo().Which() != rpccp.Call_sendResultsTo_Which_caller {
// TODO(someday): handle SendResultsTo.yourself
c.er.ReportError(fmt.Errorf("incoming call: results destination is not caller"))
c.sendMessage(ctx, func(m rpccp.Message) error {
defer releaseCall()
mm, err := m.NewUnimplemented()
if err != nil {
return rpcerr.Annotatef(err, "incoming call: send unimplemented")
}
if err = mm.SetCall(call); err != nil {
return rpcerr.Annotatef(err, "incoming call: send unimplemented")
}
return nil
}, func(err error) {
c.er.ReportError(rpcerr.Annotatef(err, "incoming call: send unimplemented"))
})
return nil
}
c.lk.Lock()
if c.lk.answers[id] != nil {
c.lk.Unlock()
releaseCall()
return rpcerr.Failedf("incoming call: answer ID %d reused", id)
}
var p parsedCall
parseErr := c.parseCall(&p, call) // parseCall sets CapTable
// Create return message.
c.lk.Unlock()
ret, send, retReleaser, err := c.newReturn()
if err != nil {
err = rpcerr.Annotate(err, "incoming call")
syncutil.With(&c.lk, func() {
c.lk.answers[id] = errorAnswer(c, id, err)
})
c.er.ReportError(err)
releaseCall()
return nil
}
ret.SetAnswerId(uint32(id))
ret.SetReleaseParamCaps(false)
// Find target and start call.
c.lk.Lock()
ans := &answer{
c: c,
id: id,
ret: ret,
sendMsg: send,
msgReleaser: retReleaser,
}
c.lk.answers[id] = ans
if parseErr != nil {
parseErr = rpcerr.Annotate(parseErr, "incoming call")
ans.sendException(rl, parseErr)
c.lk.Unlock()
c.er.ReportError(parseErr)
releaseCall()
return nil
}
released := false
releaseArgs := func() {
if released {
return
}
released = true
releaseCall()
}
switch p.target.which {
case rpccp.MessageTarget_Which_importedCap:
ent := c.findExport(p.target.importedCap)
if ent == nil {
ans.ret = rpccp.Return{}
ans.sendMsg = nil
ans.msgReleaser = nil
c.lk.Unlock()
retReleaser.Decr()
releaseCall()
return rpcerr.Failedf("incoming call: unknown export ID %d", id)
}
c.tasks.Add(1) // will be finished by answer.Return
var callCtx context.Context
callCtx, ans.cancel = context.WithCancel(c.bgctx)
c.lk.Unlock()
pcall := ent.client.RecvCall(callCtx, capnp.Recv{
Args: p.args,
Method: p.method,
ReleaseArgs: releaseArgs,
Returner: ans,
})
// Place PipelineCaller into answer. Since the receive goroutine is
// the only one that uses answer.pcall, it's fine that there's a
// time gap for this being set.
ans.setPipelineCaller(p.method, pcall)
return nil
case rpccp.MessageTarget_Which_promisedAnswer:
tgtAns := c.lk.answers[p.target.promisedAnswer]
if tgtAns == nil || tgtAns.flags.Contains(finishReceived) {
ans.ret = rpccp.Return{}
ans.sendMsg = nil
ans.msgReleaser = nil
c.lk.Unlock()
retReleaser.Decr()
releaseCall()
return rpcerr.Failedf("incoming call: use of unknown or finished answer ID %d for promised answer target", p.target.promisedAnswer)
}
if tgtAns.flags.Contains(resultsReady) {
if tgtAns.err != nil {
ans.sendException(rl, tgtAns.err)
c.lk.Unlock()
releaseCall()
return nil
}
// tgtAns.results is guaranteed to stay alive because it hasn't
// received finish yet (it would have been deleted from the
// answers table), and it can't receive a finish because this is
// happening on the receive goroutine.
content, err := tgtAns.results.Content()
if err != nil {
err = rpcerr.Failedf("incoming call: read results from target answer: %w", err)
ans.sendException(rl, err)
c.lk.Unlock()
releaseCall()
c.er.ReportError(err)
return nil
}
sub, err := capnp.Transform(content, p.target.transform)
if err != nil {
// Not reporting, as this is the caller's fault.
ans.sendException(rl, err)
c.lk.Unlock()
releaseCall()
return nil
}
iface := sub.Interface()
var tgt capnp.Client
switch {
case sub.IsValid() && !iface.IsValid():
tgt = capnp.ErrorClient(rpcerr.Failed(ErrNotACapability))
case !iface.IsValid() || int64(iface.Capability()) >= int64(len(tgtAns.results.Message().CapTable)):
tgt = capnp.Client{}
default:
tgt = tgtAns.results.Message().CapTable[iface.Capability()]
}
c.tasks.Add(1) // will be finished by answer.Return
var callCtx context.Context
callCtx, ans.cancel = context.WithCancel(c.bgctx)
c.lk.Unlock()
pcall := tgt.RecvCall(callCtx, capnp.Recv{
Args: p.args,
Method: p.method,
ReleaseArgs: releaseArgs,
Returner: ans,
})
ans.setPipelineCaller(p.method, pcall)
} else {
// Results not ready, use pipeline caller.
tgtAns.pcalls.Add(1) // will be finished by answer.Return
var callCtx context.Context
callCtx, ans.cancel = context.WithCancel(c.bgctx)
tgt := tgtAns.pcall
c.tasks.Add(1) // will be finished by answer.Return
c.lk.Unlock()
pcall := tgt.PipelineRecv(callCtx, p.target.transform, capnp.Recv{
Args: p.args,
Method: p.method,
ReleaseArgs: releaseArgs,
Returner: ans,
})
tgtAns.pcalls.Done()
ans.setPipelineCaller(p.method, pcall)
}
return nil
default:
panic("unreachable")
}
}
type parsedCall struct {
target parsedMessageTarget
method capnp.Method
args capnp.Struct
}
type parsedMessageTarget struct {
which rpccp.MessageTarget_Which
importedCap exportID
promisedAnswer answerID
transform []capnp.PipelineOp
}
func (c *Conn) parseCall(p *parsedCall, call rpccp.Call) error {
p.method = capnp.Method{
InterfaceID: call.InterfaceId(),
MethodID: call.MethodId(),
}
payload, err := call.Params()
if err != nil {
return rpcerr.Failedf("read params: %w", err)
}
ptr, _, err := c.recvPayload(payload)
if err != nil {
return rpcerr.Annotate(err, "read params")
}
p.args = ptr.Struct()
tgt, err := call.Target()
if err != nil {
return rpcerr.Failedf("read target: %w", err)
}
if err := parseMessageTarget(&p.target, tgt); err != nil {
return err
}
return nil
}
func parseMessageTarget(pt *parsedMessageTarget, tgt rpccp.MessageTarget) error {
switch pt.which = tgt.Which(); pt.which {
case rpccp.MessageTarget_Which_importedCap:
pt.importedCap = exportID(tgt.ImportedCap())
case rpccp.MessageTarget_Which_promisedAnswer:
pa, err := tgt.PromisedAnswer()
if err != nil {
return rpcerr.Failedf("read target answer: %w", err)
}
pt.promisedAnswer = answerID(pa.QuestionId())
opList, err := pa.Transform()
if err != nil {
return rpcerr.Failedf("read target transform: %w", err)
}
pt.transform, err = parseTransform(opList)
if err != nil {
return rpcerr.Annotate(err, "read target transform")
}
default:
return rpcerr.Unimplementedf("unknown message target %v", pt.which)
}
return nil
}
func parseTransform(list rpccp.PromisedAnswer_Op_List) ([]capnp.PipelineOp, error) {
ops := make([]capnp.PipelineOp, 0, list.Len())
for i := 0; i < list.Len(); i++ {
li := list.At(i)
switch li.Which() {
case rpccp.PromisedAnswer_Op_Which_noop:
// do nothing
case rpccp.PromisedAnswer_Op_Which_getPointerField:
ops = append(ops, capnp.PipelineOp{Field: li.GetPointerField()})
default:
return nil, rpcerr.Failedf("transform element %d: unknown type %v", i, li.Which())
}
}
return ops, nil
}
func (c *Conn) handleReturn(ctx context.Context, ret rpccp.Return, release capnp.ReleaseFunc) error {
c.lk.Lock()
qid := questionID(ret.AnswerId())
if uint32(qid) >= uint32(len(c.lk.questions)) {
c.lk.Unlock()
release()
return rpcerr.Failedf("incoming return: question %d does not exist", qid)
}
// Pop the question from the table. Receiving the Return message
// will always remove the question from the table, because it's the
// only time the remote vat will use it.
q := c.lk.questions[qid]
c.lk.questions[qid] = nil
if q == nil {
c.lk.Unlock()
release()
return rpcerr.Failedf("incoming return: question %d does not exist", qid)
}
canceled := q.flags&finished != 0
q.flags |= finished
if canceled {
// Wait for cancelation task to write the Finish message. If the
// Finish message could not be sent to the remote vat, we can't
// reuse the ID.
select {
case <-q.finishMsgSend:
if q.flags&finishSent != 0 {
c.lk.questionID.remove(uint32(qid))
}
c.lk.Unlock()
release()
default:
c.lk.Unlock()
release()
go func() {
<-q.finishMsgSend
syncutil.With(&c.lk, func() {
if q.flags&finishSent != 0 {
c.lk.questionID.remove(uint32(qid))
}
})
}()
}
return nil
}
pr := c.parseReturn(ret, q.called) // fills in CapTable
if pr.parseFailed {
c.er.ReportError(rpcerr.Annotate(pr.err, "incoming return"))
}
// We're going to potentially block fulfilling some promises so fork
// off a goroutine to avoid blocking the receive loop.
//
// TODO(cleanup): This is a bit weird in that we hold the lock across
// the go statement, and do the unlock in the new goroutine, but before
// we actually block. This was less weird when the go statement wasn't
// there, and we should rework this so it's easier to understand what's
// going on.
go func() {
switch {
case q.bootstrapPromise != nil:
syncutil.Without(&c.lk, func() {
q.p.Resolve(pr.result, pr.err)
q.bootstrapPromise.Fulfill(q.p.Answer().Client())
q.p.ReleaseClients()
release()
})
case pr.err != nil:
// TODO(someday): send unimplemented message back to remote if
// pr.unimplemented == true.