/
client.go
718 lines (613 loc) · 18.9 KB
/
client.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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
package gateway
import (
"context"
"errors"
"fmt"
"math/rand"
"net/http"
"sync"
"time"
"github.com/andersfylling/disgord/internal/gateway/opcode"
"github.com/andersfylling/disgord/internal/logger"
"github.com/andersfylling/disgord/json"
"go.uber.org/atomic"
)
type ClientType int
const (
clientTypeEvent ClientType = iota
clientTypeVoice
)
// Link is used to establish basic commands to create and destroy a link.
// See client.Disconnect() and client.Connect() for linking to the Discord servers
type Link interface {
Connect() error
Disconnect() error
}
//////////////////////////////////////////////////////
//
// synchronization & rate limiting
// By default, no such restrictions exist
//
//////////////////////////////////////////////////////
type connectQueue = func(shardID uint, cb func() error) error
type connectSignature = func() (evt interface{}, err error)
type discordErrListener = func(code int, reason string)
// newClient ...
func newClient(shardID uint, conf *config, connect connectSignature) (c *client, err error) {
var ws Conn
if conf.conn == nil {
ws, err = newConn(conf.HTTPClient)
if err != nil {
return nil, err
}
} else {
ws = conf.conn
}
var queueLimit int
if conf.messageQueueLimit == 0 {
queueLimit = 20
} else {
queueLimit = int(conf.messageQueueLimit)
}
c = &client{
conf: conf,
ShardID: shardID,
receiveChan: make(chan *DiscordPacket, 50),
internalEmitChan: make(chan *clientPacket, 50),
emitChan: make(chan *clientPacket, 50),
conn: ws,
ratelimit: newRatelimiter(),
timeoutMultiplier: 1,
log: conf.Logger,
behaviors: map[string]*behavior{},
poolDiscordPkt: conf.DiscordPktPool,
onceChannels: newOnceChannels(),
connect: connect,
messageQueue: newClientPktQueue(queueLimit),
activateHeartbeats: make(chan interface{}),
SystemShutdown: conf.SystemShutdown,
}
c.isConnected.Store(false)
return
}
type config struct {
HTTPClient *http.Client
// for testing only
conn Conn
// Endpoint for establishing socket connection. Either endpoints, `Gateway` or `Gateway Bot`, is used to retrieve
// a valid socket endpoint from Discord
Endpoint string
DiscordPktPool *sync.Pool
Logger logger.Logger
discordErrListener discordErrListener
// messageQueueLimit number of outgoing messages that can be queued and sent correctly.
messageQueueLimit uint
SystemShutdown chan interface{}
}
// client can be used as a base for other ws clients; voice, event. Note the use of
// client.ReleasePermit() and client.RequestPermit() in Connect (and then automatically reconnect()).
// these are used for synchronizing connecting and you must therefore correctly release the permit once you have
// such that the next shard or yourself can Connect in the future.
//
// If you do not care about these. Please overwrite both methods.
type client struct {
sync.RWMutex
clientType ClientType
conf *config
lastRestart atomic.Int64 // unix nano
pulsating uint8
pulseMutex sync.Mutex
heartbeatLatency time.Duration
heartbeatInterval uint
lastHeartbeatAck time.Time
lastHeartbeatSent time.Time
activateHeartbeats chan interface{}
ShardID uint
// sending and receiving data
ratelimit ratelimiter
receiveChan chan *DiscordPacket
internalEmitChan chan *clientPacket
emitChan chan *clientPacket
conn Conn
messageQueue clientPktQueue
// connect is blocking until a websocket connection has completed it's setup.
// eg. Normal shards that handles events are considered connected once the
// identity/resume has been sent. While for voice we wait until a ready event
// is returned.
connect connectSignature
// states
isConnected atomic.Bool
haveConnectedOnce atomic.Bool
isReconnecting atomic.Bool
isReceiving atomic.Bool // has the go routine started
isEmitting atomic.Bool // has the go routine started
onceChannels onceChannels
isRestarting atomic.Bool
// identify timeout on invalid session
// useful in unit tests when you want to drop any actual timeouts
timeoutMultiplier int
// ChannelBuffer is used to set the event channel buffer
ChannelBuffer uint
log logger.Logger
logSequence atomic.Uint32 // ARM 32bit causes panic with 64bit
// behaviours - optional
behaviors map[string]*behavior
poolDiscordPkt *sync.Pool
cancel context.CancelFunc
SystemShutdown <-chan interface{}
// receiver gets closed when the connection is lost
requestedDisconnect atomic.Bool
}
type behaviorActions map[interface{}]actionFunc
type actionFunc func(interface{}) error
type behavior struct {
addresses string
actions behaviorActions
}
func (c *client) addBehavior(b *behavior) {
c.behaviors[b.addresses] = b
}
const (
discordOperations string = "discord-ops"
discordCloseOperations string = "discord-closed-ops"
heartbeating string = "heartbeats"
sendHeartbeat = 0
)
func (c *client) startBehaviors(ctx context.Context) {
for k := range c.behaviors {
switch k {
case discordOperations:
go c.operationHandlers(ctx)
}
}
}
// operation handler de-multiplexer
func (c *client) operationHandlers(ctx context.Context) {
c.log.Debug(c.getLogPrefix(), "Ready to receive operation codes...")
for {
var p *DiscordPacket
var open bool
select {
case p, open = <-c.receive():
if !open {
c.log.Debug(c.getLogPrefix(), "operationChan is dead..")
return
}
case <-ctx.Done():
c.log.Debug(c.getLogPrefix(), "closing operations handler")
return
}
if action, defined := c.behaviors[discordOperations].actions[p.Op]; defined {
if err := action(p); err != nil {
c.log.Error(c.getLogPrefix(), err)
}
} else {
c.log.Debug(c.getLogPrefix(), "tried calling undefined discord operation", p.Op)
}
// see receiver() for creation/Get()
c.poolDiscordPkt.Put(p)
}
}
func (c *client) inactivityDetector() {
// make sure that websocket is connecting, connect or reconnecting.
}
//////////////////////////////////////////////////////
//
// LOGGING
//
//////////////////////////////////////////////////////
func (c *client) getLogPrefix() string {
var t string
if c.clientType == clientTypeVoice {
t += "v"
} else if c.clientType == clientTypeEvent {
t += "e"
} else {
t += "?"
}
nr := c.logSequence.Add(1)
return fmt.Sprintf("[ws-%s,s:%d,shard:%d]", t, nr, c.ShardID)
}
// ////////////////////////////////////////////////////
//
// LINKING: CONNECTING / DISCONNECTING / RECONNECTING
//
// ////////////////////////////////////////////////////
func (c *client) IsDisconnected() bool {
return !c.isConnected.Load()
}
func (c *client) disconnect() (err error) {
c.Lock()
defer c.Unlock()
alreadyDisconnected := c.conn.Disconnected() || !c.haveConnectedOnce.Load() || c.cancel == nil
// stop emitter, receiver and behaviors
if c.cancel != nil {
c.cancel()
c.cancel = nil
}
// use the emitter to dispatch the close message
err = c.conn.Close()
// a typical err here is that the pipe is closed. Err is returned later
// c.Emit(event.Close, nil)
// dont use emit, such that we can call shutdown at the same time as Disconnect (See Shutdown())
c.isConnected.Store(false)
if alreadyDisconnected {
return errors.New("already disconnected")
}
c.log.Info(c.getLogPrefix(), "disconnected")
return err
}
// Disconnect disconnects the socket connection
func (c *client) Disconnect() (err error) {
c.requestedDisconnect.Store(true)
return c.disconnect()
}
func (c *client) reconnect() (err error) {
if !c.isReconnecting.CAS(false, true) {
return
}
c.lastRestart.Store(time.Now().UnixNano())
defer c.isReconnecting.Store(false)
c.log.Debug(c.getLogPrefix(), "is reconnecting")
if err := c.disconnect(); err != nil {
c.log.Debug(c.getLogPrefix(), "reconnecting failed: ", err.Error())
c.RLock()
if c.requestedDisconnect.Load() {
c.RUnlock()
c.log.Debug(c.getLogPrefix(), err)
return errors.New("already disconnected, cannot reconnect")
}
c.RUnlock()
}
return c.reconnectLoop()
}
func (c *client) reconnectLoop() (err error) {
var try uint
var delay = 3 * time.Second
for {
if try == 0 {
c.log.Debug(c.getLogPrefix(), "trying to connect")
} else {
c.log.Debug(c.getLogPrefix(), "reconnect attempt ", try)
}
if _, err = c.connect(); err == nil {
c.log.Debug(c.getLogPrefix(), "establishing connection succeeded")
break
}
c.log.Error(c.getLogPrefix(), "establishing connection failed: ", err)
c.log.Info(c.getLogPrefix(), "next connection attempt in ", delay)
// wait N seconds
select {
case <-time.After(delay):
delay += (4 + time.Duration(try*2)) * time.Second
case <-c.SystemShutdown:
c.log.Debug(c.getLogPrefix(), "stopping reconnect attempt", try)
return
}
if delay > 5*60*time.Second {
delay = 60 * time.Second
}
}
return
}
//////////////////////////////////////////////////////
//
// EMITTING / DISPATCHING
//
//////////////////////////////////////////////////////
// Emit is used by Disgord users for dispatching a socket command to the Discord Gateway.
func (c *client) Emit(command string, data CmdPayload) (err error) {
return c.queueRequest(command, data)
}
func (c *client) queueRequest(command string, data CmdPayload) (err error) {
if !c.haveConnectedOnce.Load() {
return errors.New("race condition detected: you must Connect to the socket API/Gateway before you can send gateway commands: " + command)
}
op := CmdNameToOpCode(command, c.clientType)
if op == opcode.None {
return errors.New("unsupported command: " + command)
}
p := &clientPacket{
Op: op,
Data: data,
CmdName: command,
}
if accepted := c.ratelimit.Request(command); !accepted {
// we might be rate limited.. but lets see if there is another
// presence update in the queue; then it can be overwritten
if err := c.messageQueue.AddByOverwrite(p); err != nil {
return errors.New("rate limited")
} else {
return nil
}
}
return c.messageQueue.Add(p)
}
func (c *client) emit(command string, data interface{}) (err error) {
if !c.haveConnectedOnce.Load() {
return errors.New("race condition detected: you must Connect to the socket API/Gateway before you can send gateway commands: " + command)
}
c.internalEmitChan <- &clientPacket{
Op: CmdNameToOpCode(command, c.clientType),
Data: data,
CmdName: command,
}
return nil
}
// emitter holds the actually dispatching logic for sending data to the Discord Gateway.
// client#Emit depends on this.
func (c *client) emitter(ctx context.Context) {
if !c.isEmitting.CAS(false, true) {
return
}
defer c.isEmitting.Store(false)
c.log.Debug(c.getLogPrefix(), "starting emitter")
internal, cancel := context.WithCancel(context.Background())
once := sync.Once{}
write := func(msg *clientPacket) error {
// save to file
// build tag: disgord_diagnosews
saveOutgoingPacket(c, msg)
if err := c.conn.WriteJSON(msg); err != nil {
once.Do(cancel)
return err
}
return nil
}
for {
var insight string
var err error
select {
case <-ctx.Done():
c.log.Debug(c.getLogPrefix(), "closing emitter")
once.Do(cancel)
return
case <-internal.Done():
c.log.Debug(c.getLogPrefix(), "closing emitter after write error")
go c.reconnect()
return
case <-time.After(300 * time.Millisecond): // TODO: don't use fixed timeout
if !c.messageQueue.IsEmpty() {
// try to write the message
// on failure the message is put back into the queue
err = c.messageQueue.Try(write)
}
case msg, open := <-c.internalEmitChan:
if !open {
err = errors.New("emitter channel is closed")
} else if err = write(msg); err != nil {
insight = fmt.Sprintf("%v", *msg)
}
}
if err != nil {
c.log.Error(c.getLogPrefix(), err, insight)
}
}
}
//////////////////////////////////////////////////////
//
// RECEIVING
//
//////////////////////////////////////////////////////
// Receive returns the channel for receiving Discord packets
func (c *client) receive() <-chan *DiscordPacket {
return c.receiveChan
}
func (c *client) receiver(ctx context.Context) {
if !c.isReceiving.CAS(false, true) {
return
}
defer c.isReceiving.Store(false)
c.log.Debug(c.getLogPrefix(), "starting receiver")
var noopCounter int
internal, cancel := context.WithCancel(context.Background())
once := sync.Once{}
for {
// check if application has closed
// and clean up
select {
case <-ctx.Done():
c.log.Debug(c.getLogPrefix(), "closing receiver")
once.Do(cancel) // free
return
case <-internal.Done():
c.log.Debug(c.getLogPrefix(), "closing receiver after read error")
go func() {
if err := c.reconnect(); err != nil {
c.log.Error(c.getLogPrefix(), "reconnecting attempt failed: ", err.Error())
}
}()
return
default:
}
var packet []byte
var err error
if packet, err = c.conn.Read(ctx); err != nil {
if !errors.Is(err, context.Canceled) && ctx.Err() != nil {
c.log.Debug(c.getLogPrefix(), "read error: ", err.Error())
}
reconnect := true
var closeErr *CloseErr
isCloseErr := errors.As(err, &closeErr)
if isCloseErr {
if c.conf.discordErrListener != nil && closeErr.code >= 4000 && closeErr.code < 5000 {
go c.conf.discordErrListener(closeErr.code, closeErr.info)
}
if c.clientType == clientTypeEvent {
switch closeErr.code {
case 4008:
c.log.Error(c.getLogPrefix(), "Woah nelly! You're sending payloads to us too quickly. Slow it down! You will be disconnected on receiving this.")
_ = c.Disconnect()
case 4010:
c.log.Error(c.getLogPrefix(), "You sent us an invalid shard when identifying.")
_ = c.Disconnect()
close(c.receiveChan) // notify client
reconnect = false
case 4013:
c.log.Error(c.getLogPrefix(), "you sent an invalid intent for a Gateway Intent. You may have incorrectly calculated the bitwise value.")
_ = c.Disconnect()
close(c.receiveChan) // notify client
reconnect = false
case 4014:
c.log.Error(c.getLogPrefix(), "you sent a disallowed intent for a Gateway Intent. You may have tried to specify an intent that you have not enabled or are not whitelisted for.")
_ = c.Disconnect()
close(c.receiveChan) // notify client
reconnect = false
default:
}
} else if c.clientType == clientTypeVoice {
if handler, defined := c.behaviors[discordCloseOperations].actions[closeErr.code]; defined {
if err := handler(closeErr); err != nil {
c.log.Error(c.getLogPrefix(), "did not properly handle close operation: ", closeErr)
}
}
switch closeErr.code {
case 4006:
// session is no longer valid, and should do a normal identify
c.log.Debug(c.getLogPrefix(), "discord sent a 4006 websocket code and the bot will now reconnect")
_ = c.Disconnect()
case 4014:
// Disconnected: Either the channel was deleted or you were kicked. Should not reconnect.
// https://discord.com/developers/docs/topics/opcodes-and-status-codes#voice-voice-close-event-codes
c.log.Debug(c.getLogPrefix(), "discord sent a 4014 websocket code and the bot will now disconnect")
_ = c.Disconnect()
close(c.receiveChan) // notify client
reconnect = false
default:
}
}
}
select {
case <-ctx.Done():
// in this case we dont want reconnect to start, only to stop
default:
if reconnect {
once.Do(cancel)
}
}
continue
}
// parse to gateway payload object
// see operationHandler for return/Put()
evt := c.poolDiscordPkt.Get().(*DiscordPacket)
evt.reset()
//err = evt.UnmarshalJSON(packet) // custom unmarshal
if err = json.Unmarshal(packet, evt); err != nil {
c.log.Error(c.getLogPrefix(), err, "SKIPPED ERRONEOUS PACKET CONTENT:", string(packet))
c.poolDiscordPkt.Put(evt)
// noop
if noopCounter >= 10 {
c.log.Error(c.getLogPrefix(), "json unmarshal failed 10 times for this shard and reconnect is now forced")
once.Do(cancel) // on 10 continuous errors, we just force a reconnect
}
noopCounter++
continue
} else {
noopCounter = 0
}
// save to file
// build tag: disgord_diagnosews
saveIncomingPacker(c, evt, packet)
// notify listeners
c.receiveChan <- evt
}
}
//////////////////////////////////////////////////////
//
// HEARTBEAT / PULSATING
//
//////////////////////////////////////////////////////
// AllowedToStartPulsating you must notify when you are done pulsating!
func (c *client) AllowedToStartPulsating(serviceID uint8) bool {
c.pulseMutex.Lock()
defer c.pulseMutex.Unlock()
if c.pulsating == 0 {
c.pulsating = serviceID
}
return c.pulsating == serviceID
}
// StopPulsating stops sending heartbeats to Discord
func (c *client) StopPulsating(serviceID uint8) {
c.pulseMutex.Lock()
defer c.pulseMutex.Unlock()
if c.pulsating == serviceID {
c.pulsating = 0
}
}
func (c *client) prepareHeartbeating(ctx context.Context) {
serviceID := uint8(rand.Intn(254) + 1) // uint8 cap
if !c.AllowedToStartPulsating(serviceID) {
c.log.Debug(c.getLogPrefix(), "tried to start an additional pulse")
return
}
defer c.StopPulsating(serviceID)
select {
case <-ctx.Done():
c.log.Debug(c.getLogPrefix(), "heartbeat preparations cancelled")
return
case <-c.activateHeartbeats:
}
c.pulsate(ctx)
}
func (c *client) pulsate(ctx context.Context) {
c.RLock()
c.lastHeartbeatSent = time.Now()
c.lastHeartbeatAck = time.Now()
interval := time.Millisecond * time.Duration(c.heartbeatInterval)
c.RUnlock()
ticker := time.NewTicker(interval)
defer ticker.Stop()
var lastAck time.Time
var lastSent time.Time
for {
c.RLock()
lastAck = c.lastHeartbeatAck
lastSent = c.lastHeartbeatSent
c.RUnlock()
// make sure that Discord replied to the last heartbeat signal (heartbeat ack)
if lastSent.After(lastAck) {
c.log.Info(c.getLogPrefix(), "heartbeat ACK was not received, forcing reconnect")
go c.reconnect()
break
} else {
c.log.Debug(c.getLogPrefix(), "heartbeat ACK ok")
}
// update heartbeat latency record & send new heartbeat signal
c.Lock()
c.heartbeatLatency = lastAck.Sub(lastSent)
c.lastHeartbeatSent = time.Now()
c.Unlock()
if err := c.behaviors[heartbeating].actions[sendHeartbeat](nil); err != nil {
c.log.Error(c.getLogPrefix(), err)
} else {
c.log.Debug(c.getLogPrefix(), "sent heartbeat")
}
select {
case <-ticker.C:
// in case there is a race between when the ticker was started and the
// heartbeat interval was updated
c.RLock()
interval2 := time.Millisecond * time.Duration(c.heartbeatInterval)
if interval != interval2 {
ticker.Stop()
interval = interval2
ticker = time.NewTicker(interval)
}
c.RUnlock()
continue
case <-ctx.Done():
}
break
}
c.log.Debug(c.getLogPrefix(), "stopping pulse")
}
// HeartbeatLatency get the time diff between sending a heartbeat and Discord replying with a heartbeat ack
func (c *client) HeartbeatLatency() (duration time.Duration, err error) {
c.RLock()
defer c.RUnlock()
duration = c.heartbeatLatency
if duration == 0 {
err = errors.New("latency not determined yet")
}
return
}