File size: 11,917 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package graphqlapp

import (
	context "context"
	"time"

	"github.com/google/uuid"
	"github.com/target/goalert/alert"
	"github.com/target/goalert/alert/alertmetrics"
	"github.com/target/goalert/dataloader"
	"github.com/target/goalert/escalation"
	"github.com/target/goalert/gadb"
	"github.com/target/goalert/heartbeat"
	"github.com/target/goalert/notification"
	"github.com/target/goalert/notificationchannel"
	"github.com/target/goalert/schedule"
	"github.com/target/goalert/schedule/rotation"
	"github.com/target/goalert/service"
	"github.com/target/goalert/user"
	"github.com/target/goalert/user/contactmethod"
	"github.com/target/goalert/util/sqlutil"

	"github.com/pkg/errors"
)

type dataLoaderKey int

const requestLoadersKey = dataLoaderKey(1)

// loaders contains all the dataloader instances for a single request.
// These are used to batch database queries and prevent N+1 problems in GraphQL resolvers.
type loaders struct {
	Alert                     *dataloader.Loader[int, alert.Alert]
	AlertState                *dataloader.Loader[int, alert.State]
	EP                        *dataloader.Loader[string, escalation.Policy]
	Rotation                  *dataloader.Loader[string, rotation.Rotation]
	Schedule                  *dataloader.Loader[string, schedule.Schedule]
	Service                   *dataloader.Loader[string, service.Service]
	User                      *dataloader.Loader[string, user.User]
	CM                        *dataloader.Loader[string, contactmethod.ContactMethod]
	Heartbeat                 *dataloader.Loader[string, heartbeat.Monitor]
	NotificationMessageStatus *dataloader.Loader[string, notification.SendResult]
	NC                        *dataloader.Loader[string, notificationchannel.Channel]
	AlertMetrics              *dataloader.Loader[int, alertmetrics.Metric]
	AlertFeedback             *dataloader.Loader[int, alert.Feedback]
	AlertMetadata             *dataloader.Loader[int, alert.MetadataAlertID]
	AlertsByStatus            *dataloader.AggFetcher[uuid.UUID, gadb.ServiceAlertCountsRow]
	AlertStats                *dataloader.AggFetcherParam[uuid.UUID, AlertStatsParam, gadb.ServiceAlertStatsRow]
}

type AlertStatsParam struct {
	Stride    sqlutil.Interval
	Origin    time.Time
	StartTime time.Time
	EndTime   time.Time
}

// registerLoaders creates and registers all dataloaders for the request context.
// Each loader is configured with appropriate batch settings and ID extraction functions.
func (a *App) registerLoaders(ctx context.Context) context.Context {
	ctx = context.WithValue(ctx, requestLoadersKey, &loaders{
		Alert:                     dataloader.NewStoreLoader(ctx, a.AlertStore.FindMany, func(a alert.Alert) int { return a.ID }),
		AlertState:                dataloader.NewStoreLoader(ctx, a.AlertStore.State, func(s alert.State) int { return s.ID }),
		EP:                        dataloader.NewStoreLoader(ctx, a.PolicyStore.FindManyPolicies, func(p escalation.Policy) string { return p.ID }),
		Rotation:                  dataloader.NewStoreLoader(ctx, a.RotationStore.FindMany, func(r rotation.Rotation) string { return r.ID }),
		Schedule:                  dataloader.NewStoreLoader(ctx, a.ScheduleStore.FindMany, func(s schedule.Schedule) string { return s.ID }),
		Service:                   dataloader.NewStoreLoader(ctx, a.ServiceStore.FindMany, func(s service.Service) string { return s.ID }),
		User:                      dataloader.NewStoreLoader(ctx, a.UserStore.FindMany, func(u user.User) string { return u.ID }),
		CM:                        dataloader.NewStoreLoaderWithDB(ctx, a.DB, a.CMStore.FindMany, func(cm contactmethod.ContactMethod) string { return cm.ID.String() }),
		Heartbeat:                 dataloader.NewStoreLoader(ctx, a.HeartbeatStore.FindMany, func(hb heartbeat.Monitor) string { return hb.ID }),
		NotificationMessageStatus: dataloader.NewStoreLoader(ctx, a.NotificationStore.FindManyMessageStatuses, func(n notification.SendResult) string { return n.ID }),
		NC:                        dataloader.NewStoreLoader(ctx, a.NCStore.FindMany, func(nc notificationchannel.Channel) string { return nc.ID.String() }),
		AlertMetrics:              dataloader.NewStoreLoader(ctx, a.AlertMetricsStore.FindMetrics, func(m alertmetrics.Metric) int { return m.ID }),
		AlertFeedback:             dataloader.NewStoreLoader(ctx, a.AlertStore.Feedback, func(f alert.Feedback) int { return f.ID }),
		AlertMetadata: dataloader.NewStoreLoader(ctx, func(ctx context.Context, i []int) ([]alert.MetadataAlertID, error) {
			return a.AlertStore.FindManyMetadata(ctx, a.DB, i)
		}, func(md alert.MetadataAlertID) int { return int(md.ID) }),
		AlertsByStatus: dataloader.NewStoreLoaderAgg(ctx, gadb.New(a.DB).ServiceAlertCounts, func(r gadb.ServiceAlertCountsRow) uuid.UUID { return r.ServiceID.UUID }),

		AlertStats: dataloader.NewStoreLoaderAggParam(ctx, func(ctx context.Context, param AlertStatsParam, ids []uuid.UUID) ([]gadb.ServiceAlertStatsRow, error) {
			return gadb.New(a.DB).ServiceAlertStats(ctx, gadb.ServiceAlertStatsParams{
				Stride:     param.Stride,
				Origin:     param.Origin,
				StartTime:  param.StartTime,
				EndTime:    param.EndTime,
				ServiceIds: ids,
			})
		}, func(r gadb.ServiceAlertStatsRow) uuid.UUID { return r.ServiceID }),
	})
	return ctx
}

// loadersFrom extracts the loaders struct from the request context.
// Returns an empty loaders struct if none are found.
func loadersFrom(ctx context.Context) loaders {
	loader, ok := ctx.Value(requestLoadersKey).(*loaders)
	if !ok {
		return loaders{}
	}
	if loader == nil {
		return loaders{}
	}

	return *loader
}

// closeLoaders closes all dataloaders in the request context to prevent goroutine leaks.
// This should be called when the request is complete.
func (a *App) closeLoaders(ctx context.Context) {
	loader := loadersFrom(ctx)

	if loader.Alert != nil {
		loader.Alert.Close()
	}
	if loader.AlertState != nil {
		loader.AlertState.Close()
	}
	if loader.EP != nil {
		loader.EP.Close()
	}
	if loader.Rotation != nil {
		loader.Rotation.Close()
	}
	if loader.Schedule != nil {
		loader.Schedule.Close()
	}
	if loader.Service != nil {
		loader.Service.Close()
	}
	if loader.User != nil {
		loader.User.Close()
	}
	if loader.CM != nil {
		loader.CM.Close()
	}
	if loader.Heartbeat != nil {
		loader.Heartbeat.Close()
	}
	if loader.NotificationMessageStatus != nil {
		loader.NotificationMessageStatus.Close()
	}
	if loader.NC != nil {
		loader.NC.Close()
	}
	if loader.AlertMetrics != nil {
		loader.AlertMetrics.Close()
	}
	if loader.AlertFeedback != nil {
		loader.AlertFeedback.Close()
	}
	if loader.AlertMetadata != nil {
		loader.AlertMetadata.Close()
	}
	if loader.AlertsByStatus != nil {
		loader.AlertsByStatus.Close()
	}
	if loader.AlertStats != nil {
		loader.AlertStats.Close()
	}
}

func (a *App) FindAlertStats(ctx context.Context, params AlertStatsParam, serviceID uuid.UUID) ([]gadb.ServiceAlertStatsRow, error) {
	loader := loadersFrom(ctx).AlertStats
	if loader == nil {
		return gadb.New(a.DB).ServiceAlertStats(ctx, gadb.ServiceAlertStatsParams{
			Stride:     params.Stride,
			Origin:     params.Origin,
			StartTime:  params.StartTime,
			EndTime:    params.EndTime,
			ServiceIds: []uuid.UUID{serviceID},
		})
	}

	return loader.FetchAggregateParam(ctx, serviceID, params)
}

func (app *App) FindAlertCountByStatus(ctx context.Context, serviceID uuid.UUID) ([]gadb.ServiceAlertCountsRow, error) {
	loader := loadersFrom(ctx).AlertsByStatus
	if loader == nil {
		return gadb.New(app.DB).ServiceAlertCounts(ctx, []uuid.UUID{serviceID})
	}

	return loader.FetchAggregate(ctx, serviceID)
}

func (app *App) FindOneAlertMetadata(ctx context.Context, id int) (map[string]string, error) {
	loader := loadersFrom(ctx).AlertMetadata
	if loader == nil {
		return app.AlertStore.Metadata(ctx, app.DB, id)
	}

	md, err := loader.FetchOne(ctx, id)
	if err != nil {
		return nil, err
	}
	if md == nil {
		return map[string]string{}, nil
	}

	return md.Meta, nil
}

func (app *App) FindOneNotificationMessageStatus(ctx context.Context, id string) (*notification.SendResult, error) {
	loader := loadersFrom(ctx).NotificationMessageStatus
	if loader == nil {
		ms, err := app.NotificationStore.FindManyMessageStatuses(ctx, []string{id})
		if err != nil {
			return nil, err
		}
		return &ms[0], nil
	}

	return loader.FetchOne(ctx, id)
}

func (app *App) FindOneAlertFeedback(ctx context.Context, id int) (*alert.Feedback, error) {
	loader := loadersFrom(ctx).AlertFeedback
	if loader == nil {
		feedback, err := app.AlertStore.Feedback(ctx, []int{id})
		if err != nil {
			return nil, err
		}
		if len(feedback) == 0 {
			return nil, nil
		}
		return &feedback[0], nil
	}

	return loader.FetchOne(ctx, id)
}

func (app *App) FindOneRotation(ctx context.Context, id string) (*rotation.Rotation, error) {
	loader := loadersFrom(ctx).Rotation
	if loader == nil {
		return app.RotationStore.FindRotation(ctx, id)
	}

	return loader.FetchOne(ctx, id)
}

func (app *App) FindOneSchedule(ctx context.Context, id string) (*schedule.Schedule, error) {
	loader := loadersFrom(ctx).Schedule
	if loader == nil {
		return app.ScheduleStore.FindOne(ctx, id)
	}

	return loader.FetchOne(ctx, id)
}

func (app *App) FindOneUser(ctx context.Context, id string) (*user.User, error) {
	loader := loadersFrom(ctx).User
	if loader == nil {
		return app.UserStore.FindOne(ctx, id)
	}

	return loader.FetchOne(ctx, id)
}

func (app *App) FindOneAlertMetric(ctx context.Context, id int) (*alertmetrics.Metric, error) {
	loader := loadersFrom(ctx).AlertMetrics
	if loader == nil {
		m, err := app.AlertMetricsStore.FindMetrics(ctx, []int{id})
		if err != nil {
			return nil, err
		}
		if len(m) == 0 {
			return nil, nil
		}
		return &m[0], nil
	}

	return loader.FetchOne(ctx, id)
}

// FindOneCM will return a single contact method for the given id, using the contexts dataloader if enabled.
func (app *App) FindOneCM(ctx context.Context, id uuid.UUID) (*contactmethod.ContactMethod, error) {
	loader := loadersFrom(ctx).CM
	if loader == nil {
		return app.CMStore.FindOne(ctx, app.DB, id)
	}

	return loader.FetchOne(ctx, id.String())
}

// FindOneNC will return a single notification channel for the given id, using the contexts dataloader if enabled.
func (app *App) FindOneNC(ctx context.Context, id uuid.UUID) (*notificationchannel.Channel, error) {
	loader := loadersFrom(ctx).NC
	if loader == nil {
		return app.NCStore.FindOne(ctx, id)
	}

	return loader.FetchOne(ctx, id.String())
}

func (app *App) FindOnePolicy(ctx context.Context, id string) (*escalation.Policy, error) {
	loader := loadersFrom(ctx).EP
	if loader == nil {
		return app.PolicyStore.FindOnePolicyTx(ctx, nil, id)
	}

	return loader.FetchOne(ctx, id)
}

func (app *App) FindOneService(ctx context.Context, id string) (*service.Service, error) {
	loader := loadersFrom(ctx).Service
	if loader == nil {
		return app.ServiceStore.FindOne(ctx, id)
	}

	return loader.FetchOne(ctx, id)
}

func (app *App) FindOneAlertState(ctx context.Context, alertID int) (*alert.State, error) {
	loader := loadersFrom(ctx).AlertState
	if loader == nil {
		epState, err := app.AlertStore.State(ctx, []int{alertID})
		if err != nil {
			return nil, err
		}
		if len(epState) == 0 {
			return nil, errors.New("no current epState for alert")
		}
		return &epState[0], nil
	}

	return loader.FetchOne(ctx, alertID)
}

func (app *App) FindOneAlert(ctx context.Context, id int) (*alert.Alert, error) {
	loader := loadersFrom(ctx).Alert
	if loader == nil {
		return app.AlertStore.FindOne(ctx, id)
	}

	return loader.FetchOne(ctx, id)
}

func (app *App) FindOneHeartbeatMonitor(ctx context.Context, id string) (*heartbeat.Monitor, error) {
	loader := loadersFrom(ctx).Heartbeat
	if loader == nil {
		hb, err := app.HeartbeatStore.FindMany(ctx, []string{id})
		if err != nil {
			return nil, err
		}
		if len(hb) == 0 {
			return nil, nil
		}
		return &hb[0], nil
	}

	return loader.FetchOne(ctx, id)
}