This repository has been archived by the owner on May 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
connection.go
368 lines (310 loc) · 8.33 KB
/
connection.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
package webwire
import (
"encoding/json"
"errors"
"fmt"
"net"
"sync"
"time"
"github.com/qbeon/webwire-go/message"
"golang.org/x/sync/semaphore"
)
// info represents basic information about a client connection
type info struct {
Options ConnectionOptions
Creation time.Time
RemoteAddr net.Addr
}
// connection represents a connected client connected to the server
type connection struct {
// options represents the options defined during the connection upgrade
options ConnectionOptions
// stateLock protects both isActive and tasks from concurrent access
stateLock sync.RWMutex
isActive bool
// tasks represents the number of currently performed tasks
tasks int32
// handlerSlots keeps track of available handler slots
handlerSlots *semaphore.Weighted
// srv references the connection origin server instance
srv *server
// sock references the connection's socket
sock Socket
// sessionLock protects the session field from concurrent access
sessionLock sync.RWMutex
// session references the currently assigned session, can be null
session *Session
// info represents overall connection information
info info
}
// newConnection creates and returns a new client connection instance
func newConnection(
socket Socket,
srv *server,
options ConnectionOptions,
) *connection {
// the connection is considered closed when no socket is referenced
var remoteAddr net.Addr
isActive := false
if socket != nil {
isActive = true
remoteAddr = socket.RemoteAddr()
}
return &connection{
options: options,
stateLock: sync.RWMutex{},
isActive: isActive,
tasks: 0,
handlerSlots: semaphore.NewWeighted(int64(options.ConcurrencyLimit)),
srv: srv,
sock: socket,
sessionLock: sync.RWMutex{},
session: nil,
info: info{
Options: options,
Creation: time.Now(),
RemoteAddr: remoteAddr,
},
}
}
// IsActive implements the Connection interface
func (con *connection) IsActive() bool {
con.stateLock.RLock()
isActive := con.isActive
con.stateLock.RUnlock()
return isActive
}
// registerTask increments the number of currently executed tasks
func (con *connection) registerTask() {
con.stateLock.Lock()
con.tasks++
con.stateLock.Unlock()
}
// deregisterTask decrements the number of currently executed tasks
// and closes this client connection if its shutdown is requested
// and the number of tasks reached zero
func (con *connection) deregisterTask() {
unlink := false
con.stateLock.Lock()
con.tasks--
if !con.isActive && con.tasks < 1 {
unlink = true
}
con.stateLock.Unlock()
if unlink {
con.unlink()
}
}
// setSession sets a new session for this client
func (con *connection) setSession(newSess *Session) {
con.sessionLock.Lock()
con.session = newSess
con.sessionLock.Unlock()
}
// unlink resets the connection and marks it as disconnected
// preparing it for garbage collection
func (con *connection) unlink() {
// Deregister session from active sessions registry, but don't destroy it
con.srv.sessionRegistry.deregister(con, false)
con.sessionLock.Lock()
con.session = nil
con.sessionLock.Unlock()
// Close connection
con.sock.Close()
}
// Info implements the Connection interface
func (con *connection) Info(key int) interface{} {
if con.info.Options.Info == nil {
return nil
}
return con.info.Options.Info[key]
}
// Creation implements the Connection interface
func (con *connection) Creation() time.Time {
return con.info.Creation
}
// RemoteAddr implements the Connection interface
func (con *connection) RemoteAddr() net.Addr {
return con.info.RemoteAddr
}
// Signal implements the Connection interface
func (con *connection) Signal(name []byte, payload Payload) (err error) {
// Require either a name, or a payload or both
if len(name) < 1 && len(payload.Data) < 1 {
return ErrProtocol{Cause: errors.New("missing both name and payload")}
}
// Ensure the message won't exceed the buffer size
if uint32(message.CalcMsgLenSignal(name, payload.Encoding, payload.Data)) >
con.srv.options.MessageBufferSize {
return ErrBufferOverflow{}
}
writer, err := con.sock.GetWriter()
if err != nil {
return err
}
return message.WriteMsgSignal(
writer,
name,
payload.Encoding,
payload.Data,
true,
)
}
// CreateSession implements the Connection interface
func (con *connection) CreateSession(attachment SessionInfo) error {
if !con.srv.sessionsEnabled {
return ErrSessionsDisabled{}
}
if !con.sock.IsConnected() {
return ErrDisconnected{
Cause: fmt.Errorf(
"Can't create session on disconnected connection",
),
}
}
con.sessionLock.Lock()
// Abort if there's already another active session
if con.session != nil {
con.sessionLock.Unlock()
return fmt.Errorf(
"Another session (%s) on this client is already active",
con.session.Key,
)
}
// Create a new session
newSession := NewSession(attachment, con.srv.sessionKeyGen.Generate)
// Try to notify about session creation
if err := con.notifySessionCreated(&newSession); err != nil {
con.sessionLock.Unlock()
return fmt.Errorf(
"Couldn't notify client about the session creation: %s",
err,
)
}
// Register the session
con.session = &newSession
con.srv.sessionRegistry.register(con)
con.sessionLock.Unlock()
// Call session creation hook
if err := con.srv.sessionManager.OnSessionCreated(con); err != nil {
con.srv.errorLog.Printf("OnSessionCreated hook failed: %s", err)
}
return nil
}
func (con *connection) notifySessionCreated(newSession *Session) error {
// Serialize session info
var sessionInfo map[string]interface{}
if newSession.Info != nil {
sessionInfo = make(map[string]interface{})
for _, field := range newSession.Info.Fields() {
sessionInfo[field] = newSession.Info.Value(field)
}
}
encodedSessionInfo, err := json.Marshal(JSONEncodedSession{
newSession.Key,
newSession.Creation,
newSession.LastLookup,
sessionInfo,
})
if err != nil {
return fmt.Errorf("Couldn't marshal session object: %s", err)
}
// Notify client about the session creation
writer, err := con.sock.GetWriter()
if err != nil {
return err
}
return message.WriteMsgNotifySessionCreated(
writer,
encodedSessionInfo,
)
}
// notifySessionClosed notifies the client about the session destruction
func (con *connection) notifySessionClosed() error {
writer, err := con.sock.GetWriter()
if err != nil {
return err
}
return message.WriteMsgNotifySessionClosed(writer)
}
// CloseSession implements the Connection interface
func (con *connection) CloseSession() error {
if !con.srv.sessionsEnabled {
return ErrSessionsDisabled{}
}
con.sessionLock.Lock()
if con.session == nil {
con.sessionLock.Unlock()
return nil
}
// Deregister session from active sessions registry destroying it if it's
// the last connection left
con.srv.sessionRegistry.deregister(con, true)
con.session = nil
con.sessionLock.Unlock()
return con.notifySessionClosed()
}
// HasSession implements the Connection interface
func (con *connection) HasSession() bool {
con.sessionLock.RLock()
hasSession := con.session != nil
con.sessionLock.RUnlock()
return hasSession
}
// Session implements the Connection interface
func (con *connection) Session() *Session {
con.sessionLock.RLock()
clone := con.session.Clone()
con.sessionLock.RUnlock()
return clone
}
// SessionKey implements the Connection interface
func (con *connection) SessionKey() string {
con.sessionLock.RLock()
if con.session == nil {
con.sessionLock.RUnlock()
return ""
}
key := con.session.Key
con.sessionLock.RUnlock()
return key
}
// SessionCreation implements the Connection interface
func (con *connection) SessionCreation() time.Time {
con.sessionLock.RLock()
if con.session == nil {
con.sessionLock.RUnlock()
return time.Time{}
}
creation := con.session.Creation
con.sessionLock.RUnlock()
return creation
}
// SessionInfo implements the Connection interface
func (con *connection) SessionInfo(name string) interface{} {
con.sessionLock.RLock()
if con.session == nil || con.session.Info == nil {
con.sessionLock.RUnlock()
return nil
}
val := con.session.Info.Value(name)
con.sessionLock.RUnlock()
return val
}
// Close implements the Connection interface
func (con *connection) Close() {
unlink := false
con.stateLock.Lock()
if !con.isActive {
con.stateLock.Unlock()
return
}
con.isActive = false
if con.tasks < 1 {
unlink = true
}
con.stateLock.Unlock()
if unlink {
con.unlink()
}
}