-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapplication.go
More file actions
361 lines (250 loc) · 8.99 KB
/
Copy pathapplication.go
File metadata and controls
361 lines (250 loc) · 8.99 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
package sandwich
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"sync"
"sync/atomic"
"time"
"github.com/WelcomerTeam/Discord/discord"
"github.com/WelcomerTeam/Sandwich-Daemon/pkg/syncmap"
"github.com/coder/websocket"
)
type Application struct {
Logger *slog.Logger
Identifier string
Sandwich *Sandwich
Configuration *atomic.Pointer[ApplicationConfiguration]
Gateway *atomic.Pointer[discord.GatewayBotResponse]
gatewaySessionStartLimitRemaining *atomic.Int32
User *atomic.Pointer[discord.User]
producer Producer
ShardCount *atomic.Int32
ready chan struct{}
readyWg sync.WaitGroup
Shards *syncmap.Map[int32, *Shard]
guilds *syncmap.Map[discord.Snowflake, bool]
startedAt *atomic.Pointer[time.Time]
Status *atomic.Int32
}
func NewApplication(sandwich *Sandwich, config *ApplicationConfiguration) *Application {
application := &Application{
Logger: sandwich.Logger.With("application_identifier", config.ApplicationIdentifier),
Identifier: config.ApplicationIdentifier,
Sandwich: sandwich,
Configuration: &atomic.Pointer[ApplicationConfiguration]{},
Gateway: &atomic.Pointer[discord.GatewayBotResponse]{},
gatewaySessionStartLimitRemaining: &atomic.Int32{},
User: &atomic.Pointer[discord.User]{},
producer: nil,
ShardCount: &atomic.Int32{},
ready: make(chan struct{}),
readyWg: sync.WaitGroup{},
Shards: syncmap.NewSyncMap[int32, *Shard](),
guilds: syncmap.NewSyncMap[discord.Snowflake, bool](),
startedAt: &atomic.Pointer[time.Time]{},
Status: &atomic.Int32{},
}
application.Configuration.Store(config)
application.SetStatus(ApplicationStatusIdle)
return application
}
func (application *Application) SetStatus(status ApplicationStatus) {
UpdateApplicationStatus(application.Identifier, status)
application.Status.Store(int32(status))
application.Logger.Info("Application status updated", "status", status.String())
err := application.Sandwich.Broadcast(SandwichApplicationStatusUpdate, ApplicationStatusUpdateEvent{
Identifier: application.Identifier,
Status: status,
})
if err != nil {
application.Logger.Error("Failed to broadcast application status update", "error", err)
}
}
func (application *Application) SetUser(user *discord.User) {
existingUser := application.User.Load()
application.User.Store(user)
if existingUser != nil && existingUser.ID == user.ID {
return
}
application.Logger.Debug("Application user updated", "user", user.Username)
configuration := application.Configuration.Load()
application.Shards.Range(func(_ int32, shard *Shard) bool {
shard.SetMetadata(configuration)
return true
})
}
// Initialize initializes the application. This includes checking the gateway
func (application *Application) Initialize(ctx context.Context) error {
application.Logger.Debug("Initializing application")
application.Sandwich.gatewayLimiter.Lock()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, discord.EndpointGatewayBot, nil)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", "Bot "+application.Configuration.Load().BotToken)
resp, err := application.Sandwich.Client.Do(req)
if err != nil {
return fmt.Errorf("failed to do request: %w", err)
}
defer resp.Body.Close()
var gatewayBotResponse discord.GatewayBotResponse
if err := json.NewDecoder(resp.Body).Decode(&gatewayBotResponse); err != nil {
return fmt.Errorf("failed to decode gateway bot response: %w", err)
}
application.Gateway.Store(&gatewayBotResponse)
application.gatewaySessionStartLimitRemaining.Store(gatewayBotResponse.SessionStartLimit.Remaining)
configuration := application.Configuration.Load()
clientName := configuration.ClientName
// If the client name includes a random suffix, we need to add a random suffix to the client name.
if configuration.IncludeRandomSuffix {
clientName = fmt.Sprintf("%s-%s", clientName, randomHex(8))
}
producer, err := application.Sandwich.producerProvider.GetProducer(ctx, configuration.ApplicationIdentifier, clientName)
if err != nil {
return fmt.Errorf("failed to get producer: %w", err)
}
application.producer = producer
application.Logger.Debug("Application initialized")
return nil
}
func (application *Application) Start(ctx context.Context) error {
application.Logger.Info("Starting application")
application.SetStatus(ApplicationStatusStarting)
configuration := application.Configuration.Load()
shardIDs, shardCount := application.GetInitialShardCount(
configuration.ShardCount,
configuration.ShardIDs,
configuration.AutoSharded,
)
application.Logger.Debug("Initializing shards", "shard_count", shardCount, "shard_ids", shardIDs)
application.ShardCount.Store(shardCount)
ready, err := application.StartShards(ctx, shardIDs, shardCount)
if err != nil {
application.Logger.Error("Failed to start shards", "error", err)
application.SetStatus(ApplicationStatusFailed)
return fmt.Errorf("failed to start: %w", err)
}
<-ready
application.SetStatus(ApplicationStatusReady)
return nil
}
func (application *Application) Stop(ctx context.Context) error {
application.SetStatus(ApplicationStatusStopping)
application.Shards.Range(func(_ int32, shard *Shard) bool {
shard.Stop(ctx, websocket.StatusNormalClosure)
return true
})
if application.producer != nil {
application.producer.Close()
}
application.SetStatus(ApplicationStatusStopped)
return nil
}
// GetInitialShardCount returns the shard IDs and shard count for the application.
func (application *Application) GetInitialShardCount(customShardCount int32, customShardIDs string, autoSharded bool) ([]int32, int32) {
config := application.Sandwich.Config.Load()
var shardCount int32
var shardIDs []int32
if autoSharded {
shardCount = application.Gateway.Load().Shards
if customShardIDs == "" {
for i := range shardCount {
shardIDs = append(shardIDs, i)
}
} else {
shardIDs = ReturnRangeInt32(config.Sandwich.NodeCount, config.Sandwich.NodeID, customShardIDs, shardCount)
}
} else {
shardCount = customShardCount
if customShardIDs == "" {
for i := range shardCount {
shardIDs = append(shardIDs, i)
}
} else {
shardIDs = ReturnRangeInt32(config.Sandwich.NodeCount, config.Sandwich.NodeID, customShardIDs, shardCount)
}
}
// If we have a node count, split the shards evenly across nodes
if config.Sandwich.NodeCount > 1 {
filteredShardIDs := make([]int32, 0, len(shardIDs))
// Only keep shards that belong to this node based on modulo
for _, id := range shardIDs {
if id%config.Sandwich.NodeCount == config.Sandwich.NodeID {
filteredShardIDs = append(filteredShardIDs, id)
}
}
shardIDs = filteredShardIDs
}
return shardIDs, shardCount
}
func (application *Application) StartShards(ctx context.Context, shardIDs []int32, shardCount int32) (ready chan struct{}, err error) {
application.Logger.Info("Starting shards", "shard_count", shardCount, "shard_ids", shardIDs)
ready = make(chan struct{})
now := time.Now()
application.startedAt.Store(&now)
application.ShardCount.Store(shardCount)
// If we have no shards, we can't start the application
if len(shardIDs) == 0 {
application.Logger.Error("No shards to start")
return ready, ErrApplicationMissingShards
}
// Kill any shards that are already running
application.Shards.Range(func(_ int32, shard *Shard) bool {
shard.Stop(ctx, websocket.StatusNormalClosure)
return true
})
// Create new shards
for _, shardID := range shardIDs {
shard := NewShard(application.Sandwich, application, shardID)
application.Shards.Store(shardID, shard)
}
application.SetStatus(ApplicationStatusConnecting)
initialShard, ok := application.Shards.Load(shardIDs[0])
if !ok {
panic("failed to load initial shard")
}
if err := initialShard.ConnectWithRetry(ctx); err != nil {
application.Logger.Error("Failed to connect to initial shard", "error", err)
return ready, fmt.Errorf("failed to connect to initial shard: %w", err)
}
go initialShard.Start(ctx)
if err := initialShard.WaitForReady(); err != nil {
application.Logger.Error("Failed to wait for initial shard", "error", err)
return ready, fmt.Errorf("failed to wait for initial shard: %w", err)
}
application.Logger.Debug("Initial shard connected", "shard_id", shardIDs[0])
application.SetStatus(ApplicationStatusConnected)
openWg := sync.WaitGroup{}
for _, shardID := range shardIDs[1:] {
shard, ok := application.Shards.Load(shardID)
if !ok {
panic("failed to load shard")
}
openWg.Add(1)
go func(shard *Shard) {
defer openWg.Done()
if err := shard.ConnectWithRetry(ctx); err != nil {
return
}
go shard.Start(ctx)
}(shard)
}
openWg.Wait()
application.Logger.Debug("All shards connected")
// All shards have now connected, but are not ready yet.
go func() {
application.Shards.Range(func(index int32, shard *Shard) bool {
// Skip the initial shard
if index == 0 {
return true
}
shard.WaitForReady()
return true
})
close(ready)
}()
return ready, nil
}