/
app.go
274 lines (240 loc) · 7.24 KB
/
app.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
package graphqlapp
import (
context "context"
"database/sql"
"fmt"
"net/http"
"strconv"
"time"
"github.com/99designs/gqlgen/graphql"
"github.com/99designs/gqlgen/graphql/errcode"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/handler/apollotracing"
"github.com/pkg/errors"
"github.com/target/goalert/alert"
alertlog "github.com/target/goalert/alert/log"
"github.com/target/goalert/auth"
"github.com/target/goalert/calendarsubscription"
"github.com/target/goalert/config"
"github.com/target/goalert/escalation"
"github.com/target/goalert/graphql2"
"github.com/target/goalert/heartbeat"
"github.com/target/goalert/integrationkey"
"github.com/target/goalert/label"
"github.com/target/goalert/limit"
"github.com/target/goalert/notice"
"github.com/target/goalert/notification"
"github.com/target/goalert/notification/slack"
"github.com/target/goalert/notification/twilio"
"github.com/target/goalert/notificationchannel"
"github.com/target/goalert/oncall"
"github.com/target/goalert/override"
"github.com/target/goalert/permission"
"github.com/target/goalert/schedule"
"github.com/target/goalert/schedule/rotation"
"github.com/target/goalert/schedule/rule"
"github.com/target/goalert/service"
"github.com/target/goalert/timezone"
"github.com/target/goalert/user"
"github.com/target/goalert/user/contactmethod"
"github.com/target/goalert/user/favorite"
"github.com/target/goalert/user/notificationrule"
"github.com/target/goalert/util/errutil"
"github.com/target/goalert/util/log"
"github.com/target/goalert/validation"
"github.com/vektah/gqlparser/v2/gqlerror"
"go.opencensus.io/trace"
)
type App struct {
DB *sql.DB
UserStore user.Store
CMStore contactmethod.Store
NRStore notificationrule.Store
NCStore notificationchannel.Store
AlertStore alert.Store
AlertLogStore alertlog.Store
ServiceStore service.Store
FavoriteStore favorite.Store
PolicyStore escalation.Store
ScheduleStore *schedule.Store
CalSubStore *calendarsubscription.Store
RotationStore rotation.Store
OnCallStore oncall.Store
IntKeyStore integrationkey.Store
LabelStore label.Store
RuleStore rule.Store
OverrideStore override.Store
ConfigStore *config.Store
LimitStore *limit.Store
SlackStore *slack.ChannelSender
HeartbeatStore heartbeat.Store
NoticeStore notice.Store
AuthHandler *auth.Handler
NotificationStore notification.Store
Twilio *twilio.Config
TimeZoneStore *timezone.Store
}
func mustAuth(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
err := permission.LimitCheckAny(req.Context())
if errutil.HTTPError(req.Context(), w, err) {
return
}
h.ServeHTTP(w, req)
})
}
func (a *App) PlayHandler() http.Handler {
var data struct {
Version string
PackageName string
}
data.Version = playVersion
data.PackageName = playPackageName
return mustAuth(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
err := playTmpl.Execute(w, data)
if err != nil {
log.Log(req.Context(), err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}))
}
type fieldErr struct {
FieldName string `json:"fieldName"`
Message string `json:"message"`
}
type apolloTracer struct {
apollotracing.Tracer
shouldTrace func(context.Context) bool
}
func (a apolloTracer) InterceptField(ctx context.Context, next graphql.Resolver) (res interface{}, err error) {
if !a.shouldTrace(ctx) {
return next(ctx)
}
return a.Tracer.InterceptField(ctx, next)
}
func (a apolloTracer) InterceptResponse(ctx context.Context, next graphql.ResponseHandler) *graphql.Response {
if !a.shouldTrace(ctx) {
return next(ctx)
}
return a.Tracer.InterceptResponse(ctx, next)
}
func isGQLValidation(gqlErr *gqlerror.Error) bool {
if gqlErr == nil {
return false
}
var numErr *strconv.NumError
if errors.As(gqlErr, &numErr) {
return true
}
if gqlErr.Extensions == nil {
return false
}
code, ok := gqlErr.Extensions["code"].(string)
if !ok {
return false
}
return code == errcode.ValidationFailed || code == errcode.ParseFailed
}
func (a *App) Handler() http.Handler {
h := handler.NewDefaultServer(
graphql2.NewExecutableSchema(graphql2.Config{Resolvers: a}),
)
type hasTraceKey int
h.Use(apolloTracer{Tracer: apollotracing.Tracer{}, shouldTrace: func(ctx context.Context) bool {
enabled, ok := ctx.Value(hasTraceKey(1)).(bool)
return ok && enabled
}})
h.AroundFields(func(ctx context.Context, next graphql.Resolver) (res interface{}, err error) {
defer func() {
err := recover()
if err != nil {
panic(err)
}
}()
fieldCtx := graphql.GetFieldContext(ctx)
ctx, sp := trace.StartSpan(ctx, "GQL."+fieldCtx.Object+"."+fieldCtx.Field.Name, trace.WithSpanKind(trace.SpanKindServer))
defer sp.End()
sp.AddAttributes(
trace.StringAttribute("graphql.object", fieldCtx.Object),
trace.StringAttribute("graphql.field.name", fieldCtx.Field.Name),
)
start := time.Now()
res, err = next(ctx)
errVal := "0"
if err != nil {
errVal = "1"
}
if fieldCtx.IsMethod {
metricResolverHist.
WithLabelValues(fmt.Sprintf("%s.%s", fieldCtx.Object, fieldCtx.Field.Name), errVal).
Observe(time.Since(start).Seconds())
}
if err != nil {
sp.Annotate([]trace.Attribute{
trace.BoolAttribute("error", true),
}, err.Error())
} else if fieldCtx.Object == "Mutation" {
ctx = log.WithFields(ctx, log.Fields{
"MutationName": fieldCtx.Field.Name,
})
log.Logf(ctx, "Mutation.")
}
return res, err
})
h.SetErrorPresenter(func(ctx context.Context, err error) *gqlerror.Error {
err = errutil.MapDBError(err)
var gqlErr *gqlerror.Error
isUnsafe, safeErr := errutil.ScrubError(err)
if !errors.As(err, &gqlErr) {
gqlErr = &gqlerror.Error{
Message: safeErr.Error(),
}
}
if isUnsafe && !isGQLValidation(gqlErr) {
log.Log(ctx, err)
gqlErr.Message = safeErr.Error()
}
var multiFieldErr validation.MultiFieldError
var singleFieldErr validation.FieldError
if errors.As(err, &multiFieldErr) {
errs := make([]fieldErr, len(multiFieldErr.FieldErrors()))
for i, err := range multiFieldErr.FieldErrors() {
errs[i].FieldName = err.Field()
errs[i].Message = err.Reason()
}
gqlErr.Message = "Multiple fields failed validation."
gqlErr.Extensions = map[string]interface{}{
"isMultiFieldError": true,
"fieldErrors": errs,
}
} else if errors.As(err, &singleFieldErr) {
type reasonable interface {
Reason() string
}
msg := singleFieldErr.Error()
if rs, ok := singleFieldErr.(reasonable); ok {
msg = rs.Reason()
}
gqlErr.Message = msg
gqlErr.Extensions = map[string]interface{}{
"fieldName": singleFieldErr.Field(),
"isFieldError": true,
}
}
return gqlErr
})
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
ctx := req.Context()
// ensure some sort of auth before continuing
err := permission.LimitCheckAny(ctx)
if errutil.HTTPError(ctx, w, err) {
return
}
ctx = a.registerLoaders(ctx)
defer a.closeLoaders(ctx)
if req.URL.Query().Get("trace") == "1" && permission.Admin(ctx) {
ctx = context.WithValue(ctx, hasTraceKey(1), true)
}
h.ServeHTTP(w, req.WithContext(ctx))
})
}