forked from woshihaomei/pitaya
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
683 lines (587 loc) · 16.1 KB
/
session.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
// Copyright (c) nano Author and TFG Co. All Rights Reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package session
import (
"context"
"encoding/json"
"net"
"reflect"
"sync"
"sync/atomic"
"time"
"github.com/golang/protobuf/proto"
nats "github.com/nats-io/nats.go"
"github.com/hnlxhzw/pitaya/constants"
"github.com/hnlxhzw/pitaya/logger"
"github.com/hnlxhzw/pitaya/protos"
)
// NetworkEntity represent low-level network instance
type NetworkEntity interface {
Push(route string, v interface{}) error
ResponseMID(ctx context.Context, mid uint, v interface{}, isError ...bool) error
Close() error
Kick(ctx context.Context) error
RemoteAddr() net.Addr
SendRequest(ctx context.Context, serverID, route string, v interface{}) (*protos.Response, error)
}
var (
sessionBindCallbacks = make([]func(ctx context.Context, s *Session) error, 0)
afterBindCallbacks = make([]func(ctx context.Context, s *Session) error, 0)
// SessionCloseCallbacks contains global session close callbacks
SessionCloseCallbacks = make([]func(s *Session), 0)
sessionsByUID sync.Map
sessionsByID sync.Map
sessionIDSvc = newSessionIDService()
// SessionCount keeps the current number of sessions
SessionCount int64
)
// HandshakeClientData represents information about the client sent on the handshake.
type HandshakeClientData struct {
Platform string `json:"platform"`
LibVersion string `json:"libVersion"`
BuildNumber string `json:"clientBuildNumber"`
Version string `json:"clientVersion"`
}
// HandshakeData represents information about the handshake sent by the client.
// `sys` corresponds to information independent from the app and `user` information
// that depends on the app and is customized by the user.
type HandshakeData struct {
Sys HandshakeClientData `json:"sys"`
User map[string]interface{} `json:"user,omitempty"`
}
// Session represents a client session, which can store data during the connection.
// All data is released when the low-level connection is broken.
// Session instance related to the client will be passed to Handler method in the
// context parameter.
type Session struct {
sync.RWMutex // protect data
id int64 // session global unique id
uid string // binding user id
lastTime int64 // last heartbeat time
entity NetworkEntity // low-level network entity
data map[string]interface{} // session data store
handshakeData *HandshakeData // handshake data received by the client
encodedData []byte // session data encoded as a byte array
OnCloseCallbacks []func() //onClose callbacks
IsFrontend bool // if session is a frontend session
frontendID string // the id of the frontend that owns the session
frontendSessionID int64 // the id of the session on the frontend server
Subscriptions []*nats.Subscription // subscription created on bind when using nats rpc server
}
type sessionIDService struct {
sid int64
}
func newSessionIDService() *sessionIDService {
return &sessionIDService{
sid: 0,
}
}
// SessionID returns the session id
func (c *sessionIDService) sessionID() int64 {
return atomic.AddInt64(&c.sid, 1)
}
// New returns a new session instance
// a NetworkEntity is a low-level network instance
func New(entity NetworkEntity, frontend bool, UID ...string) *Session {
s := &Session{
id: sessionIDSvc.sessionID(),
entity: entity,
data: make(map[string]interface{}),
handshakeData: nil,
lastTime: time.Now().Unix(),
OnCloseCallbacks: []func(){},
IsFrontend: frontend,
}
if frontend {
sessionsByID.Store(s.id, s)
atomic.AddInt64(&SessionCount, 1)
}
if len(UID) > 0 {
s.uid = UID[0]
}
return s
}
// GetSessionByUID return a session bound to an user id
func GetSessionByUID(uid string) *Session {
// TODO: Block this operation in backend servers
if val, ok := sessionsByUID.Load(uid); ok {
return val.(*Session)
}
return nil
}
// GetSessionByID return a session bound to a frontend server id
func GetSessionByID(id int64) *Session {
// TODO: Block this operation in backend servers
if val, ok := sessionsByID.Load(id); ok {
return val.(*Session)
}
return nil
}
// OnSessionBind adds a method to be called when a session is bound
// same function cannot be added twice!
func OnSessionBind(f func(ctx context.Context, s *Session) error) {
// Prevents the same function to be added twice in onSessionBind
sf1 := reflect.ValueOf(f)
for _, fun := range sessionBindCallbacks {
sf2 := reflect.ValueOf(fun)
if sf1.Pointer() == sf2.Pointer() {
return
}
}
sessionBindCallbacks = append(sessionBindCallbacks, f)
}
// OnAfterSessionBind adds a method to be called when session is bound and after all sessionBind callbacks
func OnAfterSessionBind(f func(ctx context.Context, s *Session) error) {
// Prevents the same function to be added twice in onSessionBind
sf1 := reflect.ValueOf(f)
for _, fun := range afterBindCallbacks {
sf2 := reflect.ValueOf(fun)
if sf1.Pointer() == sf2.Pointer() {
return
}
}
afterBindCallbacks = append(afterBindCallbacks, f)
}
// OnSessionClose adds a method that will be called when every session closes
func OnSessionClose(f func(s *Session)) {
sf1 := reflect.ValueOf(f)
for _, fun := range SessionCloseCallbacks {
sf2 := reflect.ValueOf(fun)
if sf1.Pointer() == sf2.Pointer() {
return
}
}
SessionCloseCallbacks = append(SessionCloseCallbacks, f)
}
// CloseAll calls Close on all sessions
func CloseAll() {
logger.Log.Debugf("closing all sessions, %d sessions", SessionCount)
sessionsByID.Range(func(_, value interface{}) bool {
s := value.(*Session)
s.Close()
return true
})
logger.Log.Debug("finished closing sessions")
}
func (s *Session) updateEncodedData() error {
var b []byte
b, err := json.Marshal(s.data)
if err != nil {
return err
}
s.encodedData = b
return nil
}
// Push message to client
func (s *Session) Push(route string, v interface{}) error {
return s.entity.Push(route, v)
}
// ResponseMID responses message to client, mid is
// request message ID
func (s *Session) ResponseMID(ctx context.Context, mid uint, v interface{}, err ...bool) error {
return s.entity.ResponseMID(ctx, mid, v, err...)
}
// ID returns the session id
func (s *Session) ID() int64 {
return s.id
}
// UID returns uid that bind to current session
func (s *Session) UID() string {
return s.uid
}
// GetData gets the data
func (s *Session) GetData() map[string]interface{} {
s.RLock()
defer s.RUnlock()
return s.data
}
// SetData sets the whole session data
func (s *Session) SetData(data map[string]interface{}) error {
s.Lock()
defer s.Unlock()
s.data = data
return s.updateEncodedData()
}
// GetDataEncoded returns the session data as an encoded value
func (s *Session) GetDataEncoded() []byte {
return s.encodedData
}
// SetDataEncoded sets the whole session data from an encoded value
func (s *Session) SetDataEncoded(encodedData []byte) error {
if len(encodedData) == 0 {
return nil
}
var data map[string]interface{}
err := json.Unmarshal(encodedData, &data)
if err != nil {
return err
}
return s.SetData(data)
}
// SetFrontendData sets frontend id and session id
func (s *Session) SetFrontendData(frontendID string, frontendSessionID int64) {
s.frontendID = frontendID
s.frontendSessionID = frontendSessionID
}
// Bind bind UID to current session
func (s *Session) Bind(ctx context.Context, uid string) error {
if uid == "" {
return constants.ErrIllegalUID
}
if s.UID() != "" {
return constants.ErrSessionAlreadyBound
}
s.uid = uid
for _, cb := range sessionBindCallbacks {
err := cb(ctx, s)
if err != nil {
s.uid = ""
return err
}
}
for _, cb := range afterBindCallbacks {
err := cb(ctx, s)
if err != nil {
s.uid = ""
return err
}
}
// if code running on frontend server
if s.IsFrontend {
sessionsByUID.Store(uid, s)
} else {
// If frontentID is set this means it is a remote call and the current server
// is not the frontend server that received the user request
err := s.bindInFront(ctx)
if err != nil {
logger.Log.Error("error while trying to push session to front: ", err)
s.uid = ""
return err
}
}
return nil
}
// Kick kicks the user
func (s *Session) Kick(ctx context.Context) error {
err := s.entity.Kick(ctx)
if err != nil {
return err
}
return s.entity.Close()
}
// OnClose adds the function it receives to the callbacks that will be called
// when the session is closed
func (s *Session) OnClose(c func()) error {
if !s.IsFrontend {
return constants.ErrOnCloseBackend
}
s.OnCloseCallbacks = append(s.OnCloseCallbacks, c)
return nil
}
// Close terminates current session, session related data will not be released,
// all related data should be cleared explicitly in Session closed callback
func (s *Session) Close() {
atomic.AddInt64(&SessionCount, -1)
sessionsByID.Delete(s.ID())
sessionsByUID.Delete(s.UID())
// TODO: this logic should be moved to nats rpc server
if s.IsFrontend && s.Subscriptions != nil && len(s.Subscriptions) > 0 {
// if the user is bound to an userid and nats rpc server is being used we need to unsubscribe
for _, sub := range s.Subscriptions {
err := sub.Unsubscribe()
if err != nil {
logger.Log.Errorf("error unsubscribing to user's messages channel: %s, this can cause performance and leak issues", err.Error())
} else {
logger.Log.Debugf("successfully unsubscribed to user's %s messages channel", s.UID())
}
}
}
s.entity.Close()
}
// RemoteAddr returns the remote network address.
func (s *Session) RemoteAddr() net.Addr {
return s.entity.RemoteAddr()
}
// Remove delete data associated with the key from session storage
func (s *Session) Remove(key string) error {
s.Lock()
defer s.Unlock()
delete(s.data, key)
return s.updateEncodedData()
}
// Set associates value with the key in session storage
func (s *Session) Set(key string, value interface{}) error {
s.Lock()
defer s.Unlock()
s.data[key] = value
return s.updateEncodedData()
}
// HasKey decides whether a key has associated value
func (s *Session) HasKey(key string) bool {
s.RLock()
defer s.RUnlock()
_, has := s.data[key]
return has
}
// Get returns a key value
func (s *Session) Get(key string) interface{} {
s.RLock()
defer s.RUnlock()
v, ok := s.data[key]
if !ok {
return nil
}
return v
}
// Int returns the value associated with the key as a int.
func (s *Session) Int(key string) int {
s.RLock()
defer s.RUnlock()
v, ok := s.data[key]
if !ok {
return 0
}
value, ok := v.(int)
if !ok {
return 0
}
return value
}
// Int8 returns the value associated with the key as a int8.
func (s *Session) Int8(key string) int8 {
s.RLock()
defer s.RUnlock()
v, ok := s.data[key]
if !ok {
return 0
}
value, ok := v.(int8)
if !ok {
return 0
}
return value
}
// Int16 returns the value associated with the key as a int16.
func (s *Session) Int16(key string) int16 {
s.RLock()
defer s.RUnlock()
v, ok := s.data[key]
if !ok {
return 0
}
value, ok := v.(int16)
if !ok {
return 0
}
return value
}
// Int32 returns the value associated with the key as a int32.
func (s *Session) Int32(key string) int32 {
s.RLock()
defer s.RUnlock()
v, ok := s.data[key]
if !ok {
return 0
}
value, ok := v.(int32)
if !ok {
return 0
}
return value
}
// Int64 returns the value associated with the key as a int64.
func (s *Session) Int64(key string) int64 {
s.RLock()
defer s.RUnlock()
v, ok := s.data[key]
if !ok {
return 0
}
value, ok := v.(int64)
if !ok {
return 0
}
return value
}
// Uint returns the value associated with the key as a uint.
func (s *Session) Uint(key string) uint {
s.RLock()
defer s.RUnlock()
v, ok := s.data[key]
if !ok {
return 0
}
value, ok := v.(uint)
if !ok {
return 0
}
return value
}
// Uint8 returns the value associated with the key as a uint8.
func (s *Session) Uint8(key string) uint8 {
s.RLock()
defer s.RUnlock()
v, ok := s.data[key]
if !ok {
return 0
}
value, ok := v.(uint8)
if !ok {
return 0
}
return value
}
// Uint16 returns the value associated with the key as a uint16.
func (s *Session) Uint16(key string) uint16 {
s.RLock()
defer s.RUnlock()
v, ok := s.data[key]
if !ok {
return 0
}
value, ok := v.(uint16)
if !ok {
return 0
}
return value
}
// Uint32 returns the value associated with the key as a uint32.
func (s *Session) Uint32(key string) uint32 {
s.RLock()
defer s.RUnlock()
v, ok := s.data[key]
if !ok {
return 0
}
value, ok := v.(uint32)
if !ok {
return 0
}
return value
}
// Uint64 returns the value associated with the key as a uint64.
func (s *Session) Uint64(key string) uint64 {
s.RLock()
defer s.RUnlock()
v, ok := s.data[key]
if !ok {
return 0
}
value, ok := v.(uint64)
if !ok {
return 0
}
return value
}
// Float32 returns the value associated with the key as a float32.
func (s *Session) Float32(key string) float32 {
s.RLock()
defer s.RUnlock()
v, ok := s.data[key]
if !ok {
return 0
}
value, ok := v.(float32)
if !ok {
return 0
}
return value
}
// Float64 returns the value associated with the key as a float64.
func (s *Session) Float64(key string) float64 {
s.RLock()
defer s.RUnlock()
v, ok := s.data[key]
if !ok {
return 0
}
value, ok := v.(float64)
if !ok {
return 0
}
return value
}
// String returns the value associated with the key as a string.
func (s *Session) String(key string) string {
s.RLock()
defer s.RUnlock()
v, ok := s.data[key]
if !ok {
return ""
}
value, ok := v.(string)
if !ok {
return ""
}
return value
}
// Value returns the value associated with the key as a interface{}.
func (s *Session) Value(key string) interface{} {
s.RLock()
defer s.RUnlock()
return s.data[key]
}
func (s *Session) bindInFront(ctx context.Context) error {
return s.sendRequestToFront(ctx, constants.SessionBindRoute, false)
}
// PushToFront updates the session in the frontend
func (s *Session) PushToFront(ctx context.Context) error {
if s.IsFrontend {
return constants.ErrFrontSessionCantPushToFront
}
return s.sendRequestToFront(ctx, constants.SessionPushRoute, true)
}
// Clear releases all data related to current session
func (s *Session) Clear() {
s.Lock()
defer s.Unlock()
s.uid = ""
s.data = map[string]interface{}{}
s.updateEncodedData()
}
// SetHandshakeData sets the handshake data received by the client.
func (s *Session) SetHandshakeData(data *HandshakeData) {
s.Lock()
defer s.Unlock()
s.handshakeData = data
}
// GetHandshakeData gets the handshake data received by the client.
func (s *Session) GetHandshakeData() *HandshakeData {
return s.handshakeData
}
func (s *Session) sendRequestToFront(ctx context.Context, route string, includeData bool) error {
sessionData := &protos.Session{
Id: s.frontendSessionID,
Uid: s.uid,
}
if includeData {
sessionData.Data = s.encodedData
}
b, err := proto.Marshal(sessionData)
if err != nil {
return err
}
res, err := s.entity.SendRequest(ctx, s.frontendID, route, b)
if err != nil {
return err
}
logger.Log.Debugf("%s Got response: %+v", route, res)
return nil
}