forked from heroiclabs/nakama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathruntime_javascript_match_core.go
802 lines (676 loc) · 24.6 KB
/
runtime_javascript_match_core.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
// Copyright 2020 The Nakama Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/dop251/goja"
"github.com/gofrs/uuid"
"github.com/heroiclabs/nakama-common/rtapi"
"github.com/heroiclabs/nakama/v3/social"
"go.uber.org/atomic"
"go.uber.org/zap"
"google.golang.org/protobuf/encoding/protojson"
)
var matchStoppedError = errors.New("match stopped")
type RuntimeJavaScriptMatchCore struct {
logger *zap.Logger
matchRegistry MatchRegistry
router MessageRouter
deferMessageFn RuntimeMatchDeferMessageFunction
presenceList *MatchPresenceList
id uuid.UUID
node string
module string
tickRate int
createTime int64
stopped *atomic.Bool
idStr string
stream PresenceStream
label *atomic.String
vm *goja.Runtime
initFn goja.Callable
joinAttemptFn goja.Callable
joinFn goja.Callable
leaveFn goja.Callable
loopFn goja.Callable
terminateFn goja.Callable
signalFn goja.Callable
ctx *goja.Object
dispatcher goja.Value
nakamaModule goja.Value
loggerModule goja.Value
program *goja.Program
// ctxCancelFn context.CancelFunc
}
func NewRuntimeJavascriptMatchCore(logger *zap.Logger, module string, db *sql.DB, protojsonMarshaler *protojson.MarshalOptions, protojsonUnmarshaler *protojson.UnmarshalOptions, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, rankCache LeaderboardRankCache, localCache *RuntimeJavascriptLocalCache, leaderboardScheduler LeaderboardScheduler, sessionRegistry SessionRegistry, sessionCache SessionCache, matchRegistry MatchRegistry, tracker Tracker, streamManager StreamManager, router MessageRouter, matchCreateFn RuntimeMatchCreateFunction, eventFn RuntimeEventCustomFunction, id uuid.UUID, node string, stopped *atomic.Bool, matchHandlers *jsMatchHandlers, modCache *RuntimeJSModuleCache) (RuntimeMatchCore, error) {
runtime := goja.New()
jsLoggerInst, err := NewJsLogger(runtime, logger)
if err != nil {
logger.Fatal("Failed to initialize JavaScript runtime", zap.Error(err))
}
nakamaModule := NewRuntimeJavascriptNakamaModule(logger, db, protojsonMarshaler, protojsonUnmarshaler, config, socialClient, leaderboardCache, rankCache, localCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, streamManager, router, eventFn, matchCreateFn)
nk := runtime.ToValue(nakamaModule.Constructor(runtime))
nkInst, err := runtime.New(nk)
if err != nil {
logger.Fatal("Failed to initialize JavaScript runtime", zap.Error(err))
}
runtime.RunProgram(modCache.Modules[modCache.Names[0]].Program)
ctx := NewRuntimeJsInitContext(runtime, node, config.GetRuntime().Environment)
ctx.Set(__RUNTIME_JAVASCRIPT_CTX_MODE, RuntimeExecutionModeMatch)
ctx.Set(__RUNTIME_JAVASCRIPT_CTX_MATCH_ID, fmt.Sprintf("%v.%v", id.String(), node))
ctx.Set(__RUNTIME_JAVASCRIPT_CTX_MATCH_NODE, node)
// TODO: goja runtime does not currently support passing a context to the vm
// goCtx, ctxCancelFn := context.WithCancel(context.Background())
// vm.SetContext(goCtx)
initFn, ok := goja.AssertFunction(runtime.Get(matchHandlers.initFn))
if !ok {
logger.Fatal("Failed to get JavaScript match loop function reference.", zap.String("fn", string(MatchInit)), zap.String("key", matchHandlers.initFn))
}
joinAttemptFn, ok := goja.AssertFunction(runtime.Get(matchHandlers.joinAttemptFn))
if !ok {
logger.Fatal("Failed to get JavaScript match loop function reference.", zap.String("fn", string(MatchJoinAttempt)), zap.String("key", matchHandlers.joinAttemptFn))
}
joinFn, ok := goja.AssertFunction(runtime.Get(matchHandlers.joinFn))
if !ok {
logger.Fatal("Failed to get JavaScript match loop function reference.", zap.String("fn", string(MatchJoin)), zap.String("key", matchHandlers.joinFn))
}
leaveFn, ok := goja.AssertFunction(runtime.Get(matchHandlers.leaveFn))
if !ok {
logger.Fatal("Failed to get JavaScript match loop function reference.", zap.String("fn", string(MatchLeave)), zap.String("key", matchHandlers.leaveFn))
}
loopFn, ok := goja.AssertFunction(runtime.Get(matchHandlers.loopFn))
if !ok {
logger.Fatal("Failed to get JavaScript match loop function reference.", zap.String("fn", string(MatchLoop)), zap.String("key", matchHandlers.loopFn))
}
terminateFn, ok := goja.AssertFunction(runtime.Get(matchHandlers.terminateFn))
if !ok {
logger.Fatal("Failed to get JavaScript match loop function reference.", zap.String("fn", string(MatchTerminate)), zap.String("key", matchHandlers.terminateFn))
}
signalFn, ok := goja.AssertFunction(runtime.Get(matchHandlers.signalFn))
if !ok {
logger.Fatal("Failed to get JavaScript match loop function reference.", zap.String("fn", string(MatchSignal)), zap.String("key", matchHandlers.signalFn))
}
core := &RuntimeJavaScriptMatchCore{
logger: logger,
matchRegistry: matchRegistry,
router: router,
// deferMessageFn set in MatchInit.
// presenceList set in MatchInit.
// tickRate set in MatchInit.
id: id,
node: node,
stopped: stopped,
idStr: fmt.Sprintf("%v.%v", id.String(), node),
module: module,
createTime: time.Now().UTC().UnixNano() / int64(time.Millisecond),
stream: PresenceStream{
Mode: StreamModeMatchAuthoritative,
Subject: id,
Label: node,
},
label: atomic.NewString(""),
vm: runtime,
initFn: initFn,
joinAttemptFn: joinAttemptFn,
joinFn: joinFn,
leaveFn: leaveFn,
loopFn: loopFn,
terminateFn: terminateFn,
signalFn: signalFn,
ctx: ctx,
loggerModule: jsLoggerInst,
nakamaModule: nkInst,
// ctxCancelFn: ctxCancelFn,
}
dispatcher := runtime.ToValue(
func(call goja.ConstructorCall) *goja.Object {
call.This.Set("broadcastMessage", core.broadcastMessage(runtime))
call.This.Set("broadcastMessageDeferred", core.broadcastMessageDeferred(runtime))
call.This.Set("matchKick", core.matchKick(runtime))
call.This.Set("matchLabelUpdate", core.matchLabelUpdate(runtime))
freeze(call.This)
return nil
},
)
dispatcherInst, err := runtime.New(dispatcher)
if err != nil {
logger.Fatal("Failed to initialize JavaScript runtime", zap.Error(err))
}
core.dispatcher = dispatcherInst
return core, nil
}
func (rm *RuntimeJavaScriptMatchCore) MatchInit(presenceList *MatchPresenceList, deferMessageFn RuntimeMatchDeferMessageFunction, params map[string]interface{}) (interface{}, int, error) {
args := []goja.Value{rm.ctx, rm.loggerModule, rm.nakamaModule, rm.vm.ToValue(params)}
retVal, err := rm.initFn(goja.Null(), args...)
if err != nil {
return nil, 0, err
}
retMap, ok := retVal.Export().(map[string]interface{})
if !ok {
return nil, 0, errors.New("matchInit is expected to return an object with 'state', 'tickRate' and 'label' properties")
}
tickRateRet, ok := retMap["tickRate"]
if !ok {
return nil, 0, errors.New("matchInit return value has no 'tickRate' property")
}
rate, ok := tickRateRet.(int64)
if !ok {
return nil, 0, errors.New("matchInit 'tickRate' must be a number between 1 and 60")
}
if rate < 1 || rate > 60 {
return nil, 0, errors.New("matchInit 'tickRate' must be a number between 1 and 60")
}
rm.tickRate = int(rate)
var label string
labelRet, ok := retMap["label"]
if ok {
label, ok = labelRet.(string)
if !ok {
return nil, 0, errors.New("matchInit 'label' value must be a string")
}
}
state, ok := retMap["state"]
if !ok {
return nil, 0, errors.New("matchInit is expected to return an object with a 'state' property")
}
if err := rm.matchRegistry.UpdateMatchLabel(rm.id, rm.tickRate, rm.module, label, rm.createTime); err != nil {
return nil, 0, err
}
rm.label.Store(label)
rm.ctx.Set(__RUNTIME_JAVASCRIPT_CTX_MATCH_LABEL, label)
rm.ctx.Set(__RUNTIME_JAVASCRIPT_CTX_MATCH_TICK_RATE, rate)
rm.deferMessageFn = deferMessageFn
rm.presenceList = presenceList
return state, int(rate), nil
}
func (rm *RuntimeJavaScriptMatchCore) MatchJoinAttempt(tick int64, state interface{}, userID, sessionID uuid.UUID, username string, sessionExpiry int64, vars map[string]string, clientIP, clientPort, node string, metadata map[string]string) (interface{}, bool, string, error) {
// Setup presence
presenceObj := rm.vm.NewObject()
presenceObj.Set("userId", userID.String())
presenceObj.Set("sessionId", sessionID.String())
presenceObj.Set("username", username)
presenceObj.Set("node", node)
// Setup ctx
ctxObj := rm.vm.NewObject()
for _, key := range rm.ctx.Keys() {
ctxObj.Set(key, rm.ctx.Get(key))
}
ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_USER_ID, userID.String())
ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_USERNAME, username)
if vars != nil {
ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_VARS, vars)
}
ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_USER_SESSION_EXP, sessionExpiry)
ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_SESSION_ID, sessionID.String())
if clientIP != "" {
ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_CLIENT_IP, clientIP)
}
if clientPort != "" {
ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_CLIENT_PORT, clientPort)
}
pointerizeSlices(state)
args := []goja.Value{ctxObj, rm.loggerModule, rm.nakamaModule, rm.dispatcher, rm.vm.ToValue(tick), rm.vm.ToValue(state), presenceObj, rm.vm.ToValue(metadata)}
retVal, err := rm.joinAttemptFn(goja.Null(), args...)
if err != nil {
return nil, false, "", err
}
if goja.IsNull(retVal) || goja.IsUndefined(retVal) {
return nil, false, "", nil
}
retMap, ok := retVal.Export().(map[string]interface{})
if !ok {
return nil, false, "", errors.New("matchJoinAttempt is expected to return an object with 'state' and 'accept' properties")
}
allowRet, ok := retMap["accept"]
if !ok {
return nil, false, "", errors.New("matchJoinAttempt return value has an 'accept' property")
}
allow, ok := allowRet.(bool)
if !ok {
return nil, false, "", errors.New("matchJoinAttempt 'accept' property must be a boolean")
}
var rejectMsg string
if allow == false {
rejectMsgRet, ok := retMap["rejectMessage"]
if ok {
rejectMsg, ok = rejectMsgRet.(string)
if !ok {
return nil, false, "", errors.New("matchJoinAttempt 'rejectMessage' property must be a string")
}
}
}
newState, ok := retMap["state"]
if !ok {
return nil, false, "", errors.New("matchJoinAttempt is expected to return an object with 'state' property")
}
return newState, allow, rejectMsg, nil
}
func (rm *RuntimeJavaScriptMatchCore) MatchJoin(tick int64, state interface{}, joins []*MatchPresence) (interface{}, error) {
presences := make([]interface{}, 0, len(joins))
for _, p := range joins {
presenceMap := make(map[string]interface{}, 5)
presenceMap["userId"] = p.UserID.String()
presenceMap["sessionId"] = p.SessionID.String()
presenceMap["username"] = p.Username
presenceMap["node"] = p.Node
presenceMap["reason"] = p.Reason
presences = append(presences, presenceMap)
}
pointerizeSlices(state)
args := []goja.Value{rm.ctx, rm.loggerModule, rm.nakamaModule, rm.dispatcher, rm.vm.ToValue(tick), rm.vm.ToValue(state), rm.vm.ToValue(presences)}
retVal, err := rm.joinFn(goja.Null(), args...)
if err != nil {
return nil, err
}
if goja.IsNull(retVal) || goja.IsUndefined(retVal) {
return nil, nil
}
retMap, ok := retVal.Export().(map[string]interface{})
if !ok {
return nil, errors.New("matchJoin is expected to return an object with 'state' property")
}
newState, ok := retMap["state"]
if !ok {
return nil, errors.New("matchJoin is expected to return an object with 'state' property")
}
return newState, nil
}
func (rm *RuntimeJavaScriptMatchCore) MatchLeave(tick int64, state interface{}, leaves []*MatchPresence) (interface{}, error) {
presences := make([]interface{}, 0, len(leaves))
for _, p := range leaves {
presenceMap := make(map[string]interface{}, 5)
presenceMap["userId"] = p.UserID.String()
presenceMap["sessionId"] = p.SessionID.String()
presenceMap["username"] = p.Username
presenceMap["node"] = p.Node
presenceMap["reason"] = p.Reason
presences = append(presences, presenceMap)
}
pointerizeSlices(state)
args := []goja.Value{rm.ctx, rm.loggerModule, rm.nakamaModule, rm.dispatcher, rm.vm.ToValue(tick), rm.vm.ToValue(state), rm.vm.ToValue(presences)}
retVal, err := rm.leaveFn(goja.Null(), args...)
if err != nil {
return nil, err
}
if goja.IsNull(retVal) || goja.IsUndefined(retVal) {
return nil, nil
}
retMap, ok := retVal.Export().(map[string]interface{})
if !ok {
return nil, errors.New("matchLeave is expected to return an object with 'state' property")
}
newState, ok := retMap["state"]
if !ok {
return nil, errors.New("matchLeave is expected to return an object with 'state' property")
}
return newState, nil
}
func (rm *RuntimeJavaScriptMatchCore) MatchLoop(tick int64, state interface{}, inputCh <-chan *MatchDataMessage) (interface{}, error) {
size := len(inputCh)
inputs := make([]interface{}, 0, size)
for i := 0; i < size; i++ {
msg := <-inputCh
presenceMap := make(map[string]interface{}, 5)
presenceMap["userId"] = msg.UserID.String()
presenceMap["sessionId"] = msg.SessionID.String()
presenceMap["username"] = msg.Username
presenceMap["node"] = msg.Node
msgMap := make(map[string]interface{}, 5)
msgMap["sender"] = presenceMap
msgMap["opCode"] = msg.OpCode
if msg.Data == nil {
msgMap["data"] = goja.Null()
} else {
msgMap["data"] = rm.vm.NewArrayBuffer(msg.Data)
}
msgMap["reliable"] = msg.Reliable
msgMap["receiveTimeMs"] = msg.ReceiveTime
inputs = append(inputs, msgMap)
}
pointerizeSlices(state)
args := []goja.Value{rm.ctx, rm.loggerModule, rm.nakamaModule, rm.dispatcher, rm.vm.ToValue(tick), rm.vm.ToValue(state), rm.vm.ToValue(inputs)}
retVal, err := rm.loopFn(goja.Null(), args...)
if err != nil {
return nil, err
}
if goja.IsNull(retVal) || goja.IsUndefined(retVal) {
return nil, nil
}
if goja.IsNull(retVal) || goja.IsUndefined(retVal) {
return nil, nil
}
retMap, ok := retVal.Export().(map[string]interface{})
if !ok {
return nil, errors.New("matchLoop is expected to return an object with 'state' property")
}
newState, ok := retMap["state"]
if !ok {
return nil, errors.New("matchLoop is expected to return an object with 'state' property")
}
return newState, nil
}
func (rm *RuntimeJavaScriptMatchCore) MatchTerminate(tick int64, state interface{}, graceSeconds int) (interface{}, error) {
pointerizeSlices(state)
args := []goja.Value{rm.ctx, rm.loggerModule, rm.nakamaModule, rm.dispatcher, rm.vm.ToValue(tick), rm.vm.ToValue(state), rm.vm.ToValue(graceSeconds)}
retVal, err := rm.terminateFn(goja.Null(), args...)
if err != nil {
return nil, err
}
retMap, ok := retVal.Export().(map[string]interface{})
if !ok {
return nil, errors.New("matchTerminate is expected to return an object with 'state' property")
}
if goja.IsNull(retVal) || goja.IsUndefined(retVal) {
return nil, nil
}
newState, ok := retMap["state"]
if !ok {
return nil, errors.New("matchTerminate is expected to return an object with 'state' property")
}
return newState, nil
}
func (rm *RuntimeJavaScriptMatchCore) MatchSignal(tick int64, state interface{}, data string) (interface{}, string, error) {
pointerizeSlices(state)
args := []goja.Value{rm.ctx, rm.loggerModule, rm.nakamaModule, rm.dispatcher, rm.vm.ToValue(tick), rm.vm.ToValue(state), rm.vm.ToValue(data)}
retVal, err := rm.signalFn(goja.Null(), args...)
if err != nil {
return nil, "", err
}
retMap, ok := retVal.Export().(map[string]interface{})
if !ok {
return nil, "", errors.New("matchSignal is expected to return an object with 'state' property")
}
if goja.IsNull(retVal) || goja.IsUndefined(retVal) {
return nil, "", nil
}
newState, ok := retMap["state"]
if !ok {
return nil, "", errors.New("matchSignal is expected to return an object with 'state' property")
}
responseDataRet, ok := retMap["data"]
var responseData string
if ok {
responseData, ok = responseDataRet.(string)
if !ok {
return nil, "", errors.New("matchSignal 'data' property must be a string")
}
}
return newState, responseData, nil
}
func (rm *RuntimeJavaScriptMatchCore) GetState(state interface{}) (string, error) {
stateBytes, err := json.Marshal(RuntimeJsConvertJsValue(state))
if err != nil {
return "", err
}
return string(stateBytes), nil
}
func (rm *RuntimeJavaScriptMatchCore) Label() string {
return rm.label.Load()
}
func (rm *RuntimeJavaScriptMatchCore) TickRate() int {
return rm.tickRate
}
func (rm *RuntimeJavaScriptMatchCore) HandlerName() string {
return rm.module
}
func (rm *RuntimeJavaScriptMatchCore) CreateTime() int64 {
return rm.createTime
}
func (rm *RuntimeJavaScriptMatchCore) Cancel() {
// TODO: implement cancel
}
func (rm *RuntimeJavaScriptMatchCore) Cleanup() {}
func (rm *RuntimeJavaScriptMatchCore) broadcastMessage(r *goja.Runtime) func(goja.FunctionCall) goja.Value {
return func(f goja.FunctionCall) goja.Value {
if rm.stopped.Load() {
panic(r.NewGoError(matchStoppedError))
}
presenceIDs, msg, reliable := rm.validateBroadcast(r, f)
if len(presenceIDs) != 0 {
rm.router.SendToPresenceIDs(rm.logger, presenceIDs, msg, reliable)
}
return goja.Undefined()
}
}
func (rm *RuntimeJavaScriptMatchCore) broadcastMessageDeferred(r *goja.Runtime) func(goja.FunctionCall) goja.Value {
return func(f goja.FunctionCall) goja.Value {
if rm.stopped.Load() {
panic(r.NewGoError(matchStoppedError))
}
presenceIDs, msg, reliable := rm.validateBroadcast(r, f)
if len(presenceIDs) != 0 {
if err := rm.deferMessageFn(&DeferredMessage{
PresenceIDs: presenceIDs,
Envelope: msg,
Reliable: reliable,
}); err != nil {
panic(r.NewGoError(fmt.Errorf("error deferring message broadcast: %v", err)))
}
}
return goja.Undefined()
}
}
func (rm *RuntimeJavaScriptMatchCore) validateBroadcast(r *goja.Runtime, f goja.FunctionCall) ([]*PresenceID, *rtapi.Envelope, bool) {
opCode := getJsInt(r, f.Argument(0))
var dataBytes []byte
data := f.Argument(1)
if !goja.IsUndefined(data) && !goja.IsNull(data) {
dataExport := data.Export()
switch dataExport.(type) {
case string:
dataBytes = []byte(dataExport.(string))
case goja.ArrayBuffer:
dataBytes = dataExport.(goja.ArrayBuffer).Bytes()
default:
panic(r.NewTypeError("expects data to be an Uint8Array, a string or nil"))
}
}
filter := f.Argument(2)
var presenceIDs []*PresenceID
if !goja.IsUndefined(filter) && !goja.IsNull(filter) {
filterSlice, ok := filter.Export().([]interface{})
if !ok {
panic(r.NewTypeError("expects an array of presences or nil"))
}
presenceIDs = make([]*PresenceID, 0, len(filterSlice))
for _, p := range filterSlice {
pMap, ok := p.(map[string]interface{})
if !ok {
panic(r.NewTypeError("expects a valid set of presences"))
}
presenceID := &PresenceID{}
sidVal, _ := pMap["sessionId"]
if sidVal == nil {
panic(r.NewTypeError("presence is expected to contain a 'sessionId'"))
}
sidStr, ok := sidVal.(string)
if !ok {
panic(r.NewTypeError("expects a 'sessionId' string"))
}
sid, err := uuid.FromString(sidStr)
if err != nil {
panic(r.NewTypeError("expects a valid 'sessionId'"))
}
nodeVal, _ := pMap["node"]
if nodeVal == nil {
panic(r.NewTypeError("expects presence to contain a 'node'"))
}
node, ok := nodeVal.(string)
if !ok {
panic(r.NewTypeError("expects a 'nodeId' string"))
}
presenceID.SessionID = sid
presenceID.Node = node
presenceIDs = append(presenceIDs, presenceID)
}
}
if presenceIDs != nil && len(presenceIDs) == 0 {
// Filter is empty, there are no requested message targets.
return nil, nil, false
}
sender := f.Argument(3)
var presence *rtapi.UserPresence
if !goja.IsUndefined(sender) && !goja.IsNull(sender) {
presence = &rtapi.UserPresence{}
senderMap, ok := sender.Export().(map[string]interface{})
if !ok {
panic(r.NewTypeError("expects sender to be an object"))
}
userIdVal, _ := senderMap["userId"]
if userIdVal == nil {
panic(r.NewTypeError("expects presence to contain 'userId'"))
}
userIDStr, ok := userIdVal.(string)
if !ok {
panic(r.NewTypeError("expects presence to contain 'userId' string"))
}
_, err := uuid.FromString(userIDStr)
if err != nil {
panic(r.NewTypeError("expects presence to contain valid userId"))
}
presence.UserId = userIDStr
sidVal, _ := senderMap["sessionId"]
if sidVal == nil {
panic(r.NewTypeError("presence is expected to contain a 'sessionId'"))
}
sidStr, ok := sidVal.(string)
if !ok {
panic(r.NewTypeError("expects a 'sessionId' string"))
}
_, err = uuid.FromString(sidStr)
if err != nil {
panic(r.NewTypeError("expects a valid 'sessionId'"))
}
presence.SessionId = sidStr
usernameVal, _ := senderMap["username"]
if usernameVal == nil {
panic(r.NewTypeError("presence is expected to contain a 'username'"))
}
username, ok := sidVal.(string)
if !ok {
panic(r.NewTypeError("expects a 'username' string"))
}
presence.Username = username
}
if presenceIDs != nil {
// Ensure specific presences actually exist to prevent sending bogus messages to arbitrary users.
if len(presenceIDs) == 1 && filter != nil {
if !rm.presenceList.Contains(presenceIDs[0]) {
return nil, nil, false
}
} else {
presenceIDs := rm.presenceList.FilterPresenceIDs(presenceIDs)
if len(presenceIDs) == 0 {
// None of the target presenceIDs existed in the list of match members.
return nil, nil, false
}
}
}
reliable := true
reliableVal := f.Argument(4)
if !goja.IsUndefined(reliableVal) && !goja.IsNull(reliableVal) {
reliable = getJsBool(r, reliableVal)
}
msg := &rtapi.Envelope{Message: &rtapi.Envelope_MatchData{MatchData: &rtapi.MatchData{
MatchId: rm.idStr,
Presence: presence,
OpCode: opCode,
Data: dataBytes,
Reliable: reliable,
}}}
if presenceIDs == nil {
presenceIDs = rm.presenceList.ListPresenceIDs()
}
return presenceIDs, msg, reliable
}
func (rm *RuntimeJavaScriptMatchCore) matchKick(r *goja.Runtime) func(goja.FunctionCall) goja.Value {
return func(f goja.FunctionCall) goja.Value {
if rm.stopped.Load() {
panic(r.NewGoError(matchStoppedError))
}
input := f.Argument(0)
if goja.IsUndefined(input) || goja.IsNull(input) {
return goja.Undefined()
}
presencesSlice, ok := input.Export().([]interface{})
if !ok {
panic(r.NewTypeError("expects an array of presence objects"))
}
presences := make([]*MatchPresence, 0, len(presencesSlice))
for _, p := range presencesSlice {
pMap, ok := p.(map[string]interface{})
if !ok {
panic(r.NewTypeError("expects a valid set of presences"))
}
presence := &MatchPresence{}
userIdVal, _ := pMap["userId"]
if userIdVal == nil {
panic(r.NewTypeError("expects presence to contain 'userId'"))
}
userIDStr, ok := userIdVal.(string)
if !ok {
panic(r.NewTypeError("expects presence to contain 'userId' string"))
}
uid, err := uuid.FromString(userIDStr)
if err != nil {
panic(r.NewTypeError("expects presence to contain valid userId"))
}
presence.UserID = uid
sidVal, _ := pMap["sessionId"]
if sidVal == nil {
panic(r.NewTypeError("presence is expected to contain a 'sessionId'"))
}
sidStr, ok := sidVal.(string)
if !ok {
panic(r.NewTypeError("expects a 'sessionId' string"))
}
sid, err := uuid.FromString(sidStr)
if err != nil {
panic(r.NewTypeError("expects a valid 'sessionId'"))
}
presence.SessionID = sid
nodeVal, _ := pMap["node"]
if nodeVal == nil {
panic(r.NewTypeError("expects presence to contain a 'node'"))
}
node, ok := nodeVal.(string)
if !ok {
panic(r.NewTypeError("expects a 'node' string"))
}
presence.Node = node
presences = append(presences, presence)
}
rm.matchRegistry.Kick(rm.stream, presences)
return goja.Undefined()
}
}
func (rm *RuntimeJavaScriptMatchCore) matchLabelUpdate(r *goja.Runtime) func(goja.FunctionCall) goja.Value {
return func(f goja.FunctionCall) goja.Value {
if rm.stopped.Load() {
panic(r.NewGoError(matchStoppedError))
}
input := getJsString(r, f.Argument(0))
if err := rm.matchRegistry.UpdateMatchLabel(rm.id, rm.tickRate, rm.module, input, rm.createTime); err != nil {
panic(r.NewGoError(fmt.Errorf("error updating match label: %v", err.Error())))
}
rm.label.Store(input)
// This must be executed from inside a match call so safe to update here.
rm.ctx.Set(__RUNTIME_JAVASCRIPT_CTX_MATCH_LABEL, input)
return goja.Undefined()
}
}