-
Notifications
You must be signed in to change notification settings - Fork 0
/
sandwich.go
306 lines (239 loc) · 7.69 KB
/
sandwich.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
package internal
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/signal"
"runtime/debug"
"sync"
"syscall"
"time"
discord "github.com/WelcomerTeam/Discord/discord"
protobuf "github.com/WelcomerTeam/Sandwich-Daemon/protobuf"
sandwich_structs "github.com/WelcomerTeam/Sandwich-Daemon/structs"
"github.com/pkg/errors"
"github.com/rs/zerolog"
"google.golang.org/grpc"
)
// VERSION follows semantic versioning.
const VERSION = "0.3.3"
var LastRequestTimeout = time.Minute * 60
type Sandwich struct {
Logger zerolog.Logger
botsMu sync.RWMutex
Bots map[string]*Bot
SandwichEvents *Handlers
identifiersMu sync.RWMutex
Identifiers map[string]*sandwich_structs.ManagerConsumerConfiguration
lastIdentifierRequestMu sync.RWMutex
LastIdentifierRequest map[string]time.Time
RESTInterface discord.RESTInterface
SandwichClient protobuf.SandwichClient
GRPCInterface GRPC
}
func NewSandwich(conn grpc.ClientConnInterface, restInterface discord.RESTInterface, logger io.Writer) *Sandwich {
sandwich := &Sandwich{
Logger: zerolog.New(logger).With().Timestamp().Logger(),
botsMu: sync.RWMutex{},
Bots: make(map[string]*Bot),
SandwichEvents: newSandwichHandlers(),
identifiersMu: sync.RWMutex{},
Identifiers: make(map[string]*sandwich_structs.ManagerConsumerConfiguration),
lastIdentifierRequestMu: sync.RWMutex{},
LastIdentifierRequest: make(map[string]time.Time),
RESTInterface: restInterface,
SandwichClient: protobuf.NewSandwichClient(conn),
GRPCInterface: NewDefaultGRPCClient(),
}
return sandwich
}
func (sandwich *Sandwich) ListenToChannel(ctx context.Context, channel chan []byte) error {
// Signal
signalCh := make(chan os.Signal, 1)
signal.Notify(signalCh, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
// Register message channels
grpcMessages := make(chan *protobuf.ListenResponse)
go func() {
for {
grpcListener, err := sandwich.SandwichClient.Listen(ctx, &protobuf.ListenRequest{
Identifier: "",
})
if err != nil {
sandwich.Logger.Warn().Err(err).Msg("Failed to listen to grpc")
time.Sleep(time.Second)
} else {
for {
var listenResponse protobuf.ListenResponse
err = grpcListener.RecvMsg(&listenResponse)
if err != nil {
if errors.Is(err, context.Canceled) {
return
}
sandwich.Logger.Warn().Err(err).Msg("Failed to receive grpc message")
break
} else {
grpcMessages <- &listenResponse
}
}
}
}
}()
// Event Loop
eventLoop:
for {
select {
case grpcMessage := <-grpcMessages:
var payload sandwich_structs.SandwichPayload
err := json.Unmarshal(grpcMessage.Data, &payload)
if err != nil {
sandwich.Logger.Warn().Err(err).Msg("Failed to unmarshal grpc message")
} else {
sandwich.DispatchGRPCPayload(ctx, payload)
}
case stanMessage := <-channel:
var payload sandwich_structs.SandwichPayload
err := json.Unmarshal(stanMessage, &payload)
if err != nil {
sandwich.Logger.Warn().Err(err).Msg("Failed to unmarshal stan message")
} else {
err = sandwich.DispatchSandwichPayload(ctx, payload)
if err != nil {
sandwich.Logger.Warn().Err(err).Msg("Failed to dispatch sandwich payload")
}
}
case <-signalCh:
break eventLoop
}
}
return nil
}
func (sandwich *Sandwich) DispatchGRPCPayload(ctx context.Context, payload sandwich_structs.SandwichPayload) {
logger := sandwich.Logger.With().Str("application", payload.Metadata.Application).Logger()
sandwich.SandwichEvents.Dispatch(&EventContext{
Logger: logger,
Sandwich: sandwich,
Session: discord.NewSession(ctx, "", sandwich.RESTInterface),
Handlers: sandwich.SandwichEvents,
Context: ctx,
Payload: &payload,
}, payload)
}
func (sandwich *Sandwich) DispatchSandwichPayload(ctx context.Context, payload sandwich_structs.SandwichPayload) error {
sandwich.botsMu.RLock()
bot, ok := sandwich.Bots[payload.Metadata.Identifier]
sandwich.botsMu.RUnlock()
if !ok {
sandwich.Logger.Debug().
Str("identifier", payload.Metadata.Identifier).
Str("application", payload.Metadata.Application).
Msg(ErrInvalidIdentifier.Error())
return ErrInvalidIdentifier
}
logger := sandwich.Logger.With().Str("application", payload.Metadata.Application).Logger()
bot.Dispatch(&EventContext{
Logger: logger,
Sandwich: sandwich,
Session: discord.NewSession(ctx, "", sandwich.RESTInterface),
Handlers: bot.Handlers,
Context: ctx,
Payload: &payload,
}, payload)
return nil
}
func (sandwich *Sandwich) RegisterBot(identifier string, bot *Bot) {
sandwich.botsMu.Lock()
sandwich.Bots[identifier] = bot
sandwich.botsMu.Unlock()
}
func (sandwich *Sandwich) RecoverEventPanic(errorValue interface{}, eventCtx *EventContext, payload *sandwich_structs.SandwichPayload) {
sandwich.Logger.Error().Interface("errorValue", errorValue).Str("type", payload.Type).Msg("Recovered panic on event dispatch")
fmt.Println(string(debug.Stack()))
}
func (sandwich *Sandwich) FetchIdentifier(ctx context.Context, applicationName string) (identifier *sandwich_structs.ManagerConsumerConfiguration, ok bool, err error) {
sandwich.identifiersMu.RLock()
identifier, ok = sandwich.Identifiers[applicationName]
sandwich.identifiersMu.RUnlock()
if ok {
return identifier, true, nil
}
sandwich.lastIdentifierRequestMu.RLock()
lastRequest, ok := sandwich.LastIdentifierRequest[applicationName]
sandwich.lastIdentifierRequestMu.RUnlock()
if !ok || (ok && time.Now().Add(LastRequestTimeout).Before(lastRequest)) {
identifiers, err := sandwich.GRPCInterface.FetchConsumerConfiguration((&EventContext{
Sandwich: sandwich,
Session: discord.NewSession(ctx, "", sandwich.RESTInterface),
Context: ctx,
}).ToGRPCContext(), "")
if err != nil {
return nil, false, fmt.Errorf("failed to fetch consumer configuration: %w", err)
}
sandwich.identifiersMu.Lock()
sandwich.Identifiers = map[string]*sandwich_structs.ManagerConsumerConfiguration{}
for k := range identifiers.Identifiers {
v := identifiers.Identifiers[k]
sandwich.Identifiers[k] = &v
}
sandwich.identifiersMu.Unlock()
identifier, ok = sandwich.Identifiers[applicationName]
if !ok {
return nil, false, ErrInvalidApplication
}
} else {
return nil, false, ErrInvalidApplication
}
return identifier, true, nil
}
// EventContext is extra data passed to event handlers.
// This is not the same as a command's context.
type EventContext struct {
context.Context
Logger zerolog.Logger
Sandwich *Sandwich
Session *discord.Session
// Filled in on dispatch
EventHandler *EventHandler
Handlers *Handlers
Identifier *sandwich_structs.ManagerConsumerConfiguration
Guild *discord.Guild
Payload *sandwich_structs.SandwichPayload
}
func (eventCtx *EventContext) ToGRPCContext() *GRPCContext {
return &GRPCContext{
Context: eventCtx.Context,
Logger: eventCtx.Logger,
SandwichClient: eventCtx.Sandwich.SandwichClient,
GRPCInterface: eventCtx.Sandwich.GRPCInterface,
Session: eventCtx.Session,
Identifier: eventCtx.Identifier,
}
}
func (eventCtx *EventContext) Trace() sandwich_structs.SandwichTrace {
if eventCtx.Payload != nil {
return eventCtx.Payload.Trace
}
return nil
}
func (eventCtx *EventContext) DecodeContent(msg sandwich_structs.SandwichPayload, out interface{}) error {
err := json.Unmarshal(msg.Data, &out)
if err != nil {
return errors.Errorf("failed to unmarshal gateway payload: %v", err)
}
return nil
}
func (eventCtx *EventContext) DecodeExtra(msg sandwich_structs.SandwichPayload, key string, out interface{}) (ok bool, err error) {
val, ok := msg.Extra[key]
if ok {
if len(val) == 0 {
ok = false
return
}
err = json.Unmarshal(val, &out)
if err != nil {
return ok, fmt.Errorf("failed to unmarshal extra: %w", err)
}
}
return
}