-
-
Notifications
You must be signed in to change notification settings - Fork 111
/
rpc.go
1436 lines (1353 loc) · 38.3 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"
"fmt"
"sync"
"time"
"capnproto.org/go/capnp/v3"
"capnproto.org/go/capnp/v3/internal/errors"
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.
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.
Conn protects the outbound stream with a signal channel, Conn.sendCond,
referred to as the sender lock. The sender lock is required to create,
send, or release outbound transport messages. While a goroutine may
hold onto both Conn.mu and the sender lock, the goroutine must not hold
onto Conn.mu while performing any transport operations, for reasons
mentioned above.
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.
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
reporter ErrorReporter
abortTimeout time.Duration
// bgctx is a Context that is canceled when shutdown starts.
bgctx context.Context
// bgcancel cancels bgctx. It must only be called while holding mu.
bgcancel context.CancelFunc
// tasks block shutdown.
tasks sync.WaitGroup
// transport is protected by the sender lock. Only the receive goroutine can
// call RecvMessage.
transport Transport
// mu protects all the following fields in the Conn.
mu sync.Mutex
closed bool // set when Close() is called, used to distinguish user Closing multiple times
shut chan struct{} // closed when shutdown() returns
// sendCond is non-nil if an operation involving sender is in
// progress, and the channel is closed when the operation is finished.
// See the above comment for a longer explanation.
sendCond chan struct{}
// 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
}
// A type that implements 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 communications on a given
// transport. Closing the connection will close the transport.
// Passing nil for opts is the same as passing the zero value.
//
// Once a connection is created, it will immediately start receiving
// requests from the transport.
func NewConn(t Transport, opts *Options) *Conn {
bgctx, bgcancel := context.WithCancel(context.Background())
c := &Conn{
transport: t,
shut: make(chan struct{}),
bgctx: bgctx,
bgcancel: bgcancel,
answers: make(map[answerID]*answer),
imports: make(map[importID]*impent),
}
if opts != nil {
c.bootstrap = opts.BootstrapClient
c.reporter = opts.ErrorReporter
c.abortTimeout = opts.AbortTimeout
}
if c.abortTimeout == 0 {
c.abortTimeout = 100 * time.Millisecond
}
c.tasks.Add(1)
go func() {
abortErr := c.receive(c.bgctx)
c.tasks.Done()
c.mu.Lock()
select {
case <-c.bgctx.Done():
c.mu.Unlock()
default:
if abortErr != nil {
c.report(abortErr)
}
// shutdown unlocks c.mu.
if err := c.shutdown(abortErr); err != nil {
c.report(err)
}
}
}()
return c
}
// 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) *capnp.Client {
c.mu.Lock()
if !c.startTask() {
c.mu.Unlock()
return capnp.ErrorClient(disconnected("connection closed"))
}
defer c.tasks.Done()
q := c.newQuestion(capnp.Method{})
bootCtx, cancel := context.WithCancel(ctx)
bc, cp := capnp.NewPromisedClient(bootstrapClient{
c: q.p.Answer().Client().AddRef(),
cancel: cancel,
})
q.bootstrapPromise = cp // safe to write because we're still holding c.mu
err := c.sendMessage(ctx, func(msg rpccp.Message) error {
boot, err := msg.NewBootstrap()
if err != nil {
return err
}
boot.SetQuestionId(uint32(q.id))
return nil
})
if err != nil {
c.questions[q.id] = nil
c.questionID.remove(uint32(q.id))
c.mu.Unlock()
return capnp.ErrorClient(annotate(err).errorf("bootstrap"))
}
c.tasks.Add(1)
go func() {
defer c.tasks.Done()
q.handleCancel(bootCtx)
}()
c.mu.Unlock()
return bc
}
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.mu.Lock()
if c.closed {
return fail("close on closed connection")
}
c.closed = true
select {
case <-c.bgctx.Done():
c.mu.Unlock()
<-c.shut
return nil
default:
// shutdown unlocks c.mu.
return c.shutdown(errors.New(errors.Failed, "", "connection closed"))
}
}
// Done returns a channel that is closed after the connection is
// shut down.
func (c *Conn) Done() <-chan struct{} {
return c.shut
}
// shutdown tears down the connection and transport, optionally sending
// an abort message before closing. The caller must be holding onto
// c.mu, although it will be released while shutting down, and c.bgctx
// must not be Done.
func (c *Conn) shutdown(abortErr error) error {
defer close(c.shut)
// Cancel all work.
c.bgcancel()
for _, a := range c.answers {
if a != nil && a.cancel != nil {
a.cancel()
}
}
// Wait for work to stop.
c.mu.Unlock()
c.tasks.Wait()
c.mu.Lock()
// Clear all tables, releasing exported clients and unfinished answers.
exports := c.exports
answers := c.answers
embargoes := c.embargoes
c.imports = nil
c.exports = nil
c.questions = nil
c.answers = nil
c.embargoes = nil
c.mu.Unlock()
c.bootstrap.Release()
c.bootstrap = nil
for _, e := range exports {
if e != nil {
e.client.Release()
}
}
for _, e := range embargoes {
if e != nil {
e.lift()
}
}
for _, a := range answers {
if a != nil {
releaseList(a.resultCapTable).release()
// Because shutdown is now the only task running, no need to
// acquire sender lock.
a.releaseMsg()
}
}
// Send abort message (ignoring error).
if abortErr != nil {
abortCtx, cancel := context.WithTimeout(context.Background(), c.abortTimeout)
msg, send, release, err := c.transport.NewMessage(abortCtx)
if err != nil {
cancel()
goto closeTransport
}
abort, err := msg.NewAbort()
if err != nil {
release()
cancel()
goto closeTransport
}
abort.SetType(rpccp.Exception_Type(errors.TypeOf(abortErr)))
if err := abort.SetReason(abortErr.Error()); err != nil {
release()
cancel()
goto closeTransport
}
send()
release()
cancel()
}
closeTransport:
if err := c.transport.Close(); err != nil {
return errorf("close transport: %v", err)
}
return nil
}
// 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(ctx context.Context) error {
for {
recv, releaseRecv, err := c.transport.RecvMessage(ctx)
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:
exc, err := recv.Abort()
if err != nil {
releaseRecv()
c.reportf("read abort: %v", err)
return nil
}
reason, err := exc.Reason()
if err != nil {
releaseRecv()
c.reportf("read abort reason: %v", err)
return nil
}
ty := exc.Type()
releaseRecv()
c.report(errors.New(errors.Type(ty), "rpc", "remote abort: "+reason))
return nil
case rpccp.Message_Which_bootstrap:
bootstrap, err := recv.Bootstrap()
if err != nil {
releaseRecv()
c.reportf("read bootstrap: %v", err)
continue
}
qid := answerID(bootstrap.QuestionId())
releaseRecv()
if err := c.handleBootstrap(ctx, qid); err != nil {
return err
}
case rpccp.Message_Which_call:
call, err := recv.Call()
if err != nil {
releaseRecv()
c.reportf("read call: %v", err)
continue
}
if err := c.handleCall(ctx, call, releaseRecv); err != nil {
return err
}
case rpccp.Message_Which_return:
ret, err := recv.Return()
if err != nil {
releaseRecv()
c.reportf("read return: %v", err)
continue
}
if err := c.handleReturn(ctx, ret, releaseRecv); err != nil {
return err
}
case rpccp.Message_Which_finish:
fin, err := recv.Finish()
if err != nil {
releaseRecv()
c.reportf("read finish: %v", err)
continue
}
qid := answerID(fin.QuestionId())
releaseResultCaps := fin.ReleaseResultCaps()
releaseRecv()
if err := c.handleFinish(ctx, qid, releaseResultCaps); err != nil {
return err
}
case rpccp.Message_Which_release:
rel, err := recv.Release()
if err != nil {
releaseRecv()
c.reportf("read release: %v", err)
continue
}
id := exportID(rel.Id())
count := rel.ReferenceCount()
releaseRecv()
if err := c.handleRelease(ctx, id, count); err != nil {
return err
}
case rpccp.Message_Which_disembargo:
d, err := recv.Disembargo()
if err != nil {
releaseRecv()
c.reportf("read disembargo: %v", err)
continue
}
err = c.handleDisembargo(ctx, d)
releaseRecv()
if err != nil {
return err
}
default:
err := c.handleUnknownMessage(ctx, recv)
releaseRecv()
if err != nil {
return err
}
}
}
}
func (c *Conn) handleBootstrap(ctx context.Context, id answerID) error {
c.mu.Lock()
if c.answers[id] != nil {
c.mu.Unlock()
return errorf("incoming bootstrap: answer ID %d reused", id)
}
if err := c.tryLockSender(ctx); err != nil {
// Shutting down. Don't report.
c.mu.Unlock()
return nil
}
c.mu.Unlock()
ret, send, release, err := c.newReturn(ctx)
if err != nil {
err = annotate(err).errorf("incoming bootstrap")
c.mu.Lock()
c.answers[id] = errorAnswer(c, id, err)
c.unlockSender()
c.mu.Unlock()
c.report(err)
return nil
}
ret.SetAnswerId(uint32(id))
ret.SetReleaseParamCaps(false)
bootState := c.bootstrap.State()
c.mu.Lock()
ans := &answer{
c: c,
id: id,
ret: ret,
sendMsg: send,
releaseMsg: release,
}
c.answers[id] = ans
if !c.bootstrap.IsValid() {
rl := ans.sendException(errors.New(errors.Failed, "", "vat does not expose a public/bootstrap interface"))
c.unlockSender()
c.mu.Unlock()
rl.release()
return nil
}
if err := ans.setBootstrap(c.bootstrap.AddRef()); err != nil {
rl := ans.sendException(err)
c.unlockSender()
c.mu.Unlock()
rl.release()
return nil
}
rl, err := ans.sendReturn([]capnp.ClientState{bootState})
c.unlockSender()
c.mu.Unlock()
rl.release()
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 {
id := answerID(call.QuestionId())
if call.SendResultsTo().Which() != rpccp.Call_sendResultsTo_Which_caller {
// TODO(someday): handle SendResultsTo.yourself
c.reportf("incoming call: results destination is not caller")
c.mu.Lock()
err := c.sendMessage(ctx, func(m rpccp.Message) error {
mm, err := m.NewUnimplemented()
if err != nil {
return err
}
if err := mm.SetCall(call); err != nil {
return err
}
return nil
})
c.mu.Unlock()
releaseCall()
if err != nil {
c.report(annotate(err).errorf("incoming call: send unimplemented"))
}
return nil
}
// Acquire c.mu and sender lock.
c.mu.Lock()
if c.answers[id] != nil {
c.mu.Unlock()
releaseCall()
return errorf("incoming call: answer ID %d reused", id)
}
if err := c.tryLockSender(ctx); err != nil {
// Shutting down. Don't report.
c.mu.Unlock()
return nil
}
var p parsedCall
parseErr := c.parseCall(&p, call) // parseCall sets CapTable
// Create return message.
c.mu.Unlock()
ret, send, releaseRet, err := c.newReturn(ctx)
if err != nil {
err = annotate(err).errorf("incoming call")
c.mu.Lock()
c.answers[id] = errorAnswer(c, id, err)
c.unlockSender()
c.mu.Unlock()
c.report(err)
clearCapTable(call.Message())
releaseCall()
return nil
}
ret.SetAnswerId(uint32(id))
ret.SetReleaseParamCaps(false)
// Find target and start call.
c.mu.Lock()
ans := &answer{
c: c,
id: id,
ret: ret,
sendMsg: send,
releaseMsg: releaseRet,
}
c.answers[id] = ans
if parseErr != nil {
parseErr = annotate(err).errorf("incoming call")
rl := ans.sendException(parseErr)
c.unlockSender()
c.mu.Unlock()
c.report(parseErr)
rl.release()
clearCapTable(call.Message())
releaseCall()
return nil
}
released := false
releaseArgs := func() {
if released {
return
}
released = true
clearCapTable(call.Message())
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.releaseMsg = nil
c.mu.Unlock()
releaseRet()
c.mu.Lock()
c.unlockSender()
c.mu.Unlock()
clearCapTable(call.Message())
releaseCall()
return errorf("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.unlockSender()
c.mu.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(pcall)
return nil
case rpccp.MessageTarget_Which_promisedAnswer:
tgtAns := c.answers[p.target.promisedAnswer]
if tgtAns == nil || tgtAns.flags&finishReceived != 0 {
ans.ret = rpccp.Return{}
ans.sendMsg = nil
ans.releaseMsg = nil
c.mu.Unlock()
releaseRet()
c.mu.Lock()
c.unlockSender()
c.mu.Unlock()
clearCapTable(call.Message())
releaseCall()
return errorf("incoming call: use of unknown or finished answer ID %d for promised answer target", p.target.promisedAnswer)
}
if tgtAns.flags&resultsReady != 0 {
// Results ready.
if tgtAns.err != nil {
rl := ans.sendException(tgtAns.err)
c.unlockSender()
c.mu.Unlock()
rl.release()
clearCapTable(call.Message())
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 = errorf("incoming call: read results from target answer: %v", err)
rl := ans.sendException(err)
c.unlockSender()
c.mu.Unlock()
rl.release()
clearCapTable(call.Message())
releaseCall()
c.report(err)
return nil
}
sub, err := capnp.Transform(content, p.target.transform)
if err != nil {
// Not reporting, as this is the caller's fault.
rl := ans.sendException(err)
c.unlockSender()
c.mu.Unlock()
rl.release()
clearCapTable(call.Message())
releaseCall()
return nil
}
iface := sub.Interface()
var tgt *capnp.Client
switch {
case sub.IsValid() && !iface.IsValid():
tgt = capnp.ErrorClient(fail("not a capability"))
case !iface.IsValid() || int64(iface.Capability()) >= int64(len(tgtAns.resultCapTable)):
tgt = nil
default:
tgt = tgtAns.resultCapTable[iface.Capability()]
}
c.tasks.Add(1) // will be finished by answer.Return
var callCtx context.Context
callCtx, ans.cancel = context.WithCancel(c.bgctx)
c.unlockSender()
c.mu.Unlock()
pcall := tgt.RecvCall(callCtx, capnp.Recv{
Args: p.args,
Method: p.method,
ReleaseArgs: releaseArgs,
Returner: ans,
})
ans.setPipelineCaller(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.mu.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(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 errorf("read params: %v", err)
}
ptr, _, err := c.recvPayload(payload)
if err != nil {
return annotate(err).errorf("read params")
}
p.args = ptr.Struct()
tgt, err := call.Target()
if err != nil {
return errorf("read target: %v", err)
}
if err := parseMessageTarget(&p.target, tgt); err != nil {
return err
}
return nil
}
func parseMessageTarget(pt *parsedMessageTarget, tgt rpccp.MessageTarget) error {
pt.which = tgt.Which()
switch 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 errorf("read target answer: %v", err)
}
pt.promisedAnswer = answerID(pa.QuestionId())
opList, err := pa.Transform()
if err != nil {
return errorf("read target transform: %v", err)
}
pt.transform, err = parseTransform(opList)
if err != nil {
return annotate(err).errorf("read target transform")
}
default:
return 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, errorf("transform element %d: unknown type %v", i, li.Which())
}
}
return ops, nil
}
func (c *Conn) handleReturn(ctx context.Context, ret rpccp.Return, releaseRet capnp.ReleaseFunc) error {
c.mu.Lock()
qid := questionID(ret.AnswerId())
if uint32(qid) >= uint32(len(c.questions)) {
c.mu.Unlock()
releaseRet()
return errorf("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.questions[qid]
c.questions[qid] = nil
if q == nil {
c.mu.Unlock()
releaseRet()
return errorf("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.questionID.remove(uint32(qid))
}
c.mu.Unlock()
releaseRet()
default:
c.mu.Unlock()
releaseRet()
<-q.finishMsgSend
c.mu.Lock()
if q.flags&finishSent != 0 {
c.questionID.remove(uint32(qid))
}
c.mu.Unlock()
}
return nil
}
pr := c.parseReturn(ret, q.called) // fills in CapTable
if pr.parseFailed {
c.report(annotate(pr.err).errorf("incoming return"))
}
switch {
case q.bootstrapPromise != nil && pr.err == nil:
q.release = func() {}
c.mu.Unlock()
q.p.Fulfill(pr.result)
q.bootstrapPromise.Fulfill(q.p.Answer().Client())
q.p.ReleaseClients()
clearCapTable(pr.result.Message())
releaseRet()
c.mu.Lock()
case q.bootstrapPromise != nil && pr.err != nil:
// TODO(someday): send unimplemented message back to remote if
// pr.unimplemented == true.
q.release = func() {}
c.mu.Unlock()
q.p.Reject(pr.err)
q.bootstrapPromise.Fulfill(q.p.Answer().Client())
q.p.ReleaseClients()
releaseRet()
c.mu.Lock()
case q.bootstrapPromise == nil && pr.err != nil:
// TODO(someday): send unimplemented message back to remote if
// pr.unimplemented == true.
q.release = func() {}
c.mu.Unlock()
q.p.Reject(pr.err)
releaseRet()
c.mu.Lock()
default:
m := ret.Message()
q.release = func() {
clearCapTable(m)
releaseRet()
}
c.mu.Unlock()
q.p.Fulfill(pr.result)
c.mu.Lock()
}
if err := c.tryLockSender(ctx); err != nil {
close(q.finishMsgSend)
c.mu.Unlock()
c.report(annotate(err).errorf("incoming return: send finish"))
return nil
}
c.mu.Unlock()
// Send disembargoes. Failing to send one of these just never lifts
// the embargo on our side, but doesn't cause a leak.
//
// TODO(soon): make embargo resolve to error client.
for i := range pr.disembargoes {
msg, send, release, err := c.transport.NewMessage(ctx)
if err != nil {
c.report(errorf("incoming return: send disembargo: create message: %v", err))
continue
}
if err := pr.disembargoes[i].buildDisembargo(msg); err != nil {
release()
c.report(annotate(err).errorf("incoming return"))
continue
}
err = send()
release()
if err != nil {
c.report(errorf("incoming return: send disembargo: %v", err))
continue
}
}
// Send finish.
{
msg, send, release, err := c.transport.NewMessage(ctx)
if err != nil {
c.mu.Lock()
c.unlockSender()
close(q.finishMsgSend)
c.mu.Unlock()
c.report(annotate(err).errorf("incoming return: send finish"))
return nil
}
fin, err := msg.NewFinish()
if err != nil {
release()
c.mu.Lock()
c.unlockSender()
close(q.finishMsgSend)
c.mu.Unlock()
c.report(errorf("incoming return: send finish: build message: %v", err))
return nil
}
fin.SetQuestionId(uint32(qid))
fin.SetReleaseResultCaps(false)
err = send()
release()
if err != nil {
c.mu.Lock()
c.unlockSender()
close(q.finishMsgSend)
c.mu.Unlock()
c.report(errorf("incoming return: send finish: build message: %v", err))
return nil
}
}
c.mu.Lock()
c.unlockSender()
q.flags |= finishSent
c.questionID.remove(uint32(qid))
close(q.finishMsgSend)
c.mu.Unlock()
return nil
}
func (c *Conn) parseReturn(ret rpccp.Return, called [][]capnp.PipelineOp) parsedReturn {
switch ret.Which() {
case rpccp.Return_Which_results:
r, err := ret.Results()
if err != nil {
return parsedReturn{err: errorf("parse return: %v", err), parseFailed: true}
}
content, locals, err := c.recvPayload(r)
if err != nil {
return parsedReturn{err: errorf("parse return: %v", err), parseFailed: true}
}
var embargoCaps uintSet
var disembargoes []senderLoopback
mtab := ret.Message().CapTable
for _, xform := range called {
p2, _ := capnp.Transform(content, xform)
iface := p2.Interface()
if !iface.IsValid() {
continue
}
i := iface.Capability()
if int64(i) >= int64(len(mtab)) || !locals.has(uint(i)) || embargoCaps.has(uint(i)) {
continue
}
var id embargoID
id, mtab[i] = c.embargo(mtab[i])