-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinsight.go
More file actions
355 lines (311 loc) · 10.4 KB
/
insight.go
File metadata and controls
355 lines (311 loc) · 10.4 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
package flashduty
import (
"context"
"fmt"
"net/http"
)
// InsightQueryInput contains common parameters for all /insight/* endpoints
type InsightQueryInput struct {
StartTime int64 // Required: Unix seconds
EndTime int64 // Required: Unix seconds
TeamIDs []int64 // Filter by teams (max 100)
ChannelIDs []int64 // Filter by channels (max 100)
ResponderIDs []int64 // Filter by responders (max 100)
Severities []string // Filter: Critical, Warning, Info
SplitHours bool // Split metrics into work/sleep/off buckets
AggregateUnit string // day, week, or month for time-series
TimeZone string // IANA timezone (e.g., Asia/Shanghai)
Labels map[string]string // Exact-match label filters
Fields map[string]string // Exact-match field filters
SecondsToAckFrom int // Range filter on acknowledgment time (lower bound)
SecondsToAckTo int // Range filter on acknowledgment time (upper bound)
SecondsToCloseFrom int // Range filter on resolution time (lower bound)
SecondsToCloseTo int // Range filter on resolution time (upper bound)
}
// buildRequestBody constructs the common request body from InsightQueryInput
func (input *InsightQueryInput) buildRequestBody() map[string]any {
if input == nil {
return map[string]any{}
}
body := map[string]any{
"start_time": input.StartTime,
"end_time": input.EndTime,
}
if len(input.TeamIDs) > 0 {
body["team_ids"] = input.TeamIDs
}
if len(input.ChannelIDs) > 0 {
body["channel_ids"] = input.ChannelIDs
}
if len(input.ResponderIDs) > 0 {
body["responder_ids"] = input.ResponderIDs
}
if len(input.Severities) > 0 {
body["severities"] = input.Severities
}
if input.SplitHours {
body["split_hours"] = true
}
if input.AggregateUnit != "" {
body["aggregate_unit"] = input.AggregateUnit
}
if input.TimeZone != "" {
body["time_zone"] = input.TimeZone
}
if len(input.Labels) > 0 {
body["labels"] = input.Labels
}
if len(input.Fields) > 0 {
body["fields"] = input.Fields
}
if input.SecondsToAckFrom > 0 {
body["seconds_to_ack_from"] = input.SecondsToAckFrom
}
if input.SecondsToAckTo > 0 {
body["seconds_to_ack_to"] = input.SecondsToAckTo
}
if input.SecondsToCloseFrom > 0 {
body["seconds_to_close_from"] = input.SecondsToCloseFrom
}
if input.SecondsToCloseTo > 0 {
body["seconds_to_close_to"] = input.SecondsToCloseTo
}
return body
}
// QueryInsightByTeamOutput contains team-level insight metrics
type QueryInsightByTeamOutput struct {
Items []DimensionInsightItem `json:"items"`
}
// QueryInsightByTeam queries pre-aggregated metrics grouped by team
func (c *Client) QueryInsightByTeam(ctx context.Context, input *InsightQueryInput) (*QueryInsightByTeamOutput, error) {
if input == nil {
return nil, fmt.Errorf("query input is required")
}
resp, err := c.makeRequest(ctx, "POST", "/insight/team", input.buildRequestBody())
if err != nil {
return nil, fmt.Errorf("failed to query team insights: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return nil, handleAPIError(c.logger, resp)
}
var result struct {
Error *DutyError `json:"error,omitempty"`
Data *struct {
Items []DimensionInsightItem `json:"items"`
} `json:"data,omitempty"`
}
if err := parseResponse(c.logger, resp, &result); err != nil {
return nil, err
}
if result.Error != nil {
return nil, result.Error
}
items := []DimensionInsightItem{}
if result.Data != nil {
items = result.Data.Items
}
return &QueryInsightByTeamOutput{Items: items}, nil
}
// QueryInsightByResponderOutput contains per-responder insight metrics
type QueryInsightByResponderOutput struct {
Items []ResponderInsightItem `json:"items"`
}
// QueryInsightByResponder queries pre-aggregated metrics grouped by responder
func (c *Client) QueryInsightByResponder(ctx context.Context, input *InsightQueryInput) (*QueryInsightByResponderOutput, error) {
if input == nil {
return nil, fmt.Errorf("query input is required")
}
resp, err := c.makeRequest(ctx, "POST", "/insight/responder", input.buildRequestBody())
if err != nil {
return nil, fmt.Errorf("failed to query responder insights: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return nil, handleAPIError(c.logger, resp)
}
var result struct {
Error *DutyError `json:"error,omitempty"`
Data *struct {
Items []ResponderInsightItem `json:"items"`
} `json:"data,omitempty"`
}
if err := parseResponse(c.logger, resp, &result); err != nil {
return nil, err
}
if result.Error != nil {
return nil, result.Error
}
items := []ResponderInsightItem{}
if result.Data != nil {
items = result.Data.Items
}
return &QueryInsightByResponderOutput{Items: items}, nil
}
// QueryInsightByChannelOutput contains per-channel insight metrics
type QueryInsightByChannelOutput struct {
Items []DimensionInsightItem `json:"items"`
}
// QueryInsightByChannel queries pre-aggregated metrics grouped by channel
func (c *Client) QueryInsightByChannel(ctx context.Context, input *InsightQueryInput) (*QueryInsightByChannelOutput, error) {
if input == nil {
return nil, fmt.Errorf("query input is required")
}
resp, err := c.makeRequest(ctx, "POST", "/insight/channel", input.buildRequestBody())
if err != nil {
return nil, fmt.Errorf("failed to query channel insights: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return nil, handleAPIError(c.logger, resp)
}
var result struct {
Error *DutyError `json:"error,omitempty"`
Data *struct {
Items []DimensionInsightItem `json:"items"`
} `json:"data,omitempty"`
}
if err := parseResponse(c.logger, resp, &result); err != nil {
return nil, err
}
if result.Error != nil {
return nil, result.Error
}
items := []DimensionInsightItem{}
if result.Data != nil {
items = result.Data.Items
}
return &QueryInsightByChannelOutput{Items: items}, nil
}
// QueryInsightAlertTopKInput contains parameters for querying top alert sources
type QueryInsightAlertTopKInput struct {
InsightQueryInput
Label string // Required: "check" or "resource"
K int // Top K results (1-100, default 20)
OrderBy string // "total_alert_cnt" or "total_alert_event_cnt"
Asc bool // Sort ascending when true
}
// QueryInsightAlertTopKOutput contains top-K alert sources
type QueryInsightAlertTopKOutput struct {
Items []InsightAlertByLabelItem `json:"items"`
}
// QueryInsightAlertTopK queries top alert sources grouped by a label
func (c *Client) QueryInsightAlertTopK(ctx context.Context, input *QueryInsightAlertTopKInput) (*QueryInsightAlertTopKOutput, error) {
if input == nil {
return nil, fmt.Errorf("query input is required")
}
body := input.InsightQueryInput.buildRequestBody()
if input.Label != "" {
body["label"] = input.Label
}
k := input.K
if k <= 0 {
k = defaultQueryLimit
}
body["k"] = k
if input.OrderBy != "" {
body["orderby"] = input.OrderBy
}
if input.Asc {
body["asc"] = true
}
resp, err := c.makeRequest(ctx, "POST", "/insight/alert/topk-by-label", body)
if err != nil {
return nil, fmt.Errorf("failed to query alert top-K: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return nil, handleAPIError(c.logger, resp)
}
var result struct {
Error *DutyError `json:"error,omitempty"`
Data *struct {
Items []InsightAlertByLabelItem `json:"items"`
} `json:"data,omitempty"`
}
if err := parseResponse(c.logger, resp, &result); err != nil {
return nil, err
}
if result.Error != nil {
return nil, result.Error
}
items := []InsightAlertByLabelItem{}
if result.Data != nil {
items = result.Data.Items
}
return &QueryInsightAlertTopKOutput{Items: items}, nil
}
// QueryInsightIncidentListInput contains parameters for querying incidents with metrics
type QueryInsightIncidentListInput struct {
InsightQueryInput
Limit int // Max results (default 20)
Page int // Page number (default 1)
SearchAfterCtx string // Cursor for the next page when returned by the API
OrderBy string // Deprecated: the API does not support orderby for this endpoint
}
// QueryInsightIncidentListOutput contains incidents with performance metrics
type QueryInsightIncidentListOutput struct {
Items []InsightIncidentItem `json:"items"`
Total int `json:"total"`
HasNextPage bool `json:"has_next_page"`
SearchAfterCtx string `json:"search_after_ctx,omitempty"`
}
// QueryInsightIncidentList queries incidents with attached performance metrics
func (c *Client) QueryInsightIncidentList(ctx context.Context, input *QueryInsightIncidentListInput) (*QueryInsightIncidentListOutput, error) {
if input == nil {
return nil, fmt.Errorf("query input is required")
}
body := input.InsightQueryInput.buildRequestBody()
limit := input.Limit
if limit <= 0 {
limit = defaultQueryLimit
}
page := input.Page
if page <= 0 {
page = 1
}
body["limit"] = limit
body["p"] = page
if input.SearchAfterCtx != "" {
body["search_after_ctx"] = input.SearchAfterCtx
}
resp, err := c.makeRequest(ctx, "POST", "/insight/incident/list", body)
if err != nil {
return nil, fmt.Errorf("failed to query insight incidents: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return nil, handleAPIError(c.logger, resp)
}
var result struct {
Error *DutyError `json:"error,omitempty"`
Data *struct {
Items []InsightIncidentItem `json:"items"`
Total int `json:"total"`
HasNextPage bool `json:"has_next_page"`
SearchAfterCtx string `json:"search_after_ctx,omitempty"`
} `json:"data,omitempty"`
}
if err := parseResponse(c.logger, resp, &result); err != nil {
return nil, err
}
if result.Error != nil {
return nil, result.Error
}
items := []InsightIncidentItem{}
total := 0
hasNextPage := false
searchAfterCtx := ""
if result.Data != nil {
items = result.Data.Items
total = result.Data.Total
hasNextPage = result.Data.HasNextPage
searchAfterCtx = result.Data.SearchAfterCtx
}
return &QueryInsightIncidentListOutput{
Items: items,
Total: total,
HasNextPage: hasNextPage,
SearchAfterCtx: searchAfterCtx,
}, nil
}