-
Notifications
You must be signed in to change notification settings - Fork 731
Expand file tree
/
Copy pathactivity.service.ts
More file actions
1952 lines (1751 loc) · 64.6 KB
/
activity.service.ts
File metadata and controls
1952 lines (1751 loc) · 64.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
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
import vader from 'crowd-sentiment'
import isEqual from 'lodash.isequal'
import mergeWith from 'lodash.mergewith'
import {
ApplicationError,
UnrepeatableError,
distinct,
distinctBy,
escapeNullByte,
generateUUIDv1,
isValidEmail,
parseGitHubNoreplyEmail,
single,
singleOrDefault,
trimUtf8ToMaxByteLength,
} from '@crowd/common'
import { CommonMemberService, SearchSyncWorkerEmitter } from '@crowd/common_services'
import {
createOrUpdateRelations,
findIdentitiesForMembers,
findMembersByIdentities,
findMembersByVerifiedEmails,
findMembersByVerifiedUsernames,
findSegmentsForRepos,
insertActivities,
queryActivityRelations,
} from '@crowd/data-access-layer'
import { IDbActivityRelation } from '@crowd/data-access-layer/src/activityRelations/types'
import { DbStore, arePrimitivesDbEqual } from '@crowd/data-access-layer/src/database'
import {
IActivityRelationCreateOrUpdateData,
IDbActivity,
IDbActivityCreateData,
IDbActivityUpdateData,
} from '@crowd/data-access-layer/src/old/apps/data_sink_worker/repo/activity.data'
import { IDbMember } from '@crowd/data-access-layer/src/old/apps/data_sink_worker/repo/member.data'
import MemberRepository from '@crowd/data-access-layer/src/old/apps/data_sink_worker/repo/member.repo'
import RequestedForErasureMemberIdentitiesRepository from '@crowd/data-access-layer/src/old/apps/data_sink_worker/repo/requestedForErasureMemberIdentities.repo'
import SettingsRepository from '@crowd/data-access-layer/src/old/apps/data_sink_worker/repo/settings.repo'
import { QueryExecutor, dbStoreQx } from '@crowd/data-access-layer/src/queryExecutor'
import { DEFAULT_ACTIVITY_TYPE_SETTINGS, GithubActivityType } from '@crowd/integrations'
import { Logger, LoggerBase, logExecutionTimeV2 } from '@crowd/logging'
import { IQueue } from '@crowd/queue'
import { RedisClient } from '@crowd/redis'
import { Client as TemporalClient } from '@crowd/temporal'
import {
IActivityData,
IMemberData,
IMemberIdentity,
ISentimentAnalysisResult,
MemberAttributeName,
MemberIdentityType,
PlatformType,
} from '@crowd/types'
import { IActivityUpdateData, ISentimentActivityInput } from './activity.data'
import MemberService, { mergeIfAllowed } from './member.service'
import { IProcessActivityResult } from './types'
/* eslint-disable @typescript-eslint/no-explicit-any */
export default class ActivityService extends LoggerBase {
private readonly settingsRepo: SettingsRepository
private readonly memberRepo: MemberRepository
private readonly commonMemberService: CommonMemberService
private readonly requestedForErasureMemberIdentitiesRepo: RequestedForErasureMemberIdentitiesRepository
private readonly pgQx: QueryExecutor
constructor(
private readonly pgStore: DbStore,
private readonly searchSyncWorkerEmitter: SearchSyncWorkerEmitter,
private readonly redisClient: RedisClient,
private readonly temporal: TemporalClient,
private readonly client: IQueue,
parentLog: Logger,
) {
super(parentLog)
this.settingsRepo = new SettingsRepository(this.pgStore, this.log)
this.memberRepo = new MemberRepository(this.pgStore, this.log)
this.requestedForErasureMemberIdentitiesRepo =
new RequestedForErasureMemberIdentitiesRepository(this.pgStore, this.log)
this.pgQx = dbStoreQx(this.pgStore)
this.commonMemberService = new CommonMemberService(this.pgQx, temporal, this.log)
}
public async prepareForUpsert(
resultId: string,
segmentId: string,
timestamp: Date,
activity: IActivityUpdateData,
memberInfo: { isBot: boolean; isTeamMember: boolean },
existingActivityId?: string,
): Promise<IActivityPrepareForUpsertResult> {
// Use the existing activity ID if found, otherwise generate a new one.
// when existing activityId is passed, tinybird will handle the deduplication
const id = existingActivityId || generateUUIDv1()
const sentimentPromise = this.getActivitySentiment({
body: activity.body,
title: activity.title,
type: activity.type,
platform: activity.platform,
})
const payload: IDbActivityCreateData = {
id,
timestamp: timestamp.toISOString(),
platform: activity.platform,
type: activity.type,
score: activity.score,
sourceId: activity.sourceId,
sourceParentId: activity.sourceParentId,
memberId: activity.memberId,
attributes: activity.attributes,
sentiment: await sentimentPromise,
title: activity.title,
body: escapeNullByte(activity.body),
channel: activity.channel,
url: activity.url,
username: activity.username,
objectMemberId: activity.objectMemberId,
objectMemberUsername: activity.objectMemberUsername,
segmentId,
// if the member is bot, we don't want to affiliate the activity with an organization
organizationId: memberInfo.isBot ? null : activity.organizationId,
isBotActivity: memberInfo.isBot,
isTeamMemberActivity: memberInfo.isTeamMember,
}
return {
resultId,
activityId: id,
typeToCreate: activity.type,
channelToCreate: activity.channel,
payload,
}
}
private async mergeActivityData(
data: IActivityUpdateData,
original: IDbActivity,
): Promise<IDbActivityUpdateData> {
let calcSentiment = false
let body: string | undefined
if (!arePrimitivesDbEqual(original.body, data.body)) {
body = data.body
calcSentiment = true
}
let title: string | undefined
if (!arePrimitivesDbEqual(original.title, data.title)) {
title = data.title
calcSentiment = true
}
let sentiment: Promise<ISentimentAnalysisResult | undefined>
if (calcSentiment) {
sentiment = this.getActivitySentiment({
body: body,
title: title,
type: original.type,
platform: original.platform,
})
} else {
sentiment = Promise.resolve(undefined)
}
let type: string | undefined
if (!arePrimitivesDbEqual(original.type, data.type)) {
type = data.type
}
let score: number | undefined
if (!arePrimitivesDbEqual(original.score, data.score)) {
score = data.score
}
let sourceId: string | undefined
if (!arePrimitivesDbEqual(original.sourceId, data.sourceId)) {
sourceId = data.sourceId
}
let sourceParentId: string | undefined
if (!arePrimitivesDbEqual(original.sourceParentId, data.sourceParentId)) {
sourceParentId = data.sourceParentId
}
let memberId: string | undefined
if (!arePrimitivesDbEqual(original.memberId, data.memberId)) {
memberId = data.memberId
}
let username: string | undefined
if (!arePrimitivesDbEqual(original.username, data.username)) {
username = data.username
}
let objectMemberId: string | undefined
if (!arePrimitivesDbEqual(original.objectMemberId, data.objectMemberId)) {
objectMemberId = data.objectMemberId
}
let objectMemberUsername: string | undefined
if (!arePrimitivesDbEqual(original.objectMemberUsername, data.objectMemberUsername)) {
objectMemberUsername = data.objectMemberUsername
}
let attributes: Record<string, unknown> | undefined
if (data.attributes && Object.keys(data.attributes).length > 0) {
const temp = mergeWith({}, original.attributes, data.attributes)
if (!isEqual(temp, original.attributes)) {
attributes = temp
}
}
let channel: string | undefined
if (!arePrimitivesDbEqual(original.channel, data.channel)) {
channel = data.channel
}
let url: string | undefined
if (!arePrimitivesDbEqual(original.url, data.url)) {
url = data.url
}
let organizationId: string | undefined
if (!arePrimitivesDbEqual(original.organizationId, data.organizationId)) {
organizationId = data.organizationId
}
let platform: PlatformType | undefined
if (!arePrimitivesDbEqual(original.platform, data.platform)) {
platform = data.platform
}
return {
type,
score,
sourceId,
sourceParentId,
memberId,
username,
objectMemberId,
objectMemberUsername,
sentiment: await sentiment,
attributes,
body,
title,
channel,
url,
organizationId,
platform,
}
}
private prepareMemberData(
data: { resultId: string; activity: IActivityData; platform: PlatformType }[],
): Map<string, { success: boolean; err?: Error }> {
const results = new Map<string, { success: boolean; err?: Error }>()
for (const { resultId, activity, platform } of data) {
if (!activity.username && !activity.member) {
this.log.error({ platform, activity }, 'Activity does not have a username or member.')
results.set(resultId, {
success: false,
err: new UnrepeatableError('Activity does not have a username or member.'),
})
continue
}
let member = activity.member
const username = activity.username ? activity.username.trim() : undefined
if (!member && username) {
member = {
identities: [
{
platform,
value: username,
type: MemberIdentityType.USERNAME,
verified: true,
source: 'integration',
} as IMemberIdentity,
],
}
}
// When activity.username is set but differs from the member's platform identity value,
// override it so the member lookup and the identity insert use the same key.
// Example: git activities set activity.username to the author display name (e.g. "John Doe")
// while the identity stores the email (e.g. "john.doe@example.com"). Without this correction
// the lookup misses the existing member, creating an unnecessary orphan member.
if (username && member) {
const platformIdentity = member.identities.find(
(i) => i.platform === platform && i.type === MemberIdentityType.USERNAME && i.value,
)
if (platformIdentity && platformIdentity.value !== username) {
this.log.debug(
{ platform, originalUsername: username, correctedUsername: platformIdentity.value },
'Overriding activity.username with member platform identity value',
)
activity.username = platformIdentity.value
}
}
member.identities = member.identities.filter((i) => i.value)
if (!username) {
const identities = activity.member.identities.filter(
(i) => i.platform === platform && i.type === MemberIdentityType.USERNAME,
)
if (identities.length === 1) {
activity.username = identities[0].value
} else if (identities.length === 0) {
this.log.error(
{ platform, activity },
`Activity's member does not have an identity for the platform!`,
)
results.set(resultId, {
success: false,
err: new UnrepeatableError(
`Activity's member does not have an identity for the platform: ${platform}!`,
),
})
continue
} else {
this.log.error(
{ platform, activity },
`Activity's member has multiple usernames for the same platform platform!`,
)
results.set(resultId, {
success: false,
err: new UnrepeatableError(
`Activity's member has multiple usernames for the same platform: ${platform}!`,
),
})
continue
}
}
if (!member.attributes) {
member.attributes = {}
}
const objectMemberUsername = activity.objectMemberUsername
? activity.objectMemberUsername.trim()
: undefined
let objectMember = activity.objectMember
if (objectMember) {
objectMember.identities = objectMember.identities.filter((i) => i.value)
}
if (objectMember && !objectMemberUsername) {
const identities = objectMember.identities.filter(
(i) => i.platform === platform && i.type === MemberIdentityType.USERNAME,
)
if (identities.length === 1) {
activity.objectMemberUsername = identities[0].value
} else if (identities.length === 0) {
this.log.error(
{ platform, activity },
`Activity's object member does not have an identity for the platform!`,
)
results.set(resultId, {
success: false,
err: new UnrepeatableError(
`Activity's object member does not have an identity for the platform: ${platform}!`,
),
})
continue
} else {
this.log.error(
{ platform, activity },
`Activity's object member has multiple usernames for the same platform platform!`,
)
results.set(resultId, {
success: false,
err: new UnrepeatableError(
`Activity's object member has multiple usernames for the same platform: ${platform}!`,
),
})
continue
}
} else if (objectMemberUsername && !objectMember) {
objectMember = {
identities: [
{
platform,
value: objectMemberUsername,
type: MemberIdentityType.USERNAME,
verified: true,
source: 'integration',
} as IMemberIdentity,
],
}
}
results.set(resultId, { success: true })
}
return results
}
public async processActivities(
payloads: IActivityProcessData[],
onboarding: boolean,
): Promise<Map<string, IProcessActivityResult>> {
const resultMap = new Map<string, IProcessActivityResult>()
let relevantPayloads = payloads
this.log.trace(`[ACTIVITY] Processing ${relevantPayloads.length} activities!`)
const prepareMemberResults = this.prepareMemberData(relevantPayloads)
relevantPayloads = []
for (const [resultId, { success, err }] of prepareMemberResults) {
if (!success) {
resultMap.set(resultId, { success: false, err })
} else {
relevantPayloads.push(single(payloads, (a) => a.resultId === resultId))
}
}
if (relevantPayloads.length === 0) {
return resultMap
}
this.log.trace(
`[ACTIVITY] We still have ${relevantPayloads.length} activities left to process after member preparation!`,
)
const allMemberIdentities = relevantPayloads
.flatMap((a) => a.activity.member.identities)
.concat(
relevantPayloads
.filter((a) => a.activity.objectMember)
.flatMap((a) => a.activity.objectMember.identities),
)
// handle identities that were requested to be erased by the user
const toErase = await logExecutionTimeV2(
async () =>
this.requestedForErasureMemberIdentitiesRepo.someIdentitiesWereErasedByUserRequest(
allMemberIdentities,
),
this.log,
'processActivities -> someIdentitiesWereErasedByUserRequest',
)
const handleErasure = (member: IMemberData, resultId: string): boolean => {
const toEraseMemberIdentities = toErase.filter((e) =>
member.identities.some((i) => {
if (i.type === MemberIdentityType.EMAIL) {
return e.type === i.type && e.value === i.value
}
return e.type === i.type && e.value === i.value && e.platform === i.platform
}),
)
if (toEraseMemberIdentities.length > 0) {
if (toEraseMemberIdentities.some((i) => i.verified)) {
this.log.warn(
{
memberIdentities: member.identities,
},
'Member has identities that were requested to be erased by the user! Skipping activity processing!',
)
// set result to true cuz it was processed and we don't need to store error
resultMap.set(resultId, { success: true })
// remove activity from relevant activities because it's not valid anymore
relevantPayloads = relevantPayloads.filter((a) => a.resultId !== resultId)
return false
} else {
// remove unverified identities that were marked to be erased so they are not created
member.identities = member.identities.filter((i) => {
if (i.verified) return true
const maybeToErase = toEraseMemberIdentities.find(
(e) =>
e.type === i.type &&
e.value === i.value &&
(e.type === MemberIdentityType.EMAIL || e.platform === i.platform),
)
if (maybeToErase) return false
return true
})
if (member.identities.filter((i) => i.value).length === 0) {
this.log.warn(
'Member had at least one unverified identity removed as it was requested to be removed! Now there is no identities left - skipping processing!',
)
// set result map to true cuz it was processed and we don't need to store error
resultMap.set(resultId, { success: true })
// remove activity from relevant activities because it's not valid anymore
relevantPayloads = relevantPayloads.filter((a) => a.resultId !== resultId)
return false
}
}
}
return true
}
let promises = []
const repoPayloads: IActivityProcessData[] = []
for (const payload of relevantPayloads) {
if (!handleErasure(payload.activity.member, payload.resultId)) {
continue
}
if (
payload.activity.objectMember &&
!handleErasure(payload.activity.objectMember, payload.resultId)
) {
continue
}
if (payload.platform === PlatformType.GITLAB || payload.platform === PlatformType.GITHUB) {
repoPayloads.push(payload)
} else if (!payload.segmentId) {
resultMap.set(payload.resultId, {
success: false,
err: new UnrepeatableError(
'No segmentId provided! Something went wrong - it should be set in the result data or taken from integrations.segmentId column!',
),
})
relevantPayloads = relevantPayloads.filter((a) => a.resultId !== payload.resultId)
}
}
// determine segmentIds from public.repositories
const distinctChannels = distinctBy(
repoPayloads,
(a) => `${a.integrationId}-${a.activity.channel}`,
)
if (distinctChannels.length > 0) {
this.log.info(
{ repoPayloads: repoPayloads.length, distinctChannels: distinctChannels.length },
'[ACTIVITY] Looking up segments from public.repositories',
)
promises.push(
findSegmentsForRepos(
this.pgQx,
this.redisClient,
this.log,
distinctChannels.map((c) => ({
integrationId: c.integrationId,
url: c.activity.channel,
})),
).then((results) => {
for (const result of results) {
if (result.segmentId) {
for (const payload of repoPayloads.filter(
(p) =>
p.integrationId === result.integrationId && p.activity.channel === result.url,
)) {
payload.segmentId = result.segmentId
}
}
}
}),
)
}
await Promise.all(promises)
this.log.trace(
`[ACTIVITY] We still have ${relevantPayloads.length} activities left to process after finding segments!`,
)
const orConditions = relevantPayloads.map((r) => {
return {
and: [
{ timestamp: { eq: r.activity.timestamp } },
{ sourceId: { eq: r.activity.sourceId } },
{ platform: { eq: r.activity.platform } },
{ type: { eq: r.activity.type } },
{ channel: { eq: r.activity.channel } },
],
}
})
const segmentIds = distinct(relevantPayloads.map((r) => r.segmentId))
// Check activityRelations to find existence
// If found, we reuse the activityId and let tinybird handle the upsert via DEDUP keys.
// This avoids querying tinybird and merging data, simplifying the logic and making it
// more resilient to data replication delays.
const existingActivityRelations = await logExecutionTimeV2(
async () =>
queryActivityRelations(
this.pgQx,
{
segmentIds,
filter: {
and: [
{
timestamp: {
in: distinct(relevantPayloads.map((r) => r.activity.timestamp)),
},
},
{
or: orConditions,
},
],
},
limit: relevantPayloads.length,
noCount: true,
},
[
'activityId',
'timestamp',
'memberId',
'objectMemberId',
'organizationId',
'conversationId',
'parentId',
'type',
'sourceId',
'sourceParentId',
'channel',
'segmentId',
'platform',
'username',
'objectMemberUsername',
'sentimentScore',
'gitInsertions',
'gitDeletions',
'score',
'pullRequestReviewState',
],
),
this.log,
'processActivities -> queryActivityRelations',
)
// map existing activities to payloads for further processing
const payloadsNotInDb: IActivityProcessData[] = []
for (const payload of relevantPayloads) {
const existingRelation = singleOrDefault(existingActivityRelations.rows, (a) => {
if (a.segmentId !== payload.segmentId) {
return false
}
if (a.platform !== payload.platform) {
return false
}
if (a.type !== payload.activity.type) {
return false
}
if (a.sourceId !== payload.activity.sourceId) {
return false
}
if (payload.activity.channel) {
if (a.channel !== payload.activity.channel) {
return false
}
}
const aTimestamp = new Date(a.timestamp).toISOString()
const pTimestamp = new Date(payload.activity.timestamp).toISOString()
return aTimestamp === pTimestamp
})
if (existingRelation) {
payload.activityId = existingRelation.activityId
payload.dbActivityRelation = existingRelation
}
// Regardless of whether the activity already exists, we always resolve the
// owning member from identities (username/email/etc.) instead of trusting
// the existing relation.memberId. This ensures activities always follow
// the current owner of the identity.
payloadsNotInDb.push(payload)
}
if (payloadsNotInDb.length > 0) {
// map DB results to payloads by matching platform + value
const mapResultsToPayloads = (
results: Map<string | { platform: string; value: string }, any>,
matchFn: (p: any, value: string, platform?: string) => boolean,
setMemberFn: (p: any, member: any) => void,
) => {
for (const [key, dbMember] of results) {
const value = typeof key === 'string' ? key : key.value
const platform = typeof key === 'string' ? undefined : key.platform
payloadsNotInDb
.filter((p) => matchFn(p, value, platform))
.forEach((p) => setMemberFn(p, dbMember))
}
}
// Look up members using verified usernames (same platform)
const usernameFilter = payloadsNotInDb
.filter((p) => !p.dbMember)
.map((p) => ({
platform: p.platform,
username: p.activity.username,
segmentId: p.segmentId,
}))
.concat(
payloadsNotInDb
.filter((p) => !p.dbObjectMember && p.activity.objectMemberUsername)
.map((p) => ({
platform: p.platform,
username: p.activity.objectMemberUsername,
segmentId: p.segmentId,
})),
)
if (usernameFilter.length > 0) {
const dbMembersByUsername = await logExecutionTimeV2(
async () => findMembersByVerifiedUsernames(this.pgQx, usernameFilter),
this.log,
'processActivities -> memberRepo.findMembersByUsernames',
)
mapResultsToPayloads(
dbMembersByUsername,
(p, value, platform) =>
!p.dbMember &&
p.platform === platform &&
p.activity.username?.toLowerCase() === value.toLowerCase(),
(p, member) => {
p.dbMember = member
p.dbMemberSource = 'username'
},
)
mapResultsToPayloads(
dbMembersByUsername,
(p, value, platform) =>
!p.dbObjectMember &&
p.platform === platform &&
p.activity.objectMemberUsername?.toLowerCase() === value.toLowerCase(),
(p, member) => {
p.dbObjectMember = member
p.dbObjectMemberSource = 'username'
},
)
}
// Look up members using verified emails (same platform)
const emails = new Set<string>()
for (const payload of payloadsNotInDb.filter((p) => !p.dbMember)) {
for (const identity of payload.activity.member.identities.filter(
(i) => i.verified && i.type === MemberIdentityType.EMAIL,
)) {
emails.add(identity.value)
}
}
for (const payload of payloadsNotInDb.filter(
(p) => !p.dbObjectMember && p.activity.objectMember,
)) {
for (const identity of payload.activity.objectMember.identities.filter(
(i) => i.verified && i.type === MemberIdentityType.EMAIL,
)) {
emails.add(identity.value)
}
}
if (emails.size > 0) {
const dbMembersByEmail = await logExecutionTimeV2(
() => findMembersByVerifiedEmails(this.pgQx, Array.from(emails)),
this.log,
'processActivities -> memberRepo.findMembersByEmails',
)
mapResultsToPayloads(
dbMembersByEmail,
(p, value) =>
!p.dbMember &&
p.activity.member.identities.some(
(i) =>
i.verified &&
i.type === MemberIdentityType.EMAIL &&
i.value.toLowerCase() === value.toLowerCase(),
),
(p, member) => {
p.dbMember = member
p.dbMemberSource = 'email'
},
)
mapResultsToPayloads(
dbMembersByEmail,
(p, value) =>
!p.dbObjectMember &&
p.activity.objectMember?.identities.some(
(i) =>
i.verified &&
i.type === MemberIdentityType.EMAIL &&
i.value.toLowerCase() === value.toLowerCase(),
),
(p, member) => {
p.dbObjectMember = member
p.dbObjectMemberSource = 'email'
},
)
}
// Look up members by parsing noreply emails to extract platform usernames
// e.g. "123+john@users.noreply.github.com" -> GitHub username "john"
const noreplyEmailFilterMap = new Map<
string,
{ platform: PlatformType; username: string; segmentId: string }
>()
for (const payload of payloadsNotInDb.filter((p) => !p.dbMember)) {
for (const identity of payload.activity.member.identities.filter(
(i) => i.verified && i.type === MemberIdentityType.EMAIL,
)) {
const ghUsername = parseGitHubNoreplyEmail(identity.value)
if (ghUsername) {
const key = `${PlatformType.GITHUB}:${ghUsername}:${payload.segmentId}`
if (!noreplyEmailFilterMap.has(key)) {
noreplyEmailFilterMap.set(key, {
platform: PlatformType.GITHUB,
username: ghUsername,
segmentId: payload.segmentId,
})
}
}
}
}
for (const payload of payloadsNotInDb.filter(
(p) => !p.dbObjectMember && p.activity.objectMember,
)) {
for (const identity of payload.activity.objectMember.identities.filter(
(i) => i.verified && i.type === MemberIdentityType.EMAIL,
)) {
const ghUsername = parseGitHubNoreplyEmail(identity.value)
if (ghUsername) {
const key = `${PlatformType.GITHUB}:${ghUsername}:${payload.segmentId}`
if (!noreplyEmailFilterMap.has(key)) {
noreplyEmailFilterMap.set(key, {
platform: PlatformType.GITHUB,
username: ghUsername,
segmentId: payload.segmentId,
})
}
}
}
}
if (noreplyEmailFilterMap.size > 0) {
const dbMembersByNoreplyEmail = await logExecutionTimeV2(
async () =>
findMembersByVerifiedUsernames(this.pgQx, Array.from(noreplyEmailFilterMap.values())),
this.log,
'processActivities -> memberRepo.findMembersByVerifiedUsernames (noreply-email)',
)
mapResultsToPayloads(
dbMembersByNoreplyEmail,
(p, value) =>
!p.dbMember &&
p.activity.member.identities.some(
(i) =>
i.verified &&
i.type === MemberIdentityType.EMAIL &&
parseGitHubNoreplyEmail(i.value) === value.toLowerCase(),
),
(p, member) => {
p.dbMember = member
p.dbMemberSource = 'email'
},
)
mapResultsToPayloads(
dbMembersByNoreplyEmail,
(p, value) =>
!p.dbObjectMember &&
p.activity.objectMember?.identities.some(
(i) =>
i.verified &&
i.type === MemberIdentityType.EMAIL &&
parseGitHubNoreplyEmail(i.value) === value.toLowerCase(),
),
(p, member) => {
p.dbObjectMember = member
p.dbObjectMemberSource = 'email'
},
)
}
// Look up members using cross-identity matching (different platforms)
// we will check only on platforms that store email identities as usernames
// only these platforms are considered for emails-as-usernames
const EMAIL_AS_USERNAME_PLATFORMS: PlatformType[] = [
PlatformType.GERRIT,
PlatformType.JIRA,
PlatformType.CONFLUENCE,
]
// Verified email identities -> match to verified usernames
const emailAsUsernameFilter = payloadsNotInDb
.filter(
(p) =>
!p.dbMember &&
p.activity.username &&
p.activity.member.identities.some(
(i) => i.verified && i.type === MemberIdentityType.EMAIL,
),
)
.flatMap((p) =>
EMAIL_AS_USERNAME_PLATFORMS.map((platform) => ({
platform,
username: p.activity.username,
segmentId: p.segmentId,
})),
)
.concat(
payloadsNotInDb
.filter(
(p) =>
!p.dbObjectMember &&
p.activity.objectMember &&
p.activity.objectMemberUsername &&
p.activity.objectMember.identities.some(
(i) => i.verified && i.type === MemberIdentityType.EMAIL,
),
)
.flatMap((p) =>
EMAIL_AS_USERNAME_PLATFORMS.map((platform) => ({
platform,
username: p.activity.objectMemberUsername,
segmentId: p.segmentId,
})),
),
)
if (emailAsUsernameFilter.length > 0) {
const dbMembersByEmailAsUsername = await logExecutionTimeV2(
async () => findMembersByVerifiedUsernames(this.pgQx, emailAsUsernameFilter),
this.log,
'processActivities -> memberRepo.findMembersByVerifiedUsernames (email-as-username)',
)
mapResultsToPayloads(
dbMembersByEmailAsUsername,
(p, value) =>
!p.dbMember &&
p.activity.member.identities.some(
(i) =>
i.verified &&
i.type === MemberIdentityType.EMAIL &&
i.value.toLowerCase() === value.toLowerCase(),
),
(p, member) => {
p.dbMember = member
p.dbMemberSource = 'username'
},
)
mapResultsToPayloads(
dbMembersByEmailAsUsername,
(p, value) =>
!p.dbObjectMember &&
p.activity.objectMember?.identities.some(
(i) =>
i.verified &&
i.type === MemberIdentityType.EMAIL &&
i.value.toLowerCase() === value.toLowerCase(),
),
(p, member) => {
p.dbObjectMember = member
p.dbObjectMemberSource = 'username'
},
)
}
// Verified email-like usernames -> match to verified email identities
const emailLikeUsernames = new Set<string>()