forked from heroiclabs/nakama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsession_ws.go
279 lines (238 loc) · 7.94 KB
/
session_ws.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
// 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 (
"go.uber.org/zap"
"sync"
"go.uber.org/atomic"
"github.com/gorilla/websocket"
"time"
"github.com/satori/go.uuid"
"bytes"
"github.com/golang/protobuf/jsonpb"
"errors"
"github.com/heroiclabs/nakama/rtapi"
"fmt"
)
var ErrQueueFull = errors.New("outgoing queue full")
type sessionWS struct {
sync.Mutex
logger *zap.Logger
config Config
id uuid.UUID
userID uuid.UUID
username *atomic.String
expiry int64
jsonpbMarshaler *jsonpb.Marshaler
jsonpbUnmarshaler *jsonpb.Unmarshaler
tracker Tracker
registry *SessionRegistry
stopped bool
conn *websocket.Conn
pingTicker *time.Ticker
outgoingCh chan []byte
outgoingStopCh chan struct{}
}
func NewSessionWS(logger *zap.Logger, config Config, userID uuid.UUID, username string, expiry int64, jsonpbMarshaler *jsonpb.Marshaler, jsonpbUnmarshaler *jsonpb.Unmarshaler, conn *websocket.Conn, tracker Tracker, registry *SessionRegistry) session {
sessionID := uuid.NewV4()
sessionLogger := logger.With(zap.String("uid", userID.String()), zap.String("sid", sessionID.String()))
sessionLogger.Debug("New WebSocket session connected")
return &sessionWS{
logger: sessionLogger,
config: config,
id: sessionID,
userID: userID,
username: atomic.NewString(username),
expiry: expiry,
jsonpbMarshaler: jsonpbMarshaler,
jsonpbUnmarshaler: jsonpbUnmarshaler,
tracker: tracker,
registry: registry,
stopped: false,
conn: conn,
pingTicker: time.NewTicker(time.Duration(config.GetSocket().PingPeriodMs) * time.Millisecond),
outgoingCh: make(chan []byte, config.GetSocket().OutgoingQueueSize),
outgoingStopCh: make(chan struct{}),
}
}
func (s *sessionWS) Logger() *zap.Logger {
return s.logger
}
func (s *sessionWS) ID() uuid.UUID {
return s.id
}
func (s *sessionWS) UserID() uuid.UUID {
return s.userID
}
func (s *sessionWS) Username() string {
return s.username.Load()
}
func (s *sessionWS) SetUsername(username string) {
s.username.Store(username)
}
func (s *sessionWS) Expiry() int64 {
return s.expiry
}
func (s *sessionWS) Consume(processRequest func(logger *zap.Logger, session session, envelope *rtapi.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.
if !s.pingNow() {
// If the first ping fails abort the rest of the consume sequence immediately.
return
}
// Start a routine to process outbound messages.
go s.processOutgoing()
for {
_, data, err := s.conn.ReadMessage()
if err != nil {
if !websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway, websocket.CloseNoStatusReceived) {
s.logger.Warn("Error reading message from client", zap.Error(err))
}
break
}
request := &rtapi.Envelope{}
if err = s.jsonpbUnmarshaler.Unmarshal(bytes.NewReader(data), request); err != nil {
// If the payload is malformed the client is incompatible or misbehaving, either way disconnect it now.
s.logger.Warn("Received malformed payload", zap.String("data", string(data)))
s.Send(&rtapi.Envelope{Message: &rtapi.Envelope_Error{Error: &rtapi.Error{
Code: int32(rtapi.Error_UNRECOGNIZED_PAYLOAD),
Message: "Unrecognized payload",
}}})
break
} 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.Cid))
processRequest(requestLogger, s, request)
}
}
}
func (s *sessionWS) processOutgoing() {
for {
select {
case <-s.outgoingStopCh:
// Session is closing, close the outgoing process routine.
return
case <-s.pingTicker.C:
// Periodically send pings.
if !s.pingNow() {
// If ping fails the session will be stopped, clean up the loop.
return
}
case payload := <-s.outgoingCh:
// Process the outgoing message queue.
s.conn.SetWriteDeadline(time.Now().Add(time.Duration(s.config.GetSocket().WriteWaitMs) * time.Millisecond))
if err := s.conn.WriteMessage(websocket.TextMessage, payload); err != nil {
s.logger.Warn("Could not write message", zap.Error(err))
return
}
}
}
}
func (s *sessionWS) 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))
// The connection has already failed.
s.cleanupClosedConnection()
return false
}
return true
}
func (s *sessionWS) Format() SessionFormat {
return SessionFormatJson
}
func (s *sessionWS) Send(envelope *rtapi.Envelope) error {
s.logger.Debug(fmt.Sprintf("Sending %T message", envelope.Message), zap.String("cid", envelope.Cid))
payload, err := s.jsonpbMarshaler.MarshalToString(envelope)
if err != nil {
s.logger.Warn("Could not marshal to json", zap.Error(err))
return err
}
return s.SendBytes([]byte(payload))
}
func (s *sessionWS) SendBytes(payload []byte) error {
s.Lock()
if s.stopped {
s.Unlock()
return nil
}
select {
case s.outgoingCh <-payload:
s.Unlock()
return nil
default:
// The outgoing queue is full, likely because the remote client can't keep up.
// Terminate the connection immediately because the only alternative that doesn't block the server is
// to start dropping messages, which might cause unexpected behaviour.
s.Unlock()
s.logger.Warn("Could not write message, outgoing queue full")
s.cleanupClosedConnection()
return ErrQueueFull
}
}
func (s *sessionWS) cleanupClosedConnection() {
s.Lock()
if s.stopped {
s.Unlock()
return
}
s.stopped = true
s.Unlock()
s.logger.Debug("Cleaning up closed client connection", zap.String("remoteAddress", s.conn.RemoteAddr().String()))
// When connection close originates internally in the session, ensure cleanup of external resources and references.
s.registry.remove(s.id)
s.tracker.UntrackAll(s.id)
// Clean up internals.
s.pingTicker.Stop()
close(s.outgoingStopCh)
close(s.outgoingCh)
// Close WebSocket.
s.conn.Close()
s.logger.Debug("Closed client connection")
}
func (s *sessionWS) Close() {
s.Lock()
if s.stopped {
s.Unlock()
return
}
s.stopped = true
s.Unlock()
// Expect the caller of this session.Close() to clean up external resources (like presences) separately.
// Clean up internals.
s.pingTicker.Stop()
close(s.outgoingStopCh)
close(s.outgoingCh)
// Send close message.
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))
}
// Close WebSocket.
s.conn.Close()
s.logger.Debug("Closed client connection")
}