/
shard_manager_impl.go
195 lines (166 loc) · 5.88 KB
/
shard_manager_impl.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
package sharding
import (
"context"
"errors"
"fmt"
"log/slog"
"sync"
"github.com/disgoorg/snowflake/v2"
"github.com/gorilla/websocket"
"github.com/disgoorg/disgo/gateway"
)
var _ ShardManager = (*shardManagerImpl)(nil)
// New creates a new default ShardManager with the given token, eventHandlerFunc and ConfigOpt(s).
func New(token string, eventHandlerFunc gateway.EventHandlerFunc, opts ...ConfigOpt) ShardManager {
config := DefaultConfig()
config.Apply(opts)
config.Logger = config.Logger.With(slog.String("name", "sharding"))
return &shardManagerImpl{
shards: map[int]gateway.Gateway{},
token: token,
eventHandlerFunc: eventHandlerFunc,
config: *config,
}
}
type shardManagerImpl struct {
shards map[int]gateway.Gateway
shardsMu sync.Mutex
token string
eventHandlerFunc gateway.EventHandlerFunc
config Config
}
func (m *shardManagerImpl) closeHandler(shard gateway.Gateway, err error) {
var closeError *websocket.CloseError
if !m.config.AutoScaling || !errors.As(err, &closeError) || gateway.CloseEventCodeByCode(closeError.Code) != gateway.CloseEventCodeShardingRequired {
return
}
m.config.Logger.Debug("shard requires re-sharding", slog.Int("shardID", shard.ShardID()))
// make sure shard is closed
shard.Close(context.TODO())
m.shardsMu.Lock()
defer m.shardsMu.Unlock()
delete(m.shards, shard.ShardID())
delete(m.config.ShardIDs, shard.ShardID())
newShardCount := shard.ShardCount() * m.config.ShardSplitCount
if newShardCount > m.config.ShardCount {
m.config.ShardCount = newShardCount
}
newShardID := shard.ShardID()
var newShardIDs []int
for len(newShardIDs) < m.config.ShardSplitCount {
newShardIDs = append(newShardIDs, newShardID)
newShardID += m.config.ShardSplitCount
}
var wg sync.WaitGroup
for i := range newShardIDs {
shardID := newShardIDs[i]
wg.Add(1)
go func() {
defer wg.Done()
if err := m.config.RateLimiter.WaitBucket(context.TODO(), shardID); err != nil {
m.config.Logger.Error("failed to wait shard bucket", slog.String("err", err.Error()), slog.Int("shard_id", shardID))
return
}
defer m.config.RateLimiter.UnlockBucket(shardID)
newShard := m.config.GatewayCreateFunc(m.token, m.eventHandlerFunc, m.closeHandler, append(m.config.GatewayConfigOpts, gateway.WithShardID(shardID), gateway.WithShardCount(newShardCount))...)
m.shards[shardID] = newShard
if err := newShard.Open(context.TODO()); err != nil {
m.config.Logger.Error("failed to re shard", slog.String("err", err.Error()), slog.Int("shard_id", shardID))
}
}()
}
wg.Wait()
m.config.Logger.Debug("re-sharded shard", slog.Int("shard_id", shard.ShardID()), slog.String("new_shard_ids", fmt.Sprint(newShardIDs)), slog.Int("new_shard_count", newShardCount))
}
func (m *shardManagerImpl) Open(ctx context.Context) {
m.config.Logger.Debug("opening shards", slog.String("shard_ids", fmt.Sprint(m.config.ShardIDs)))
var wg sync.WaitGroup
m.shardsMu.Lock()
defer m.shardsMu.Unlock()
for shardInt := range m.config.ShardIDs {
shardID := shardInt
if _, ok := m.shards[shardID]; ok {
continue
}
wg.Add(1)
go func() {
defer wg.Done()
if err := m.config.RateLimiter.WaitBucket(ctx, shardID); err != nil {
m.config.Logger.Error("failed to wait shard bucket", slog.String("err", err.Error()), slog.Int("shard_id", shardID))
return
}
defer m.config.RateLimiter.UnlockBucket(shardID)
shard := m.config.GatewayCreateFunc(m.token, m.eventHandlerFunc, m.closeHandler, append(m.config.GatewayConfigOpts, gateway.WithShardID(shardID), gateway.WithShardCount(m.config.ShardCount))...)
m.shards[shardID] = shard
if err := shard.Open(ctx); err != nil {
m.config.Logger.Error("failed to open shard", slog.String("err", err.Error()), slog.Int("shard_id", shardID))
}
}()
}
wg.Wait()
}
func (m *shardManagerImpl) Close(ctx context.Context) {
m.config.Logger.Debug("closing shards", slog.String("shard_ids", fmt.Sprint(m.config.ShardIDs)))
var wg sync.WaitGroup
m.shardsMu.Lock()
defer m.shardsMu.Unlock()
for shardID := range m.shards {
shard := m.shards[shardID]
delete(m.shards, shardID)
wg.Add(1)
go func() {
defer wg.Done()
shard.Close(ctx)
}()
}
wg.Wait()
}
func (m *shardManagerImpl) OpenShard(ctx context.Context, shardID int) error {
return m.openShard(ctx, shardID, m.config.ShardCount)
}
func (m *shardManagerImpl) openShard(ctx context.Context, shardID int, shardCount int) error {
m.config.Logger.Debug("opening shard", slog.Int("shard_id", shardID))
if err := m.config.RateLimiter.WaitBucket(ctx, shardID); err != nil {
return err
}
defer m.config.RateLimiter.UnlockBucket(shardID)
shard := m.config.GatewayCreateFunc(m.token, m.eventHandlerFunc, m.closeHandler, append(m.config.GatewayConfigOpts, gateway.WithShardID(shardID), gateway.WithShardCount(shardCount))...)
m.shardsMu.Lock()
defer m.shardsMu.Unlock()
m.config.ShardIDs[shardID] = struct{}{}
m.shards[shardID] = shard
return shard.Open(ctx)
}
func (m *shardManagerImpl) CloseShard(ctx context.Context, shardID int) {
m.config.Logger.Debug("closing shard", slog.Int("shard_id", shardID))
m.shardsMu.Lock()
defer m.shardsMu.Unlock()
shard, ok := m.shards[shardID]
if ok {
shard.Close(ctx)
delete(m.shards, shardID)
}
}
func (m *shardManagerImpl) ShardByGuildID(guildId snowflake.ID) gateway.Gateway {
shardCount := m.config.ShardCount
var shard gateway.Gateway
for shard == nil || shardCount != 0 {
shard = m.Shard(ShardIDByGuild(guildId, shardCount))
shardCount /= m.config.ShardSplitCount
}
return shard
}
func (m *shardManagerImpl) Shard(shardID int) gateway.Gateway {
m.shardsMu.Lock()
defer m.shardsMu.Unlock()
return m.shards[shardID]
}
func (m *shardManagerImpl) Shards() map[int]gateway.Gateway {
m.shardsMu.Lock()
defer m.shardsMu.Unlock()
shards := make(map[int]gateway.Gateway, len(m.shards))
for shardID, shard := range m.shards {
shards[shardID] = shard
}
return m.shards
}