-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
event_logs.go
1925 lines (1712 loc) · 67.5 KB
/
event_logs.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 database
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"net/url"
"strings"
"time"
"github.com/gofrs/uuid"
"github.com/keegancsmith/sqlf"
"github.com/lib/pq"
sgactor "github.com/sourcegraph/sourcegraph/internal/actor"
"github.com/sourcegraph/sourcegraph/internal/conf"
"github.com/sourcegraph/sourcegraph/internal/database/basestore"
"github.com/sourcegraph/sourcegraph/internal/database/batch"
"github.com/sourcegraph/sourcegraph/internal/database/dbutil"
"github.com/sourcegraph/sourcegraph/internal/eventlogger"
"github.com/sourcegraph/sourcegraph/internal/featureflag"
"github.com/sourcegraph/sourcegraph/internal/jsonc"
"github.com/sourcegraph/sourcegraph/internal/timeutil"
"github.com/sourcegraph/sourcegraph/internal/types"
"github.com/sourcegraph/sourcegraph/internal/version"
"github.com/sourcegraph/sourcegraph/lib/errors"
)
type EventLogStore interface {
// AggregatedCodeIntelEvents calculates CodeIntelAggregatedEvent for each unique event type related to code intel.
AggregatedCodeIntelEvents(ctx context.Context) ([]types.CodeIntelAggregatedEvent, error)
// AggregatedCodeIntelInvestigationEvents calculates CodeIntelAggregatedInvestigationEvent for each unique investigation type.
AggregatedCodeIntelInvestigationEvents(ctx context.Context) ([]types.CodeIntelAggregatedInvestigationEvent, error)
// AggregatedCodyEvents calculates CodyAggregatedEvent for each every unique event type related to Cody.
AggregatedCodyEvents(ctx context.Context, now time.Time) ([]types.CodyAggregatedEvent, error)
// AggregatedRepoMetadataEvents calculates RepoMetadataAggregatedEvent for each every unique event type related to RepoMetadata.
AggregatedRepoMetadataEvents(ctx context.Context, now time.Time, period PeriodType) (*types.RepoMetadataAggregatedEvents, error)
// AggregatedSearchEvents calculates SearchAggregatedEvent for each every unique event type related to search.
AggregatedSearchEvents(ctx context.Context, now time.Time) ([]types.SearchAggregatedEvent, error)
BulkInsert(ctx context.Context, events []*Event) error
// CodeIntelligenceCrossRepositoryWAUs returns the WAU (current week) with any (precise or search-based) cross-repository code intelligence event.
CodeIntelligenceCrossRepositoryWAUs(ctx context.Context) (int, error)
// CodeIntelligencePreciseCrossRepositoryWAUs returns the WAU (current week) with precise-based cross-repository code intelligence events.
CodeIntelligencePreciseCrossRepositoryWAUs(ctx context.Context) (int, error)
// CodeIntelligencePreciseWAUs returns the WAU (current week) with precise-based code intelligence events.
CodeIntelligencePreciseWAUs(ctx context.Context) (int, error)
// CodeIntelligenceRepositoryCounts returns the counts of repositories with code intelligence
// properties (number of repositories with intel, with automatic/manual index configuration, etc).
CodeIntelligenceRepositoryCounts(ctx context.Context) (counts CodeIntelligenceRepositoryCounts, err error)
// CodeIntelligenceRepositoryCountsByLanguage returns the counts of repositories with code intelligence
// properties (number of repositories with intel, with automatic/manual index configuration, etc), grouped
// by language.
CodeIntelligenceRepositoryCountsByLanguage(ctx context.Context) (_ map[string]CodeIntelligenceRepositoryCountsForLanguage, err error)
// CodeIntelligenceSearchBasedCrossRepositoryWAUs returns the WAU (current week) with searched-base cross-repository code intelligence events.
CodeIntelligenceSearchBasedCrossRepositoryWAUs(ctx context.Context) (int, error)
// CodeIntelligenceSearchBasedWAUs returns the WAU (current week) with searched-base code intelligence events.
CodeIntelligenceSearchBasedWAUs(ctx context.Context) (int, error)
// CodeIntelligenceSettingsPageViewCount returns the number of view of pages related code intelligence
// administration (upload, index records, index configuration, etc) in the past week.
CodeIntelligenceSettingsPageViewCount(ctx context.Context) (int, error)
// RequestsByLanguage returns a map of language names to the number of requests of precise support for that language.
RequestsByLanguage(ctx context.Context) (map[string]int, error)
// CodeIntelligenceWAUs returns the WAU (current week) with any (precise or search-based) code intelligence event.
CodeIntelligenceWAUs(ctx context.Context) (int, error)
// CountByUserID gets a count of events logged by a given user.
CountByUserID(ctx context.Context, userID int32) (int, error)
// CountByUserIDAndEventName gets a count of events logged by a given user and with a given event name.
CountByUserIDAndEventName(ctx context.Context, userID int32, name string) (int, error)
// CountByUserIDAndEventNamePrefix gets a count of events logged by a given user and with a given event name prefix.
CountByUserIDAndEventNamePrefix(ctx context.Context, userID int32, namePrefix string) (int, error)
// CountByUserIDAndEventNames gets a count of events logged by a given user that match a list of given event names.
CountByUserIDAndEventNames(ctx context.Context, userID int32, names []string) (int, error)
// CountUniqueUsersAll provides a count of unique active users in a given time span.
CountUniqueUsersAll(ctx context.Context, startDate, endDate time.Time, opt *CountUniqueUsersOptions) (int, error)
// CountUniqueUsersByEventName provides a count of unique active users in a given time span that logged a given event.
CountUniqueUsersByEventName(ctx context.Context, startDate, endDate time.Time, name string) (int, error)
// CountUniqueUsersByEventNamePrefix provides a count of unique active users in a given time span that logged an event with a given prefix.
CountUniqueUsersByEventNamePrefix(ctx context.Context, startDate, endDate time.Time, namePrefix string) (int, error)
// CountUniqueUsersByEventNames provides a count of unique active users in a given time span that logged any event that matches a list of given event names
CountUniqueUsersByEventNames(ctx context.Context, startDate, endDate time.Time, names []string) (int, error)
// SiteUsageMultiplePeriods provides a count of unique active users in given time spans, broken up into periods of
// a given type. The value of `now` should be the current time in UTC.
SiteUsageMultiplePeriods(ctx context.Context, now time.Time, dayPeriods int, weekPeriods int, monthPeriods int, opt *CountUniqueUsersOptions) (*types.SiteUsageStatistics, error)
// CountUsersWithSetting returns the number of users wtih the given temporary setting set to the given value.
CountUsersWithSetting(ctx context.Context, setting string, value any) (int, error)
Insert(ctx context.Context, e *Event) error
// LatestPing returns the most recently recorded ping event.
LatestPing(ctx context.Context) (*Event, error)
// ListAll gets all event logs in descending order of timestamp.
ListAll(ctx context.Context, opt EventLogsListOptions) ([]*Event, error)
// ListExportableEvents gets a batch of event logs that are allowed to be exported.
ListExportableEvents(ctx context.Context, after, limit int) ([]*Event, error)
ListUniqueUsersAll(ctx context.Context, startDate, endDate time.Time) ([]int32, error)
// MaxTimestampByUserID gets the max timestamp among event logs for a given user.
MaxTimestampByUserID(ctx context.Context, userID int32) (*time.Time, error)
// MaxTimestampByUserIDAndSource gets the max timestamp among event logs for a given user and event source.
MaxTimestampByUserIDAndSource(ctx context.Context, userID int32, source string) (*time.Time, error)
SiteUsageCurrentPeriods(ctx context.Context) (types.SiteUsageSummary, error)
// UsersUsageCounts returns a list of UserUsageCounts for all active users that produced 'SearchResultsQueried' and any
// '%codeintel%' events in the event_logs table.
UsersUsageCounts(ctx context.Context) (counts []types.UserUsageCounts, err error)
// OwnershipFeatureActivity returns (M|W|D)AUs for the most recent of each period
// for each of given event names.
OwnershipFeatureActivity(ctx context.Context, now time.Time, eventNames ...string) (map[string]*types.OwnershipUsageStatisticsActiveUsers, error)
WithTransact(context.Context, func(EventLogStore) error) error
With(other basestore.ShareableStore) EventLogStore
basestore.ShareableStore
}
type eventLogStore struct {
*basestore.Store
}
// EventLogsWith instantiates and returns a new EventLogStore using the other store handle.
func EventLogsWith(other basestore.ShareableStore) EventLogStore {
return &eventLogStore{Store: basestore.NewWithHandle(other.Handle())}
}
func (l *eventLogStore) With(other basestore.ShareableStore) EventLogStore {
return &eventLogStore{Store: l.Store.With(other)}
}
func (l *eventLogStore) WithTransact(ctx context.Context, f func(EventLogStore) error) error {
return l.Store.WithTransact(ctx, func(tx *basestore.Store) error {
return f(&eventLogStore{Store: tx})
})
}
// SanitizeEventURL makes the given URL is using HTTP/HTTPS scheme and within
// the current site determined by `conf.ExternalURL()`.
func SanitizeEventURL(raw string) string {
if raw == "" {
return ""
}
// Check if the URL looks like a real URL
u, err := url.Parse(raw)
if err != nil ||
(u.Scheme != "http" && u.Scheme != "https") {
return ""
}
// Check if the URL belongs to the current site
normalized := u.String()
if strings.HasPrefix(normalized, conf.ExternalURL()) || strings.HasSuffix(u.Host, "sourcegraph.com") {
return normalized
}
return ""
}
// Event contains information needed for logging an event.
type Event struct {
ID int32
Name string
URL string
UserID uint32
AnonymousUserID string
Argument json.RawMessage
PublicArgument json.RawMessage
Source string
Version string
Timestamp time.Time
EvaluatedFlagSet featureflag.EvaluatedFlagSet
CohortID *string // date in YYYY-MM-DD format
FirstSourceURL *string
LastSourceURL *string
Referrer *string
DeviceID *string
InsertID *string
}
func (l *eventLogStore) Insert(ctx context.Context, e *Event) error {
return l.BulkInsert(ctx, []*Event{e})
}
const EventLogsSourcegraphOperatorKey = "sourcegraph_operator"
func (l *eventLogStore) BulkInsert(ctx context.Context, events []*Event) error {
coalesce := func(v json.RawMessage) json.RawMessage {
if v != nil {
return v
}
return json.RawMessage(`{}`)
}
ensureUuid := func(in *string) string {
if in == nil || len(*in) == 0 {
u, _ := uuid.NewV4()
return u.String()
}
return *in
}
actor := sgactor.FromContext(ctx)
rowValues := make(chan []any, len(events))
for _, event := range events {
featureFlags, err := json.Marshal(event.EvaluatedFlagSet)
if err != nil {
return err
}
// Add an attribution for Sourcegraph operator to be distinguished in our analytics pipelines
publicArgument := coalesce(event.PublicArgument)
if actor.SourcegraphOperator {
result, err := jsonc.Edit(
string(publicArgument),
true,
EventLogsSourcegraphOperatorKey,
)
publicArgument = json.RawMessage(result)
if err != nil {
return errors.Wrap(err, `edit "public_argument" for Sourcegraph operator`)
}
}
rowValues <- []any{
event.Name,
// 🚨 SECURITY: It is important to sanitize event URL before
// being stored to the database to help guarantee no malicious
// data at rest.
SanitizeEventURL(event.URL),
event.UserID,
event.AnonymousUserID,
event.Source,
coalesce(event.Argument),
publicArgument,
version.Version(),
event.Timestamp.UTC(),
featureFlags,
event.CohortID,
event.FirstSourceURL,
event.LastSourceURL,
event.Referrer,
ensureUuid(event.DeviceID),
ensureUuid(event.InsertID),
}
}
close(rowValues)
return batch.InsertValues(
ctx,
l.Handle(),
"event_logs",
batch.MaxNumPostgresParameters,
[]string{
"name",
"url",
"user_id",
"anonymous_user_id",
"source",
"argument",
"public_argument",
"version",
"timestamp",
"feature_flags",
"cohort_id",
"first_source_url",
"last_source_url",
"referrer",
"device_id",
"insert_id",
},
rowValues,
)
}
func (l *eventLogStore) getBySQL(ctx context.Context, querySuffix *sqlf.Query) ([]*Event, error) {
q := sqlf.Sprintf("SELECT id, name, url, user_id, anonymous_user_id, source, argument, public_argument, version, timestamp, feature_flags, cohort_id, first_source_url, last_source_url, referrer, device_id, insert_id FROM event_logs %s", querySuffix)
rows, err := l.Query(ctx, q)
if err != nil {
return nil, err
}
defer rows.Close()
events := []*Event{}
for rows.Next() {
r := Event{}
var rawFlags []byte
err := rows.Scan(&r.ID, &r.Name, &r.URL, &r.UserID, &r.AnonymousUserID, &r.Source, &r.Argument, &r.PublicArgument, &r.Version, &r.Timestamp, &rawFlags, &r.CohortID, &r.FirstSourceURL, &r.LastSourceURL, &r.Referrer, &r.DeviceID, &r.InsertID)
if err != nil {
return nil, err
}
if rawFlags != nil {
marshalErr := json.Unmarshal(rawFlags, &r.EvaluatedFlagSet)
if marshalErr != nil {
return nil, errors.Wrap(marshalErr, "json.Unmarshal")
}
}
events = append(events, &r)
}
if err := rows.Err(); err != nil {
return nil, err
}
return events, nil
}
// EventLogsListOptions specifies the options for listing event logs.
type EventLogsListOptions struct {
// UserID specifies the user whose events should be included.
UserID int32
*LimitOffset
EventName *string
// AfterID specifies a minimum event ID of listed events.
AfterID int
}
func (l *eventLogStore) ListAll(ctx context.Context, opt EventLogsListOptions) ([]*Event, error) {
conds := []*sqlf.Query{sqlf.Sprintf("TRUE")}
orderDirection := "DESC"
if opt.AfterID > 0 {
conds = append(conds, sqlf.Sprintf("id > %d", opt.AfterID))
orderDirection = "ASC"
}
if opt.UserID != 0 {
conds = append(conds, sqlf.Sprintf("user_id = %d", opt.UserID))
}
if opt.EventName != nil {
conds = append(conds, sqlf.Sprintf("name = %s", opt.EventName))
}
queryTemplate := fmt.Sprintf("WHERE %%s ORDER BY id %s %%s", orderDirection)
return l.getBySQL(ctx, sqlf.Sprintf(queryTemplate, sqlf.Join(conds, "AND"), opt.LimitOffset.SQL()))
}
func (l *eventLogStore) ListExportableEvents(ctx context.Context, after, limit int) ([]*Event, error) {
suffix := "WHERE event_logs.id > %d AND name IN (SELECT event_name FROM event_logs_export_allowlist) ORDER BY event_logs.id LIMIT %d"
return l.getBySQL(ctx, sqlf.Sprintf(suffix, after, limit))
}
func (l *eventLogStore) LatestPing(ctx context.Context) (*Event, error) {
rows, err := l.getBySQL(ctx, sqlf.Sprintf(`WHERE name='ping' ORDER BY id DESC LIMIT 1`))
if err != nil {
return nil, err
}
if len(rows) == 0 {
return nil, sql.ErrNoRows
}
return rows[0], err
}
func (l *eventLogStore) CountByUserID(ctx context.Context, userID int32) (int, error) {
return l.countBySQL(ctx, sqlf.Sprintf("WHERE user_id = %d", userID))
}
func (l *eventLogStore) CountByUserIDAndEventName(ctx context.Context, userID int32, name string) (int, error) {
return l.countBySQL(ctx, sqlf.Sprintf("WHERE user_id = %d AND name = %s", userID, name))
}
func (l *eventLogStore) CountByUserIDAndEventNamePrefix(ctx context.Context, userID int32, namePrefix string) (int, error) {
return l.countBySQL(ctx, sqlf.Sprintf("WHERE user_id = %d AND name LIKE %s", userID, namePrefix+"%"))
}
func (l *eventLogStore) CountByUserIDAndEventNames(ctx context.Context, userID int32, names []string) (int, error) {
items := []*sqlf.Query{}
for _, v := range names {
items = append(items, sqlf.Sprintf("%s", v))
}
return l.countBySQL(ctx, sqlf.Sprintf("WHERE user_id = %d AND name IN (%s)", userID, sqlf.Join(items, ",")))
}
// countBySQL gets a count of event logs.
func (l *eventLogStore) countBySQL(ctx context.Context, querySuffix *sqlf.Query) (int, error) {
q := sqlf.Sprintf("SELECT COUNT(*) FROM event_logs %s", querySuffix)
r := l.QueryRow(ctx, q)
var count int
err := r.Scan(&count)
return count, err
}
func (l *eventLogStore) MaxTimestampByUserID(ctx context.Context, userID int32) (*time.Time, error) {
return l.maxTimestampBySQL(ctx, sqlf.Sprintf("WHERE user_id = %d", userID))
}
func (l *eventLogStore) MaxTimestampByUserIDAndSource(ctx context.Context, userID int32, source string) (*time.Time, error) {
return l.maxTimestampBySQL(ctx, sqlf.Sprintf("WHERE user_id = %d AND source = %s", userID, source))
}
// maxTimestampBySQL gets the max timestamp among event logs.
func (l *eventLogStore) maxTimestampBySQL(ctx context.Context, querySuffix *sqlf.Query) (*time.Time, error) {
q := sqlf.Sprintf("SELECT MAX(timestamp) FROM event_logs %s", querySuffix)
r := l.QueryRow(ctx, q)
var t time.Time
err := r.Scan(&dbutil.NullTime{Time: &t})
if t.IsZero() {
return nil, err
}
return &t, err
}
// SiteUsageValues is a set of UsageValues representing usage on daily, weekly, and monthly bases.
type SiteUsageValues struct {
DAUs []UsageValue
WAUs []UsageValue
MAUs []UsageValue
}
// UsageValue is a single count of usage for a time period starting on a given date.
type UsageValue struct {
Start time.Time
Type PeriodType
Count int
CountRegistered int
}
// PeriodType is the type of period in which to count events and unique users.
type PeriodType string
const (
// Daily is used to get a count of events or unique users within a day.
Daily PeriodType = "daily"
// Weekly is used to get a count of events or unique users within a week.
Weekly PeriodType = "weekly"
// Monthly is used to get a count of events or unique users within a month.
Monthly PeriodType = "monthly"
)
var ErrInvalidPeriodType = errors.New("invalid period type")
// calcStartDate calculates the the starting date of a number of periods given the period type.
// from the current time supplied as `now`. Returns an error if the period type is
// illegal.
func calcStartDate(now time.Time, periodType PeriodType, periods int) (time.Time, error) {
periodsAgo := periods - 1
switch periodType {
case Daily:
return time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC).AddDate(0, 0, -periodsAgo), nil
case Weekly:
return timeutil.StartOfWeek(now, periodsAgo), nil
case Monthly:
return time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC).AddDate(0, -periodsAgo, 0), nil
}
return time.Time{}, errors.Wrapf(ErrInvalidPeriodType, "%q is not a valid PeriodType", periodType)
}
// calcEndDate calculates the the ending date of a number of periods given the period type.
// Returns a second false value if the period type is illegal.
func calcEndDate(startDate time.Time, periodType PeriodType, periods int) (time.Time, error) {
periodsAgo := periods - 1
switch periodType {
case Daily:
return startDate.AddDate(0, 0, periodsAgo), nil
case Weekly:
return startDate.AddDate(0, 0, 7*periodsAgo), nil
case Monthly:
return startDate.AddDate(0, periodsAgo, 0), nil
}
return time.Time{}, errors.Wrapf(ErrInvalidPeriodType, "%q is not a valid PeriodType", periodType)
}
// CommonUsageOptions provides a set of options that are common across different usage calculations.
type CommonUsageOptions struct {
// Exclude backend system users.
ExcludeSystemUsers bool
// Exclude events that don't meet the criteria of "active" usage of Sourcegraph. These
// are mostly actions taken by signed-out users.
ExcludeNonActiveUsers bool
// Exclude Sourcegraph (employee) admins.
//
// Deprecated: Use ExcludeSourcegraphOperators instead. If you have to use this,
// then set both fields with the same value at the same time.
ExcludeSourcegraphAdmins bool
// ExcludeSourcegraphOperators indicates whether to exclude Sourcegraph Operator
// user accounts.
ExcludeSourcegraphOperators bool
}
// CountUniqueUsersOptions provides options for counting unique users.
type CountUniqueUsersOptions struct {
CommonUsageOptions
// If set, adds additional restrictions on the event types.
EventFilters *EventFilterOptions
}
// EventFilterOptions provides options for filtering events.
type EventFilterOptions struct {
// If set, only include events with a given prefix.
ByEventNamePrefix string
// If set, only include events with the given name.
ByEventName string
// If not empty, only include events that matche a list of given event names
ByEventNames []string
// Must be used with ByEventName
//
// If set, only include events that match a specified condition.
ByEventNameWithCondition *sqlf.Query
}
// EventArgumentMatch provides the options for matching an event with
// a specific JSON value passed as an argument.
type EventArgumentMatch struct {
// The name of the JSON key to match against.
ArgumentName string
// The actual value passed to the JSON key to match.
ArgumentValue string
}
// PercentileValue is a slice of Nth percentile values calculated from a field of events
// in a time period starting on a given date.
type PercentileValue struct {
Start time.Time
Values []float64
}
func (l *eventLogStore) CountUsersWithSetting(ctx context.Context, setting string, value any) (int, error) {
count, _, err := basestore.ScanFirstInt(l.Store.Query(ctx, sqlf.Sprintf(`SELECT COUNT(*) FROM temporary_settings WHERE %s <@ contents`, jsonSettingFragment(setting, value))))
return count, err
}
func jsonSettingFragment(setting string, value any) string {
raw, _ := json.Marshal(map[string]any{setting: value})
return string(raw)
}
func buildCountUniqueUserConds(opt *CountUniqueUsersOptions) []*sqlf.Query {
conds := []*sqlf.Query{sqlf.Sprintf("TRUE")}
if opt != nil {
conds = BuildCommonUsageConds(&opt.CommonUsageOptions, conds)
if opt.EventFilters != nil {
if opt.EventFilters.ByEventNamePrefix != "" {
conds = append(conds, sqlf.Sprintf("name LIKE %s", opt.EventFilters.ByEventNamePrefix+"%"))
}
if opt.EventFilters.ByEventName != "" {
conds = append(conds, sqlf.Sprintf("name = %s", opt.EventFilters.ByEventName))
}
if opt.EventFilters.ByEventNameWithCondition != nil {
conds = append(conds, opt.EventFilters.ByEventNameWithCondition)
}
if len(opt.EventFilters.ByEventNames) > 0 {
items := []*sqlf.Query{}
for _, v := range opt.EventFilters.ByEventNames {
items = append(items, sqlf.Sprintf("%s", v))
}
conds = append(conds, sqlf.Sprintf("name IN (%s)", sqlf.Join(items, ",")))
}
}
}
return conds
}
func BuildCommonUsageConds(opt *CommonUsageOptions, conds []*sqlf.Query) []*sqlf.Query {
if opt != nil {
if opt.ExcludeSystemUsers {
conds = append(conds, sqlf.Sprintf("event_logs.user_id > 0 OR event_logs.anonymous_user_id <> 'backend'"))
}
if opt.ExcludeNonActiveUsers {
conds = append(conds, sqlf.Sprintf("event_logs.name NOT IN ('"+strings.Join(eventlogger.NonActiveUserEvents, "','")+"')"))
}
// NOTE: This is a hack which should be replaced when we have proper user types.
// However, for billing purposes and more accurate ping data, we need a way to
// exclude Sourcegraph (employee) admins when counting users. The following
// username patterns, in conjunction with the presence of a corresponding
// "@sourcegraph.com" email address, are used to filter out Sourcegraph admins:
//
// - managed-*
// - sourcegraph-management-*
// - sourcegraph-admin
//
// This method of filtering is imperfect and may still incur false positives, but
// the two together should help prevent that in the majority of cases, and we
// acknowledge this risk as we would prefer to undercount rather than overcount.
//
// TODO(jchen): This hack will be removed as part of https://github.com/sourcegraph/customer/issues/1531
if opt.ExcludeSourcegraphAdmins {
conds = append(conds, sqlf.Sprintf(`
-- No matching user exists
users.username IS NULL
-- Or, the user does not...
OR NOT(
-- ...have a known Sourcegraph admin username pattern
(users.username ILIKE 'managed-%%'
OR users.username ILIKE 'sourcegraph-management-%%'
OR users.username = 'sourcegraph-admin')
-- ...and have a matching sourcegraph email address
AND EXISTS (
SELECT
1 FROM user_emails
WHERE
user_emails.user_id = users.id
AND user_emails.email ILIKE '%%@sourcegraph.com')
)
`))
}
if opt.ExcludeSourcegraphOperators {
conds = append(conds, sqlf.Sprintf(fmt.Sprintf(`NOT event_logs.public_argument @> '{"%s": true}'`, EventLogsSourcegraphOperatorKey)))
}
}
return conds
}
func (l *eventLogStore) SiteUsageMultiplePeriods(ctx context.Context, now time.Time, dayPeriods int, weekPeriods int, monthPeriods int, opt *CountUniqueUsersOptions) (*types.SiteUsageStatistics, error) {
startDateDays, err := calcStartDate(now, Daily, dayPeriods)
if err != nil {
return nil, err
}
endDateDays, err := calcEndDate(startDateDays, Daily, dayPeriods)
if err != nil {
return nil, err
}
startDateWeeks, err := calcStartDate(now, Weekly, weekPeriods)
if err != nil {
return nil, err
}
endDateWeeks, err := calcEndDate(startDateWeeks, Weekly, weekPeriods)
if err != nil {
return nil, err
}
startDateMonths, err := calcStartDate(now, Monthly, monthPeriods)
if err != nil {
return nil, err
}
endDateMonths, err := calcEndDate(startDateMonths, Monthly, monthPeriods)
if err != nil {
return nil, err
}
conds := buildCountUniqueUserConds(opt)
return l.siteUsageMultiplePeriodsBySQL(ctx, startDateDays, endDateDays, startDateWeeks, endDateWeeks, startDateMonths, endDateMonths, conds)
}
func (l *eventLogStore) siteUsageMultiplePeriodsBySQL(ctx context.Context, startDateDays, endDateDays, startDateWeeks, endDateWeeks, startDateMonths, endDateMonths time.Time, conds []*sqlf.Query) (*types.SiteUsageStatistics, error) {
q := sqlf.Sprintf(siteUsageMultiplePeriodsQuery, startDateDays, endDateDays, startDateWeeks, endDateWeeks, startDateMonths, endDateMonths, sqlf.Join(conds, ") AND ("))
rows, err := l.Query(ctx, q)
if err != nil {
return nil, err
}
defer rows.Close()
dauCounts := []*types.SiteActivityPeriod{}
wauCounts := []*types.SiteActivityPeriod{}
mauCounts := []*types.SiteActivityPeriod{}
for rows.Next() {
var v UsageValue
err := rows.Scan(&v.Start, &v.Type, &v.Count, &v.CountRegistered)
if err != nil {
return nil, err
}
v.Start = v.Start.UTC()
if v.Type == "day" {
dauCounts = append(dauCounts, &types.SiteActivityPeriod{
StartTime: v.Start,
UserCount: int32(v.Count),
RegisteredUserCount: int32(v.CountRegistered),
AnonymousUserCount: int32(v.Count - v.CountRegistered),
// No longer used in site admin usage stats views. Use GetSiteUsageStats if you need this instead.
IntegrationUserCount: 0,
})
}
if v.Type == "week" {
wauCounts = append(wauCounts, &types.SiteActivityPeriod{
StartTime: v.Start,
UserCount: int32(v.Count),
RegisteredUserCount: int32(v.CountRegistered),
AnonymousUserCount: int32(v.Count - v.CountRegistered),
// No longer used in site admin usage stats views. Use GetSiteUsageStats if you need this instead.
IntegrationUserCount: 0,
})
}
if v.Type == "month" {
mauCounts = append(mauCounts, &types.SiteActivityPeriod{
StartTime: v.Start,
UserCount: int32(v.Count),
RegisteredUserCount: int32(v.CountRegistered),
AnonymousUserCount: int32(v.Count - v.CountRegistered),
// No longer used in site admin usage stats views. Use GetSiteUsageStats if you need this instead.
IntegrationUserCount: 0,
})
}
}
if err = rows.Err(); err != nil {
return nil, err
}
return &types.SiteUsageStatistics{
DAUs: dauCounts,
WAUs: wauCounts,
MAUs: mauCounts,
}, nil
}
var siteUsageMultiplePeriodsQuery = `
WITH all_periods AS (
SELECT generate_series((%s)::timestamp, (%s)::timestamp, ('1 day')::interval) AS period, 'day' AS type
UNION ALL
SELECT generate_series((%s)::timestamp, (%s)::timestamp, ('1 week')::interval) AS period, 'week' AS type
UNION ALL
SELECT generate_series((%s)::timestamp, (%s)::timestamp, ('1 month')::interval) AS period, 'month' AS type),
unique_users_by_dwm AS (
SELECT
` + makeDateTruncExpression("day", "timestamp") + ` AS day_period,
` + makeDateTruncExpression("week", "timestamp") + ` AS week_period,
` + makeDateTruncExpression("month", "timestamp") + ` AS month_period,
event_logs.user_id > 0 AS registered,
` + aggregatedUserIDQueryFragment + ` as aggregated_user_id
FROM event_logs
LEFT OUTER JOIN users ON users.id = event_logs.user_id
WHERE (%s) AND anonymous_user_id != 'backend'
GROUP BY day_period, week_period, month_period, aggregated_user_id, registered
),
unique_users_by_day AS (
SELECT
day_period,
COUNT(DISTINCT aggregated_user_id) as count,
COUNT(DISTINCT aggregated_user_id) FILTER (WHERE registered) as count_registered
FROM unique_users_by_dwm
GROUP BY day_period
),
unique_users_by_week AS (
SELECT
week_period,
COUNT(DISTINCT aggregated_user_id) as count,
COUNT(DISTINCT aggregated_user_id) FILTER (WHERE registered) as count_registered
FROM unique_users_by_dwm
GROUP BY week_period
),
unique_users_by_month AS (
SELECT
month_period,
COUNT(DISTINCT aggregated_user_id) as count,
COUNT(DISTINCT aggregated_user_id) FILTER (WHERE registered) as count_registered
FROM unique_users_by_dwm
GROUP BY month_period
)
SELECT
all_periods.period,
all_periods.type,
COALESCE(CASE WHEN all_periods.type = 'day'
THEN unique_users_by_day.count
ELSE CASE WHEN all_periods.type = 'week'
THEN unique_users_by_week.count
ELSE unique_users_by_month.count
END
END, 0) count,
COALESCE(CASE WHEN all_periods.type = 'day'
THEN unique_users_by_day.count_registered
ELSE CASE WHEN all_periods.type = 'week'
THEN unique_users_by_week.count_registered
ELSE unique_users_by_month.count_registered
END
END, 0) count_registered
FROM all_periods
LEFT OUTER JOIN unique_users_by_day ON all_periods.type = 'day' AND all_periods.period = (unique_users_by_day.day_period)::timestamp
LEFT OUTER JOIN unique_users_by_week ON all_periods.type = 'week' AND all_periods.period = (unique_users_by_week.week_period)::timestamp
LEFT OUTER JOIN unique_users_by_month ON all_periods.type = 'month' AND all_periods.period = (unique_users_by_month.month_period)::timestamp
ORDER BY period DESC
`
func (l *eventLogStore) CountUniqueUsersAll(ctx context.Context, startDate, endDate time.Time, opt *CountUniqueUsersOptions) (int, error) {
conds := buildCountUniqueUserConds(opt)
return l.countUniqueUsersBySQL(ctx, startDate, endDate, conds)
}
func (l *eventLogStore) CountUniqueUsersByEventNamePrefix(ctx context.Context, startDate, endDate time.Time, namePrefix string) (int, error) {
return l.countUniqueUsersBySQL(ctx, startDate, endDate, []*sqlf.Query{sqlf.Sprintf("name LIKE %s ", namePrefix+"%")})
}
func (l *eventLogStore) CountUniqueUsersByEventName(ctx context.Context, startDate, endDate time.Time, name string) (int, error) {
return l.countUniqueUsersBySQL(ctx, startDate, endDate, []*sqlf.Query{sqlf.Sprintf("name = %s", name)})
}
func (l *eventLogStore) CountUniqueUsersByEventNames(ctx context.Context, startDate, endDate time.Time, names []string) (int, error) {
items := []*sqlf.Query{}
for _, v := range names {
items = append(items, sqlf.Sprintf("%s", v))
}
return l.countUniqueUsersBySQL(ctx, startDate, endDate, []*sqlf.Query{sqlf.Sprintf("name IN (%s)", sqlf.Join(items, ","))})
}
func (l *eventLogStore) countUniqueUsersBySQL(ctx context.Context, startDate, endDate time.Time, conds []*sqlf.Query) (int, error) {
if len(conds) == 0 {
conds = []*sqlf.Query{sqlf.Sprintf("TRUE")}
}
q := sqlf.Sprintf(`SELECT COUNT(DISTINCT `+userIDQueryFragment+`)
FROM event_logs
LEFT OUTER JOIN users ON users.id = event_logs.user_id
WHERE (DATE(TIMEZONE('UTC'::text, timestamp)) >= %s) AND (DATE(TIMEZONE('UTC'::text, timestamp)) <= %s) AND (%s)`, startDate, endDate, sqlf.Join(conds, ") AND ("))
r := l.QueryRow(ctx, q)
var count int
err := r.Scan(&count)
return count, err
}
func (l *eventLogStore) ListUniqueUsersAll(ctx context.Context, startDate, endDate time.Time) ([]int32, error) {
rows, err := l.Handle().QueryContext(ctx, `SELECT user_id
FROM event_logs
WHERE user_id > 0 AND DATE(TIMEZONE('UTC'::text, timestamp)) >= $1 AND DATE(TIMEZONE('UTC'::text, timestamp)) <= $2
GROUP BY user_id`, startDate, endDate)
if err != nil {
return nil, err
}
var users []int32
defer rows.Close()
for rows.Next() {
var userID int32
err := rows.Scan(&userID)
if err != nil {
return nil, err
}
users = append(users, userID)
}
if err = rows.Err(); err != nil {
return nil, err
}
return users, nil
}
func (l *eventLogStore) UsersUsageCounts(ctx context.Context) (counts []types.UserUsageCounts, err error) {
rows, err := l.Handle().QueryContext(ctx, usersUsageCountsQuery)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var c types.UserUsageCounts
err := rows.Scan(
&c.Date,
&c.UserID,
&dbutil.NullInt32{N: &c.SearchCount},
&dbutil.NullInt32{N: &c.CodeIntelCount},
)
if err != nil {
return nil, err
}
counts = append(counts, c)
}
if err = rows.Err(); err != nil {
return nil, err
}
return counts, nil
}
const usersUsageCountsQuery = `
SELECT
DATE(timestamp),
user_id,
COUNT(*) FILTER (WHERE event_logs.name ='SearchResultsQueried') as search_count,
COUNT(*) FILTER (WHERE event_logs.name LIKE '%codeintel%') as codeintel_count
FROM event_logs
WHERE anonymous_user_id != 'backend'
GROUP BY 1, 2
ORDER BY 1 DESC, 2 ASC;
`
// SiteUsageOptions specifies the options for Site Usage calculations.
type SiteUsageOptions struct {
CommonUsageOptions
}
func (l *eventLogStore) SiteUsageCurrentPeriods(ctx context.Context) (types.SiteUsageSummary, error) {
return l.siteUsageCurrentPeriods(ctx, time.Now().UTC(), &SiteUsageOptions{
CommonUsageOptions{
ExcludeSystemUsers: true,
ExcludeNonActiveUsers: true,
ExcludeSourcegraphAdmins: true,
ExcludeSourcegraphOperators: true,
},
})
}
func (l *eventLogStore) siteUsageCurrentPeriods(ctx context.Context, now time.Time, opt *SiteUsageOptions) (summary types.SiteUsageSummary, err error) {
conds := []*sqlf.Query{sqlf.Sprintf("TRUE")}
if opt != nil {
conds = BuildCommonUsageConds(&opt.CommonUsageOptions, conds)
}
query := sqlf.Sprintf(siteUsageCurrentPeriodsQuery, now, now, now, now, now, now, sqlf.Join(conds, ") AND ("))
err = l.QueryRow(ctx, query).Scan(
&summary.RollingMonth,
&summary.Month,
&summary.Week,
&summary.Day,
&summary.UniquesRollingMonth,
&summary.UniquesMonth,
&summary.UniquesWeek,
&summary.UniquesDay,
&summary.RegisteredUniquesRollingMonth,
&summary.RegisteredUniquesMonth,
&summary.RegisteredUniquesWeek,
&summary.RegisteredUniquesDay,
&summary.IntegrationUniquesRollingMonth,
&summary.IntegrationUniquesMonth,
&summary.IntegrationUniquesWeek,
&summary.IntegrationUniquesDay,
)
return summary, err
}
var siteUsageCurrentPeriodsQuery = `
SELECT
current_rolling_month,
current_month,
current_week,
current_day,
COUNT(DISTINCT user_id) FILTER (WHERE rolling_month = current_rolling_month) AS uniques_rolling_month,
COUNT(DISTINCT user_id) FILTER (WHERE month = current_month) AS uniques_month,
COUNT(DISTINCT user_id) FILTER (WHERE week = current_week) AS uniques_week,
COUNT(DISTINCT user_id) FILTER (WHERE day = current_day) AS uniques_day,
COUNT(DISTINCT user_id) FILTER (WHERE rolling_month = current_rolling_month AND registered) AS registered_uniques_rolling_month,
COUNT(DISTINCT user_id) FILTER (WHERE month = current_month AND registered) AS registered_uniques_month,
COUNT(DISTINCT user_id) FILTER (WHERE week = current_week AND registered) AS registered_uniques_week,
COUNT(DISTINCT user_id) FILTER (WHERE day = current_day AND registered) AS registered_uniques_day,
COUNT(DISTINCT user_id) FILTER (WHERE rolling_month = current_rolling_month AND source = 'CODEHOSTINTEGRATION')
AS integration_uniques_rolling_month,
COUNT(DISTINCT user_id) FILTER (WHERE month = current_month AND source = 'CODEHOSTINTEGRATION')
AS integration_uniques_month,
COUNT(DISTINCT user_id) FILTER (WHERE week = current_week AND source = 'CODEHOSTINTEGRATION')
AS integration_uniques_week,
COUNT(DISTINCT user_id) FILTER (WHERE day = current_day AND source = 'CODEHOSTINTEGRATION')
AS integration_uniques_day
FROM (
-- This sub-query is here to avoid re-doing this work above on each aggregation.
-- rolling_month will always be the current_rolling_month, but is retained for clarity of the CTE
SELECT
name,
user_id != 0 as registered,
` + aggregatedUserIDQueryFragment + ` AS user_id,
source,
` + makeDateTruncExpression("rolling_month", "%s::timestamp") + ` as rolling_month,
` + makeDateTruncExpression("month", "timestamp") + ` as month,
` + makeDateTruncExpression("week", "timestamp") + ` as week,
` + makeDateTruncExpression("day", "timestamp") + ` as day,
` + makeDateTruncExpression("rolling_month", "%s::timestamp") + ` as current_rolling_month,
` + makeDateTruncExpression("month", "%s::timestamp") + ` as current_month,
` + makeDateTruncExpression("week", "%s::timestamp") + ` as current_week,
` + makeDateTruncExpression("day", "%s::timestamp") + ` as current_day
FROM event_logs
LEFT OUTER JOIN users ON users.id = event_logs.user_id
WHERE (timestamp >= ` + makeDateTruncExpression("rolling_month", "%s::timestamp") + `) AND (%s) AND anonymous_user_id != 'backend'
) events
GROUP BY current_rolling_month, rolling_month, current_month, current_week, current_day
`
func (l *eventLogStore) CodeIntelligencePreciseWAUs(ctx context.Context) (int, error) {
eventNames := []string{
"codeintel.lsifHover",
"codeintel.lsifDefinitions",
"codeintel.lsifReferences",
}
return l.codeIntelligenceWeeklyUsersCount(ctx, eventNames, time.Now().UTC())
}
func (l *eventLogStore) CodeIntelligenceSearchBasedWAUs(ctx context.Context) (int, error) {
eventNames := []string{
"codeintel.searchHover",
"codeintel.searchDefinitions",
"codeintel.searchReferences",