forked from seatgeek/mailroom
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
228 lines (191 loc) · 6.43 KB
/
Copy pathserver.go
File metadata and controls
228 lines (191 loc) · 6.43 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
// Copyright 2025 SeatGeek, Inc.
//
// Licensed under the terms of the Apache-2.0 license. See LICENSE file in project root for terms.
package mailroom
import (
"context"
"fmt"
"log/slog"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/seatgeek/mailroom/pkg/event"
"github.com/seatgeek/mailroom/pkg/notifier"
"github.com/seatgeek/mailroom/pkg/notifier/preference"
"github.com/seatgeek/mailroom/pkg/server"
"github.com/seatgeek/mailroom/pkg/user"
"github.com/seatgeek/mailroom/pkg/validation"
)
// Server is the heart of the mailroom application
// It listens for incoming webhooks, parses them, generates notifications, and dispatches them to users.
type Server struct {
listenAddr string
parsers map[string]event.Parser
processors []event.Processor
notifier notifier.Notifier
transports []notifier.Transport
defaultPreferences preference.Provider
userStore user.Store
router *mux.Router
}
type Opt func(s *Server)
// New returns a new server
func New(opts ...Opt) *Server {
s := &Server{
listenAddr: "0.0.0.0:8000",
router: mux.NewRouter(),
parsers: make(map[string]event.Parser),
defaultPreferences: preference.Default(true),
}
for _, opt := range opts {
opt(s)
}
s.notifier = notifier.New(s.transports, preference.Chain{
user.NewPreferenceProvider(s.userStore),
s.defaultPreferences,
})
return s
}
// WithListenAddr sets the IP and port the server listens on, in the form "host:port"
func WithListenAddr(addr string) Opt {
return func(s *Server) {
s.listenAddr = addr
}
}
// WithParser adds an event.Parser to the server with the given key.
// The key is used as the API endpoint for the server.
func WithParser(key string, parser event.Parser) Opt {
return func(s *Server) {
s.parsers[key] = parser
}
}
// WithParserAndGenerator is a convenience function that adds an event.Parser and its corresponding processor (which generates notifications) in a single call.
func WithParserAndGenerator(key string, parser event.Parser, generator event.Processor) Opt {
return func(s *Server) {
s.parsers[key] = parser
s.processors = append(s.processors, generator)
}
}
// WithProcessors adds event.Processor instances to the server in the order given.
func WithProcessors(processors ...event.Processor) Opt {
return func(s *Server) {
s.processors = append(s.processors, processors...)
}
}
// WithTransports adds notifier.Transport instances to the server
func WithTransports(transports ...notifier.Transport) Opt {
return func(s *Server) {
s.transports = append(s.transports, transports...)
}
}
// WithUserStore sets the user.Store for the server
func WithUserStore(us user.Store) Opt {
return func(s *Server) {
s.userStore = us
}
}
// WithDefaultPreferences sets the default preferences for the server
func WithDefaultPreferences(prefs preference.Provider) Opt {
return func(s *Server) {
s.defaultPreferences = prefs
}
}
// WithRouter sets the mux.Router used for the server
func WithRouter(router *mux.Router) Opt {
return func(s *Server) {
s.router = router
}
}
func (s *Server) validate(ctx context.Context) error { //nolint:revive // high cognitive complexity okay here
for key, parser := range s.parsers {
if v, ok := parser.(validation.Validator); ok {
if err := v.Validate(ctx); err != nil {
return fmt.Errorf("parser %s (%T) failed to validate: %w", key, parser, err)
}
}
}
for _, processor := range s.processors {
if v, ok := processor.(validation.Validator); ok {
if err := v.Validate(ctx); err != nil {
return fmt.Errorf("processor %T failed to validate: %w", processor, err)
}
}
}
for _, t := range s.transports {
if v, ok := t.(validation.Validator); ok {
if err := v.Validate(ctx); err != nil {
return fmt.Errorf("transport %s failed to validate: %w", t.Key(), err)
}
}
}
if v, ok := s.userStore.(validation.Validator); ok {
if err := v.Validate(ctx); err != nil {
return fmt.Errorf("user store failed to validate: %w", err)
}
}
if v, ok := s.defaultPreferences.(validation.Validator); ok {
if err := v.Validate(ctx); err != nil {
return fmt.Errorf("default preferences failed to validate: %w", err)
}
}
return nil
}
// Run starts the server in a Goroutine and blocks until the server is shut down.
// If the given context is canceled, the server will attempt to shut down gracefully.
func (s *Server) Run(ctx context.Context) error {
if err := s.validate(ctx); err != nil {
return fmt.Errorf("server validation failed: %w", err)
}
return s.serveHttp(ctx)
}
func (s *Server) serveHttp(ctx context.Context) error {
hsm := s.router
hsm.HandleFunc("/healthz", func(writer http.ResponseWriter, _ *http.Request) {
writer.WriteHeader(200)
_, _ = writer.Write([]byte("^_^\n"))
})
// Mount all parsers
for key, parser := range s.parsers {
endpoint := "/event/" + key
slog.DebugContext(ctx, "mounting parser", "endpoint", endpoint)
hsm.HandleFunc(endpoint, server.CreateEventProcessingHandler(key, parser, s.processors, s.notifier))
}
// Expose routes for managing user preferences
prefs := user.NewPreferencesHandler(s.userStore, s.parsers, transportKeys(s.transports), s.defaultPreferences)
hsm.HandleFunc("/users/{key}/preferences", prefs.GetPreferences).Methods("GET")
hsm.HandleFunc("/users/{key}/preferences", prefs.UpdatePreferences).Methods("PUT")
hsm.HandleFunc("/configuration", prefs.ListOptions).Methods("GET")
hs := &http.Server{
Addr: s.listenAddr,
Handler: hsm,
ReadHeaderTimeout: 2 * time.Second,
}
// Run the server in a Goroutine
httpExited := make(chan error)
go (func() {
defer close(httpExited)
slog.InfoContext(ctx, "http server listening on "+s.listenAddr)
httpExited <- hs.ListenAndServe()
})()
select {
// Wait for the context to be canceled
case <-ctx.Done():
slog.InfoContext(ctx, "shutting down http server gracefully")
shutdownCtx, cancelShutdown := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelShutdown()
if err := hs.Shutdown(shutdownCtx); err != nil { //nolint:contextcheck
return fmt.Errorf("failed to gracefully shutdown http server: %w", err)
}
return nil
// Or wait for the server to exit on its own (with some error)
case err := <-httpExited:
return err
}
}
func transportKeys(transports []notifier.Transport) []event.TransportKey {
keys := make([]event.TransportKey, len(transports))
for i, t := range transports {
keys[i] = t.Key()
}
return keys
}