-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdshardmanager.go
578 lines (468 loc) · 12.5 KB
/
dshardmanager.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
package dshardmanager
import (
"fmt"
"github.com/bwmarrin/discordgo"
"github.com/pkg/errors"
"log"
"strconv"
"strings"
"sync"
"time"
)
const (
VersionMajor = 0
VersionMinor = 2
VersionPath = 0
)
var (
VersionString = strconv.Itoa(VersionMajor) + "." + strconv.Itoa(VersionMinor) + "." + strconv.Itoa(VersionPath)
)
type SessionFunc func(token string) (*discordgo.Session, error)
type Manager struct {
sync.RWMutex
// Name of the bot, to appear before log messages as a prefix
// and in the title of the updated status message
Name string
// All the shard sessions
Sessions []*discordgo.Session
eventHandlers []interface{}
// If set logs connection status events to this channel
LogChannel string
// If set keeps an updated satus message in this channel
StatusMessageChannel string
// The function that provides the guild counts per shard, used fro the updated status message
// Should return a slice of guild counts, with the index being the shard number
GuildCountsFunc func() []int
// Called on events, by default this is set to a function that logs it to log.Printf
// You can override this if you want another behaviour, or just set it to nil for nothing.
OnEvent func(e *Event)
// SessionFunc creates a new session and returns it, override the default one if you have your own
// session settings to apply
SessionFunc SessionFunc
nextStatusUpdate time.Time
statusUpdaterStarted bool
numShards int
token string
bareSession *discordgo.Session
started bool
}
// New creates a new shard manager with the defaults set, after you have created this you call Manager.Start
// To start connecting
// dshardmanager.New("Bot asd", OptLogChannel(someChannel), OptLogEventsToDiscord(true, true))
func New(token string) *Manager {
// Setup defaults
manager := &Manager{
token: token,
numShards: -1,
}
manager.OnEvent = manager.LogConnectionEventStd
manager.SessionFunc = manager.StdSessionFunc
manager.bareSession, _ = discordgo.New(token)
return manager
}
// GetRecommendedCount gets the recommended sharding count from discord, this will also
// set the shard count internally if called
// Should not be called after calling Start(), will have undefined behaviour
func (m *Manager) GetRecommendedCount() (int, error) {
resp, err := m.bareSession.GatewayBot()
if err != nil {
return 0, errors.WithMessage(err, "GetRecommendedCount()")
}
m.numShards = resp.Shards
if m.numShards < 1 {
m.numShards = 1
}
return m.numShards, nil
}
// GetNumShards returns the current set number of shards
func (m *Manager) GetNumShards() int {
return m.numShards
}
// SetNumShards sets the number of shards to use, if you want to override the recommended count
// Should not be called after calling Start(), will panic
func (m *Manager) SetNumShards(n int) {
m.Lock()
defer m.Unlock()
if m.started {
panic("Can't set num shard after started")
}
m.numShards = n
}
// Adds an event handler to all shards
// All event handlers will be added to new sessions automatically.
func (m *Manager) AddHandler(handler interface{}) {
m.Lock()
defer m.Unlock()
m.eventHandlers = append(m.eventHandlers, handler)
if len(m.Sessions) > 0 {
for _, v := range m.Sessions {
v.AddHandler(handler)
}
}
}
// Init initializesthe manager, retreiving the recommended shard count if needed
// and initalizes all the shards
func (m *Manager) Init() error {
m.Lock()
if m.numShards < 1 {
_, err := m.GetRecommendedCount()
if err != nil {
return errors.WithMessage(err, "Start")
}
}
m.Sessions = make([]*discordgo.Session, m.numShards)
for i := 0; i < m.numShards; i++ {
err := m.initSession(i)
if err != nil {
m.Unlock()
return errors.WithMessage(err, "initSession")
}
}
if !m.statusUpdaterStarted {
m.statusUpdaterStarted = true
go m.statusRoutine()
}
m.nextStatusUpdate = time.Now()
m.Unlock()
return nil
}
// Start starts the shard manager, opening all gateway connections
func (m *Manager) Start() error {
m.Lock()
if m.Sessions == nil {
m.Unlock()
err := m.Init()
if err != nil {
return err
}
m.Lock()
}
m.Unlock()
for i := 0; i < m.numShards; i++ {
if i != 0 {
// One indentify every 5 seconds
time.Sleep(time.Second * 5)
}
m.Lock()
err := m.startSession(i)
m.Unlock()
if err != nil {
return errors.WithMessage(err, fmt.Sprintf("Failed starting shard %d", i))
}
}
return nil
}
// StopAll stops all the shard sessions and returns the last error that occured
func (m *Manager) StopAll() (err error) {
m.Lock()
for _, v := range m.Sessions {
if e := v.Close(); e != nil {
err = e
}
}
m.Unlock()
return
}
func (m *Manager) initSession(shard int) error {
session, err := m.SessionFunc(m.token)
if err != nil {
return errors.WithMessage(err, "startSession.SessionFunc")
}
session.ShardCount = m.numShards
session.ShardID = shard
session.AddHandler(m.OnDiscordConnected)
session.AddHandler(m.OnDiscordDisconnected)
session.AddHandler(m.OnDiscordReady)
session.AddHandler(m.OnDiscordResumed)
// Add the user event handlers retroactively
for _, v := range m.eventHandlers {
session.AddHandler(v)
}
m.Sessions[shard] = session
return nil
}
func (m *Manager) startSession(shard int) error {
err := m.Sessions[shard].Open()
if err != nil {
return errors.Wrap(err, "startSession.Open")
}
m.handleEvent(EventOpen, shard, "")
return nil
}
// SessionForGuildS is the same as SessionForGuild but accepts the guildID as a string for convenience
func (m *Manager) SessionForGuildS(guildID string) *discordgo.Session {
// Question is, should we really ignore this error?
// In reality, the guildID should never be invalid but...
parsed, _ := strconv.ParseInt(guildID, 10, 64)
return m.SessionForGuild(parsed)
}
// SessionForGuild returns the session for the specified guild
func (m *Manager) SessionForGuild(guildID int64) *discordgo.Session {
// (guild_id >> 22) % num_shards == shard_id
// That formula is taken from the sharding issue on the api docs repository on github
m.RLock()
defer m.RUnlock()
shardID := (guildID >> 22) % int64(m.numShards)
return m.Sessions[shardID]
}
// Session retrieves a session from the sessions map, rlocking it in the process
func (m *Manager) Session(shardID int) *discordgo.Session {
m.RLock()
defer m.RUnlock()
return m.Sessions[shardID]
}
// LogConnectionEventStd is the standard connection event logger, it logs it to whatever log.output is set to.
func (m *Manager) LogConnectionEventStd(e *Event) {
log.Printf("[Shard Manager] %s", e.String())
}
func (m *Manager) handleError(err error, shard int, msg string) bool {
if err == nil {
return false
}
m.handleEvent(EventError, shard, msg+": "+err.Error())
return true
}
func (m *Manager) handleEvent(typ EventType, shard int, msg string) {
if m.OnEvent == nil {
return
}
evt := &Event{
Type: typ,
Shard: shard,
NumShards: m.numShards,
Msg: msg,
Time: time.Now(),
}
go m.OnEvent(evt)
if m.LogChannel != "" {
go m.logEventToDiscord(evt)
}
go func() {
m.Lock()
m.nextStatusUpdate = time.Now().Add(time.Second * 2)
m.Unlock()
}()
}
// StdSessionFunc is the standard session provider, it does nothing to the actual session
func (m *Manager) StdSessionFunc(token string) (*discordgo.Session, error) {
s, err := discordgo.New(token)
if err != nil {
return nil, errors.WithMessage(err, "StdSessionFunc")
}
return s, nil
}
func (m *Manager) logEventToDiscord(evt *Event) {
if evt.Type == EventError {
return
}
prefix := ""
if m.Name != "" {
prefix = m.Name + ": "
}
str := evt.String()
embed := &discordgo.MessageEmbed{
Description: prefix + str,
Timestamp: evt.Time.Format(time.RFC3339),
Color: eventColors[evt.Type],
}
_, err := m.bareSession.ChannelMessageSendEmbed(m.LogChannel, embed)
m.handleError(err, evt.Shard, "Failed sending event to discord")
}
func (m *Manager) statusRoutine() {
if m.StatusMessageChannel == "" {
return
}
mID := ""
// Find the initial message id and reuse that message if found
msgs, err := m.bareSession.ChannelMessages(m.StatusMessageChannel, 50, "", "", "")
if err != nil {
m.handleError(err, -1, "Failed requesting message history in channel")
} else {
for _, msg := range msgs {
// Dunno our own bot id so best we can do is bot
if !msg.Author.Bot || len(msg.Embeds) < 1 {
continue
}
nameStr := ""
if m.Name != "" {
nameStr = " for " + m.Name
}
embed := msg.Embeds[0]
if embed.Title == "Sharding status"+nameStr {
// Found it sucessfully
mID = msg.ID
break
}
}
}
ticker := time.NewTicker(time.Second)
for {
select {
case <-ticker.C:
m.RLock()
after := time.Now().After(m.nextStatusUpdate)
m.RUnlock()
if after {
m.Lock()
m.nextStatusUpdate = time.Now().Add(time.Minute)
m.Unlock()
nID, err := m.updateStatusMessage(mID)
if !m.handleError(err, -1, "Failed updating status message") {
mID = nID
}
}
}
}
}
func (m *Manager) updateStatusMessage(mID string) (string, error) {
content := ""
status := m.GetFullStatus()
for _, shard := range status.Shards {
emoji := ""
if !shard.Started {
emoji = "🕒"
} else if shard.OK {
emoji = "👌"
} else {
emoji = "🔥"
}
content += fmt.Sprintf("[%d/%d]: %s (%d,%d)\n", shard.Shard, m.numShards, emoji, shard.NumGuilds, status.NumGuilds)
}
nameStr := ""
if m.Name != "" {
nameStr = " for " + m.Name
}
embed := &discordgo.MessageEmbed{
Title: "Sharding status" + nameStr,
Description: content,
Color: 0x4286f4,
Timestamp: time.Now().Format(time.RFC3339),
}
if mID == "" {
msg, err := m.bareSession.ChannelMessageSendEmbed(m.StatusMessageChannel, embed)
if err != nil {
return "", err
}
return msg.ID, err
}
_, err := m.bareSession.ChannelMessageEditEmbed(m.StatusMessageChannel, mID, embed)
return mID, err
}
// GetFullStatus retrieves the full status at this instant
func (m *Manager) GetFullStatus() *Status {
var shardGuilds []int
if m.GuildCountsFunc != nil {
shardGuilds = m.GuildCountsFunc()
} else {
shardGuilds = m.StdGuildCountsFunc()
}
m.RLock()
result := make([]*ShardStatus, len(m.Sessions))
for i, shard := range m.Sessions {
result[i] = &ShardStatus{
Shard: i,
}
if shard != nil {
result[i].Started = true
shard.RLock()
result[i].OK = shard.DataReady
shard.RUnlock()
}
}
m.RUnlock()
totalGuilds := 0
for shard, guilds := range shardGuilds {
totalGuilds += guilds
result[shard].NumGuilds = guilds
}
return &Status{
Shards: result,
NumGuilds: totalGuilds,
}
}
// StdGuildsFunc uses the standard states to return the guilds
func (m *Manager) StdGuildCountsFunc() []int {
m.RLock()
nShards := m.numShards
result := make([]int, nShards)
for i, session := range m.Sessions {
if session == nil {
continue
}
session.State.RLock()
result[i] = len(session.State.Guilds)
session.State.RUnlock()
}
m.RUnlock()
return result
}
type Status struct {
Shards []*ShardStatus `json:"shards"`
NumGuilds int `json:"num_guilds"`
}
type ShardStatus struct {
Shard int `json:"shard"`
OK bool `json:"ok"`
Started bool `json:"started"`
NumGuilds int `json:"num_guilds"`
}
// Event holds data for an event
type Event struct {
Type EventType
Shard int
NumShards int
Msg string
// When this event occured
Time time.Time
}
func (c *Event) String() string {
prefix := ""
if c.Shard > -1 {
prefix = fmt.Sprintf("[%d/%d] ", c.Shard, c.NumShards)
}
s := fmt.Sprintf("%s%s", prefix, strings.Title(c.Type.String()))
if c.Msg != "" {
s += ": " + c.Msg
}
return s
}
type EventType int
const (
// Sent when the connection to the gateway was established
EventConnected EventType = iota
// Sent when the connection is lose
EventDisconnected
// Sent when the connection was sucessfully resumed
EventResumed
// Sent on ready
EventReady
// Sent when Open() is called
EventOpen
// Sent when Close() is called
EventClose
// Sent when an error occurs
EventError
)
var (
eventStrings = map[EventType]string{
EventOpen: "opened",
EventClose: "closed",
EventConnected: "connected",
EventDisconnected: "disconnected",
EventResumed: "resumed",
EventReady: "ready",
EventError: "error",
}
eventColors = map[EventType]int{
EventOpen: 0xec58fc,
EventClose: 0xff7621,
EventConnected: 0x54d646,
EventDisconnected: 0xcc2424,
EventResumed: 0x5985ff,
EventReady: 0x00ffbf,
EventError: 0x7a1bad,
}
)
func (c EventType) String() string {
return eventStrings[c]
}