-
Notifications
You must be signed in to change notification settings - Fork 320
/
resolver.go
3602 lines (3211 loc) · 132 KB
/
resolver.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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package graph
import (
"compress/gzip"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"hash/fnv"
"io"
"net/http"
"net/mail"
url2 "net/url"
"regexp"
"sort"
"strconv"
"strings"
"time"
"go.opentelemetry.io/otel/codes"
semconv "go.opentelemetry.io/otel/semconv/v1.25.0"
"go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/otel/attribute"
"golang.org/x/sync/errgroup"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"github.com/PaesslerAG/jsonpath"
"github.com/aws/smithy-go/ptr"
"github.com/google/uuid"
lru "github.com/hashicorp/golang-lru/v2"
"github.com/highlight-run/go-resthooks"
"github.com/mssola/user_agent"
"github.com/openlyinc/pointy"
e "github.com/pkg/errors"
"github.com/samber/lo"
"github.com/sendgrid/sendgrid-go"
log "github.com/sirupsen/logrus"
"github.com/highlight-run/highlight/backend/alerts"
"github.com/highlight-run/highlight/backend/clickhouse"
"github.com/highlight-run/highlight/backend/email"
"github.com/highlight-run/highlight/backend/embeddings"
"github.com/highlight-run/highlight/backend/errorgroups"
parse "github.com/highlight-run/highlight/backend/event-parse"
kafka_queue "github.com/highlight-run/highlight/backend/kafka-queue"
"github.com/highlight-run/highlight/backend/lambda"
"github.com/highlight-run/highlight/backend/model"
"github.com/highlight-run/highlight/backend/parser"
"github.com/highlight-run/highlight/backend/phonehome"
"github.com/highlight-run/highlight/backend/pricing"
privateModel "github.com/highlight-run/highlight/backend/private-graph/graph/model"
modelInputs "github.com/highlight-run/highlight/backend/public-graph/graph/model"
publicModel "github.com/highlight-run/highlight/backend/public-graph/graph/model"
"github.com/highlight-run/highlight/backend/redis"
"github.com/highlight-run/highlight/backend/stacktraces"
"github.com/highlight-run/highlight/backend/storage"
"github.com/highlight-run/highlight/backend/store"
tempalerts "github.com/highlight-run/highlight/backend/temp-alerts"
"github.com/highlight-run/highlight/backend/util"
"github.com/highlight-run/highlight/backend/zapier"
"github.com/highlight/highlight/sdk/highlight-go"
hlog "github.com/highlight/highlight/sdk/highlight-go/log"
hmetric "github.com/highlight/highlight/sdk/highlight-go/metric"
)
// This file will not be regenerated automatically.
//
//
// It serves as dependency injection for your app, add any dependencies you require here.
type Resolver struct {
DB *gorm.DB
Tracer trace.Tracer
ProducerQueue kafka_queue.MessageQueue
BatchedQueue kafka_queue.MessageQueue
DataSyncQueue kafka_queue.MessageQueue
TracesQueue kafka_queue.MessageQueue
MailClient *sendgrid.Client
StorageClient storage.Client
EmbeddingsClient embeddings.Client
Redis *redis.Client
Clickhouse *clickhouse.Client
RH *resthooks.Resthook
Store *store.Store
LambdaClient *lambda.Client
SessionCache *lru.Cache[string, *model.Session]
}
type Location struct {
City string `json:"city"`
Postal string `json:"postal"`
Latitude interface{} `json:"latitude"`
Longitude interface{} `json:"longitude"`
State string `json:"state"`
Country string `json:"country_name"`
}
type DeviceDetails struct {
IsBot bool `json:"is_bot"`
OSName string `json:"os_name"`
OSVersion string `json:"os_version"`
BrowserName string `json:"browser_name"`
BrowserVersion string `json:"browser_version"`
}
type Property string
var PropertyType = struct {
USER Property
SESSION Property
TRACK Property
}{
USER: "user",
SESSION: "session",
TRACK: "track",
}
type ErrorMetaData struct {
Timestamp time.Time `json:"timestamp"`
ErrorID int `json:"error_id"`
SessionID int `json:"session_id"`
Browser string `json:"browser"`
OS string `json:"os"`
VisitedURL string `json:"visited_url"`
Identifier string `json:"identifier"`
Fingerprint int `json:"fingerprint"`
}
type FieldData struct {
Name string
Value string
}
type Request struct {
ID string `json:"id"`
URL string `json:"url"`
Method string `json:"verb"`
Headers map[string]string `json:"headers"`
Body any `json:"body"`
}
type Response struct {
Status float64 `json:"status"`
Size float64 `json:"size"`
Headers map[string]string `json:"headers"`
Body any `json:"body"`
}
type RequestResponsePairs struct {
Request Request `json:"request"`
Response Response `json:"response"`
URLBlocked bool `json:"urlBlocked"`
}
type NetworkResource struct {
// Deprecated, use the absolute version `StartTimeAbs` instead
StartTime float64 `json:"startTime"`
// Deprecated, use the absolute version `ResponseEndAbs` instead
ResponseEnd float64 `json:"responseEnd"`
StartTimeAbs float64 `json:"startTimeAbs"`
ResponseEndAbs float64 `json:"responseEndAbs"`
ConnectStartAbs float64 `json:"connectStartAbs"`
ConnectEndAbs float64 `json:"connectEndAbs"`
DomainLookupStartAbs float64 `json:"domainLookupStartAbs"`
DomainLookupEndAbs float64 `json:"domainLookupEndAbs"`
FetchStartAbs float64 `json:"fetchStartAbs"`
RedirectStartAbs float64 `json:"redirectStartAbs"`
RedirectEndAbs float64 `json:"redirectEndAbs"`
RequestStartAbs float64 `json:"requestStartAbs"`
ResponseStartAbs float64 `json:"responseStartAbs"`
SecureConnectionStartAbs float64 `json:"secureConnectionStartAbs"`
WorkerStartAbs float64 `json:"workerStartAbs"`
DecodedBodySize int64 `json:"decodedBodySize"`
TransferSize int64 `json:"transferSize"`
EncodedBodySize int64 `json:"encodedBodySize"`
NextHopProtocol string `json:"nextHopProtocol"`
InitiatorType string `json:"initiatorType"`
Name string `json:"name"`
RequestResponsePairs RequestResponsePairs `json:"requestResponsePairs"`
}
func (re *NetworkResource) Start(sessionStart time.Time) time.Time {
start := time.UnixMicro(int64(1000. * re.StartTimeAbs))
if start.Before(time.Date(2023, time.January, 1, 0, 0, 0, 0, time.UTC)) {
start = sessionStart.Add(time.Microsecond * time.Duration(1000.*re.StartTime))
}
return start
}
func (re *NetworkResource) End(sessionStart time.Time) time.Time {
end := time.UnixMicro(int64(1000. * re.ResponseEndAbs))
if end.Before(time.Date(2023, time.January, 1, 0, 0, 0, 0, time.UTC)) {
end = sessionStart.Add(time.Microsecond * time.Duration(1000.*re.ResponseEnd))
}
return end
}
const ERROR_EVENT_MAX_LENGTH = 10000
const SESSION_FIELD_MAX_LENGTH = 2000
const PAYLOAD_STAGING_COUNT_MAX = 100
var NumberRegex = regexp.MustCompile(`^\d+$`)
var ErrQuotaExceeded = e.New(string(publicModel.PublicGraphErrorBillingQuotaExceeded))
var ErrUserFilteredError = e.New("User filtered error")
var SessionProcessDelaySeconds = 120 // a session will be processed after not receiving events for this time
var SessionProcessLockMinutes = 30 // a session marked as processing can be reprocessed after this time
func init() {
if util.IsDevEnv() {
SessionProcessDelaySeconds = 8
SessionProcessLockMinutes = 1
}
}
// Change to AppendProperties(sessionId,properties,type)
func (r *Resolver) AppendProperties(ctx context.Context, sessionID int, properties map[string]string, propType Property) error {
outerSpan, ctx := util.StartSpanFromContext(ctx, "public-graph.AppendProperties",
util.ResourceName("go.sessions.AppendProperties"), util.Tag("sessionID", sessionID))
defer outerSpan.Finish()
loadSessionSpan, ctx := util.StartSpanFromContext(ctx, "public-graph.AppendProperties",
util.ResourceName("go.sessions.AppendProperties.loadSessions"), util.Tag("sessionID", sessionID))
session := &model.Session{}
res := r.DB.WithContext(ctx).Where(&model.Session{Model: model.Model{ID: sessionID}}).Take(&session)
if err := res.Error; err != nil {
return e.Wrapf(err, "error getting session(id=%d) in append properties(type=%s)", sessionID, propType)
}
loadSessionSpan.Finish()
propsSpan, ctx := util.StartSpanFromContext(ctx, "public-graph.AppendProperties",
util.ResourceName("processProperties"), util.Tag("num_properties", len(properties)))
var modelFields []*model.Field
projectID := session.ProjectID
for k, fv := range properties {
if len(fv) > SESSION_FIELD_MAX_LENGTH {
log.WithContext(ctx).Warnf("property %s from session %d exceeds max expected field length, skipping", k, sessionID)
} else if fv == "" {
// Skip when the field value is blank
} else if NumberRegex.MatchString(k) {
// Skip when the field name is a number
// (this can be sent by clients if a string is passed as an `addProperties` payload)
} else {
modelFields = append(modelFields, &model.Field{ProjectID: projectID, Name: k, Value: fv, Type: string(propType)})
}
}
if len(modelFields) > 1000 {
modelFields = modelFields[:1000]
log.WithContext(ctx).WithField("session_id", sessionID).Warnf("attempted to append more than 1000 fields - truncating")
}
propsSpan.Finish()
if len(modelFields) > 0 {
err := r.AppendFields(ctx, modelFields, session)
if err != nil {
return e.Wrap(err, "error appending fields")
}
}
project, err := r.Store.GetProject(ctx, session.ProjectID)
if err != nil {
log.WithContext(ctx).Error(e.Wrap(err, "error querying project"))
return err
}
workspace, err := r.Store.GetWorkspace(ctx, project.WorkspaceID)
if err != nil {
log.WithContext(ctx).Error(e.Wrap(err, "error querying workspace"))
return err
}
if propType == PropertyType.USER {
return r.SendSessionUserPropertiesAlert(ctx, workspace, project, session)
} else if propType == PropertyType.TRACK {
return r.SendSessionTrackPropertiesAlert(ctx, workspace, project, session, properties)
}
return nil
}
func (r *Resolver) AppendFields(ctx context.Context, fields []*model.Field, session *model.Session) error {
outerSpan, ctx := util.StartSpanFromContext(ctx, "public-graph.AppendFields",
util.ResourceName("go.sessions.AppendFields"), util.Tag("sessionID", session.ID))
defer outerSpan.Finish()
result := r.DB.
Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "project_id"}, {Name: "type"}, {Name: "name"}, {Name: "value"}},
DoNothing: true}).
Create(&fields)
if err := result.Error; err != nil {
return e.Wrap(err, "error inserting new fields")
}
var allFields []*model.Field
inClause := [][]interface{}{}
for _, f := range fields {
inClause = append(inClause, []interface{}{f.ProjectID, f.Type, f.Name, f.Value})
}
if err := r.DB.WithContext(ctx).Where("(project_id, type, name, value) IN ?", inClause).Order("id DESC").
Find(&allFields).Error; err != nil {
return e.Wrap(err, "error retrieving all fields")
}
sort.Slice(allFields, func(i, j int) bool {
return allFields[i].ID < allFields[j].ID
})
var entries []struct {
SessionID int
FieldID int64
}
for _, f := range allFields {
entries = append(entries, struct {
SessionID int
FieldID int64
}{
SessionID: session.ID,
FieldID: f.ID,
})
}
// Associate the fields with this session.
// Do this manually to avoid updating the session `updated_at` column since this operation
// is typically done as part of other steps that update the session `updated_at`.
// Constantly writing to `updated_at` is a source of DB contention for session updates.
if err := r.DB.WithContext(ctx).Table("session_fields").Clauses(clause.OnConflict{
DoNothing: true,
}).Create(entries).Error; err != nil {
return e.Wrap(err, "error updating fields")
}
if err := r.DataSyncQueue.Submit(ctx, strconv.Itoa(session.ID), &kafka_queue.Message{Type: kafka_queue.SessionDataSync, SessionDataSync: &kafka_queue.SessionDataSyncArgs{SessionID: session.ID}}); err != nil {
return err
}
return nil
}
func getIncrementedEnvironmentCount(ctx context.Context, errorGroup *model.ErrorGroup, errorObj *model.ErrorObject) string {
environmentsMap := make(map[string]int)
if errorGroup.Environments != "" {
err := json.Unmarshal([]byte(errorGroup.Environments), &environmentsMap)
if err != nil {
log.WithContext(ctx).Error(e.Wrap(err, "error unmarshalling environments from error group into map"))
}
}
if len(errorObj.Environment) > 0 {
if _, ok := environmentsMap[strings.ToLower(errorObj.Environment)]; ok {
environmentsMap[strings.ToLower(errorObj.Environment)]++
} else {
environmentsMap[strings.ToLower(errorObj.Environment)] = 1
}
}
environmentsBytes, err := json.Marshal(environmentsMap)
if err != nil {
log.WithContext(ctx).Error(e.Wrap(err, "error marshalling environment map into json"))
}
environmentsString := string(environmentsBytes)
return environmentsString
}
func (r *Resolver) GetErrorAppVersion(ctx context.Context, errorObj *model.ErrorObject) *string {
// get version from session
var session *model.Session
if err := r.DB.WithContext(ctx).Model(&session).
Where("id = ?", errorObj.SessionID).
Pluck("app_version", &session).Error; err == nil && session.AppVersion != nil {
return session.AppVersion
}
// guess version from error service
if errorObj.ServiceVersion != "" {
return pointy.String(errorObj.ServiceVersion)
}
return nil
}
func (r *Resolver) getMappedStackTraceString(ctx context.Context, stackTrace []*publicModel.StackFrameInput, projectID int, errorObj *model.ErrorObject) (*string, []*privateModel.ErrorTrace, error) {
span, ctx := util.StartSpanFromContext(ctx, "getMappedStackTraceString")
defer span.Finish()
var newMappedStackTraceString *string
mappedStackTrace, err := stacktraces.EnhanceStackTrace(ctx, stackTrace, projectID, r.GetErrorAppVersion(ctx, errorObj), r.StorageClient)
if err != nil {
log.WithContext(ctx).Error(e.Wrapf(err, "error object: %+v", errorObj))
} else {
mappedStackTraceBytes, err := json.Marshal(mappedStackTrace)
if err != nil {
return nil, nil, e.Wrap(err, "error marshalling mapped stack trace")
}
mappedStackTraceString := string(mappedStackTraceBytes)
newMappedStackTraceString = &mappedStackTraceString
}
return newMappedStackTraceString, mappedStackTrace, nil
}
func (r *Resolver) tagErrorGroup(ctx context.Context, errorObj *model.ErrorObject) *int {
eMatchCtx, cancel := context.WithTimeout(ctx, embeddings.InferenceTimeout)
defer cancel()
query := embeddings.GetErrorObjectQuery(errorObj)
tags, err := embeddings.MatchErrorTag(eMatchCtx, r.DB, r.EmbeddingsClient, query)
if err == nil && len(tags) > 0 {
return &tags[0].ID
} else {
log.WithContext(ctx).WithError(err).WithField("error_object_id", errorObj.ID).Error("failed to get embeddings for error group tag")
}
return nil
}
func (r *Resolver) GetOrCreateErrorGroup(ctx context.Context, errorObj *model.ErrorObject, matchFn func() (*int, error), onCreateGroup func(int) error, tagGroup bool) (*model.ErrorGroup, error) {
match, err := matchFn()
if err != nil {
return nil, err
}
// no match means we are planning to create an error group
// we should lock the write path to make sure we do not write duplicate error groups
if match == nil {
key := fmt.Sprintf("GetOrCreateErrorGroup-project-%d", errorObj.ProjectID)
mutex, err := r.Redis.AcquireLock(ctx, key, time.Minute)
if err != nil {
return nil, err
}
defer func() {
if _, err := mutex.Unlock(); err != nil {
log.WithContext(ctx).WithError(err).WithField("key", key).Error("failed to release lock")
}
}()
// recheck the match with the lock held, then perform the write
match, err = matchFn()
if err != nil {
return nil, err
}
}
errorGroup := &model.ErrorGroup{}
if match == nil {
environmentsString := getIncrementedEnvironmentCount(ctx, errorGroup, errorObj)
newErrorGroup := &model.ErrorGroup{
ProjectID: errorObj.ProjectID,
Event: errorObj.Event,
StackTrace: *errorObj.StackTrace,
MappedStackTrace: errorObj.MappedStackTrace,
Type: errorObj.Type,
State: privateModel.ErrorStateOpen,
Fields: []*model.ErrorField{},
Environments: environmentsString,
ServiceName: errorObj.ServiceName,
}
if tagGroup {
newErrorGroup.ErrorTagID = r.tagErrorGroup(ctx, errorObj)
}
if err := r.DB.WithContext(ctx).Create(newErrorGroup).Error; err != nil {
return nil, e.Wrap(err, "Error creating new error group")
}
if onCreateGroup != nil {
if err := onCreateGroup(newErrorGroup.ID); err != nil {
return nil, err
}
}
errorGroup = newErrorGroup
} else {
if err := r.DB.WithContext(ctx).Where(&model.ErrorGroup{
Model: model.Model{ID: *match},
}).Take(&errorGroup).Error; err != nil {
return nil, e.Wrap(err, "error retrieving top matched error group")
}
environmentsString := getIncrementedEnvironmentCount(ctx, errorGroup, errorObj)
updatedState := errorGroup.State
// Reopen resolved errors
// Note that ignored errors do change state
if updatedState == privateModel.ErrorStateResolved {
updatedState = privateModel.ErrorStateOpen
}
if errorGroup.ErrorTagID == nil && tagGroup {
errorGroup.ErrorTagID = r.tagErrorGroup(ctx, errorObj)
}
if err := r.DB.WithContext(ctx).Model(errorGroup).Updates(&model.ErrorGroup{
StackTrace: *errorObj.StackTrace,
MappedStackTrace: errorObj.MappedStackTrace,
Environments: environmentsString,
Event: errorObj.Event,
State: updatedState,
ServiceName: errorObj.ServiceName,
ErrorTagID: errorGroup.ErrorTagID,
}).Error; err != nil {
return nil, e.Wrap(err, "Error updating error group")
}
}
if err := r.DataSyncQueue.Submit(ctx, strconv.Itoa(errorGroup.ID), &kafka_queue.Message{Type: kafka_queue.ErrorGroupDataSync, ErrorGroupDataSync: &kafka_queue.ErrorGroupDataSyncArgs{ErrorGroupID: errorGroup.ID}}); err != nil {
return nil, err
}
return errorGroup, nil
}
func (r *Resolver) GetTopErrorGroupMatchByEmbedding(ctx context.Context, projectID int, method model.ErrorGroupingMethod, embedding model.Vector, threshold float64) (*int, error) {
span, ctx := util.StartSpanFromContext(ctx, "public-resolver", util.ResourceName("GetTopErrorGroupMatchByEmbedding"), util.Tag("projectID", projectID))
defer span.Finish()
result := struct {
Score float64 `json:"score"`
CombinedScore float64 `json:"combined_score"`
ErrorGroupID int `json:"error_group_id"`
}{}
if method == model.ErrorGroupingMethodGteLargeEmbeddingV3 {
if err := r.DB.WithContext(ctx).Raw(`
select (gte_large_embedding <=> @embedding) * 10 as score,
error_group_id
from error_group_embeddings
where project_id = @projectID
and gte_large_embedding is not null
order by 1
limit 1;`,
map[string]interface{}{
"embedding": embedding,
"projectID": projectID,
}).Scan(&result).Error; err != nil {
return nil, e.Wrap(err, "error querying top error group match")
}
}
if result.ErrorGroupID > 0 {
lg := log.WithContext(ctx).WithField("combined_score", result.CombinedScore).WithField("score", result.Score).WithField("matched_error_group_id", result.ErrorGroupID).WithField("threshold", threshold)
if result.Score < threshold {
lg.Info("matched error group by embeddings")
// Update the error group's embedding as a weighted average of the previous embedding plus this new one
if method == model.ErrorGroupingMethodGteLargeEmbeddingV3 {
if err := r.DB.WithContext(ctx).Exec(`
update error_group_embeddings
set gte_large_embedding = gte_large_embedding * array_fill(count::numeric / (count + 1), '{1024}')::vector
+ @embedding * array_fill(1::numeric / (count + 1), '{1024}')::vector,
count = count + 1
where project_id = @projectID
and error_group_id = @errorGroupID`,
map[string]interface{}{
"embedding": embedding,
"projectID": projectID,
"errorGroupID": result.ErrorGroupID,
}).Error; err != nil {
return nil, e.Wrap(err, "error updating embedding")
}
}
return &result.ErrorGroupID, nil
}
lg.Info("found error group by embeddings but score too high")
}
return nil, nil
}
func (r *Resolver) GetTopErrorGroupMatch(ctx context.Context, event string, projectID int, fingerprints []*model.ErrorFingerprint) (*int, error) {
firstCode := ""
firstMeta := ""
restCode := []string{}
restMeta := []string{}
jsonResults := []string{}
for _, fingerprint := range fingerprints {
if fingerprint.Type == model.Fingerprint.StackFrameCode {
if fingerprint.Index == 0 {
firstCode = fingerprint.Value
} else if fingerprint.Index <= 4 {
restCode = append(restCode, fingerprint.Value)
}
} else if fingerprint.Type == model.Fingerprint.StackFrameMetadata {
if fingerprint.Index == 0 {
firstMeta = fingerprint.Value
} else if fingerprint.Index <= 4 {
restMeta = append(restMeta, fingerprint.Value)
}
} else if fingerprint.Type == model.Fingerprint.JsonResult {
jsonResults = append(jsonResults, fingerprint.Value)
}
}
// Reversing the json results so that ordinality can be used as score
jsonResultsReversed := lo.Reverse(jsonResults)
jsonBytes, err := json.Marshal(jsonResultsReversed)
if err != nil {
return nil, e.Wrap(err, "error marshalling json results")
}
jsonString := string(jsonBytes)
result := struct {
Id int
Sum int
}{}
// temporarily disable error group matching
// for Gorillamind
// because their huge traceback
// slows this process down too much
if projectID == 356 {
return nil, nil
}
start := time.Now()
if err := r.DB.WithContext(context.TODO()).Raw(`
WITH json_results AS (
SELECT CAST(value as VARCHAR), (2 ^ ordinality) * 1000 as score
FROM json_array_elements_text(@jsonString) with ordinality
)
SELECT id, sum(score) FROM (
SELECT id, 100 AS score, 0
FROM error_groups
WHERE event = @event
AND id IS NOT NULL
AND project_id = @projectID
UNION ALL
(SELECT DISTINCT ef.error_group_id, jr.score, 0
FROM error_fingerprints ef
INNER JOIN json_results jr
on ef.value = jr.value
WHERE
(ef.type = 'JSON'
AND ef.project_id = @projectID
AND ef.error_group_id IS NOT NULL))
UNION ALL
(SELECT DISTINCT error_group_id, 10 AS score, 0
FROM error_fingerprints
WHERE
((type = 'META'
AND value = @firstMeta
AND index = 0)
OR (type = 'CODE'
AND value = @firstCode
AND index = 0))
AND project_id = @projectID
AND error_group_id IS NOT NULL)
UNION ALL
(SELECT DISTINCT error_group_id, 1 AS score, index
FROM error_fingerprints
WHERE
((type = 'META'
AND value in @restMeta
AND index > 0 and index <= 4)
OR (type = 'CODE'
AND value in @restCode
AND index > 0 and index <= 4))
AND project_id = @projectID
AND error_group_id IS NOT NULL)
) a
GROUP BY id
ORDER BY sum DESC, id DESC
LIMIT 1`,
map[string]interface{}{
"jsonString": jsonString,
"event": event,
"projectID": projectID,
"firstMeta": firstMeta,
"firstCode": firstCode,
"restMeta": restMeta,
"restCode": restCode}).
Scan(&result).Error; err != nil {
return nil, e.Wrap(err, "error querying top error group match")
}
hmetric.Histogram(ctx, "GetTopErrorGroupMatch.groupSQL.durationMs", float64(time.Since(start).Milliseconds()), nil, 1)
minScore := 10 + len(restMeta) - 1
if len(restCode) > len(restMeta) {
minScore = 10 + len(restCode) - 1
}
if result.Sum > minScore {
return &result.Id, nil
} else {
return nil, nil
}
}
func (r *Resolver) isWithinErrorQuota(ctx context.Context, workspace *model.Workspace) bool {
withinBillingQuota, quotaPercent := r.IsWithinQuota(ctx, model.PricingProductTypeErrors, workspace, time.Now())
go func() {
defer util.Recover()
if quotaPercent >= 1 {
if err := model.SendBillingNotifications(ctx, r.DB, r.MailClient, email.BillingErrorsUsage100Percent, workspace); err != nil {
log.WithContext(ctx).Error(e.Wrap(err, "failed to send billing notifications"))
}
} else if quotaPercent >= .8 {
if err := model.SendBillingNotifications(ctx, r.DB, r.MailClient, email.BillingErrorsUsage80Percent, workspace); err != nil {
log.WithContext(ctx).Error(e.Wrap(err, "failed to send billing notifications"))
}
}
}()
return withinBillingQuota
}
// Matches the ErrorObject with an existing ErrorGroup, or creates a new one if the group does not exist
func (r *Resolver) HandleErrorAndGroup(ctx context.Context, errorObj *model.ErrorObject, structuredStackTrace []*privateModel.ErrorTrace, fields []*model.ErrorField, projectID int, workspace *model.Workspace) (*model.ErrorGroup, error) {
span, ctx := util.StartSpanFromContext(ctx, "HandleErrorAndGroup", util.Tag("projectID", projectID))
defer span.Finish()
if errorObj == nil {
return nil, e.New("error object was nil")
}
if errorObj.Event == "" {
return nil, e.New("error object event was empty")
}
if errorObj.StackTrace == nil {
return nil, errors.New("error object stacktrace was empty")
}
project, err := r.Store.GetProject(ctx, projectID)
if err != nil {
return nil, e.Wrap(err, "error querying project")
}
if errorgroups.IsErrorTraceFiltered(*project, structuredStackTrace) {
return nil, ErrUserFilteredError
}
if len(errorObj.Event) > ERROR_EVENT_MAX_LENGTH {
errorObj.Event = strings.Repeat(errorObj.Event[:ERROR_EVENT_MAX_LENGTH], 1)
}
if len(structuredStackTrace) > 0 {
if len(structuredStackTrace) > stacktraces.ERROR_STACK_MAX_FRAME_COUNT {
structuredStackTrace = structuredStackTrace[:stacktraces.ERROR_STACK_MAX_FRAME_COUNT]
firstFrameBytes, err := json.Marshal(structuredStackTrace)
if err != nil {
return nil, e.Wrap(err, "Error marshalling first frame")
}
errorObj.StackTrace = ptr.String(string(firstFrameBytes))
}
}
fingerprints := []*model.ErrorFingerprint{}
fingerprints = append(fingerprints, errorgroups.GetFingerprints(projectID, structuredStackTrace)...)
// Try unmarshalling the Event to JSON.
// If this works, create an error fingerprint for each of the project's JSON paths.
jsonStrings := []string{}
if err := json.Unmarshal([]byte(errorObj.Event), &jsonStrings); err == nil && len(jsonStrings) == 1 {
errorAsJson := interface{}(nil)
if err := json.Unmarshal([]byte(jsonStrings[0]), &errorAsJson); err == nil {
for _, path := range project.ErrorJsonPaths {
value, err := jsonpath.Get(path, errorAsJson)
if err == nil {
marshalled, err := json.Marshal(value)
if err == nil {
jsonResult := model.ErrorFingerprint{
ProjectID: projectID,
Type: model.Fingerprint.JsonResult,
Value: path + "=" + string(marshalled),
}
fingerprints = append(fingerprints, &jsonResult)
}
}
}
}
}
var errorGroup *model.ErrorGroup
var settings *model.AllWorkspaceSettings
if workspace != nil {
if settings, err = r.Store.GetAllWorkspaceSettings(ctx, workspace.ID); err != nil {
return nil, err
}
}
var embedding *model.ErrorObjectEmbeddings
if settings != nil && settings.ErrorEmbeddingsGroup {
eCtx, cancel := context.WithTimeout(ctx, embeddings.InferenceTimeout)
defer cancel()
var emb []*model.ErrorObjectEmbeddings
emb, err = r.EmbeddingsClient.GetEmbeddings(eCtx, []*model.ErrorObject{errorObj})
if err != nil || len(emb) == 0 {
log.WithContext(ctx).WithError(err).WithField("error_object_id", errorObj.ID).Error("failed to get embeddings")
errorObj.ErrorGroupingMethod = model.ErrorGroupingMethodClassic
} else {
embedding = emb[0]
embeddingType := model.ErrorGroupingMethodGteLargeEmbeddingV3
errorGroup, err = r.GetOrCreateErrorGroup(ctx, errorObj, func() (*int, error) {
match, err := r.GetTopErrorGroupMatchByEmbedding(ctx, errorObj.ProjectID, embeddingType, embedding.GteLargeEmbedding, settings.ErrorEmbeddingsThreshold)
if err != nil {
log.WithContext(ctx).WithError(err).WithField("error_object_id", errorObj.ID).Error("failed to group error using embeddings")
}
return match, err
}, func(errorGroupId int) error {
newEmbedding := model.ErrorGroupEmbeddings{
ProjectID: errorObj.ProjectID,
ErrorGroupID: errorGroupId,
Count: 1,
GteLargeEmbedding: embedding.GteLargeEmbedding,
}
return r.DB.WithContext(ctx).Create(&newEmbedding).Error
}, settings.ErrorEmbeddingsTagGroup)
if err != nil {
return nil, e.Wrap(err, "Error getting or creating error group")
}
errorObj.ErrorGroupingMethod = embeddingType
}
} else {
errorObj.ErrorGroupingMethod = model.ErrorGroupingMethodClassic
}
if errorGroup == nil {
log.WithContext(ctx).WithError(err).WithField("error_object_id", errorObj.ID).Error("failed to create error group by embedding; using classic match")
errorGroup, err = r.GetOrCreateErrorGroup(ctx, errorObj, func() (*int, error) {
match, err := r.GetTopErrorGroupMatch(ctx, errorObj.Event, errorObj.ProjectID, fingerprints)
if err != nil {
return nil, e.Wrap(err, "Error getting top error group match")
}
return match, err
}, nil, settings != nil && settings.ErrorEmbeddingsTagGroup)
if err != nil {
return nil, e.Wrap(err, "Error getting or creating error group")
}
}
errorObj.ErrorGroupID = errorGroup.ID
if err := r.DB.WithContext(ctx).Create(errorObj).Error; err != nil {
return nil, e.Wrap(err, "Error performing error insert for error")
}
if err := r.DataSyncQueue.Submit(ctx, strconv.Itoa(errorObj.ID), &kafka_queue.Message{Type: kafka_queue.ErrorObjectDataSync, ErrorObjectDataSync: &kafka_queue.ErrorObjectDataSyncArgs{ErrorObjectID: errorObj.ID}}); err != nil {
return nil, err
}
if err := r.AppendErrorFields(ctx, fields, errorGroup); err != nil {
return nil, e.Wrap(err, "error appending error fields")
}
if err := r.DB.Transaction(func(tx *gorm.DB) error {
for _, f := range fingerprints {
f.ErrorGroupId = errorGroup.ID
}
if len(fingerprints) > 0 {
if err := r.DB.WithContext(ctx).Model(&model.ErrorFingerprint{}).Create(fingerprints).Error; err != nil {
return e.Wrap(err, "error appending new fingerprints")
}
}
var newIds []int
for _, fingerprint := range fingerprints {
newIds = append(newIds, fingerprint.ID)
}
if err := r.DB.Exec(`
UPDATE error_fingerprints
SET error_group_id = NULL
WHERE id IN (
SELECT id
FROM error_fingerprints
WHERE id NOT IN (?)
AND error_group_id = ?
ORDER BY id
FOR UPDATE
)
`, newIds, errorGroup.ID).Error; err != nil {
return e.Wrap(err, "error removing old fingerprints from the error group")
}
return nil
}); err != nil {
return nil, e.Wrap(err, "error replacing error group fingerprints")
}
return errorGroup, nil
}
func (r *Resolver) AppendErrorFields(ctx context.Context, fields []*model.ErrorField, errorGroup *model.ErrorGroup) error {
fieldsToAppend := []*model.ErrorField{}
for _, f := range fields {
field := &model.ErrorField{}
res := r.DB.WithContext(ctx).Raw(`
SELECT * FROM error_fields
WHERE project_id = ?
AND name = ?
AND value = ?
AND md5(value)::uuid = md5(?)::uuid
`, f.ProjectID, f.Name, f.Value, f.Value).Take(&field)
// If the field doesn't exist, we create it.
if err := res.Error; err != nil || e.Is(err, gorm.ErrRecordNotFound) {
if err := r.DB.WithContext(ctx).Create(f).Error; err != nil {
return e.Wrap(err, "error creating error field")
}
fieldsToAppend = append(fieldsToAppend, f)
} else {
fieldsToAppend = append(fieldsToAppend, field)
}
}
var entries []struct {
ErrorGroupID int
ErrorFieldID int
}
for _, f := range fieldsToAppend {
entries = append(entries, struct {
ErrorGroupID int
ErrorFieldID int
}{
ErrorGroupID: errorGroup.ID,
ErrorFieldID: f.ID,
})
}
if len(entries) > 0 {
if err := r.DB.Table("error_group_fields").Clauses(clause.OnConflict{
DoNothing: true,
}).Create(entries).Error; err != nil {
return e.Wrap(err, "error updating fields")
}
}
return nil
}
func GetLocationFromIP(ctx context.Context, ip string) (location *Location, err error) {
s, _ := util.StartSpanFromContext(ctx, "public-graph.GetLocationFromIP",
util.ResourceName("getLocationFromIP"))
defer s.Finish()
url := fmt.Sprintf("http://geolocation-db.com/json/%s", ip)
method := "GET"
client := &http.Client{}
req, err := http.NewRequest(method, url, nil)
if err != nil {
return nil, err
}
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
err = json.Unmarshal(body, &location)
if err != nil {
return nil, err
}
// long and lat should be float
switch location.Longitude.(type) {
case float64:
default:
location.Longitude = float64(0)
}
switch location.Latitude.(type) {
case float64:
default:
location.Latitude = float64(0)
}
return location, nil
}
func GetDeviceDetails(userAgentString string) (deviceDetails DeviceDetails) {
userAgent := user_agent.New(userAgentString)
deviceDetails.IsBot = userAgent.Bot()
deviceDetails.OSName = userAgent.OSInfo().Name
deviceDetails.OSVersion = userAgent.OSInfo().Version
deviceDetails.BrowserName, deviceDetails.BrowserVersion = userAgent.Browser()
return deviceDetails
}
func (r *Resolver) IndexSessionClickhouse(ctx context.Context, session *model.Session) error {
sessionProperties := map[string]string{
"os_name": session.OSName,
"os_version": session.OSVersion,
"browser_name": session.BrowserName,
"browser_version": session.BrowserVersion,
"environment": session.Environment,
"device_id": strconv.Itoa(session.Fingerprint),
"city": session.City,
"state": session.State,
"country": session.Country,
"ip": session.IP,
"service_name": session.ServiceName,
}