-
Notifications
You must be signed in to change notification settings - Fork 323
/
errors.go
811 lines (685 loc) · 25.9 KB
/
errors.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
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
package clickhouse
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/highlight-run/highlight/backend/parser"
"github.com/highlight-run/highlight/backend/parser/listener"
"github.com/ClickHouse/clickhouse-go/v2"
"github.com/highlight-run/highlight/backend/model"
modelInputs "github.com/highlight-run/highlight/backend/private-graph/graph/model"
model2 "github.com/highlight-run/highlight/backend/public-graph/graph/model"
"github.com/huandu/go-sqlbuilder"
"github.com/openlyinc/pointy"
"github.com/samber/lo"
)
type ClickhouseErrorGroup struct {
ProjectID int32
CreatedAt int64
UpdatedAt int64
ID int64
SecureID string
Event string
Status string
Type string
ErrorTagID int64
ErrorTagTitle string
ErrorTagDescription string
}
type ClickhouseErrorObject struct {
ProjectID int32
Timestamp int64
ErrorGroupID int64
HasSession bool
ID int64
Browser string
Environment string
OSName string
ServiceName string
ServiceVersion string
ClientID string
VisitedURL string
TraceID string
SecureSessionID string
}
const ErrorGroupsTable = "error_groups"
const ErrorObjectsTable = "error_objects"
const errorsTimeRangeField = "error-field_timestamp"
func (client *Client) WriteErrorGroups(ctx context.Context, groups []*model.ErrorGroup) error {
chGroups := []interface{}{}
for _, group := range groups {
if group == nil {
return errors.New("nil group")
}
chEg := ClickhouseErrorGroup{
ProjectID: int32(group.ProjectID),
CreatedAt: group.CreatedAt.UTC().UnixMicro(),
UpdatedAt: group.UpdatedAt.UTC().UnixMicro(),
ID: int64(group.ID),
SecureID: group.SecureID,
Event: group.Event,
Status: string(group.State),
Type: group.Type,
}
if group.ErrorTag != nil {
chEg.ErrorTagID = int64(group.ErrorTag.ID)
chEg.ErrorTagTitle = group.ErrorTag.Title
chEg.ErrorTagDescription = group.ErrorTag.Description
}
chGroups = append(chGroups, &chEg)
}
chCtx := clickhouse.Context(ctx, clickhouse.WithSettings(clickhouse.Settings{
"async_insert": 1,
"wait_for_async_insert": 1,
}))
if len(chGroups) > 0 {
sql, args := sqlbuilder.
NewStruct(new(ClickhouseErrorGroup)).
InsertInto(ErrorGroupsTable, chGroups...).
BuildWithFlavor(sqlbuilder.ClickHouse)
sql, args = replaceTimestampInserts(sql, args, map[int]bool{1: true, 2: true}, MicroSeconds)
return client.conn.Exec(chCtx, sql, args...)
}
return nil
}
func (client *Client) WriteErrorObjects(ctx context.Context, objects []*model.ErrorObject, sessions []*model.Session) error {
chObjects := []interface{}{}
sessionsById := lo.KeyBy(sessions, func(session *model.Session) int {
return session.ID
})
for _, object := range objects {
if object == nil {
return errors.New("nil object")
}
hasSession := false
clientId := ""
secureSessionId := ""
if object.SessionID != nil {
relatedSession := sessionsById[*object.SessionID]
if relatedSession != nil {
clientId = relatedSession.ClientID
hasSession = !relatedSession.Excluded
secureSessionId = relatedSession.SecureID
}
}
traceId := ""
if object.TraceID != nil {
traceId = *object.TraceID
}
chEg := ClickhouseErrorObject{
ProjectID: int32(object.ProjectID),
Timestamp: object.Timestamp.UTC().UnixMicro(),
ErrorGroupID: int64(object.ErrorGroupID),
HasSession: hasSession,
ID: int64(object.ID),
Browser: object.Browser,
Environment: object.Environment,
OSName: object.OS,
ServiceName: object.ServiceName,
ServiceVersion: object.ServiceVersion,
ClientID: clientId,
VisitedURL: object.URL,
TraceID: traceId,
SecureSessionID: secureSessionId,
}
chObjects = append(chObjects, &chEg)
}
chCtx := clickhouse.Context(ctx, clickhouse.WithSettings(clickhouse.Settings{
"async_insert": 1,
"wait_for_async_insert": 1,
}))
if len(chObjects) > 0 {
sql, args := sqlbuilder.
NewStruct(new(ClickhouseErrorObject)).
InsertInto(ErrorObjectsTable, chObjects...).
BuildWithFlavor(sqlbuilder.ClickHouse)
sql, args = replaceTimestampInserts(sql, args, map[int]bool{1: true}, MicroSeconds)
return client.conn.Exec(chCtx, sql, args...)
}
return nil
}
func getErrorQueryImplDeprecated(tableName string, selectColumns string, query modelInputs.ClickhouseQuery, projectId int, groupBy *string, orderBy *string, limit *int, offset *int) (string, []interface{}, error) {
rules, err := deserializeRules(query.Rules)
if err != nil {
return "", nil, err
}
end := query.DateRange.EndDate.UTC()
start := query.DateRange.StartDate.UTC()
timeRangeRule := Rule{
Field: errorsTimeRangeField,
Op: BetweenDate,
Val: []string{fmt.Sprintf("%s_%s", start.Format(timeFormat), end.Format(timeFormat))},
}
rules = append(rules, timeRangeRule)
sb, err := parseErrorRules(tableName, selectColumns, query.IsAnd, rules, projectId, start, end)
if err != nil {
return "", nil, err
}
if groupBy != nil {
sb.GroupBy(*groupBy)
}
if orderBy != nil {
sb.OrderBy(*orderBy)
}
if limit != nil {
sb.Limit(*limit)
}
if offset != nil {
sb.Offset(*offset)
}
sql, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
return sql, args, nil
}
func (client *Client) QueryErrorGroupIdsDeprecated(ctx context.Context, projectId int, count int, query modelInputs.ClickhouseQuery, page *int) ([]int64, int64, error) {
pageInt := 1
if page != nil {
pageInt = *page
}
offset := (pageInt - 1) * count
sql, args, err := getErrorQueryImplDeprecated(ErrorGroupsTable, "ID, count() OVER() AS total", query, projectId, nil, pointy.String("UpdatedAt DESC, ID DESC"), pointy.Int(count), pointy.Int(offset))
if err != nil {
return nil, 0, err
}
rows, err := client.conn.Query(ctx, sql, args...)
if err != nil {
return nil, 0, err
}
ids := []int64{}
var total uint64
for rows.Next() {
var id int64
if err := rows.Scan(&id, &total); err != nil {
return nil, 0, err
}
ids = append(ids, id)
}
return ids, int64(total), nil
}
func (client *Client) QueryErrorGroupFrequencies(ctx context.Context, projectId int, errorGroupIds []int, params modelInputs.ErrorGroupFrequenciesParamsInput) ([]*modelInputs.ErrorDistributionItem, error) {
if params.DateRange == nil {
return nil, errors.New("params.DateRange must not be nil")
}
sb := sqlbuilder.NewSelectBuilder()
mins := params.ResolutionMinutes
builders := []sqlbuilder.Builder{}
sbInner := sqlbuilder.NewSelectBuilder()
sbInner.Select(fmt.Sprintf("ErrorGroupID, intDiv(toRelativeMinuteNum(Timestamp), %s) AS index, count(*) AS count", sbInner.Var(mins))).
From("error_objects FINAL").
Where(sbInner.Equal("ProjectID", projectId)).
Where(sbInner.In("ErrorGroupID", errorGroupIds)).
Where(sbInner.Between("Timestamp", params.DateRange.StartDate, params.DateRange.EndDate)).
GroupBy("1, 2")
builders = append(builders, sbInner)
for _, id := range errorGroupIds {
defaultInner := sqlbuilder.Buildf(`
SELECT %s as ErrorGroupID, intDiv(toRelativeMinuteNum(%s), %s), 0
ORDER BY
1 WITH FILL,
2 WITH FILL FROM intDiv(toRelativeMinuteNum(%s), %s) TO intDiv(toRelativeMinuteNum(%s), %s)`,
id, params.DateRange.StartDate, mins, params.DateRange.StartDate, mins, params.DateRange.EndDate, mins)
builders = append(builders, defaultInner)
}
sql, args := sb.Select(fmt.Sprintf("ErrorGroupID, addMinutes(makeDate(0, 0), index * %s), sum(count)", sb.Var(mins))).
From(sb.BuilderAs(sqlbuilder.UnionAll(builders...), "inner")).
GroupBy("1, 2").
OrderBy("1, 2").
BuildWithFlavor(sqlbuilder.ClickHouse)
rows, err := client.conn.Query(ctx, sql, args...)
if err != nil {
return nil, err
}
items := []*modelInputs.ErrorDistributionItem{}
for rows.Next() {
var errorGroupId int64
var date time.Time
var count uint64
if err := rows.Scan(&errorGroupId, &date, &count); err != nil {
return nil, err
}
items = append(items, &modelInputs.ErrorDistributionItem{
ErrorGroupID: int(errorGroupId),
Date: date,
Name: "count",
Value: int64(count),
})
}
return items, err
}
func (client *Client) QueryErrorGroupAggregateFrequency(ctx context.Context, projectId int, errorGroupIds []int) ([]*modelInputs.ErrorDistributionItem, error) {
sb := sqlbuilder.NewSelectBuilder()
sql, args := sb.Select(`ErrorGroupID,
now(),
countIf(Timestamp >= now() - INTERVAL 30 DAY) as monthCount,
uniqIf(ClientID, Timestamp >= now() - INTERVAL 30 DAY) as monthIdentifierCount,
countIf(Timestamp >= now() - INTERVAL 7 DAY) as weekCount,
uniqIf(ClientID, Timestamp >= now() - INTERVAL 7 DAY) as weekIdentifierCount,
countIf(Timestamp BETWEEN now() - INTERVAL 14 DAY AND now() - INTERVAL 7 DAY) as prevWeekCount,
uniqIf(ClientID, Timestamp BETWEEN now() - INTERVAL 14 DAY AND now() - INTERVAL 7 DAY) as prevWeekIdentifierCount`).
From("error_objects FINAL").
Where(sb.Equal("ProjectID", projectId)).
Where(sb.In("ErrorGroupID", errorGroupIds)).
GroupBy("1").
BuildWithFlavor(sqlbuilder.ClickHouse)
rows, err := client.conn.Query(ctx, sql, args...)
if err != nil {
return nil, err
}
items := []*modelInputs.ErrorDistributionItem{}
for rows.Next() {
var errorGroupId int64
var now time.Time
var monthCount uint64
var monthIdentifierCount uint64
var weekCount uint64
var weekIdentifierCount uint64
var prevWeekCount uint64
var prevWeekIdentifierCount uint64
if err := rows.Scan(&errorGroupId, &now, &monthCount, &monthIdentifierCount,
&weekCount, &weekIdentifierCount, &prevWeekCount, &prevWeekIdentifierCount); err != nil {
return nil, err
}
items = append(items, &modelInputs.ErrorDistributionItem{
ErrorGroupID: int(errorGroupId),
Date: now.AddDate(0, 0, -30),
Name: "monthCount",
Value: int64(monthCount),
})
items = append(items, &modelInputs.ErrorDistributionItem{
ErrorGroupID: int(errorGroupId),
Date: now.AddDate(0, 0, -30),
Name: "monthIdentifierCount",
Value: int64(monthIdentifierCount),
})
items = append(items, &modelInputs.ErrorDistributionItem{
ErrorGroupID: int(errorGroupId),
Date: now.AddDate(0, 0, -14),
Name: "weekCount",
Value: int64(prevWeekCount),
})
items = append(items, &modelInputs.ErrorDistributionItem{
ErrorGroupID: int(errorGroupId),
Date: now.AddDate(0, 0, -14),
Name: "weekIdentifierCount",
Value: int64(prevWeekIdentifierCount),
})
items = append(items, &modelInputs.ErrorDistributionItem{
ErrorGroupID: int(errorGroupId),
Date: now.AddDate(0, 0, -7),
Name: "weekCount",
Value: int64(weekCount),
})
items = append(items, &modelInputs.ErrorDistributionItem{
ErrorGroupID: int(errorGroupId),
Date: now.AddDate(0, 0, -7),
Name: "weekIdentifierCount",
Value: int64(weekIdentifierCount),
})
}
return items, err
}
func (client *Client) QueryErrorGroupOccurrences(ctx context.Context, projectId int, errorGroupId int) (*time.Time, *time.Time, error) {
sb := sqlbuilder.NewSelectBuilder()
sql, args := sb.Select(`
min(Timestamp) as firstOccurrence,
max(Timestamp) as lastOccurrence`).
From("error_objects FINAL").
Where(sb.Equal("ProjectID", projectId)).
Where(sb.Equal("ErrorGroupID", errorGroupId)).
BuildWithFlavor(sqlbuilder.ClickHouse)
rows, err := client.conn.Query(ctx, sql, args...)
if err != nil {
return nil, nil, err
}
var firstOccurrence time.Time
var lastOccurrence time.Time
for rows.Next() {
if err := rows.Scan(&firstOccurrence, &lastOccurrence); err != nil {
return nil, nil, err
}
}
return &firstOccurrence, &lastOccurrence, nil
}
func (client *Client) QueryErrorGroupTags(ctx context.Context, projectId int, errorGroupId int) ([]*modelInputs.ErrorGroupTagAggregation, error) {
tags := map[string]string{
"browser": "Browser",
"environment": "Environment",
"os_name": "OSName",
}
builders := []sqlbuilder.Builder{}
sb := sqlbuilder.NewSelectBuilder()
sb.Select("'total', 'total', count(*)").
From("error_objects FINAL").
Where(sb.Equal("ProjectID", projectId)).
Where(sb.Equal("ErrorGroupID", errorGroupId))
builders = append(builders, sb)
for key, bucket := range tags {
sb := sqlbuilder.NewSelectBuilder()
sb.Select(fmt.Sprintf("'%s', %s, count(*)", key, bucket)).
From("error_objects FINAL").
Where(sb.Equal("ProjectID", projectId)).
Where(sb.Equal("ErrorGroupID", errorGroupId)).
GroupBy(bucket)
builders = append(builders, sb)
}
sql, args := sqlbuilder.UnionAll(builders...).
BuildWithFlavor(sqlbuilder.ClickHouse)
rows, err := client.conn.Query(ctx, sql, args...)
if err != nil {
return nil, err
}
aggs := map[string]*modelInputs.ErrorGroupTagAggregation{}
for key := range tags {
aggs[key] = &modelInputs.ErrorGroupTagAggregation{
Key: key,
Buckets: []*modelInputs.ErrorGroupTagAggregationBucket{},
}
}
var total uint64
for rows.Next() {
var key string
var bucket string
var count uint64
if err := rows.Scan(&key, &bucket, &count); err != nil {
return nil, err
}
if key == "total" {
total = count
} else {
aggs[key].Buckets = append(aggs[key].Buckets, &modelInputs.ErrorGroupTagAggregationBucket{
Key: bucket,
DocCount: int64(count),
})
}
}
// In some versions of ClickHouse, the total result will not always be returned first,
// so calculate each bucket's percentage after iterating through the results.
for _, value := range aggs {
for _, bucket := range value.Buckets {
bucket.Percent = float64(bucket.DocCount) / float64(total)
}
}
return lo.Values(aggs), nil
}
func (client *Client) QueryErrorFieldValues(ctx context.Context, projectId int, count int, fieldName string, query string, start time.Time, end time.Time) ([]string, error) {
var table string
var mappedName string
var ok bool
// needed to support "Tag" for backwards compatibility (can remove with new query language)
fieldName = strings.ToLower(fieldName)
if mappedName, ok = ErrorGroupsTableConfig.KeysToColumns[modelInputs.ReservedErrorGroupKey(fieldName)]; ok {
table = ErrorGroupsTable
} else if mappedName, ok = ErrorObjectsTableConfig.KeysToColumns[modelInputs.ReservedErrorObjectKey(fieldName)]; ok {
table = ErrorObjectsTable
} else {
return nil, fmt.Errorf("unknown column %s", fieldName)
}
sb := sqlbuilder.NewSelectBuilder()
sb = sb.
Select(fmt.Sprintf("toString(%s)", mappedName)).
From(table).
Where(sb.Equal("ProjectID", projectId)).
Where(fmt.Sprintf("toString(%s) ILIKE %s", mappedName, sb.Var("%"+query+"%"))).
Where(fmt.Sprintf("toString(%s) <> ''", mappedName))
if table == ErrorGroupsTable {
sb = sb.Where(sb.Or(
sb.Between("CreatedAt", start, end),
sb.Between("UpdatedAt", start, end)))
} else {
sb = sb.Where(sb.Between("Timestamp", start, end))
}
sql, args := sb.GroupBy("1").
OrderBy("count() DESC").
Limit(count).
BuildWithFlavor(sqlbuilder.ClickHouse)
rows, err := client.conn.Query(ctx, sql, args...)
if err != nil {
return nil, err
}
values := []string{}
for rows.Next() {
var value string
if err := rows.Scan(&value); err != nil {
return nil, err
}
values = append(values, value)
}
return values, nil
}
func (client *Client) QueryErrorHistogramDeprecated(ctx context.Context, projectId int, query modelInputs.ClickhouseQuery, options modelInputs.DateHistogramOptions) ([]time.Time, []int64, error) {
aggFn, addFn, location, err := getClickhouseHistogramSettings(options)
if err != nil {
return nil, nil, err
}
selectCols := fmt.Sprintf("%s(Timestamp, '%s') as time, count() as count", aggFn, location.String())
orderBy := fmt.Sprintf("1 WITH FILL FROM %s(?, '%s') TO %s(?, '%s') STEP 1", aggFn, location.String(), aggFn, location.String())
sql, args, err := getErrorQueryImplDeprecated(ErrorObjectsTable, selectCols, query, projectId, pointy.String("1"), &orderBy, nil, nil)
if err != nil {
return nil, nil, err
}
args = append(args, *options.Bounds.StartDate, *options.Bounds.EndDate)
sql = fmt.Sprintf("SELECT %s(makeDate(0, 0), time), count from (%s)", addFn, sql)
rows, err := client.conn.Query(ctx, sql, args...)
if err != nil {
return nil, nil, err
}
bucketTimes := []time.Time{}
totals := []int64{}
for rows.Next() {
var time time.Time
var total uint64
if err := rows.Scan(&time, &total); err != nil {
return nil, nil, err
}
bucketTimes = append(bucketTimes, time)
totals = append(totals, int64(total))
}
return bucketTimes, totals, nil
}
var ErrorGroupsTableConfig = model.TableConfig[modelInputs.ReservedErrorGroupKey]{
TableName: ErrorGroupsTable,
KeysToColumns: map[modelInputs.ReservedErrorGroupKey]string{
modelInputs.ReservedErrorGroupKeyEvent: "Event",
modelInputs.ReservedErrorGroupKeySecureID: "SecureID",
modelInputs.ReservedErrorGroupKeyStatus: "Status",
modelInputs.ReservedErrorGroupKeyTag: "ErrorTagTitle",
modelInputs.ReservedErrorGroupKeyType: "Type",
},
BodyColumn: "Event",
ReservedKeys: modelInputs.AllReservedErrorGroupKey,
}
var ErrorObjectsTableConfig = model.TableConfig[modelInputs.ReservedErrorObjectKey]{
TableName: ErrorObjectsTable,
KeysToColumns: map[modelInputs.ReservedErrorObjectKey]string{
modelInputs.ReservedErrorObjectKeyBrowser: "Browser",
modelInputs.ReservedErrorObjectKeyClientID: "ClientID",
modelInputs.ReservedErrorObjectKeyEnvironment: "Environment",
modelInputs.ReservedErrorObjectKeyHasSession: "HasSession",
modelInputs.ReservedErrorObjectKeyOsName: "OSName",
modelInputs.ReservedErrorObjectKeySecureSessionID: "SecureSessionID",
modelInputs.ReservedErrorObjectKeyServiceName: "ServiceName",
modelInputs.ReservedErrorObjectKeyServiceVersion: "ServiceVersion",
modelInputs.ReservedErrorObjectKeyTimestamp: "Timestamp",
modelInputs.ReservedErrorObjectKeyTraceID: "TraceID",
modelInputs.ReservedErrorObjectKeyVisitedURL: "VisitedURL",
},
ReservedKeys: modelInputs.AllReservedErrorObjectKey,
}
var ErrorsJoinedTableConfig = model.TableConfig[modelInputs.ReservedErrorsJoinedKey]{
TableName: "errors_joined_vw",
KeysToColumns: map[modelInputs.ReservedErrorsJoinedKey]string{
modelInputs.ReservedErrorsJoinedKeyID: "ID",
modelInputs.ReservedErrorsJoinedKeyBrowser: "Browser",
modelInputs.ReservedErrorsJoinedKeyClientID: "ClientID",
modelInputs.ReservedErrorsJoinedKeyEnvironment: "Environment",
modelInputs.ReservedErrorsJoinedKeyEvent: "Event",
modelInputs.ReservedErrorsJoinedKeyHasSession: "HasSession",
modelInputs.ReservedErrorsJoinedKeyOsName: "OSName",
modelInputs.ReservedErrorsJoinedKeySecureID: "SecureID",
modelInputs.ReservedErrorsJoinedKeySecureSessionID: "SecureSessionID",
modelInputs.ReservedErrorsJoinedKeyServiceName: "ServiceName",
modelInputs.ReservedErrorsJoinedKeyServiceVersion: "ServiceVersion",
modelInputs.ReservedErrorsJoinedKeyStatus: "Status",
modelInputs.ReservedErrorsJoinedKeyTag: "ErrorTagTitle",
modelInputs.ReservedErrorsJoinedKeyTimestamp: "Timestamp",
modelInputs.ReservedErrorsJoinedKeyTraceID: "TraceID",
modelInputs.ReservedErrorsJoinedKeyType: "Type",
modelInputs.ReservedErrorsJoinedKeyVisitedURL: "VisitedURL",
},
BodyColumn: "Event",
ReservedKeys: modelInputs.AllReservedErrorsJoinedKey,
}
var BackendErrorObjectInputConfig = model.TableConfig[modelInputs.ReservedErrorsJoinedKey]{
KeysToColumns: map[modelInputs.ReservedErrorsJoinedKey]string{
modelInputs.ReservedErrorsJoinedKeyEnvironment: "Environment",
modelInputs.ReservedErrorsJoinedKeyEvent: "Event",
modelInputs.ReservedErrorsJoinedKeyHasSession: "SessionSecureID",
modelInputs.ReservedErrorsJoinedKeyServiceName: "Service.Name",
modelInputs.ReservedErrorsJoinedKeyServiceVersion: "Service.Version",
modelInputs.ReservedErrorsJoinedKeyTimestamp: "Timestamp",
modelInputs.ReservedErrorsJoinedKeyType: "Type",
modelInputs.ReservedErrorsJoinedKeyVisitedURL: "URL",
},
BodyColumn: "Event",
ReservedKeys: modelInputs.AllReservedErrorsJoinedKey,
}
var errorsSampleableTableConfig = sampleableTableConfig[modelInputs.ReservedErrorsJoinedKey]{
tableConfig: ErrorsJoinedTableConfig,
useSampling: func(time.Duration) bool {
return false
},
}
func ErrorMatchesQuery(errorObject *model2.BackendErrorObjectInput, filters listener.Filters) bool {
return matchesQuery(errorObject, BackendErrorObjectInputConfig, filters, listener.OperatorAnd)
}
func (client *Client) ReadErrorsMetrics(ctx context.Context, projectID int, params modelInputs.QueryInput, column string, metricTypes []modelInputs.MetricAggregator, groupBy []string, nBuckets *int, bucketBy string, limit *int, limitAggregator *modelInputs.MetricAggregator, limitColumn *string) (*modelInputs.MetricsBuckets, error) {
return readMetrics(ctx, client, errorsSampleableTableConfig, projectID, params, column, metricTypes, groupBy, nBuckets, bucketBy, limit, limitAggregator, limitColumn)
}
func (client *Client) ReadWorkspaceErrorCounts(ctx context.Context, projectIDs []int, params modelInputs.QueryInput) (*modelInputs.MetricsBuckets, error) {
// 12 buckets - 12 months in a year, or 12 weeks in a quarter
return readWorkspaceMetrics(ctx, client, errorsSampleableTableConfig, projectIDs, params, "id", []modelInputs.MetricAggregator{modelInputs.MetricAggregatorCount}, nil, pointy.Int(12), modelInputs.MetricBucketByTimestamp.String(), nil, nil, nil)
}
func (client *Client) ErrorsKeyValues(ctx context.Context, projectID int, keyName string, startDate time.Time, endDate time.Time) ([]string, error) {
return client.QueryErrorFieldValues(ctx, projectID, 10, keyName, "", startDate, endDate)
}
func (client *Client) QueryErrorObjectsHistogram(ctx context.Context, projectId int, params modelInputs.QueryInput, options modelInputs.DateHistogramOptions) ([]time.Time, []int64, error) {
aggFn, addFn, location, err := getClickhouseHistogramSettings(options)
if err != nil {
return nil, nil, err
}
sb, err := readErrorsObjects(params, projectId)
if err != nil {
return nil, nil, err
}
sb.Select(fmt.Sprintf("%s(Timestamp, '%s') as time, count() as count", aggFn, location.String()))
sb.GroupBy("1")
sb.OrderBy(fmt.Sprintf("1 WITH FILL FROM %s(?, '%s') TO %s(?, '%s') STEP 1", aggFn, location.String(), aggFn, location.String()))
sql, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
args = append(args, *options.Bounds.StartDate, *options.Bounds.EndDate)
sql = fmt.Sprintf("SELECT %s(makeDate(0, 0), time), count from (%s)", addFn, sql)
rows, err := client.conn.Query(ctx, sql, args...)
if err != nil {
return nil, nil, err
}
bucketTimes := []time.Time{}
totals := []int64{}
for rows.Next() {
var time time.Time
var total uint64
if err := rows.Scan(&time, &total); err != nil {
return nil, nil, err
}
bucketTimes = append(bucketTimes, time)
totals = append(totals, int64(total))
}
return bucketTimes, totals, nil
}
func (client *Client) QueryErrorObjects(ctx context.Context, projectId int, errorGroupId int, count int, params modelInputs.QueryInput, page *int) ([]int64, int64, error) {
pageInt := 1
if page != nil {
pageInt = *page
}
offset := (pageInt - 1) * count
sb, err := readErrorsObjects(params, projectId)
if err != nil {
return nil, 0, err
}
sb.Where(sb.Equal("ErrorGroupID", errorGroupId))
sb.Select("ID, count() OVER() AS total")
sb.OrderBy("Timestamp DESC")
sb.Limit(count)
sb.Offset(offset)
sql, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
rows, err := client.conn.Query(ctx, sql, args...)
if err != nil {
return nil, 0, err
}
ids := []int64{}
var total uint64
for rows.Next() {
var id int64
if err := rows.Scan(&id, &total); err != nil {
return nil, 0, err
}
ids = append(ids, id)
}
return ids, int64(total), nil
}
func (client *Client) QueryErrorGroups(ctx context.Context, projectId int, count int, params modelInputs.QueryInput, page *int) ([]int64, int64, error) {
pageInt := 1
if page != nil {
pageInt = *page
}
offset := (pageInt - 1) * count
var sb *sqlbuilder.SelectBuilder
var err error
sb, err = readErrorGroups(params, projectId)
if err != nil {
return nil, 0, err
}
sb.Select("ID, count() OVER() AS total")
sb.OrderBy("UpdatedAt DESC, ID DESC")
sb.Limit(count)
sb.Offset(offset)
sql, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
rows, err := client.conn.Query(ctx, sql, args...)
if err != nil {
return nil, 0, err
}
ids := []int64{}
var total uint64
for rows.Next() {
var id int64
if err := rows.Scan(&id, &total); err != nil {
return nil, 0, err
}
ids = append(ids, id)
}
return ids, int64(total), nil
}
func readErrorGroups(params modelInputs.QueryInput, projectId int) (*sqlbuilder.SelectBuilder, error) {
sb := sqlbuilder.NewSelectBuilder()
sb.From(fmt.Sprintf("%s FINAL", ErrorGroupsTableConfig.TableName))
sbInner := sqlbuilder.NewSelectBuilder()
sbInner.Select("ErrorGroupID")
sbInner.From(fmt.Sprintf("%s FINAL", ErrorsJoinedTableConfig.TableName))
sbInner.Where(sbInner.Equal("ProjectId", projectId))
sbInner.Where(sbInner.LessEqualThan("Timestamp", params.DateRange.EndDate)).
Where(sbInner.GreaterEqualThan("Timestamp", params.DateRange.StartDate))
parser.AssignSearchFilters(sbInner, params.Query, ErrorsJoinedTableConfig)
sb.Where(sb.In("ID", sbInner))
return sb, nil
}
func readErrorsObjects(params modelInputs.QueryInput, projectId int) (*sqlbuilder.SelectBuilder, error) {
sb := sqlbuilder.NewSelectBuilder()
sb.From(fmt.Sprintf("%s FINAL", ErrorsJoinedTableConfig.TableName))
sb.Where(sb.Equal("ProjectId", projectId))
sb.Where(sb.LessEqualThan("Timestamp", params.DateRange.EndDate)).
Where(sb.GreaterEqualThan("Timestamp", params.DateRange.StartDate))
parser.AssignSearchFilters(sb, params.Query, ErrorsJoinedTableConfig)
return sb, nil
}
func (client *Client) ErrorsLogLines(ctx context.Context, projectID int, params modelInputs.QueryInput) ([]*modelInputs.LogLine, error) {
return logLines(ctx, client, ErrorsJoinedTableConfig, projectID, params)
}