-
Notifications
You must be signed in to change notification settings - Fork 58
/
dealer.go
1538 lines (1406 loc) · 45.4 KB
/
dealer.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 router
import (
"context"
"errors"
"fmt"
"math/rand"
"strings"
"time"
"github.com/gammazero/nexus/v3/stdlog"
"github.com/gammazero/nexus/v3/wamp"
)
const (
// sendResultDeadline is the amount of time until the dealer gives up
// trying to send a RESULT to a blocked caller. This is different that the
// CALL timeout which spedifies how long the callee may take to answer.
sendResultDeadline = time.Minute
// yieldRetryDelay is the initial delay before reprocessing a blocked yield.
yieldRetryDelay = time.Millisecond
)
// Role information for this broker.
var dealerRole = wamp.Dict{
"features": wamp.Dict{
wamp.FeatureCallCanceling: true,
wamp.FeatureCallTimeout: true,
wamp.FeatureCallerIdent: true,
wamp.FeaturePatternBasedReg: true,
wamp.FeatureProgCallResults: true,
wamp.FeatureProgCallInvocations: true,
wamp.FeatureSessionMetaAPI: true,
wamp.FeatureSharedReg: true,
wamp.FeatureRegMetaAPI: true,
wamp.FeatureTestamentMetaAPI: true,
wamp.FeaturePayloadPassthruMode: true,
},
}
// remoteProcedure tracks in-progress remote procedure call
type registration struct {
id wamp.ID // registration ID
procedure wamp.URI // procedure this registration is for
created string // when registration was created
match string // how procedure uri is matched to registration
policy string // how callee is selected if shared registration
disclose bool // callee requests disclosure of caller identity
forwardTimeout bool // callee requests to handle the timeout logic
nextCallee int // choose callee for round-robin invocation.
// Multiple sessions can register as callees depending on invocation policy
// resulting in multiple procedures for the same registration ID.
callees []*wamp.Session
}
// invocation tracks in-progress invocation.
type invocation struct {
callID requestID
callee *wamp.Session
canceled bool
inProgress bool
timerCancel context.CancelFunc
options wamp.Dict
}
type requestID struct {
session wamp.ID
request wamp.ID
}
type dealer struct {
// procedure URI -> registration ID
procRegMap map[wamp.URI]*registration
pfxProcRegMap map[wamp.URI]*registration
wcProcRegMap map[wamp.URI]*registration
// registration ID -> registration
// Used to lookup registration by ID, needed for unregister.
registrations map[wamp.ID]*registration
// call ID -> caller session
calls map[requestID]*wamp.Session
// invocation ID -> {call ID, callee, canceled}
invocations map[wamp.ID]*invocation
// call ID -> invocation ID (for cancel)
invocationByCall map[requestID]wamp.ID
// callee session -> registration ID set.
// Used to lookup registrations when removing a callee session.
calleeRegIDSet map[*wamp.Session]map[wamp.ID]struct{}
actionChan chan func()
stopped chan struct{}
// Generate registration IDs.
idGen *wamp.IDGen
// Used for round-robin call invocation.
prng *rand.Rand
// Dealer behavior flags.
strictURI bool
allowDisclose bool
metaPeer wamp.Peer
log stdlog.StdLog
debug bool
}
// newDealer creates the default Dealer implementation.
//
// Messages are routed serially by the dealer's message handling goroutine.
// This serialization is limited to the work of determining the message's
// destination, and then the message is handed off to the next goroutine,
// typically the receiving client's send handler.
func newDealer(logger stdlog.StdLog, strictURI, allowDisclose, debug bool) *dealer {
d := &dealer{
procRegMap: map[wamp.URI]*registration{},
pfxProcRegMap: map[wamp.URI]*registration{},
wcProcRegMap: map[wamp.URI]*registration{},
registrations: map[wamp.ID]*registration{},
calls: map[requestID]*wamp.Session{},
invocations: map[wamp.ID]*invocation{},
invocationByCall: map[requestID]wamp.ID{},
calleeRegIDSet: map[*wamp.Session]map[wamp.ID]struct{}{},
// The action handler should be nearly always runable, since it is the
// critical section that does the only routing. So, and unbuffered
// channel is appropriate.
actionChan: make(chan func()),
stopped: make(chan struct{}),
idGen: new(wamp.IDGen),
prng: rand.New(rand.NewSource(time.Now().Unix())),
strictURI: strictURI,
allowDisclose: allowDisclose,
log: logger,
debug: debug,
}
go d.run()
return d
}
// setMetaPeer sets the client that the dealer uses to publish meta events.
func (d *dealer) setMetaPeer(metaPeer wamp.Peer) {
d.actionChan <- func() {
d.metaPeer = metaPeer
}
}
// role returns the role information for the "dealer" role. The data returned
// is suitable for use as broker role info in a WELCOME message.
func (d *dealer) role() wamp.Dict {
return dealerRole
}
// register registers a callee to handle calls to a procedure.
//
// If the shared_registration feature is supported, and if allowed by the
// invocation policy, multiple callees may register to handle the same
// procedure.
func (d *dealer) register(callee *wamp.Session, msg *wamp.Register) {
if callee == nil || msg == nil {
panic("dealer.Register with nil session or message")
}
// Validate procedure URI. For REGISTER, must be valid URI (either strict
// or loose), and all URI components must be non-empty other than for
// wildcard or prefix matched procedures.
match, _ := wamp.AsString(msg.Options[wamp.OptMatch])
if !msg.Procedure.ValidURI(d.strictURI, match) {
errMsg := fmt.Sprintf(
"register for invalid procedure URI %v (URI strict checking %v)",
msg.Procedure, d.strictURI)
d.trySend(callee, &wamp.Error{
Type: msg.MessageType(),
Request: msg.Request,
Error: wamp.ErrInvalidURI,
Arguments: wamp.List{errMsg},
Details: wamp.Dict{},
})
return
}
wampURI := strings.HasPrefix(string(msg.Procedure), "wamp.")
// Disallow registration of procedures starting with "wamp." by sessions
// other than the meta session.
if wampURI && callee.ID != metaID {
errMsg := fmt.Sprintf("register for restricted procedure URI %v",
msg.Procedure)
d.trySend(callee, &wamp.Error{
Type: msg.MessageType(),
Request: msg.Request,
Error: wamp.ErrInvalidURI,
Arguments: wamp.List{errMsg},
Details: wamp.Dict{},
})
return
}
// If callee requests disclosure of caller identity, but dealer does not
// allow, then send error as registration response.
disclose, _ := msg.Options[wamp.OptDiscloseCaller].(bool)
// allow disclose for trusted clients
if !d.allowDisclose && disclose {
callee.Lock()
authrole, _ := wamp.AsString(callee.Details["authrole"])
callee.Unlock()
if authrole != "trusted" {
d.trySend(callee, &wamp.Error{
Type: msg.MessageType(),
Request: msg.Request,
Details: wamp.Dict{},
Error: wamp.ErrOptionDisallowedDiscloseMe,
})
return
}
}
invoke, _ := wamp.AsString(msg.Options[wamp.OptInvoke])
forwardTimeout, _ := msg.Options[wamp.OptForwardTimeout].(bool)
var metaPubs []*wamp.Publish
done := make(chan struct{})
d.actionChan <- func() {
metaPubs = d.syncRegister(callee, msg, match, invoke, disclose, forwardTimeout, wampURI)
close(done)
}
<-done
for _, pub := range metaPubs {
d.metaPeer.Send() <- pub
}
}
// unregister removes a remote procedure previously registered by the callee.
func (d *dealer) unregister(callee *wamp.Session, msg *wamp.Unregister) {
if callee == nil || msg == nil {
panic("dealer.Unregister with nil session or message")
}
var metaPubs []*wamp.Publish
done := make(chan struct{})
d.actionChan <- func() {
metaPubs = d.syncUnregister(callee, msg)
close(done)
}
<-done
for _, pub := range metaPubs {
d.metaPeer.Send() <- pub
}
}
// call invokes a registered remote procedure.
func (d *dealer) call(caller *wamp.Session, msg *wamp.Call) {
if caller == nil || msg == nil {
panic("dealer.Call with nil session or message")
}
d.actionChan <- func() {
d.syncCall(caller, msg)
}
}
// cancel actively cancels a call that is in progress.
//
// Cancellation behaves differently depending on the mode:
//
// "skip": The pending call is canceled and ERROR is send immediately back to
// the caller. No INTERRUPT is sent to the callee and the result is discarded
// when received.
//
// "kill": INTERRUPT is sent to the client, but ERROR is not returned to the
// caller until after the callee has responded to the canceled call. In this
// case the caller may receive RESULT or ERROR depending whether the callee
// finishes processing the invocation or the interrupt first.
//
// "killnowait": The pending call is canceled and ERROR is send immediately
// back to the caller. INTERRUPT is sent to the callee and any response to the
// invocation or interrupt from the callee is discarded when received.
//
// If the callee does not support call canceling, then behavior is "skip".
func (d *dealer) cancel(caller *wamp.Session, msg *wamp.Cancel) {
if caller == nil || msg == nil {
panic("dealer.Cancel with nil session or message")
}
// Cancel mode should be one of: "skip", "kill", "killnowait"
mode, _ := wamp.AsString(msg.Options[wamp.OptMode])
switch mode {
case wamp.CancelModeKillNoWait, wamp.CancelModeKill, wamp.CancelModeSkip:
case "":
mode = wamp.CancelModeKillNoWait
default:
d.trySend(caller, &wamp.Error{
Type: msg.MessageType(),
Request: msg.Request,
Error: wamp.ErrInvalidArgument,
Arguments: wamp.List{fmt.Sprint("invalid cancel mode ", mode)},
Details: wamp.Dict{},
})
return
}
d.actionChan <- func() {
d.syncCancel(caller, msg, mode, wamp.ErrCanceled, nil)
}
}
// yield handles the result of successfully processing and finishing the
// execution of a call, send from callee to dealer.
//
// If the RESULT could not be sent to the caller because the caller was blocked
// (send queue full), then retry sending until timeout. If timeout while
// trying to send RESULT, then cancel call.
func (d *dealer) yield(callee *wamp.Session, msg *wamp.Yield) {
if callee == nil || msg == nil {
panic("dealer.Yield with nil session or message")
}
var again bool
progress, _ := msg.Options[wamp.OptProgress].(bool)
done := make(chan struct{})
d.actionChan <- func() {
again = d.syncYield(callee, msg, progress, true)
done <- struct{}{}
}
<-done
// If blocked, retry
if again {
retry := true
delay := yieldRetryDelay
start := time.Now()
// Retry processing YIELD until caller gone or deadline reached
for {
if d.debug {
d.log.Println("Retry sending RESULT after", delay)
}
<-time.After(delay)
// Do not retry if the elapsed time exceeds deadline
if time.Since(start) >= sendResultDeadline {
retry = false
}
d.actionChan <- func() {
again = d.syncYield(callee, msg, progress, retry)
done <- struct{}{}
}
<-done
if !again {
break
}
delay *= 2
}
}
}
// error handles an invocation error returned by the callee.
func (d *dealer) error(msg *wamp.Error) {
if msg == nil {
panic("dealer.Error with nil message")
}
d.actionChan <- func() {
d.syncError(msg)
}
}
// removeSessiom removes a callee's registrations. This is called when a
// client leaves the realm by sending a GOODBYE message or by disconnecting
// from the router. If there are any registrations for this session
// wamp.registration.on_unregister and wamp.registration.on_delete meta events
// are published for each.
func (d *dealer) removeSession(sess *wamp.Session) {
if sess == nil {
// No session specified, no session removed.
return
}
// Meta events must be returned by removeSession and must not be sent to
// metaPeer while running inside the dealer goroutine. Sending to metaPeer
// from inside the dealer goroutine can deadlock since metaPeer may alredy
// be waiting for the dealer goroutine to process a yield.
var metaPubs []*wamp.Publish
done := make(chan struct{})
d.actionChan <- func() {
metaPubs = d.syncRemoveSession(sess)
close(done)
}
<-done
for _, pub := range metaPubs {
d.metaPeer.Send() <- pub
}
}
// close stops the dealer, letting already queued actions finish.
func (d *dealer) close() {
close(d.actionChan)
<-d.stopped
if d.debug {
d.log.Print("Dealer stopped")
}
}
func (d *dealer) run() {
for action := range d.actionChan {
action()
}
close(d.stopped)
}
func (d *dealer) syncRegister(callee *wamp.Session, msg *wamp.Register, match, invokePolicy string, disclose, forwardTimeout, wampURI bool) []*wamp.Publish { //nolint:lll
var metaPubs []*wamp.Publish
var reg *registration
switch match {
default:
reg = d.procRegMap[msg.Procedure]
case wamp.MatchPrefix:
reg = d.pfxProcRegMap[msg.Procedure]
case wamp.MatchWildcard:
reg = d.wcProcRegMap[msg.Procedure]
}
var created string
var regID wamp.ID
// If no existing registration found for the procedure, then create a new
// registration.
if reg == nil {
regID = d.idGen.Next()
created = wamp.NowISO8601()
reg = ®istration{
id: regID,
procedure: msg.Procedure,
created: created,
match: match,
policy: invokePolicy,
disclose: disclose,
forwardTimeout: forwardTimeout,
callees: []*wamp.Session{callee},
}
d.registrations[regID] = reg
switch match {
default:
d.procRegMap[msg.Procedure] = reg
case wamp.MatchPrefix:
d.pfxProcRegMap[msg.Procedure] = reg
case wamp.MatchWildcard:
d.wcProcRegMap[msg.Procedure] = reg
}
if !wampURI && d.metaPeer != nil {
// wamp.registration.on_create is fired when a registration is
// created through a registration request for an URI which was
// previously without a registration.
details := wamp.Dict{
"id": regID,
"created": created,
"uri": msg.Procedure,
wamp.OptMatch: match,
wamp.OptInvoke: invokePolicy,
}
metaPubs = append(metaPubs, &wamp.Publish{
Request: wamp.GlobalID(),
Topic: wamp.MetaEventRegOnCreate,
Arguments: wamp.List{callee.ID, details},
})
}
} else {
// There is an existing registration(s) for this procedure. See if
// invocation policy allows another.
// Found an existing registration that has an invocation strategy that
// only allows a single callee on the given registration.
if reg.policy == "" || reg.policy == wamp.InvokeSingle {
d.log.Println("REGISTER for already registered procedure",
msg.Procedure, "from callee", callee)
d.trySend(callee, &wamp.Error{
Type: msg.MessageType(),
Request: msg.Request,
Details: wamp.Dict{},
Error: wamp.ErrProcedureAlreadyExists,
})
return metaPubs
}
// Found an existing registration that has an invocation strategy
// different from the one requested by the new callee
if reg.policy != invokePolicy {
d.log.Println("REGISTER for already registered procedure",
msg.Procedure, "with conflicting invocation policy (has",
reg.policy, "and requested", invokePolicy)
d.trySend(callee, &wamp.Error{
Type: msg.MessageType(),
Request: msg.Request,
Details: wamp.Dict{},
Error: wamp.ErrProcedureAlreadyExists,
})
return metaPubs
}
regID = reg.id
// Add callee for the registration.
reg.callees = append(reg.callees, callee)
}
// Add the registration ID to the callees set of registrations.
if _, ok := d.calleeRegIDSet[callee]; !ok {
d.calleeRegIDSet[callee] = map[wamp.ID]struct{}{}
}
d.calleeRegIDSet[callee][regID] = struct{}{}
if d.debug {
d.log.Printf("Registered procedure %v (regID=%v) to callee %v",
msg.Procedure, regID, callee)
}
d.trySend(callee, &wamp.Registered{
Request: msg.Request,
Registration: regID,
})
if !wampURI && d.metaPeer != nil {
// Publish wamp.registration.on_register meta event. Fired when a
// session is added to a registration. A wamp.registration.on_register
// event MUST be fired subsequent to a wamp.registration.on_create
// event, since the first registration results in both the creation of
// the registration and the addition of a session.
metaPubs = append(metaPubs, &wamp.Publish{
Request: wamp.GlobalID(),
Topic: wamp.MetaEventRegOnRegister,
Arguments: wamp.List{callee.ID, regID},
})
}
return metaPubs
}
func (d *dealer) syncUnregister(callee *wamp.Session, msg *wamp.Unregister) []*wamp.Publish {
var metaPubs []*wamp.Publish
// Delete the registration ID from the callee's set of registrations.
if _, ok := d.calleeRegIDSet[callee]; ok {
delete(d.calleeRegIDSet[callee], msg.Registration)
if len(d.calleeRegIDSet[callee]) == 0 {
delete(d.calleeRegIDSet, callee)
}
}
delReg, err := d.syncDelCalleeReg(callee, msg.Registration)
if err != nil {
d.log.Println("Cannot unregister:", err)
d.trySend(callee, &wamp.Error{
Type: msg.MessageType(),
Request: msg.Request,
Details: wamp.Dict{},
Error: wamp.ErrNoSuchRegistration,
})
return metaPubs
}
d.trySend(callee, &wamp.Unregistered{Request: msg.Request})
if d.metaPeer == nil {
return metaPubs
}
// Publish wamp.registration.on_unregister meta event. Fired when a
// session is removed from a subscription.
metaPubs = append(metaPubs, &wamp.Publish{
Request: wamp.GlobalID(),
Topic: wamp.MetaEventRegOnUnregister,
Arguments: wamp.List{callee.ID, msg.Registration},
})
if delReg {
// Publish wamp.registration.on_delete meta event. Fired when a
// registration is deleted after the last session attached to it has
// been removed. The wamp.registration.on_delete event MUST be
// preceded by a wamp.registration.on_unregister event.
metaPubs = append(metaPubs, &wamp.Publish{
Request: wamp.GlobalID(),
Topic: wamp.MetaEventRegOnDelete,
Arguments: wamp.List{callee.ID, msg.Registration},
})
}
return metaPubs
}
// syncMatchProcedure finds the best matching registration given a procedure
// URI.
//
// If there are both matching prefix and wildcard registrations, then find the
// one with the more specific match (longest matched pattern).
func (d *dealer) syncMatchProcedure(procedure wamp.URI) (*registration, bool) {
// Find registered procedures with exact match.
reg, ok := d.procRegMap[procedure]
if !ok {
// No exact match was found. So, search for a prefix or wildcard
// match, and prefer the most specific math (longest matched pattern).
// If there is a tie, then prefer the first longest prefix.
matchCount := -1 // initialize matchCount to -1 to catch an empty registration.
for pfxProc, pfxReg := range d.pfxProcRegMap {
if procedure.PrefixMatch(pfxProc) {
if len(pfxProc) > matchCount {
reg = pfxReg
matchCount = len(pfxProc)
ok = true
}
}
}
// According to the spec, we have to prefer prefix match over wildcard
// match:
// https://wamp-proto.org/static/rfc/draft-oberstet-hybi-crossbar-wamp.html#rfc.section.14.3.8.1.4.2
if ok {
return reg, ok
}
for wcProc, wcReg := range d.wcProcRegMap {
if procedure.WildcardMatch(wcProc) {
if len(wcProc) > matchCount {
reg = wcReg
matchCount = len(wcProc)
ok = true
}
}
}
}
return reg, ok
}
func (d *dealer) syncCall(caller *wamp.Session, msg *wamp.Call) {
reg, ok := d.syncMatchProcedure(msg.Procedure)
if !ok || len(reg.callees) == 0 {
// If no registered procedure, send error.
d.trySend(caller, &wamp.Error{
Type: msg.MessageType(),
Request: msg.Request,
Details: wamp.Dict{},
Error: wamp.ErrNoSuchProcedure,
})
return
}
var callee *wamp.Session
var invocationID wamp.ID
var invk *invocation
var timeout int64
callReqID := requestID{
session: caller.ID,
request: msg.Request,
}
storedInvocationID, ok := d.invocationByCall[callReqID]
isInProgress, _ := msg.Options[wamp.OptProgress].(bool)
details := wamp.Dict{}
details[wamp.OptProgress] = isInProgress
if isInProgress && !caller.HasFeature(wamp.RoleCaller, wamp.FeatureProgCallInvocations) {
// The Caller did not announce the progressive call invocations feature during the HELLO handshake.
abortMsg := wamp.Abort{Reason: wamp.ErrProtocolViolation}
abortMsg.Details = wamp.Dict{}
abortMsg.Details[wamp.OptMessage] = "Peer is trying to use Progressive Call Invocations while it was not " +
"announced during HELLO handshake"
d.trySend(caller, &abortMsg)
caller.Close()
return
}
// If it is a simple one-time call or first call of progressive call
// then we need to init call-invocation-runtime
// otherwise we must reuse runtime-data. E.g. not to generate new ID
if !ok {
// If there are multiple callees, then select a callee based invocation
// policy.
if len(reg.callees) > 1 {
switch reg.policy {
case wamp.InvokeFirst:
callee = reg.callees[0]
case wamp.InvokeRoundRobin:
if reg.nextCallee >= len(reg.callees) {
reg.nextCallee = 0
}
callee = reg.callees[reg.nextCallee]
reg.nextCallee++
case wamp.InvokeRandom:
callee = reg.callees[d.prng.Int63n(int64(len(reg.callees)))]
case wamp.InvokeLast:
callee = reg.callees[len(reg.callees)-1]
default:
errMsg := fmt.Sprintf("multiple callees registered for %s with '%s' policy", msg.Procedure, wamp.InvokeSingle)
// This is disallowed by the dealer, and is a programming error if
// it ever happened, so panic.
panic(errMsg)
}
} else {
callee = reg.callees[0]
}
reqID := requestID{
session: caller.ID,
request: msg.Request,
}
d.calls[reqID] = caller
invocationID = d.idGen.Next()
invk = &invocation{
callID: reqID,
callee: callee,
inProgress: isInProgress,
options: msg.Options,
}
d.invocations[invocationID] = invk
d.invocationByCall[reqID] = invocationID
// Let's check if callee supports this feature
// A Callee that supports progressive call invocations, but does not support call canceling,
// shall be considered by the Dealer as not supporting progressive call invocations.
if isInProgress &&
(!callee.HasFeature(wamp.RoleCallee, wamp.FeatureProgCallInvocations) ||
!callee.HasFeature(wamp.RoleCallee, wamp.FeatureCallCanceling)) {
d.trySend(caller, &wamp.Error{
Type: msg.MessageType(),
Request: msg.Request,
Details: wamp.Dict{},
Error: wamp.ErrFeatureNotSupported,
})
return
}
// TODO: handle trust levels
// Check and handle Payload PassThru Mode
// @see https://wamp-proto.org/wamp_latest_ietf.html#name-payload-passthru-mode
if pptScheme, _ := invk.options[wamp.OptPPTScheme].(string); pptScheme != "" {
// Let's check: was ppt feature announced by caller?
if !caller.HasFeature(wamp.RoleCaller, wamp.FeaturePayloadPassthruMode) {
// It's protocol violation, so we need to abort connection
abortMsg := wamp.Abort{Reason: wamp.ErrProtocolViolation}
abortMsg.Details = wamp.Dict{}
abortMsg.Details[wamp.OptMessage] = "Peer is trying to use Payload PassThru Mode while it was not " +
"announced during HELLO handshake"
d.trySend(caller, &abortMsg)
caller.Close()
return
}
// Let's check if callee supports this feature
if !callee.HasFeature(wamp.RoleCallee, wamp.FeaturePayloadPassthruMode) {
d.trySend(caller, &wamp.Error{
Type: msg.MessageType(),
Request: msg.Request,
Details: wamp.Dict{},
Error: wamp.ErrFeatureNotSupported,
})
return
}
// Every side supports PPT feature
// Let's fill PPT options for callee
pptOptionsToDetails(invk.options, details)
}
// If the callee has requested disclosure of caller identity when the
// registration was created, and this was allowed by the dealer.
if reg.disclose {
if callee.ID == metaID {
details[wamp.RoleCaller] = caller.ID
}
discloseCaller(caller, details)
} else {
// A Caller MAY request the disclosure of its identity (its WAMP
// session ID) to endpoints of a routed call. This is indicated by the
// "disclose_me" flag in the message options.
if opt, _ := invk.options[wamp.OptDiscloseMe].(bool); opt {
// Dealer MAY deny a Caller's request to disclose its identity.
if !d.allowDisclose {
// Do not continue a call when discloseMe was disallowed.
d.trySend(caller, &wamp.Error{
Type: msg.MessageType(),
Request: msg.Request,
Details: wamp.Dict{},
Error: wamp.ErrOptionDisallowedDiscloseMe,
})
return
}
if callee.HasFeature(wamp.RoleCallee, wamp.FeatureCallerIdent) {
discloseCaller(caller, details)
}
}
}
// A Caller indicates its willingness to receive progressive results by
// setting CALL.Options.receive_progress|bool := true
if opt, _ := invk.options[wamp.OptReceiveProgress].(bool); opt {
// If the Callee supports progressive calls, the Dealer will forward
// the Caller's willingness to receive progressive results by setting.
//
// The Callee must support call canceling, as this is necessary to stop
// progressive results if the caller session is closed during
// progressive result delivery.
if callee.HasFeature(wamp.RoleCallee, wamp.FeatureProgCallResults) &&
callee.HasFeature(wamp.RoleCallee, wamp.FeatureCallCanceling) {
details[wamp.OptReceiveProgress] = true
}
}
if reg.match != wamp.MatchExact {
// According to the spec, a router must provide the actual procedure to
// the client.
details[wamp.OptProcedure] = msg.Procedure
}
} else {
// It is an ongoing progressive call (not first one)
invk = d.invocations[storedInvocationID]
invk.inProgress = isInProgress
callee = invk.callee
invocationID = storedInvocationID
}
// A Caller might want to issue a call providing a timeout for the call to
// finish.
//
// A timeout allows to automatically cancel a call after a specified time
// either at the Callee or at the Dealer.
//
// Callees wanting to handle the timeout logic MAY specify this intention via
// the REGISTER.Options.forward_timeout|boolean option. The Dealer, upon receiving
// a CALL with the timeout option set, checks if the matching RPC registration had
// the forward_timeout option set, then accordingly either forwards the timeout value
// or handles the timeout logic locally without forwarding the timeout value.
callerTimeout, _ := wamp.AsInt64(invk.options[wamp.OptTimeout])
if callerTimeout > 0 {
// Check that callee supports call_timeout and requested forward_timeout -
// if YES then propagate timeout value and handling to the callee side
if callee.HasFeature(wamp.RoleCallee, wamp.FeatureCallTimeout) && reg.forwardTimeout {
if !ok { // Propagate the option only during first progressive call
details[wamp.OptTimeout] = callerTimeout
}
} else {
// Callee doesn't support timeouts so let's handle it on the dealer's side
timeout = callerTimeout
}
}
// Send INVOCATION to the endpoint that has registered the requested
// procedure.
invMsg := &wamp.Invocation{
Request: invocationID,
Registration: reg.id,
Details: details,
Arguments: msg.Arguments,
ArgumentsKw: msg.ArgumentsKw,
}
select {
case callee.Send() <- invMsg:
default:
d.syncError(&wamp.Error{
Type: wamp.INVOCATION,
Request: invocationID,
Details: wamp.Dict{},
Error: wamp.ErrNetworkFailure,
Arguments: wamp.List{"callee blocked - cannot call procedure"},
})
return
}
// If the Callee does not support Call Timeouts, a Dealer supporting this feature MUST
// start a timeout timer upon receiving a CALL message with a timeout option. The message
// flow for call timeouts is identical to Call Canceling, except that there is no
// CANCEL message that originates from the Caller. The cancellation mode is implicitly
// killnowait if the Callee supports call cancellation, otherwise the cancellation mode is skip.
//
// The error message that is returned to the Caller MUST use wamp.error.timeout as the reason URI.
if timeout > 0 {
// Timer removed if context canceled, call cancelled if timeout.
var timerCtx context.Context
timerCtx, invk.timerCancel = context.WithTimeout(context.Background(),
time.Duration(timeout)*time.Millisecond)
// Start goroutine to cancel pending call on timeout. Works like
// Cancel with mode=killnowait, and includes an error message argument
// "call timeout"
go func() {
<-timerCtx.Done()
if errors.Is(timerCtx.Err(), context.Canceled) {
// Timer canceled. Got response from callee, or caller
// canceled or ended session.
return
}
d.actionChan <- func() {
errArgs := wamp.List{"call timeout"}
d.syncCancel(caller, &wamp.Cancel{Request: msg.Request},
wamp.CancelModeKillNoWait, wamp.ErrTimeout, errArgs)
}
}()
}
}
func (d *dealer) syncCancel(caller *wamp.Session, msg *wamp.Cancel, mode string, reason wamp.URI, errArgs wamp.List) {
reqID := requestID{
session: caller.ID,
request: msg.Request,
}
procCaller, ok := d.calls[reqID]
if !ok {
// There is no pending call to cancel.
return
}
// Check if the caller of cancel is also the caller of the procedure.
if caller != procCaller {
// The caller is trying to cancel calls that it does not own. It it
// either confused or trying to do something bad.
d.log.Println("CANCEL received from caller", caller,
"for call owned by different session")
return
}
// Find the pending invocation.
invocationID, ok := d.invocationByCall[reqID]
if !ok {
// If there is no pending invocation, ignore cancel.
d.log.Print("Found call with no pending invocation")
return
}
invk, ok := d.invocations[invocationID]
if !ok {
d.log.Print("CRITICAL: missing caller for pending invocation")
return
}
// For those who repeatedly press elevator buttons.
if invk.canceled {
return
}
invk.canceled = true
// Stop any call timeout timer.
if invk.timerCancel != nil {
invk.timerCancel()
}
// If mode is "kill" or "killnowait", then send INTERRUPT.
if mode != wamp.CancelModeSkip {
// Check that callee supports call canceling to see if it is alright to
// send INTERRUPT to callee.
if !invk.callee.HasFeature(wamp.RoleCallee, wamp.FeatureCallCanceling) {
// Cancel in dealer without sending INTERRUPT to callee.
d.log.Println("Callee", invk.callee, "does not support call canceling")
} else {
// Send INTERRUPT message to callee.
intrMsg := &wamp.Interrupt{
Request: invocationID,
Options: wamp.Dict{wamp.OptReason: reason, wamp.OptMode: mode},
}
select {
case invk.callee.Send() <- intrMsg:
d.log.Println("Dealer sent INTERRUPT to cancel invocation",
invocationID, "for call", msg.Request, "mode:", mode)
// If mode is "kill" then let error from callee trigger the
// response to the caller. This is how the caller waits for
// the callee to cancel the call.
if mode == wamp.CancelModeKill {
return
}
default:
}
}
}
// Treat any unrecognized mode the same as "skip".
// Immediately delete the pending call and send ERROR back to the
// caller. This will cause any RESULT or ERROR arriving later from the
// callee to be dropped.
//
// This also stops repeated CANCEL messages.
delete(d.calls, reqID)
delete(d.invocationByCall, reqID)
delete(d.invocations, invocationID)
errMsg := &wamp.Error{
Type: wamp.CALL,
Request: msg.Request,
Error: reason,
Details: wamp.Dict{},
}
if len(errArgs) != 0 {
errMsg.Arguments = errArgs
}
// Send error to the caller.
d.trySend(caller, errMsg)
}
func (d *dealer) syncYield(callee *wamp.Session, msg *wamp.Yield, progress, canRetry bool) bool {
// Find and delete pending invocation.
invk, ok := d.invocations[msg.Request]