forked from heroiclabs/nakama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
208 lines (180 loc) · 6.04 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
// Copyright 2017 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 (
"sync"
"time"
"fmt"
"github.com/gogo/protobuf/proto"
"github.com/gorilla/websocket"
"github.com/satori/go.uuid"
"go.uber.org/atomic"
"go.uber.org/zap"
)
type session struct {
sync.Mutex
logger *zap.Logger
config Config
id uuid.UUID
userID uuid.UUID
handle *atomic.String
lang string
expiry int64
stopped bool
conn *websocket.Conn
pingTicker *time.Ticker
pingTickerStopCh chan (bool)
unregister func(s *session)
}
// NewSession creates a new session which encapsulates a socket connection
func NewSession(logger *zap.Logger, config Config, userID uuid.UUID, handle string, lang string, expiry int64, websocketConn *websocket.Conn, unregister func(s *session)) *session {
sessionID := uuid.NewV4()
sessionLogger := logger.With(zap.String("uid", userID.String()), zap.String("sid", sessionID.String()))
sessionLogger.Info("New session connected")
return &session{
logger: sessionLogger,
config: config,
id: sessionID,
userID: userID,
handle: atomic.NewString(handle),
lang: lang,
expiry: expiry,
conn: websocketConn,
stopped: false,
pingTicker: time.NewTicker(time.Duration(config.GetSocket().PingPeriodMs) * time.Millisecond),
pingTickerStopCh: make(chan bool),
unregister: unregister,
}
}
func (s *session) Consume(processRequest func(logger *zap.Logger, session *session, envelope *Envelope)) {
defer s.cleanupClosedConnection()
s.conn.SetReadLimit(s.config.GetSocket().MaxMessageSizeBytes)
s.conn.SetReadDeadline(time.Now().Add(time.Duration(s.config.GetSocket().PongWaitMs) * time.Millisecond))
s.conn.SetPongHandler(func(string) error {
s.conn.SetReadDeadline(time.Now().Add(time.Duration(s.config.GetSocket().PongWaitMs) * time.Millisecond))
return nil
})
// Send an initial ping immediately, then at intervals.
s.pingNow()
go s.pingPeriodically()
for {
_, data, err := s.conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway, websocket.CloseNoStatusReceived) {
s.logger.Warn("Error reading message from client", zap.Error(err))
}
break
}
request := &Envelope{}
err = proto.Unmarshal(data, request)
if err != nil {
s.logger.Warn("Received malformed payload", zap.Any("data", data))
s.Send(ErrorMessage(request.CollationId, UNRECOGNIZED_PAYLOAD, "Unrecognized payload"))
} else {
// TODO Add session-global context here to cancel in-progress operations when the session is closed.
requestLogger := s.logger.With(zap.String("cid", request.CollationId))
processRequest(requestLogger, s, request)
}
}
}
func (s *session) pingPeriodically() {
for {
select {
case <-s.pingTicker.C:
if !s.pingNow() {
// If ping fails the session will be stopped, clean up the loop.
return
}
case <-s.pingTickerStopCh:
return
}
}
}
func (s *session) pingNow() bool {
s.Lock()
if s.stopped {
s.Unlock()
return false
}
s.conn.SetWriteDeadline(time.Now().Add(time.Duration(s.config.GetSocket().WriteWaitMs) * time.Millisecond))
err := s.conn.WriteMessage(websocket.PingMessage, []byte{})
s.Unlock()
if err != nil {
s.logger.Warn("Could not send ping. Closing channel", zap.String("remoteAddress", s.conn.RemoteAddr().String()), zap.Error(err))
s.cleanupClosedConnection() // The connection has already failed
return false
}
// Server heartbeat.
err = s.Send(&Envelope{Payload: &Envelope_Heartbeat{&Heartbeat{Timestamp: nowMs()}}})
if err != nil {
s.logger.Warn("Could not send heartbeat", zap.String("remoteAddress", s.conn.RemoteAddr().String()), zap.Error(err))
}
return true
}
func (s *session) Send(envelope *Envelope) error {
s.logger.Debug(fmt.Sprintf("Sending %T message", envelope.Payload), zap.String("cid", envelope.CollationId))
payload, err := proto.Marshal(envelope)
if err != nil {
s.logger.Warn("Could not marshall Response to byte[]", zap.Error(err))
return err
}
return s.SendBytes(payload)
}
func (s *session) SendBytes(payload []byte) error {
// TODO Improve on mutex usage here.
s.Lock()
defer s.Unlock()
if s.stopped {
return nil
}
s.conn.SetWriteDeadline(time.Now().Add(time.Duration(s.config.GetSocket().WriteWaitMs) * time.Millisecond))
err := s.conn.WriteMessage(websocket.BinaryMessage, payload)
if err != nil {
s.logger.Warn("Could not write message", zap.Error(err))
//TODO investigate whether we need to cleanupClosedConnection if write fails
}
return err
}
func (s *session) cleanupClosedConnection() {
s.Lock()
if s.stopped {
s.Unlock()
return
}
s.stopped = true
s.Unlock()
s.logger.Info("Cleaning up closed client connection", zap.String("remoteAddress", s.conn.RemoteAddr().String()))
s.unregister(s)
s.pingTicker.Stop()
s.pingTickerStopCh <- true
s.conn.Close()
s.logger.Info("Closed client connection")
}
func (s *session) close() {
s.Lock()
if s.stopped {
s.Unlock()
return
}
s.stopped = true
s.Unlock()
s.pingTicker.Stop()
s.pingTickerStopCh <- true
err := s.conn.WriteControl(websocket.CloseMessage, []byte{}, time.Now().Add(time.Duration(s.config.GetSocket().WriteWaitMs)*time.Millisecond))
if err != nil {
s.logger.Warn("Could not send close message. Closing prematurely.", zap.String("remoteAddress", s.conn.RemoteAddr().String()), zap.Error(err))
}
s.conn.Close()
s.logger.Info("Closed client connection")
}