-
Notifications
You must be signed in to change notification settings - Fork 322
/
model.go
2474 lines (2201 loc) · 76.8 KB
/
model.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 model
import (
"context"
"database/sql"
"database/sql/driver"
"encoding/json"
"fmt"
"os"
"regexp"
"strconv"
"strings"
"time"
Email "github.com/highlight-run/highlight/backend/email"
modelInputs "github.com/highlight-run/highlight/backend/private-graph/graph/model"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5/pgconn"
"github.com/ReneKroon/ttlcache"
"github.com/lib/pq"
"github.com/mitchellh/mapstructure"
"github.com/rs/xid"
"github.com/sendgrid/sendgrid-go"
"github.com/slack-go/slack"
"github.com/speps/go-hashids"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/logger"
"github.com/pkg/errors"
e "github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
var (
env = os.Getenv("ENVIRONMENT")
DevEnv = "dev"
TestEnv = "test"
)
func IsDevEnv() bool {
return env == DevEnv
}
func IsTestEnv() bool {
return env == TestEnv
}
func IsDevOrTestEnv() bool {
return IsTestEnv() || IsDevEnv()
}
var (
DB *gorm.DB
HashID *hashids.HashID
emailHistoryCache *ttlcache.Cache
F = false
T = true
)
const (
SUGGESTION_LIMIT_CONSTANT = 8
EVENTS_OBJECTS_ADVISORY_LOCK_ID = 1337
InternalMetricCategory = "__internal"
AWS_REGION_US_EAST_2 = "us-east-2"
)
// TODO(et) - replace this with generated SessionAlertType
var AlertType = struct {
ERROR string
NEW_USER string
TRACK_PROPERTIES string
USER_PROPERTIES string
ERROR_FEEDBACK string
RAGE_CLICK string
NEW_SESSION string
LOG string
}{
ERROR: "ERROR_ALERT",
NEW_USER: "NEW_USER_ALERT",
TRACK_PROPERTIES: "TRACK_PROPERTIES_ALERT",
USER_PROPERTIES: "USER_PROPERTIES_ALERT",
ERROR_FEEDBACK: "ERROR_FEEDBACK_ALERT",
RAGE_CLICK: "RAGE_CLICK_ALERT",
NEW_SESSION: "NEW_SESSION_ALERT",
LOG: "LOG",
}
var AdminRole = struct {
ADMIN string
MEMBER string
}{
ADMIN: "ADMIN",
MEMBER: "MEMBER",
}
var SessionCommentTypes = struct {
// Comments created by a Highlight user on the Highlight app.
ADMIN string
// Comments created by a Highlight customer, comes from feedback from their app.
FEEDBACK string
}{
ADMIN: "ADMIN",
FEEDBACK: "FEEDBACK",
}
type contextString string
var ContextKeys = struct {
IP contextString
UserAgent contextString
AcceptLanguage contextString
UID contextString
OAuthClientID contextString
// The email for the current user. If the email is a @highlight.run, the email will need to be verified, otherwise `Email` will be an empty string.
Email contextString
AcceptEncoding contextString
ZapierToken contextString
ZapierProject contextString
SessionId contextString
}{
IP: "ip",
UserAgent: "userAgent",
AcceptLanguage: "acceptLanguage",
UID: "uid",
Email: "email",
AcceptEncoding: "acceptEncoding",
ZapierToken: "parsedToken",
ZapierProject: "project",
SessionId: "sessionId",
}
var Models = []interface{}{
&AWSMarketplaceCustomer{},
&ErrorObject{},
&ErrorGroup{},
&ErrorGroupEmbeddings{},
&ErrorField{},
&SavedSegment{},
&Organization{},
&Segment{},
&Admin{},
&Session{},
&SessionInterval{},
&SessionExport{},
&DailySessionCount{},
&DailyErrorCount{},
&Field{},
&EmailSignup{},
&ExternalAttachment{},
&SessionComment{},
&SessionCommentTag{},
&ErrorComment{},
&CommentReply{},
&CommentFollower{},
&CommentSlackThread{},
&ErrorAlert{},
&ErrorAlertEvent{},
&SessionAlert{},
&SessionAlertEvent{},
&LogAlert{},
&LogAlertEvent{},
&Project{},
&RageClickEvent{},
&Workspace{},
&WorkspaceAdmin{},
&WorkspaceInviteLink{},
&WorkspaceAccessRequest{},
&EnhancedUserDetails{},
&RegistrationData{},
&MetricGroup{},
&Metric{},
&MetricMonitor{},
&ErrorFingerprint{},
&EventChunk{},
&SavedAsset{},
&Dashboard{},
&DashboardMetric{},
&DashboardMetricFilter{},
&DeleteSessionsTask{},
&VercelIntegrationConfig{},
&OAuthClientStore{},
&OAuthOperation{},
&ResthookSubscription{},
&IntegrationProjectMapping{},
&IntegrationWorkspaceMapping{},
&EmailOptOut{},
&BillingEmailHistory{},
&Service{},
&SetupEvent{},
&SessionAdminsView{},
&ErrorGroupAdminsView{},
&LogAdminsView{},
&ProjectFilterSettings{},
&AllWorkspaceSettings{},
&ErrorGroupActivityLog{},
&UserJourneyStep{},
&SystemConfiguration{},
&SessionInsight{},
&ErrorTag{},
&Graph{},
&Visualization{},
}
func init() {
hd := hashids.NewData()
hd.MinLength = 8
hd.Alphabet = "abcdefghijklmnopqrstuvwxyz1234567890"
hid, err := hashids.NewWithData(hd)
if err != nil {
log.WithContext(context.Background()).Fatalf("error creating hash id client: %v", err)
}
HashID = hid
emailHistoryCache = ttlcache.NewCache()
emailHistoryCache.SetTTL(15 * time.Minute)
emailHistoryCache.SkipTtlExtensionOnHit(true)
}
type Model struct {
ID int `gorm:"primary_key;type:integer;autoIncrement" json:"id" deep:"-"`
CreatedAt time.Time `json:"created_at" deep:"-"`
UpdatedAt time.Time `json:"updated_at" deep:"-"`
DeletedAt *time.Time `json:"deleted_at" deep:"-"`
}
type Int64Model struct {
ID int64 `gorm:"primary_key;type:bigint;autoIncrement" json:"id" deep:"-"`
CreatedAt time.Time `json:"created_at" deep:"-"`
UpdatedAt time.Time `json:"updated_at" deep:"-"`
DeletedAt *time.Time `json:"deleted_at" deep:"-"`
}
type Organization struct {
Model
Name *string
BillingEmail *string
Secret *string `json:"-"`
Admins []Admin `gorm:"many2many:organization_admins;"`
TrialEndDate *time.Time `json:"trial_end_date"`
// Slack API Interaction.
SlackAccessToken *string
SlackWebhookURL *string
SlackWebhookChannel *string
SlackWebhookChannelID *string
SlackChannels *string
// Manual monthly session limit override
MonthlySessionLimit *int
}
type Workspace struct {
Model
Name *string
Secret *string // Needed for workspace-level team
Admins []Admin `gorm:"many2many:workspace_admins;"`
SlackAccessToken *string
SlackWebhookURL *string
SlackWebhookChannel *string
SlackWebhookChannelID *string
JiraDomain *string
JiraCloudID *string
MicrosoftTeamsTenantId *string
SlackChannels *string
LinearAccessToken *string
VercelAccessToken *string
VercelTeamID *string
Projects []Project
MigratedFromProjectID *int // Column can be removed after migration is done
HubspotCompanyID *int
StripeCustomerID *string
AWSMarketplaceCustomer *AWSMarketplaceCustomer `gorm:"foreignKey:WorkspaceID"`
PlanTier string `gorm:"default:Free"`
UnlimitedMembers bool `gorm:"default:false"`
BillingPeriodStart *time.Time
BillingPeriodEnd *time.Time
NextInvoiceDate *time.Time
MonthlySessionLimit *int
MonthlyMembersLimit *int
MonthlyErrorsLimit *int
MonthlyLogsLimit *int
MonthlyTracesLimit *int
RetentionPeriod *modelInputs.RetentionPeriod
ErrorsRetentionPeriod *modelInputs.RetentionPeriod
LogsRetentionPeriod *modelInputs.RetentionPeriod
TracesRetentionPeriod *modelInputs.RetentionPeriod
SessionsMaxCents *int
ErrorsMaxCents *int
LogsMaxCents *int
TracesMaxCents *int
StripeSessionOveragePriceID *string
StripeErrorOveragePriceID *string
StripeLogOveragePriceID *string
StripeTracesOveragePriceID *string
TrialEndDate *time.Time `json:"trial_end_date"`
AllowMeterOverage bool `gorm:"default:true"`
AllowedAutoJoinEmailOrigins *string `json:"allowed_auto_join_email_origins"`
EligibleForTrialExtension bool `gorm:"default:false"`
TrialExtensionEnabled bool `gorm:"default:false"`
ClearbitEnabled bool `gorm:"default:false"`
DiscordGuildId *string
ClickupAccessToken *string
PromoCode *string
}
func (w *Workspace) GetRetentionPeriod() modelInputs.RetentionPeriod {
if w.RetentionPeriod != nil {
return *w.RetentionPeriod
}
// Retention period is six months for any workspace grandfathered in
return modelInputs.RetentionPeriodSixMonths
}
func (w *Workspace) AdminEmailAddresses(db *gorm.DB) ([]struct {
AdminID int
Email string
}, error) {
var toAddrs []struct {
AdminID int
Email string
}
if err := db.Raw(`
SELECT a.id as admin_id, a.email
FROM workspace_admins wa
INNER JOIN admins a
ON wa.admin_id = a.id
WHERE wa.workspace_id = ?
AND wa.role = 'ADMIN'
AND NOT EXISTS (
SELECT *
FROM email_opt_outs eoo
WHERE eoo.admin_id = a.id
AND eoo.category IN ('All', 'Billing')
)
`, w.ID).Scan(&toAddrs).Error; err != nil {
return nil, e.Wrap(err, "error querying recipient emails")
}
return toAddrs, nil
}
type WorkspaceAdmin struct {
AdminID int `gorm:"primaryKey"`
WorkspaceID int `gorm:"primaryKey"`
CreatedAt time.Time `json:"created_at" deep:"-"`
UpdatedAt time.Time `json:"updated_at" deep:"-"`
DeletedAt *time.Time `json:"deleted_at" deep:"-"`
Role *string `json:"role" gorm:"default:ADMIN"`
}
type WorkspaceAdminRole struct {
Admin *Admin
Role string
}
type WorkspaceInviteLink struct {
Model
WorkspaceID *int
InviteeEmail *string
InviteeRole *string
ExpirationDate *time.Time
Secret *string
}
type WorkspaceAccessRequest struct {
Model
AdminID int `gorm:"uniqueIndex"`
LastRequestedWorkspace int
}
type AWSMarketplaceCustomer struct {
Model
WorkspaceID int `gorm:"uniqueIndex"`
CustomerIdentifier *string
CustomerAWSAccountID *string
ProductCode *string
}
type Project struct {
Model
Name *string
ZapierAccessToken *string
FrontAccessToken *string
FrontRefreshToken *string
FrontTokenExpiresAt *time.Time
BillingEmail *string
Secret *string `json:"-"`
Admins []Admin `gorm:"many2many:project_admins;"`
TrialEndDate *time.Time `json:"trial_end_date"`
// Manual monthly session limit override
MonthlySessionLimit *int
WorkspaceID int
FreeTier bool `gorm:"default:false"`
ExcludedUsers pq.StringArray `json:"excluded_users" gorm:"type:text[]"`
ErrorFilters pq.StringArray `gorm:"type:text[]"`
ErrorJsonPaths pq.StringArray `gorm:"type:text[]"`
// BackendSetup will be true if this is the session where HighlightBackend is run for the first time
BackendSetup *bool `json:"backend_setup"`
SetupEvent []*SetupEvent `gorm:"foreignKey:ProjectID"`
// Maximum time window considered for a rage click event
RageClickWindowSeconds int `gorm:"default:5"`
// Maximum distance between clicks for a rage click event
RageClickRadiusPixels int `gorm:"default:8"`
// Minimum count of clicks in a rage click event
RageClickCount int `gorm:"default:5"`
// Applies to all browser extensions
// TODO - rename to FilterBrowserExtension #5811
FilterChromeExtension *bool `gorm:"default:false"`
}
type MarkBackendSetupType = string
const (
// Generic is temporary and can be removed once all messages are processed.
MarkBackendSetupTypeGeneric MarkBackendSetupType = "generic"
MarkBackendSetupTypeSession MarkBackendSetupType = "session"
MarkBackendSetupTypeError MarkBackendSetupType = "error"
MarkBackendSetupTypeLogs MarkBackendSetupType = "logs"
MarkBackendSetupTypeTraces MarkBackendSetupType = "traces"
)
type SetupEvent struct {
ID int `gorm:"primary_key;type:integer;autoIncrement" json:"id" deep:"-"`
CreatedAt time.Time `json:"created_at" deep:"-"`
ProjectID int `gorm:"uniqueIndex:idx_project_id_type"`
Type MarkBackendSetupType `gorm:"uniqueIndex:idx_project_id_type"`
}
type ProjectFilterSettings struct {
Model
Project *Project
ProjectID int
FilterSessionsWithoutError bool `gorm:"default:false"`
AutoResolveStaleErrorsDayInterval int `gorm:"default:0"`
SessionSamplingRate float64 `gorm:"default:1"`
ErrorSamplingRate float64 `gorm:"default:1"`
LogSamplingRate float64 `gorm:"default:1"`
TraceSamplingRate float64 `gorm:"default:1"`
SessionMinuteRateLimit *int64
ErrorMinuteRateLimit *int64
LogMinuteRateLimit *int64
TraceMinuteRateLimit *int64
SessionExclusionQuery *string
ErrorExclusionQuery *string
LogExclusionQuery *string
TraceExclusionQuery *string
}
type AllWorkspaceSettings struct {
Model
WorkspaceID int `gorm:"uniqueIndex"`
AIApplication bool `gorm:"default:true"`
AIInsights bool `gorm:"default:false"`
// use embeddings to group errors in this workspace
ErrorEmbeddingsGroup bool `gorm:"default:true"`
// use embeddings to tag error groups in this workspace
ErrorEmbeddingsTagGroup bool `gorm:"default:true"`
ErrorEmbeddingsThreshold float64 `gorm:"default:0.2"`
ReplaceAssets bool `gorm:"default:false"`
StoreIP bool `gorm:"default:false"`
EnableSessionExport bool `gorm:"default:false"`
EnableIngestSampling bool `gorm:"default:false"`
EnableUnlistedSharing bool `gorm:"default:true"`
EnableNetworkTraces bool `gorm:"default:true"`
EnableBillingLimits bool `gorm:"default:false"` // old plans grandfathered in to true
EnableDataDeletion bool `gorm:"default:true"`
CanShowBillingIssueBanner bool `gorm:"default:true"`
EnableGrafanaDashboard bool `gorm:"default:false"`
}
type HasSecret interface {
GetSecret() *string
}
func (project *Project) GetSecret() *string { return project.Secret }
func (workspace *Workspace) GetSecret() *string { return workspace.Secret }
type EnhancedUserDetails struct {
Model
Email *string `gorm:"uniqueIndex"`
PersonJSON *string
CompanyJSON *string
}
type ResthookSubscription struct {
Model
ProjectID int `json:"project_id"`
Event *string `json:"event"`
TargetUrl *string `json:"target_url"`
}
type RegistrationData struct {
Model
WorkspaceID int
TeamSize *string
Role *string
UseCase *string
HeardAbout *string
Pun *string
}
type Dashboard struct {
Model
ProjectID int `gorm:"index;not null;"`
Name string
LastAdminToEditID *int
Layout *string
Metrics []*DashboardMetric `gorm:"foreignKey:DashboardID;"`
IsDefault *bool
}
type DashboardMetric struct {
Model
DashboardID int `gorm:"index;not null;"`
Name string
Description string
ComponentType *modelInputs.MetricViewComponentType
ChartType *modelInputs.DashboardChartType
Aggregator *modelInputs.MetricAggregator `gorm:"default:P50"`
MaxGoodValue *float64
MaxNeedsImprovementValue *float64
PoorValue *float64
Units *string
HelpArticle *string
MinValue *float64
MinPercentile *float64
MaxValue *float64
MaxPercentile *float64
Filters []*DashboardMetricFilter `gorm:"foreignKey:MetricID"`
Groups pq.StringArray `gorm:"type:text[]"`
}
type DashboardMetricFilter struct {
Model
MetricID int
MetricMonitorID int
Tag string
Op modelInputs.MetricTagFilterOp `gorm:"default:equals"`
Value string
}
type SlackChannel struct {
WebhookAccessToken string
WebhookURL string
WebhookChannel string
WebhookChannelID string
}
func (u *Workspace) IntegratedSlackChannels() ([]SlackChannel, error) {
parsedChannels := []SlackChannel{}
if u.SlackChannels != nil {
err := json.Unmarshal([]byte(*u.SlackChannels), &parsedChannels)
if err != nil {
return nil, e.Wrap(err, "error parsing details json")
}
} else {
return parsedChannels, nil
}
repeat := false
for _, c := range parsedChannels {
if u.SlackWebhookChannelID != nil && c.WebhookChannelID == *u.SlackWebhookChannelID {
repeat = true
}
}
if u.SlackWebhookChannel != nil && !repeat {
// Archived channels or users will not have a channel ID.
if u.SlackWebhookChannelID != nil {
parsedChannels = append(parsedChannels, SlackChannel{
WebhookAccessToken: *u.SlackAccessToken,
WebhookURL: *u.SlackWebhookURL,
WebhookChannel: *u.SlackWebhookChannel,
WebhookChannelID: *u.SlackWebhookChannelID,
})
}
}
return parsedChannels, nil
}
func (u *Project) VerboseID() string {
str, err := HashID.Encode([]int{u.ID})
if err != nil {
log.WithContext(context.TODO()).Errorf("error generating hash id: %v", err)
str = strconv.Itoa(u.ID)
}
return str
}
func FromVerboseID(verboseId string) (int, error) {
// Try to convert the id to an integer in the case that the client is out of date.
if projectID, err := strconv.Atoi(verboseId); err == nil {
return projectID, nil
}
// Otherwise, decode with HashID library
if ints, err := HashID.DecodeWithError(verboseId); err == nil {
if len(ints) != 1 {
return 1, e.Errorf("An unsupported verboseID was used: %s", verboseId)
}
return ints[0], nil
}
return 0, e.New(fmt.Sprintf("failed to decode %s", verboseId))
}
func (u *Project) BeforeCreate(tx *gorm.DB) (err error) {
x := xid.New().String()
u.Secret = &x
return
}
func (u *Workspace) BeforeCreate(tx *gorm.DB) (err error) {
x := xid.New().String()
u.Secret = &x
return
}
func (s *Session) BeforeCreate(tx *gorm.DB) (err error) {
if s.LastUserInteractionTime.IsZero() {
s.LastUserInteractionTime = time.UnixMilli(0)
}
return
}
func (s *SystemConfiguration) BeforeCreate(tx *gorm.DB) (err error) {
if s.ErrorFilters == nil {
s.ErrorFilters = pq.StringArray{"ENOENT.*", "connect ECONNREFUSED.*"}
}
if s.IgnoredFiles == nil {
s.IgnoredFiles = pq.StringArray{".*/node_modules/.*", ".*/go/pkg/mod/.*", ".*/site-packages/.*"}
}
return
}
type Admin struct {
Model
Name *string
FirstName *string
LastName *string
HubspotContactID *int
Email *string
AboutYouDetailsFilled *bool
Phone *string
NumberOfSessionsViewed *int
NumberOfErrorGroupsViewed *int
NumberOfLogsViewed *int
EmailVerified *bool `gorm:"default:false"`
PhotoURL *string `json:"photo_url"`
UID *string `gorm:"uniqueIndex"`
Organizations []Organization `gorm:"many2many:organization_admins;"`
Projects []Project `gorm:"many2many:project_admins;"`
SessionComments []SessionComment `gorm:"many2many:session_comment_admins;"`
ErrorComments []ErrorComment `gorm:"many2many:error_comment_admins;"`
Workspaces []Workspace `gorm:"many2many:workspace_admins;"`
SlackIMChannelID *string
// How/where this user was referred from to sign up to Highlight.
Referral *string `json:"referral"`
// This is the role the Admin has specified. This is their role in their organization, not within Highlight. This should not be used for authorization checks.
UserDefinedRole *string `json:"user_defined_role"`
UserDefinedTeamSize *string `json:"user_defined_team_size"`
UserDefinedPersona *string `json:"user_defined_persona"`
HeardAbout *string `json:"heard_about"`
PhoneHomeContactAllowed *bool `json:"phone_home_contact_allowed"`
}
type EmailSignup struct {
Model
Email string `gorm:"uniqueIndex"`
ApolloData string
ApolloDataShortened string
}
type SessionsHistogram struct {
BucketTimes []time.Time `json:"bucket_times"`
SessionsWithoutErrors []int64 `json:"sessions_without_errors"`
SessionsWithErrors []int64 `json:"sessions_with_errors"`
TotalSessions []int64 `json:"total_sessions"`
}
type SessionResults struct {
Sessions []Session
TotalCount int64
}
type Session struct {
Model
// The ID used publicly for the URL on the client; used for sharing
SecureID string `json:"secure_id" gorm:"uniqueIndex;not null;default:secure_id_generator()"`
// For associating unidentified sessions with a user after identification
ClientID string `json:"client_id" gorm:"not null;default:''"`
// Whether a session has been identified.
Identified bool `json:"identified" gorm:"default:false;not null"`
Fingerprint int `json:"fingerprint"`
// User provided identifier (see IdentifySession)
Identifier string `json:"identifier"`
ProjectID int `json:"project_id"`
Email *string `json:"email"`
// Location data based off user ip (see InitializeSession)
IP string `json:"ip"`
City string `json:"city"`
State string `json:"state"`
Postal string `json:"postal"`
Country string `json:"country"`
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
// Details based off useragent (see Initialize Session)
OSName string `json:"os_name"`
OSVersion string `json:"os_version"`
BrowserName string `json:"browser_name"`
BrowserVersion string `json:"browser_version"`
Language string `json:"language"`
// Tells us if 'beforeunload' was fired on the client - note this is not necessarily fired on every session end
HasUnloaded bool `gorm:"default:false"`
// Tells us if the session has been parsed by a worker.
Processed *bool `json:"processed"`
HasComments bool `json:"has_comments" gorm:"default:false"`
HasRageClicks *bool `json:"has_rage_clicks"`
HasErrors *bool `json:"has_errors"`
HasOutOfOrderEvents bool `gorm:"default:false"`
// The timestamp of the first payload received after the session got processed (if applicable)
ResumedAfterProcessedTime *time.Time `json:"resumed_after_processed_time"`
// The length of a session.
Length int64 `json:"length"`
ActiveLength int64 `json:"active_length"`
Fields []*Field `json:"fields" gorm:"many2many:session_fields;"`
Environment string `json:"environment"`
AppVersion *string `json:"app_version"`
ServiceName string
UserObject JSONB `json:"user_object" gorm:"type:jsonb"`
UserProperties string `json:"user_properties"`
// Whether this is the first session created by this user.
FirstTime *bool `json:"first_time" gorm:"default:false"`
PayloadUpdatedAt *time.Time `json:"payload_updated_at"`
LastUserInteractionTime time.Time `json:"last_user_interaction_time"`
// Set if the last payload was a beacon; cleared on the next non-beacon payload
BeaconTime *time.Time `json:"beacon_time"`
// Custom properties
Viewed *bool `json:"viewed"`
Starred *bool `json:"starred"`
FieldGroup *string `json:"field_group"`
EnableStrictPrivacy *bool `json:"enable_strict_privacy"`
PrivacySetting *string `json:"privacy_setting"`
EnableRecordingNetworkContents *bool `json:"enable_recording_network_contents"`
// The version of Highlight's Client.
ClientVersion string `json:"client_version"`
// The version of Highlight's Firstload.
FirstloadVersion string `json:"firstload_version"`
// The client configuration that the end-user sets up. This is used for debugging purposes.
ClientConfig *string `json:"client_config" gorm:"type:jsonb"`
// Determines whether this session should be viewable. This enforces billing.
WithinBillingQuota *bool `json:"within_billing_quota" gorm:"default:true"`
// Used for shareable links. No authentication is needed if IsPublic is true
IsPublic bool `json:"is_public" gorm:"default:false"`
// EventCounts is a len()=100 slice that contains the count of events for the session normalized over 100 points
EventCounts *string
// Number of pages visited during a session
PagesVisited int
ObjectStorageEnabled *bool `json:"object_storage_enabled"`
DirectDownloadEnabled bool `json:"direct_download_enabled" gorm:"default:false"`
AllObjectsCompressed bool `json:"all_resources_compressed" gorm:"default:false"`
PayloadSize *int64 `json:"payload_size"`
VerboseID string `json:"verbose_id"`
// Excluded will be true when we would typically have deleted the session
Excluded bool `gorm:"default:false"`
ExcludedReason *modelInputs.SessionExcludedReason
// Lock is the timestamp at which a session was locked
// - when selecting sessions, ignore Locks that are > 10 minutes old
// ex. SELECT * FROM sessions WHERE (lock IS NULL OR lock < NOW() - 10 * (INTERVAL '1 MINUTE'))
Lock sql.NullTime
RetryCount int
// Represents the admins that have viewed this session.
ViewedByAdmins []Admin `json:"viewed_by_admins" gorm:"many2many:session_admins_views;"`
Chunked *bool
ProcessWithRedis bool
Normalness *float64
}
type SessionAdminsView struct {
SessionID int `gorm:"primaryKey"`
AdminID int `gorm:"primaryKey"`
ViewedAt time.Time `gorm:"default:NOW()"`
}
type SessionInsight struct {
Model
SessionID int `gorm:"index"`
Insight string
}
type SessionExportFormat = string
const (
SessionExportFormatMP4 SessionExportFormat = "video/mp4"
SessionExportFormatGif SessionExportFormat = "image/gif"
SessionExportFormatPng SessionExportFormat = "image/png"
)
type SessionExport struct {
Model
SessionID int `gorm:"uniqueIndex:idx_session_exports"`
Type SessionExportFormat `gorm:"uniqueIndex:idx_session_exports"`
URL string
Error string
TargetEmails pq.StringArray `gorm:"type:text[];"`
}
type EventChunk struct {
Model
SessionID int `gorm:"index"`
ChunkIndex int
Timestamp int64
}
type Field struct {
Int64Model
// 'user_property', 'session_property'.
Type string `gorm:"uniqueIndex:idx_fields_type_name_value_project_id"`
// 'email', 'identifier', etc.
Name string `gorm:"uniqueIndex:idx_fields_type_name_value_project_id"`
// 'email@email.com'
Value string `gorm:"uniqueIndex:idx_fields_type_name_value_project_id"`
ProjectID int `json:"project_id" gorm:"uniqueIndex:idx_fields_type_name_value_project_id"`
Sessions []Session `gorm:"many2many:session_fields;"`
}
type ResourcesObject struct {
Model
ID int `json:"id"` // Shadow Model.ID to avoid creating a pkey constraint
SessionID int
Resources string
IsBeacon bool `gorm:"default:false"`
}
func (r *ResourcesObject) Contents() string {
return r.Resources
}
type SearchParams struct {
UserProperties []*UserProperty `json:"user_properties"`
ExcludedProperties []*UserProperty `json:"excluded_properties"`
TrackProperties []*UserProperty `json:"track_properties"`
ExcludedTrackProperties []*UserProperty `json:"excluded_track_properties"`
DateRange *DateRange `json:"date_range"`
LengthRange *LengthRange `json:"length_range"`
Browser *string `json:"browser"`
OS *string `json:"os"`
Environments []*string `json:"environments"`
AppVersions []*string `json:"app_versions"`
DeviceID *string `json:"device_id"`
VisitedURL *string `json:"visited_url"`
Referrer *string `json:"referrer"`
Identified bool `json:"identified"`
HideViewed bool `json:"hide_viewed"`
FirstTime bool `json:"first_time"`
ShowLiveSessions bool `json:"show_live_sessions"`
Query *string `json:"query"`
}
type Segment struct {
Model
Name *string
Params *string `json:"params"`
ProjectID int `json:"project_id"`
}
type DailySessionCount struct {
Model
Date *time.Time `json:"date"`
Count int64 `json:"count"`
ProjectID int `json:"project_id"`
}
const (
SESSIONS_TBL = "sessions"
METRIC_GROUPS_NAME_SESSION_UNIQ = "metric_groups_name_session_uniq"
DASHBOARD_METRIC_FILTERS_UNIQ = "dashboard_metric_filters_uniq"
)
type DailyErrorCount struct {
Model
Date *time.Time `json:"date"`
Count int64 `json:"count"`
ProjectID int `json:"project_id"`
ErrorType string `gorm:"default:FRONTEND"`
}
func (s *SearchParams) GormDataType() string {
out, err := json.Marshal(s)
if err != nil {
return ""
}
return string(out)
}
func (s *SearchParams) GormValue(ctx context.Context, db *gorm.DB) clause.Expr {
return clause.Expr{
SQL: fmt.Sprintf("ST_PointFromText(%v)", s.GormDataType()),
}
}
type DateRange struct {
StartDate time.Time
EndDate time.Time
}
type LengthRange struct {
Min float64
Max float64
}
type UserProperty struct {
ID int `json:"id"`
Name string `json:"name"`
Value string `json:"value"`
}
type TrackProperty struct {
ID int `json:"id"`
Name string `json:"name"`
Value string `json:"value"`
}
type Object interface {
Contents() string
}
type SessionData struct {
Data string
}
func (sd *SessionData) Contents() string {
return sd.Data
}
type MessagesObject struct {
Model
ID int `json:"id"` // Shadow Model.ID to avoid creating a pkey constraint
SessionID int
Messages string
IsBeacon bool `gorm:"default:false"`
}
type Metric struct {
CreatedAt time.Time `json:"created_at" deep:"-"`
MetricGroupID int `gorm:"index"`
Name string
Value float64
Category string
}
type MetricGroup struct {
ID int `gorm:"primary_key;type:bigint;autoIncrement" json:"id" deep:"-"`
GroupName string
SessionID int
ProjectID int
Metrics []*Metric `gorm:"foreignKey:MetricGroupID;"`
}
type MetricMonitor struct {
Model
ProjectID int `gorm:"index;not null;"`
Name string
Aggregator modelInputs.MetricAggregator `gorm:"default:P50"`
PeriodMinutes *int // apply aggregator function on PeriodMinutes lookback
Threshold float64
Units *string // Threshold value is in these Units.
MetricToMonitor string
ChannelsToNotify *string `gorm:"channels_to_notify"`
EmailsToNotify *string `gorm:"emails_to_notify"`
LastAdminToEditID int `gorm:"last_admin_to_edit_id"`
Disabled *bool `gorm:"default:false"`
Filters []*DashboardMetricFilter `gorm:"foreignKey:MetricMonitorID"`
AlertIntegrations
}
func (m *MessagesObject) Contents() string {
return m.Messages
}
type EventsObject struct {
Model
ID int `json:"id"` // Shadow Model.ID to avoid creating a pkey constraint
SessionID int
Events string
IsBeacon bool `gorm:"default:false"`
}
func (m *EventsObject) Contents() string {
return m.Events
}