forked from antoniodipinto/ikisocket
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathikisocket.go
More file actions
628 lines (544 loc) · 14.6 KB
/
ikisocket.go
File metadata and controls
628 lines (544 loc) · 14.6 KB
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
package ikisocket
import (
"context"
"errors"
"math/rand"
"sync"
"time"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/websocket/v2"
)
// Source @url:https://github.com/gorilla/websocket/blob/master/conn.go#L61
// The message types are defined in RFC 6455, section 11.8.
const (
// TextMessage denotes a text data message. The text message payload is
// interpreted as UTF-8 encoded text data.
TextMessage = 1
// BinaryMessage denotes a binary data message.
BinaryMessage = 2
// CloseMessage denotes a close control message. The optional message
// payload contains a numeric code and text. Use the FormatCloseMessage
// function to format a close message payload.
CloseMessage = 8
// PingMessage denotes a ping control message. The optional message payload
// is UTF-8 encoded text.
PingMessage = 9
// PongMessage denotes a pong control message. The optional message payload
// is UTF-8 encoded text.
PongMessage = 10
)
// Supported event list
const (
// EventMessage Fired when a Text/Binary message is received
EventMessage = "message"
// EventPing More details here:
// @url https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#Pings_and_Pongs_The_Heartbeat_of_WebSockets
EventPing = "ping"
EventPong = "pong"
// EventDisconnect Fired on disconnection
// The error provided in disconnection event
// is defined in RFC 6455, section 11.7.
// @url https://github.com/gofiber/websocket/blob/cd4720c435de415b864d975a9ca23a47eaf081ef/websocket.go#L192
EventDisconnect = "disconnect"
// EventConnect Fired on first connection
EventConnect = "connect"
// EventClose Fired when the connection is actively closed from the server
EventClose = "close"
// EventError Fired when some error appears useful also for debugging websockets
EventError = "error"
)
var (
// ErrorInvalidConnection The addressed ws connection is not available anymore
// error data is the uuid of that connection
ErrorInvalidConnection = errors.New("message cannot be delivered invalid/gone connection")
// ErrorUUIDDuplication The UUID already exists in the pool
ErrorUUIDDuplication = errors.New("UUID already exists in the available connections pool")
)
var (
PongTimeout = 1 * time.Second
// RetrySendTimeout retry after 20 ms if there is an error
RetrySendTimeout = 20 * time.Millisecond
//MaxSendRetry define max retries if there are socket issues
MaxSendRetry = 5
// ReadTimeout Instead of reading in a for loop, try to avoid full CPU load taking some pause
ReadTimeout = 10 * time.Millisecond
)
// Raw form of websocket message
type message struct {
// Message type
mType int
// Message data
data []byte
// Message send retries when error
retries int
}
// EventPayload Event Payload is the object that
// stores all the information about the event and
// the connection
type EventPayload struct {
// The connection object
Kws *Websocket
// The name of the event
Name string
// Unique connection UUID
SocketUUID string
// Optional websocket attributes
SocketAttributes map[string]interface{}
// Optional error when are fired events like
// - Disconnect
// - Error
Error error
// Data is used on Message and on Error event
Data []byte
}
type ws interface {
IsAlive() bool
GetUUID() string
SetUUID(uuid string)
SetAttribute(key string, attribute interface{})
GetAttribute(key string) interface{}
GetIntAttribute(key string) int
GetStringAttribute(key string) string
EmitToList(uuids []string, message []byte)
EmitTo(uuid string, message []byte) error
Broadcast(message []byte, except bool)
Fire(event string, data []byte)
Emit(message []byte)
Close()
pong(ctx context.Context)
write(messageType int, messageBytes []byte)
run()
read(ctx context.Context)
disconnected(err error)
createUUID() string
randomUUID() string
fireEvent(event string, data []byte, error error)
}
type Websocket struct {
mu sync.RWMutex
// The Fiber.Websocket connection
ws *websocket.Conn
// Define if the connection is alive or not
isAlive bool
// Queue of messages sent from the socket
queue chan message
// Channel to signal when this websocket is closed
// so go routines will stop gracefully
done chan struct{}
// Attributes map collection for the connection
attributes map[string]interface{}
// Unique id of the connection
UUID string
// Wrap Fiber Locals function
Locals func(key string) interface{}
// Wrap Fiber Params function
Params func(key string, defaultValue ...string) string
// Wrap Fiber Query function
Query func(key string, defaultValue ...string) string
// Wrap Fiber Cookies function
Cookies func(key string, defaultValue ...string) string
}
type safePool struct {
sync.RWMutex
// List of the connections alive
conn map[string]ws
}
// Pool with the active connections
var pool = safePool{
conn: make(map[string]ws),
}
func (p *safePool) set(ws ws) {
p.Lock()
p.conn[ws.GetUUID()] = ws
p.Unlock()
}
func (p *safePool) all() map[string]ws {
p.RLock()
ret := make(map[string]ws, 0)
for uuid, kws := range p.conn {
ret[uuid] = kws
}
p.RUnlock()
return ret
}
func (p *safePool) get(key string) ws {
p.RLock()
ret, ok := p.conn[key]
p.RUnlock()
if !ok {
panic("not found")
}
return ret
}
func (p *safePool) contains(key string) bool {
p.RLock()
_, ok := p.conn[key]
p.RUnlock()
return ok
}
func (p *safePool) delete(key string) {
p.Lock()
delete(p.conn, key)
p.Unlock()
}
func (p *safePool) reset() {
p.Lock()
p.conn = make(map[string]ws)
p.Unlock()
}
type safeListeners struct {
sync.RWMutex
list map[string][]eventCallback
}
func (l *safeListeners) set(event string, callback eventCallback) {
l.Lock()
listeners.list[event] = append(listeners.list[event], callback)
l.Unlock()
}
func (l *safeListeners) get(event string) []eventCallback {
l.RLock()
defer l.RUnlock()
if _, ok := l.list[event]; !ok {
return make([]eventCallback, 0)
}
ret := make([]eventCallback, 0)
for _, v := range l.list[event] {
ret = append(ret, v)
}
return ret
}
// List of the listeners for the events
var listeners = safeListeners{
list: make(map[string][]eventCallback),
}
func New(callback func(kws *Websocket)) func(*fiber.Ctx) error {
return websocket.New(func(c *websocket.Conn) {
kws := &Websocket{
ws: c,
Locals: func(key string) interface{} {
return c.Locals(key)
},
Params: func(key string, defaultValue ...string) string {
return c.Params(key, defaultValue...)
},
Query: func(key string, defaultValue ...string) string {
return c.Query(key, defaultValue...)
},
Cookies: func(key string, defaultValue ...string) string {
return c.Cookies(key, defaultValue...)
},
queue: make(chan message, 100),
done: make(chan struct{}, 1),
attributes: make(map[string]interface{}),
isAlive: true,
}
// Generate uuid
kws.UUID = kws.createUUID()
// register the connection into the pool
pool.set(kws)
// execute the callback of the socket initialization
callback(kws)
kws.fireEvent(EventConnect, nil, nil)
// Run the loop for the given connection
kws.run()
})
}
func (kws *Websocket) GetUUID() string {
kws.mu.RLock()
defer kws.mu.RUnlock()
return kws.UUID
}
func (kws *Websocket) SetUUID(uuid string) {
kws.mu.Lock()
defer kws.mu.Unlock()
if pool.contains(uuid) {
panic(ErrorUUIDDuplication)
}
kws.UUID = uuid
}
// SetAttribute Set a specific attribute for the specific socket connection
func (kws *Websocket) SetAttribute(key string, attribute interface{}) {
kws.mu.Lock()
defer kws.mu.Unlock()
kws.attributes[key] = attribute
}
// GetAttribute Get a specific attribute from the socket attributes
func (kws *Websocket) GetAttribute(key string) interface{} {
kws.mu.RLock()
defer kws.mu.RUnlock()
value, ok := kws.attributes[key]
if ok {
return value
}
return nil
}
// GetIntAttribute Convenience method to retrieve an attribute as an int.
// Will panic if attribute is not an int.
func (kws *Websocket) GetIntAttribute(key string) int {
kws.mu.RLock()
defer kws.mu.RUnlock()
value, ok := kws.attributes[key]
if ok {
return value.(int)
}
return 0
}
// GetStringAttribute Convenience method to retrieve an attribute as a string.
// Will panic if attribute is not an int.
func (kws *Websocket) GetStringAttribute(key string) string {
kws.mu.RLock()
defer kws.mu.RUnlock()
value, ok := kws.attributes[key]
if ok {
return value.(string)
}
return ""
}
// EmitToList Emit the message to a specific socket uuids list
func (kws *Websocket) EmitToList(uuids []string, message []byte) {
for _, uuid := range uuids {
err := kws.EmitTo(uuid, message)
if err != nil {
kws.fireEvent(EventError, message, err)
}
}
}
// EmitToList Emit the message to a specific socket uuids list
// Ignores all errors
func EmitToList(uuids []string, message []byte) {
for _, uuid := range uuids {
_ = EmitTo(uuid, message)
}
}
// EmitTo Emit to a specific socket connection
func (kws *Websocket) EmitTo(uuid string, message []byte) error {
if !pool.contains(uuid) || !pool.get(uuid).IsAlive() {
kws.fireEvent(EventError, []byte(uuid), ErrorInvalidConnection)
return ErrorInvalidConnection
}
pool.get(uuid).Emit(message)
return nil
}
// EmitTo Emit to a specific socket connection
func EmitTo(uuid string, message []byte) error {
if !pool.contains(uuid) {
return ErrorInvalidConnection
}
if !pool.get(uuid).IsAlive() {
return ErrorInvalidConnection
}
pool.get(uuid).Emit(message)
return nil
}
// Broadcast to all the active connections
// except avoid broadcasting the message to itself
func (kws *Websocket) Broadcast(message []byte, except bool) {
for uuid := range pool.all() {
if except && kws.UUID == uuid {
continue
}
err := kws.EmitTo(uuid, message)
if err != nil {
kws.fireEvent(EventError, message, err)
}
}
}
// Broadcast to all the active connections
func Broadcast(message []byte) {
for _, kws := range pool.all() {
kws.Emit(message)
}
}
// Fire custom event
func (kws *Websocket) Fire(event string, data []byte) {
kws.fireEvent(event, data, nil)
}
// Fire custom event on all connections
func Fire(event string, data []byte) {
fireGlobalEvent(event, data, nil)
}
// Emit Emit/Write the message into the given connection
func (kws *Websocket) Emit(message []byte) {
kws.write(TextMessage, message)
}
// Close Actively close the connection from the server
func (kws *Websocket) Close() {
kws.write(CloseMessage, []byte("Connection closed"))
kws.fireEvent(EventClose, nil, nil)
}
func (kws *Websocket) IsAlive() bool {
kws.mu.RLock()
defer kws.mu.RUnlock()
return kws.isAlive
}
func (kws *Websocket) hasConn() bool {
kws.mu.RLock()
defer kws.mu.RUnlock()
return kws.ws.Conn != nil
}
func (kws *Websocket) setAlive(alive bool) {
kws.mu.Lock()
defer kws.mu.Unlock()
kws.isAlive = alive
}
func (kws *Websocket) queueLength() int {
kws.mu.RLock()
defer kws.mu.RUnlock()
return len(kws.queue)
}
// pong writes a control message to the client
func (kws *Websocket) pong(ctx context.Context) {
timeoutTicker := time.Tick(PongTimeout)
for {
select {
case <- timeoutTicker:
kws.write(PongMessage, []byte{})
case <-ctx.Done():
return
}
}
}
// Add in message queue
func (kws *Websocket) write(messageType int, messageBytes []byte) {
kws.queue <- message{
mType: messageType,
data: messageBytes,
retries: 0,
}
}
// Send out message queue
func (kws *Websocket) send(ctx context.Context) {
for {
select {
case message := <-kws.queue:
if !kws.hasConn() {
if message.retries <= MaxSendRetry {
// retry without blocking the sending thread
go func() {
time.Sleep(RetrySendTimeout)
message.retries = message.retries + 1
kws.queue <- message
}()
}
continue
}
kws.mu.RLock()
err := kws.ws.WriteMessage(message.mType, message.data)
kws.mu.RUnlock()
if err != nil {
kws.disconnected(err)
}
case <-ctx.Done():
return
}
}
}
// Start Pong/Read/Write functions
//
// Needs to be blocking, otherwise the connection would close.
func (kws *Websocket) run() {
ctx, cancelFunc := context.WithCancel(context.Background())
go kws.pong(ctx)
go kws.read(ctx)
go kws.send(ctx)
<-kws.done // block until one event is sent to the done channel
cancelFunc()
}
// Listen for incoming messages
// and filter by message type
func (kws *Websocket) read(ctx context.Context) {
timeoutTicker := time.Tick(ReadTimeout)
for {
select {
case <- timeoutTicker:
if !kws.hasConn() {
continue
}
kws.mu.RLock()
mtype, msg, err := kws.ws.ReadMessage()
kws.mu.RUnlock()
if mtype == PingMessage {
kws.fireEvent(EventPing, nil, nil)
continue
}
if mtype == PongMessage {
kws.fireEvent(EventPong, nil, nil)
continue
}
if mtype == CloseMessage {
kws.disconnected(nil)
return
}
if err != nil {
kws.disconnected(err)
return
}
// We have a message and we fire the message event
kws.fireEvent(EventMessage, msg, nil)
case <-ctx.Done():
return
}
}
}
// When the connection closes, disconnected method
func (kws *Websocket) disconnected(err error) {
kws.fireEvent(EventDisconnect, nil, err)
// may be called multiple times from different go routines
if kws.IsAlive() {
close(kws.done)
}
kws.setAlive(false)
// Fire error event if the connection is
// disconnected by an error
if err != nil {
kws.fireEvent(EventError, nil, err)
}
// Remove the socket from the pool
pool.delete(kws.UUID)
}
// Create random UUID for each connection
func (kws *Websocket) createUUID() string {
uuid := kws.randomUUID()
//make sure about the uniqueness of the uuid
if pool.contains(uuid) {
return kws.createUUID()
}
return uuid
}
//TODO implement Google UUID library instead of random string
func (kws *Websocket) randomUUID() string {
length := 100
seed := rand.New(rand.NewSource(time.Now().UnixNano()))
charset := "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"
b := make([]byte, length)
for i := range b {
b[i] = charset[seed.Intn(len(charset))]
}
return string(b)
}
// Fires event on all connections.
func fireGlobalEvent(event string, data []byte, error error) {
for _, kws := range pool.all() {
kws.fireEvent(event, data, error)
}
}
// Checks if there is at least a listener for a given event
// and loop over the callbacks registered
func (kws *Websocket) fireEvent(event string, data []byte, error error) {
callbacks := listeners.get(event)
for _, callback := range callbacks {
callback(&EventPayload{
Kws: kws,
Name: event,
SocketUUID: kws.UUID,
SocketAttributes: kws.attributes,
Data: data,
Error: error,
})
}
}
type eventCallback func(payload *EventPayload)
// On Add listener callback for an event into the listeners list
func On(event string, callback eventCallback) {
listeners.set(event, callback)
}