forked from heroiclabs/nakama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipeline_match.go
376 lines (343 loc) · 11.9 KB
/
pipeline_match.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
// Copyright 2018 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 (
"fmt"
"strings"
"crypto"
"github.com/dgrijalva/jwt-go"
"github.com/golang/protobuf/ptypes/wrappers"
"github.com/heroiclabs/nakama/rtapi"
"github.com/satori/go.uuid"
"go.uber.org/zap"
)
type matchDataFilter struct {
userID uuid.UUID
sessionID uuid.UUID
}
func (p *Pipeline) matchCreate(logger *zap.Logger, session Session, envelope *rtapi.Envelope) {
matchID := uuid.Must(uuid.NewV4())
username := session.Username()
if success, _ := p.tracker.Track(session.ID(), PresenceStream{Mode: StreamModeMatchRelayed, Subject: matchID}, session.UserID(), PresenceMeta{
Username: username,
Format: session.Format(),
}, false); !success {
// Presence creation was rejected due to `allowIfFirstForSession` flag, session is gone so no need to reply.
return
}
self := &rtapi.UserPresence{
UserId: session.UserID().String(),
SessionId: session.ID().String(),
Username: username,
}
session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Match{Match: &rtapi.Match{
MatchId: fmt.Sprintf("%v.", matchID.String()),
Authoritative: false,
// No label.
Size: 1,
Presences: []*rtapi.UserPresence{self},
Self: self,
}}})
}
func (p *Pipeline) matchJoin(logger *zap.Logger, session Session, envelope *rtapi.Envelope) {
incoming := envelope.GetMatchJoin()
var err error
var matchID uuid.UUID
var node string
var matchIDString string
allowEmpty := false
switch incoming.Id.(type) {
case *rtapi.MatchJoin_MatchId:
matchIDString = incoming.GetMatchId()
// Validate the match ID.
matchIDComponents := strings.SplitN(matchIDString, ".", 2)
if len(matchIDComponents) != 2 {
session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{
Code: int32(rtapi.Error_BAD_INPUT),
Message: "Invalid match ID",
}}})
return
}
matchID, err = uuid.FromString(matchIDComponents[0])
if err != nil {
session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{
Code: int32(rtapi.Error_BAD_INPUT),
Message: "Invalid match ID",
}}})
return
}
node = matchIDComponents[1]
case *rtapi.MatchJoin_Token:
token, err := jwt.Parse(incoming.GetToken(), func(token *jwt.Token) (interface{}, error) {
if s, ok := token.Method.(*jwt.SigningMethodHMAC); !ok || s.Hash != crypto.SHA256 {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return []byte(p.config.GetSession().EncryptionKey), nil
})
if err != nil {
session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{
Code: int32(rtapi.Error_BAD_INPUT),
Message: "Invalid match token",
}}})
return
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok || !token.Valid {
session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{
Code: int32(rtapi.Error_BAD_INPUT),
Message: "Invalid match token",
}}})
return
}
matchIDString = claims["mid"].(string)
// Validate the match ID.
matchIDComponents := strings.SplitN(matchIDString, ".", 2)
if len(matchIDComponents) != 2 {
session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{
Code: int32(rtapi.Error_BAD_INPUT),
Message: "Invalid match token",
}}})
return
}
matchID, err = uuid.FromString(matchIDComponents[0])
if err != nil {
session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{
Code: int32(rtapi.Error_BAD_INPUT),
Message: "Invalid match token",
}}})
return
}
node = matchIDComponents[1]
allowEmpty = true
case nil:
session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{
Code: int32(rtapi.Error_BAD_INPUT),
Message: "No match ID or token found",
}}})
return
default:
session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{
Code: int32(rtapi.Error_BAD_INPUT),
Message: "Unrecognized match ID or token",
}}})
return
}
// Decide if it's an authoritative or relayed match.
mode := StreamModeMatchRelayed
if node != "" {
mode = StreamModeMatchAuthoritative
}
stream := PresenceStream{Mode: mode, Subject: matchID, Label: node}
// Relayed matches must 'exist' by already having some members, unless they're being joined via a token.
if mode == StreamModeMatchRelayed && !allowEmpty && !p.tracker.StreamExists(stream) {
session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{
Code: int32(rtapi.Error_MATCH_NOT_FOUND),
Message: "Match not found",
}}})
return
}
var label *wrappers.StringValue
meta := p.tracker.GetLocalBySessionIDStreamUserID(session.ID(), stream, session.UserID())
if meta == nil {
username := session.Username()
found := true
allow := true
var reason string
var l string
// The user is not yet part of the match, attempt to join.
if mode == StreamModeMatchAuthoritative {
// If it's an authoritative match, ask the match handler if it will allow the join.
found, allow, reason, l = p.matchRegistry.Join(matchID, node, session.UserID(), session.ID(), username, p.node)
}
if !found {
// Match did not exist.
session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{
Code: int32(rtapi.Error_MATCH_NOT_FOUND),
Message: "Match not found",
}}})
return
}
if !allow {
// Use the reject reason set by the match handler, if available.
if reason == "" {
reason = "Match join rejected"
}
// Match exists, but rejected the join.
session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{
Code: int32(rtapi.Error_MATCH_JOIN_REJECTED),
Message: reason,
}}})
return
}
if mode == StreamModeMatchAuthoritative {
// If we've reached here, it was an accepted authoritative join.
label = &wrappers.StringValue{Value: l}
}
m := PresenceMeta{
Username: username,
Format: session.Format(),
}
if success, _ := p.tracker.Track(session.ID(), stream, session.UserID(), m, false); !success {
// Presence creation was rejected due to `allowIfFirstForSession` flag, session is gone so no need to reply.
return
}
meta = &m
}
// Whether the user has just (successfully) joined the match or was already a member, return the match info anyway.
ps := p.tracker.ListByStream(stream, true)
presences := make([]*rtapi.UserPresence, 0, len(ps))
for _, p := range ps {
presences = append(presences, &rtapi.UserPresence{
UserId: p.UserID.String(),
SessionId: p.ID.SessionID.String(),
Username: p.Meta.Username,
})
}
self := &rtapi.UserPresence{
UserId: session.UserID().String(),
SessionId: session.ID().String(),
Username: meta.Username,
}
session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Match{Match: &rtapi.Match{
MatchId: matchIDString,
Authoritative: mode == StreamModeMatchAuthoritative,
Label: label,
Size: int32(len(presences)),
Presences: presences,
Self: self,
}}})
}
func (p *Pipeline) matchLeave(logger *zap.Logger, session Session, envelope *rtapi.Envelope) {
// Validate the match ID.
matchIDComponents := strings.SplitN(envelope.GetMatchLeave().MatchId, ".", 2)
if len(matchIDComponents) != 2 {
session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{
Code: int32(rtapi.Error_BAD_INPUT),
Message: "Invalid match ID",
}}})
return
}
matchID, err := uuid.FromString(matchIDComponents[0])
if err != nil {
session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{
Code: int32(rtapi.Error_BAD_INPUT),
Message: "Invalid match ID",
}}})
return
}
// Decide if it's an authoritative or relayed match.
mode := StreamModeMatchRelayed
if matchIDComponents[1] != "" {
mode = StreamModeMatchAuthoritative
}
// Check and drop the presence if possible, will always succeed.
stream := PresenceStream{Mode: mode, Subject: matchID, Label: matchIDComponents[1]}
p.tracker.Untrack(session.ID(), stream, session.UserID())
session.Send(&rtapi.Envelope{Cid: envelope.Cid})
}
func (p *Pipeline) matchDataSend(logger *zap.Logger, session Session, envelope *rtapi.Envelope) {
incoming := envelope.GetMatchDataSend()
// Validate the match ID.
matchIDComponents := strings.SplitN(incoming.MatchId, ".", 2)
if len(matchIDComponents) != 2 {
return
}
matchID, err := uuid.FromString(matchIDComponents[0])
if err != nil {
return
}
// If it's an authoritative match pass the data to the match handler.
if matchIDComponents[1] != "" {
if p.tracker.GetLocalBySessionIDStreamUserID(session.ID(), PresenceStream{Mode: StreamModeMatchAuthoritative, Subject: matchID, Label: matchIDComponents[1]}, session.UserID()) == nil {
// User is not part of the match.
return
}
p.matchRegistry.SendData(matchID, matchIDComponents[1], session.UserID(), session.ID(), session.Username(), p.node, incoming.OpCode, incoming.Data)
return
}
// Parse any filters.
var filters []*matchDataFilter
if len(incoming.Presences) != 0 {
filters = make([]*matchDataFilter, len(incoming.Presences))
for i := 0; i < len(incoming.Presences); i++ {
userID, err := uuid.FromString(incoming.Presences[i].UserId)
if err != nil {
return
}
sessionID, err := uuid.FromString(incoming.Presences[i].SessionId)
if err != nil {
return
}
filters[i] = &matchDataFilter{userID: userID, sessionID: sessionID}
}
}
// If it was a relayed match, proceed with filter and data routing logic.
stream := PresenceStream{Mode: StreamModeMatchRelayed, Subject: matchID}
presenceIDs := p.tracker.ListPresenceIDByStream(stream)
if len(presenceIDs) == 0 {
return
}
senderFound := false
for i := 0; i < len(presenceIDs); i++ {
presenceID := presenceIDs[i]
if presenceID.SessionID == session.ID() {
// Don't echo back to sender.
presenceIDs[i] = presenceIDs[len(presenceIDs)-1]
presenceIDs = presenceIDs[:len(presenceIDs)-1]
senderFound = true
if filters == nil {
break
} else {
i--
}
} else if filters != nil {
// Check if this presence is specified in the filters.
filterFound := false
for j := 0; j < len(filters); j++ {
if filter := filters[j]; presenceID.SessionID == filter.sessionID {
// If a filter matches, drop it.
filters[j] = filters[len(filters)-1]
filters = filters[:len(filters)-1]
filterFound = true
break
}
}
if !filterFound {
// If this presence wasn't in the filters, it's not needed.
presenceIDs[i] = presenceIDs[len(presenceIDs)-1]
presenceIDs = presenceIDs[:len(presenceIDs)-1]
i--
}
}
}
// If sender wasn't in the presences for this match, they're not a member.
if !senderFound {
return
}
// Check if there are any recipients left.
if len(presenceIDs) == 0 {
return
}
outgoing := &rtapi.Envelope{Message: &rtapi.Envelope_MatchData{MatchData: &rtapi.MatchData{
MatchId: incoming.MatchId,
Presence: &rtapi.UserPresence{
UserId: session.UserID().String(),
SessionId: session.ID().String(),
Username: session.Username(),
},
OpCode: incoming.OpCode,
Data: incoming.Data,
}}}
p.router.SendToPresenceIDs(logger, presenceIDs, outgoing)
}