-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathStatisticsService.js
More file actions
4908 lines (4401 loc) · 161 KB
/
Copy pathStatisticsService.js
File metadata and controls
4908 lines (4401 loc) · 161 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
/**
* This service provides operations of statistics.
*/
const _ = require('lodash')
const Joi = require('joi')
const config = require('config')
const helper = require('../common/helper')
const logger = require('../common/logger')
const errors = require('../common/errors')
const prismaManager = require('../common/prisma')
const { Prisma } = prismaManager
const prisma = prismaManager.getClient()
const skillsPrisma = prismaManager.getSkillsClient()
const prismaHelper = require('../common/prismaHelper')
const reviewDb = require('../common/reviewDb')
const { resolveChallengeResultRelation } = require('../common/reviewDbHelper')
const { rerateDevTrack } = require('../ratings/developRatingEngine')
const {
RATING_METADATA_SELECT,
isChallengeRated
} = require('../ratings/challengeRatingStatus')
const {
fetchRatingPathParticipantsForChallenge,
resolveRatingPathParticipantId,
rerateMmTrack
} = require('../ratings/mmRatingEngine')
const {
buildRatingPathTypeId,
challengeMatchesRatingPath,
getConfiguredRatingPath,
getConfiguredRatingPathByTypeId,
normalizeRatingPathConfigs
} = require('../ratings/ratingPathConfig')
const {
TRACK_NAMES,
TYPE_NAMES,
getCanonicalTrackName,
getCanonicalTypeName,
loadChallengeDimensionLookup,
resolveTrackIdFromLookup,
resolveTypeIdFromLookup,
resolveTrackNameFromLookup,
resolveTypeNameFromLookup
} = require('../common/statsDimensionHelper')
const DISTRIBUTION_FIELDS = ['track', 'subTrack', 'distribution', 'createdAt', 'updatedAt',
'createdBy', 'updatedBy']
const DISTRIBUTION_FIELDS_NO_DATE = ['track', 'subTrack', 'distribution']
const HISTORY_STATS_FIELDS = ['userId', 'groupId', 'handle', 'handleLower', 'DEVELOP', 'DESIGN', 'DATA_SCIENCE', 'QA',
'createdAt', 'updatedAt', 'createdBy', 'updatedBy']
const MEMBER_STATS_FIELDS = ['userId', 'groupId', 'handle', 'handleLower', 'maxRating',
'challenges', 'wins', 'DEVELOP', 'DESIGN', 'DATA_SCIENCE', 'QA', 'COPILOT', 'createdAt',
'updatedAt', 'createdBy', 'updatedBy']
const LEGACY_STATS_READ_SOURCE = 'legacy'
const SUPPORTED_STATS_READ_SOURCES = ['unified', LEGACY_STATS_READ_SOURCE]
const DISTRIBUTION_RANGES = _.range(0, 4000, 100)
const DISTRIBUTION_MIN_RATING = 0
const DISTRIBUTION_MAX_RATING_EXCLUSIVE = 4000
const configuredStatsReadSource = _.toLower(String(config.STATS_READ_SOURCE || 'unified').trim())
if (!_.includes(SUPPORTED_STATS_READ_SOURCES, configuredStatsReadSource)) {
logger.warn(`Invalid STATS_READ_SOURCE='${config.STATS_READ_SOURCE}'. Falling back to 'unified'.`)
}
const USE_LEGACY_STATS_READS = configuredStatsReadSource === LEGACY_STATS_READ_SOURCE
const RATING_SOURCE_DEVELOPMENT = 'DEVELOPMENT_CHALLENGE'
const RATING_SOURCE_DATA_SCIENCE_CHALLENGE = 'DATA_SCIENCE_CHALLENGE'
const RATING_SOURCE_QUALITY_ASSURANCE_CHALLENGE = 'QUALITY_ASSURANCE_CHALLENGE'
const RATING_SOURCE_MARATHON_MATCH = 'MARATHON_MATCH'
const RERATE_MARATHON_ACTOR = 'rerate-mm-stats'
const CHALLENGE_TRACK_QUALITY_ASSURANCE = 'QUALITY_ASSURANCE'
const CHALLENGE_WINNER_PLACEMENT_TYPE = 'PLACEMENT'
const CHALLENGE_WINNER_PASSED_REVIEW_TYPE = 'PASSED_REVIEW'
const CHALLENGE_WINNER_HISTORY_TYPES = [CHALLENGE_WINNER_PLACEMENT_TYPE, CHALLENGE_WINNER_PASSED_REVIEW_TYPE]
const CHALLENGE_WINNER_RATING_TYPES = [CHALLENGE_WINNER_PLACEMENT_TYPE]
/**
* Join Prisma SQL condition fragments with a literal AND separator.
* Prisma joins with a Prisma.sql separator stringify that separator to [object Object].
* @param {Array<Object>} conditions Prisma SQL condition fragments
* @returns {Object} joined Prisma SQL fragment
*/
function joinSqlConditions (conditions) {
return Prisma.join(conditions, ' AND ')
}
function toOptionalInt (value) {
if (_.isNil(value) || value === '') {
return undefined
}
return _.toInteger(value)
}
function toOptionalFloat (value) {
if (_.isNil(value) || value === '') {
return undefined
}
return Number(value)
}
function toOptionalDate (value) {
if (_.isNil(value)) {
return undefined
}
return prismaHelper.convertDate(value)
}
/**
* Normalize request challenge identifiers into the string form documented by the API.
* Numeric compatibility inputs are echoed back as strings, while omitted values remain null.
* @param {*} value request challenge identifier
* @returns {string|null} normalized challenge identifier
*/
function normalizeChallengeIdForResponse (value) {
if (_.isNil(value)) {
return null
}
return String(value)
}
let challengeDimensionLookupPromise
const legacyChallengePageSummaryPromiseCache = new Map()
const LEGACY_CODE_PAGE_TIMEOUT_MS = 5000
const GENERIC_LEGACY_PAGE_TAG_NAMES = new Set([
'OTHER',
'DATA SCIENCE',
'DEVELOPMENT',
'DESIGN',
'QUALITY ASSURANCE',
'QA',
'COPILOT'
])
function decodeBasicHtmlEntities (value) {
if (_.isNil(value)) {
return null
}
return String(value)
.replace(/"/g, '"')
.replace(/'/g, '\'')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/ /g, ' ')
.trim()
}
function safeDecodeUriComponent (value) {
if (_.isNil(value)) {
return null
}
try {
return decodeURIComponent(String(value))
} catch (error) {
return String(value)
}
}
function stripLegacyChallengeTitlePrefix (value) {
if (_.isNil(value)) {
return null
}
return String(value).replace(/^\[[^\]]+\]\s*-\s*/, '').trim()
}
function parseLegacyChallengePageSummary (html, challengeId) {
const normalizedChallengeId = _.isNil(challengeId) ? null : String(challengeId).trim()
if (!normalizedChallengeId || !html) {
return null
}
let title = null
const titleMarker = 'name="twitter:title" content="'
const titleMarkerIndex = html.indexOf(titleMarker)
if (titleMarkerIndex >= 0) {
title = html.slice(titleMarkerIndex + titleMarker.length).split('"', 1)[0]
}
if (!title) {
const headingMarker = '<h1 class="'
const headingMarkerIndex = html.indexOf(headingMarker)
if (headingMarkerIndex >= 0) {
const afterHeadingMarker = html.slice(headingMarkerIndex + headingMarker.length)
const headingOpenTagEnd = afterHeadingMarker.indexOf('>')
if (headingOpenTagEnd >= 0) {
title = afterHeadingMarker.slice(headingOpenTagEnd + 1).split('</h1>', 1)[0]
}
}
}
const searchTags = []
const searchTagNeedle = 'href="/challenges?search='
let searchTagIndex = 0
while (searchTagIndex >= 0) {
searchTagIndex = html.indexOf(searchTagNeedle, searchTagIndex)
if (searchTagIndex < 0) {
break
}
const encodedTag = html
.slice(searchTagIndex + searchTagNeedle.length)
.split('"', 1)[0]
.split('&', 1)[0]
const decodedTag = decodeBasicHtmlEntities(safeDecodeUriComponent(encodedTag))
if (decodedTag) {
searchTags.push(decodedTag)
}
searchTagIndex += searchTagNeedle.length
}
return {
challengeId: normalizedChallengeId,
title: stripLegacyChallengeTitlePrefix(decodeBasicHtmlEntities(title)),
searchTags: _.uniq(searchTags)
}
}
function isLegacyCodeChallengePageSummary (summary) {
if (!summary || !summary.title || summary.title === 'Topcoder') {
return false
}
const specificTags = _.filter(summary.searchTags || [], (tag) => {
const normalizedTag = String(tag || '').trim().toUpperCase()
return normalizedTag && !GENERIC_LEGACY_PAGE_TAG_NAMES.has(normalizedTag)
})
return specificTags.length > 0
}
/**
* Fetch one legacy challenge page summary from topcoder.com.
* This is only used as a narrow fallback for older CODE history rows when
* neither ChallengeLegacy nor ChallengeWinner data can map legacy review ids.
* @param {string|number} challengeId legacy numeric challenge identifier
* @returns {Promise<Object|null>} parsed title/tag summary when available
*/
async function fetchLegacyChallengePageSummary (challengeId) {
const normalizedChallengeId = _.isNil(challengeId) ? null : String(challengeId).trim()
if (!normalizedChallengeId || !/^\d+$/.test(normalizedChallengeId) || typeof global.fetch !== 'function') {
return null
}
if (!legacyChallengePageSummaryPromiseCache.has(normalizedChallengeId)) {
legacyChallengePageSummaryPromiseCache.set(normalizedChallengeId, (async () => {
try {
const fetchOptions = {
headers: {
'user-agent': 'member-api-v6/legacy-code-history'
}
}
if (typeof global.AbortSignal !== 'undefined' &&
typeof global.AbortSignal.timeout === 'function') {
fetchOptions.signal = global.AbortSignal.timeout(LEGACY_CODE_PAGE_TIMEOUT_MS)
}
const response = await global.fetch(`https://www.topcoder.com/challenges/${normalizedChallengeId}`, fetchOptions)
if (!response.ok) {
logger.warn(`Unable to load legacy challenge page summary for challengeId=${normalizedChallengeId}: status ${response.status}`)
return null
}
return parseLegacyChallengePageSummary(await response.text(), normalizedChallengeId)
} catch (error) {
logger.warn(`Unable to load legacy challenge page summary for challengeId=${normalizedChallengeId}: ${error.message}`)
return null
}
})())
}
return legacyChallengePageSummaryPromiseCache.get(normalizedChallengeId)
}
/**
* Load the shared challenge track/type lookup used by unified stats reads and writes.
* The lookup translates between stored UUID ids and the canonical API labels used
* by request payloads, filters, and response builders.
* @returns {Promise<Object>} cached challenge dimension lookup
*/
async function getChallengeDimensionLookup () {
if (!challengeDimensionLookupPromise) {
challengeDimensionLookupPromise = loadChallengeDimensionLookup(prismaManager.getChallengesClient())
}
return challengeDimensionLookupPromise
}
/**
* Normalize a track label into the canonical API name used by rerate endpoints.
* @param {*} trackId raw track label
* @returns {string|undefined} canonical track name when recognized
*/
function resolveTrackName (trackId) {
return getCanonicalTrackName(trackId)
}
/**
* Normalize a type label into the canonical API name used by rerate endpoints.
* @param {*} typeId raw type label
* @returns {string|undefined} canonical type name when recognized
*/
function resolveTypeName (typeId) {
return getCanonicalTypeName(typeId)
}
/**
* Resolve a configured rating path from the service config.
* @param {*} ratingName requested rating path name
* @returns {Object|null} normalized rating path config, or null when no name is supplied
* @throws {errors.BadRequestError} when the requested rating path is not configured
*/
function resolveConfiguredRatingPath (ratingName) {
if (_.isNil(ratingName) || String(ratingName).trim() === '') {
return null
}
const ratingPath = getConfiguredRatingPath(config.RATING_PATHS, ratingName)
if (!ratingPath) {
throw new errors.BadRequestError(`Rating path '${ratingName}' is not configured.`)
}
return ratingPath
}
/**
* Convert a member identifier into the BigInt shape used by Prisma relations.
* @param {*} value raw member user id
* @returns {BigInt} normalized user id
*/
function toBigIntUserId (value) {
if (Object.prototype.toString.call(value) === '[object BigInt]') {
return value
}
if (typeof global.BigInt !== 'function') {
throw new Error('BigInt is not supported in this runtime')
}
return global.BigInt(String(value).trim())
}
/**
* Convert a user id into a stable response/cache key.
* @param {*} value raw user id
* @returns {string} string user id
*/
function stringifyUserId (value) {
return String(value)
}
/**
* Resolve whether challenge metadata allows rating updates.
* Missing rating metadata defaults to rated, matching the rating engines'
* historical replay behavior for older challenges.
* @param {Object} challenge challenge metadata row
* @returns {boolean} true when the challenge should be considered rated
*/
function isChallengeRatingEnabled (challenge) {
return isChallengeRated(challenge)
}
/**
* Normalize challenge track labels for source-routing checks.
* @param {*} value raw challenge track label, enum value, or abbreviation
* @returns {string} uppercase source track key
*/
function normalizeChallengeSourceTrack (value) {
return String(value || '')
.trim()
.toUpperCase()
.replace(/[\s-]+/g, '_')
}
/**
* Check whether a challenge source track is Quality Assurance.
* @param {*} value raw challenge track label, enum value, or abbreviation
* @returns {boolean} true when the source track is QA
*/
function isQualityAssuranceChallengeSourceTrack (value) {
const normalizedTrack = normalizeChallengeSourceTrack(value)
return normalizedTrack === CHALLENGE_TRACK_QUALITY_ASSURANCE || normalizedTrack === 'QA'
}
/**
* Build the source tracks replayed for Data Science Challenge ratings.
* @returns {Array<string>} challenge source track labels
*/
function getDataScienceChallengeSourceTrackNames () {
return [TRACK_NAMES.DATA_SCIENCE]
}
/**
* Build the source tracks replayed for Quality Assurance Challenge ratings.
* @returns {Array<string>} challenge source track labels
*/
function getQualityAssuranceChallengeSourceTrackNames () {
return [CHALLENGE_TRACK_QUALITY_ASSURANCE]
}
/**
* Load challenge metadata needed to decide which ratings apply.
* @param {Object} challengeClient prisma challenge client
* @param {string|number} challengeId challenge UUID or legacy numeric id
* @returns {Promise<Object|null>} challenge metadata or null when absent
*/
async function fetchChallengeForRatingUpdate (challengeClient, challengeId) {
const normalizedChallengeId = String(challengeId || '').trim()
if (!normalizedChallengeId) {
return null
}
const numericChallengeId = /^\d+$/.test(normalizedChallengeId)
? Number(normalizedChallengeId)
: null
const where = numericChallengeId && Number.isSafeInteger(numericChallengeId)
? {
OR: [
{ id: normalizedChallengeId },
{ legacyId: numericChallengeId },
{
legacyRecord: {
is: {
legacySystemId: numericChallengeId
}
}
}
]
}
: { id: normalizedChallengeId }
return challengeClient.challenge.findFirst({
where,
select: {
id: true,
status: true,
endDate: true,
trackId: true,
typeId: true,
track: {
select: {
name: true,
track: true
}
},
type: {
select: {
name: true
}
},
tags: true,
skills: {
select: {
skillId: true
}
},
metadata: RATING_METADATA_SELECT
}
})
}
/**
* Resolve the rating source supported by the engines for a challenge.
* Marathon Match challenges are type-driven because some Challenge API rows
* carry the Development track while still belonging to the MM rating stream.
* @param {Object} challenge challenge metadata row
* @returns {string|null} source identifier or null when unsupported
*/
function resolveChallengeRatingSource (challenge) {
const rawTrackName = _.get(challenge, 'track.track') || _.get(challenge, 'track.name') || _.get(challenge, 'trackId')
const trackName = getCanonicalTrackName(rawTrackName)
const typeName = getCanonicalTypeName(_.get(challenge, 'type.name') || _.get(challenge, 'typeId'))
if (trackName === TRACK_NAMES.DEVELOP && typeName === TYPE_NAMES.CHALLENGE) {
return RATING_SOURCE_DEVELOPMENT
}
if (isQualityAssuranceChallengeSourceTrack(rawTrackName) && typeName === TYPE_NAMES.CHALLENGE) {
return RATING_SOURCE_QUALITY_ASSURANCE_CHALLENGE
}
if (trackName === TRACK_NAMES.DATA_SCIENCE && typeName === TYPE_NAMES.CHALLENGE) {
return RATING_SOURCE_DATA_SCIENCE_CHALLENGE
}
if (typeName === TYPE_NAMES.MARATHON_MATCH) {
return RATING_SOURCE_MARATHON_MATCH
}
return null
}
/**
* Build the native track/type rating job for a supported challenge.
* @param {Object} challenge challenge metadata row
* @param {string|null} source resolved challenge rating source
* @returns {Object|null} rating job or null when unsupported/unrated
*/
function buildBaseRatingJob (challenge, source) {
if (!source || !isChallengeRatingEnabled(challenge)) {
return null
}
if (source === RATING_SOURCE_DEVELOPMENT) {
return {
source,
trackId: TRACK_NAMES.DEVELOP,
typeId: TYPE_NAMES.CHALLENGE
}
}
if (source === RATING_SOURCE_DATA_SCIENCE_CHALLENGE) {
return {
source,
trackId: TRACK_NAMES.DATA_SCIENCE,
typeId: TYPE_NAMES.CHALLENGE
}
}
if (source === RATING_SOURCE_QUALITY_ASSURANCE_CHALLENGE) {
return {
source,
trackId: TRACK_NAMES.QA,
typeId: TYPE_NAMES.CHALLENGE
}
}
if (source === RATING_SOURCE_MARATHON_MATCH) {
return {
source,
trackId: TRACK_NAMES.DATA_SCIENCE,
typeId: TYPE_NAMES.MARATHON_MATCH
}
}
return null
}
/**
* Build all rating jobs that apply to one completed challenge.
* The base track/type job is included for supported rated challenges, and
* configured named rating paths are included when their tags/skills match.
* @param {Object} challenge challenge metadata row
* @returns {Array<Object>} rating jobs to run
*/
function buildChallengeRatingJobs (challenge) {
const source = resolveChallengeRatingSource(challenge)
const jobs = []
const baseJob = buildBaseRatingJob(challenge, source)
if (baseJob) {
jobs.push(baseJob)
}
if (!source || !isChallengeRatingEnabled(challenge)) {
return jobs
}
normalizeRatingPathConfigs(config.RATING_PATHS).forEach((ratingPath) => {
if (!challengeMatchesRatingPath(challenge, ratingPath)) {
return
}
jobs.push({
source,
trackId: ratingPath.trackName,
typeId: ratingPath.name,
ratingName: ratingPath.name,
ratingPath
})
})
return _.uniqBy(jobs, (job) => `${job.ratingName || ''}::${job.trackId}::${job.typeId}`)
}
/**
* Fetch review-api challengeResult participants with score or placement data.
* @param {Object} reviewDbClient raw pg review database client
* @param {string|number} challengeId challenge identifier
* @returns {Promise<Array<BigInt>>} participant user ids
*/
async function fetchChallengeResultParticipantIds (reviewDbClient, challengeId) {
const challengeResultRelation = await resolveChallengeResultRelation(reviewDbClient)
const result = await reviewDbClient.query(
`
SELECT DISTINCT "userId"
FROM ${challengeResultRelation}
WHERE "challengeId" = $1
AND "userId" IS NOT NULL
AND "validSubmission" IS DISTINCT FROM FALSE
AND "submissionId" IS NOT NULL
AND (
"finalScore" IS NOT NULL OR
("placement" IS NOT NULL AND "placement" > 0)
)
ORDER BY "userId" ASC
`,
[String(challengeId)]
)
return result.rows.map((row) => toBigIntUserId(row.userId))
}
/**
* Fetch placement winner participants from challenge-api for completed
* Development/Data Science/QA rating rerates. This covers challenges where winners
* can be assigned without a review-api challengeResult row for the same member.
* @param {Object} challengeClient challenge Prisma client
* @param {string|number} challengeId challenge identifier
* @returns {Promise<Array<BigInt>>} winner user ids
*/
async function fetchChallengeWinnerParticipantIds (challengeClient, challengeId) {
if (!challengeClient || !challengeClient.ChallengeWinner ||
typeof challengeClient.ChallengeWinner.findMany !== 'function') {
return []
}
const winnerRows = await challengeClient.ChallengeWinner.findMany({
where: {
challengeId: String(challengeId),
type: {
in: CHALLENGE_WINNER_RATING_TYPES
}
},
select: {
userId: true
}
})
return winnerRows.map((row) => toBigIntUserId(row.userId))
}
/**
* Fetch Marathon Match participants from review summations when challengeResult
* rows are not available yet.
* @param {Object} reviewDbClient raw pg review database client
* @param {string|number} challengeId challenge identifier
* @returns {Promise<Array<BigInt>>} participant user ids
*/
async function fetchMarathonMatchParticipantIds (reviewDbClient, challengeId) {
const { participantRows } = await fetchRatingPathParticipantsForChallenge(
reviewDbClient,
{
challengeId: String(challengeId),
source: RATING_SOURCE_MARATHON_MATCH
}
)
return participantRows.map((row) => resolveRatingPathParticipantId(row, RATING_SOURCE_MARATHON_MATCH))
}
/**
* Resolve submitter ids for the challenge and rating source.
* Challenge ratings include placement winners so completed challenges without
* challengeResult rows still rerate paid winners. Marathon Match submitters
* are loaded from both challengeResult and final review summations so partially
* synced result rows cannot omit lower-placed participants from rerating.
* @param {Object} reviewDbClient raw pg review database client
* @param {Object} challengeClient challenge Prisma client
* @param {string|number} challengeId challenge identifier
* @param {string} source rating source identifier
* @returns {Promise<Array<BigInt>>} unique participant user ids
*/
async function fetchRatingParticipantIds (reviewDbClient, challengeClient, challengeId, source) {
const challengeResultUserIds = await fetchChallengeResultParticipantIds(reviewDbClient, challengeId)
if (source === RATING_SOURCE_DEVELOPMENT ||
source === RATING_SOURCE_DATA_SCIENCE_CHALLENGE ||
source === RATING_SOURCE_QUALITY_ASSURANCE_CHALLENGE) {
return _.uniqBy(
challengeResultUserIds.concat(await fetchChallengeWinnerParticipantIds(challengeClient, challengeId)),
stringifyUserId
)
}
if (source !== RATING_SOURCE_MARATHON_MATCH) {
return _.uniqBy(challengeResultUserIds, stringifyUserId)
}
return _.uniqBy(
challengeResultUserIds.concat(await fetchMarathonMatchParticipantIds(reviewDbClient, challengeId)),
stringifyUserId
)
}
/**
* Filter discovered submitters down to members that exist in member-api storage.
* @param {Object} membersClient prisma members client
* @param {Array<BigInt>} participantIds discovered submitter ids
* @returns {Promise<Object>} existing member ids and skipped ids
*/
async function filterExistingRatingParticipantIds (membersClient, participantIds) {
const uniqueParticipantIds = _.uniqBy(participantIds, stringifyUserId)
if (uniqueParticipantIds.length === 0) {
return {
existingParticipantIds: [],
skippedParticipantIds: []
}
}
const existingMembers = await membersClient.member.findMany({
where: {
userId: {
in: uniqueParticipantIds
}
},
select: {
userId: true
}
})
const existingIds = existingMembers.map((member) => member.userId)
const existingIdSet = new Set(existingIds.map(stringifyUserId))
return {
existingParticipantIds: existingIds,
skippedParticipantIds: uniqueParticipantIds.filter((userId) => !existingIdSet.has(stringifyUserId(userId)))
}
}
/**
* Run one rating job for one member.
* @param {Object} challengeClient prisma challenge client
* @param {Object} reviewDbClient raw pg review database client
* @param {BigInt} userId target member id
* @param {string} challengeId starting challenge id
* @param {Object} job rating job to execute
* @returns {Promise<Object>} engine rerate summary
*/
async function rerateChallengeRatingJobForMember (challengeClient, reviewDbClient, userId, challengeId, job) {
if (job.ratingPath) {
return rerateMmTrack(
prisma,
challengeClient,
null,
reviewDbClient,
userId,
challengeId,
{
ratingPath: job.ratingPath
}
)
}
if (job.source === RATING_SOURCE_DEVELOPMENT ||
job.source === RATING_SOURCE_DATA_SCIENCE_CHALLENGE ||
job.source === RATING_SOURCE_QUALITY_ASSURANCE_CHALLENGE) {
let rerateOptions
if (job.source === RATING_SOURCE_DATA_SCIENCE_CHALLENGE) {
rerateOptions = {
targetTrackName: TRACK_NAMES.DATA_SCIENCE,
targetTypeName: TYPE_NAMES.CHALLENGE,
challengeTrackNames: getDataScienceChallengeSourceTrackNames(),
challengeTypeNames: [TYPE_NAMES.CHALLENGE]
}
} else if (job.source === RATING_SOURCE_QUALITY_ASSURANCE_CHALLENGE) {
rerateOptions = {
targetTrackName: TRACK_NAMES.QA,
targetTypeName: TYPE_NAMES.CHALLENGE,
challengeTrackNames: getQualityAssuranceChallengeSourceTrackNames(),
challengeTypeNames: [TYPE_NAMES.CHALLENGE]
}
}
return rerateDevTrack(
prisma,
challengeClient,
reviewDbClient,
userId,
challengeId,
rerateOptions
)
}
return rerateMmTrack(
prisma,
challengeClient,
null,
reviewDbClient,
userId,
challengeId
)
}
function isLegacyMaxRatingPayload (value) {
return _.isPlainObject(value) && !_.isNil(value.rating) && !_.isNil(value.ratingColor)
}
function normalizeUnifiedRecord (record, isPrivate, dimensionLookup) {
if (!record || !record.trackId || !record.typeId) {
return null
}
const normalized = _.omitBy({
trackId: resolveTrackIdFromLookup(dimensionLookup, record.trackId),
typeId: resolveTypeIdFromLookup(dimensionLookup, record.typeId),
challenges: toOptionalInt(record.challenges),
wins: toOptionalInt(record.wins),
mostRecentSubmission: toOptionalDate(record.mostRecentSubmission),
mostRecentEventDate: toOptionalDate(record.mostRecentEventDate),
rating: toOptionalInt(record.rating),
avgRank: toOptionalFloat(record.avgRank),
avgNumSubmissions: toOptionalInt(record.avgNumSubmissions),
bestRank: toOptionalInt(record.bestRank),
globalRank: toOptionalInt(record.globalRank),
countryRank: toOptionalInt(record.countryRank),
schoolRank: toOptionalInt(record.schoolRank),
volatility: toOptionalInt(record.volatility),
maxRating: toOptionalInt(record.maxRating),
minRating: toOptionalInt(record.minRating),
topFiveFinishes: toOptionalInt(record.topFiveFinishes),
topTenFinishes: toOptionalInt(record.topTenFinishes),
isPrivate
}, _.isUndefined)
if (!normalized.trackId || !normalized.typeId) {
return null
}
return normalized
}
function pushUnifiedRecord (collection, record, isPrivate, dimensionLookup) {
const normalized = normalizeUnifiedRecord(record, isPrivate, dimensionLookup)
if (normalized) {
collection.push(normalized)
}
}
function buildUnifiedStatsRecordsFromPayload (payload, isPrivate, dimensionLookup, options = {}) {
const data = payload || {}
const records = []
const isPartial = !!options.partial
const unifiedMaxRating = isLegacyMaxRatingPayload(data.maxRating) ? undefined : data.maxRating
const rootPayload = {
trackId: data.trackId,
typeId: data.typeId,
challenges: data.challenges,
wins: data.wins,
mostRecentSubmission: data.mostRecentSubmission,
mostRecentEventDate: data.mostRecentEventDate,
rating: data.rating,
avgRank: data.avgRank,
avgNumSubmissions: data.avgNumSubmissions,
bestRank: data.bestRank,
globalRank: data.globalRank,
countryRank: data.countryRank,
schoolRank: data.schoolRank,
volatility: data.volatility,
maxRating: unifiedMaxRating,
minRating: data.minRating,
topFiveFinishes: data.topFiveFinishes,
topTenFinishes: data.topTenFinishes
}
if (rootPayload.trackId && rootPayload.typeId) {
pushUnifiedRecord(records, rootPayload, isPrivate, dimensionLookup)
}
if (_.isArray(data.records)) {
_.forEach(data.records, (record) => {
pushUnifiedRecord(records, record, isPrivate, dimensionLookup)
})
}
if (!isPartial && records.length === 0 && (!_.isNil(data.challenges) || !_.isNil(data.wins))) {
pushUnifiedRecord(records, {
trackId: data.trackId || TRACK_NAMES.DEVELOP,
typeId: data.typeId || TYPE_NAMES.CHALLENGE,
challenges: data.challenges,
wins: data.wins,
mostRecentSubmission: data.mostRecentSubmission,
mostRecentEventDate: data.mostRecentEventDate,
rating: data.rating,
avgRank: data.avgRank,
avgNumSubmissions: data.avgNumSubmissions,
bestRank: data.bestRank,
globalRank: data.globalRank,
countryRank: data.countryRank,
schoolRank: data.schoolRank,
volatility: data.volatility,
maxRating: unifiedMaxRating,
minRating: data.minRating,
topFiveFinishes: data.topFiveFinishes,
topTenFinishes: data.topTenFinishes
}, isPrivate, dimensionLookup)
}
// Last record wins for duplicate (trackId, typeId) keys.
return _.values(_.keyBy(records, record => `${record.trackId}::${record.typeId}`))
}
function buildStatsTrackTypeKey (trackId, typeId) {
return `${trackId}::${typeId}`
}
/**
* Determine whether a unified stats row needs a computed global rank fallback.
* Only positive ratings are rankable; missing, zero, and negative persisted ranks
* are treated as unavailable because public legacy marathon data often stores
* unrated rank placeholders as zero.
* @param {Object} row unified memberStats row
* @returns {Boolean} true when the row can be ranked from its rating
*/
function shouldComputeGlobalRank (row) {
if (!row || !row.trackId || !row.typeId || _.isNil(row.rating)) {
return false
}
const rating = Number(row.rating)
const globalRank = _.isNil(row.globalRank) ? null : Number(row.globalRank)
return Number.isFinite(rating) && rating > 0 &&
(_.isNil(globalRank) || !Number.isFinite(globalRank) || globalRank <= 0)
}
/**
* Build the cache key for a stats row's rank scope.
* Rows sharing track, type, privacy, and rating share the same computed rank.
* @param {Object} row unified memberStats row
* @returns {String} cache key for computed rank lookups
*/
function buildGlobalRankScopeKey (row) {
return [
row.trackId,
row.typeId,
row.isPrivate ? 'private' : 'public',
Number(row.rating)
].join('::')
}
/**
* Fill invalid or missing globalRank values using current unified ratings.
* The computed value matches SQL RANK semantics: one plus the number of rows in
* the same track/type/privacy scope with a strictly higher positive rating.
* @param {Array<Object>} statsRows unified memberStats rows returned for one member
* @returns {Promise<Array<Object>>} rows with computed globalRank fallbacks applied
* @throws {Error} propagates Prisma count failures
*/
async function hydrateComputedGlobalRanks (statsRows) {
const rankTargets = _.filter(statsRows, shouldComputeGlobalRank)
if (rankTargets.length === 0) {
return statsRows
}
const uniqueRankTargets = _.uniqBy(rankTargets, buildGlobalRankScopeKey)
const rankByScope = new Map()
await Promise.all(_.map(uniqueRankTargets, async (row) => {
const higherRatedCount = await prisma.memberStats.count({
where: {
trackId: row.trackId,
typeId: row.typeId,
isPrivate: row.isPrivate === true,
rating: {
gt: Number(row.rating)
}
}
})
rankByScope.set(buildGlobalRankScopeKey(row), higherRatedCount + 1)
}))
return _.map(statsRows, (row) => {
const computedRank = shouldComputeGlobalRank(row)
? rankByScope.get(buildGlobalRankScopeKey(row))
: undefined
if (_.isNil(computedRank)) {
return row
}
return {
...row,
globalRank: computedRank
}
})
}
/**
* Check whether a resolved challenge type is Marathon Match.
* @param {string|undefined} typeName canonical or raw type name
* @returns {boolean} true when the type should be exposed as Marathon Match
*/
function isMarathonMatchType (typeName) {
return getCanonicalTypeName(typeName) === TYPE_NAMES.MARATHON_MATCH
}
/**
* Resolve the public stats dimensions for a challenge-backed row.
* Marathon Match rows are part of the public DATA_SCIENCE bucket even when
* source challenge metadata uses a different track. QA Challenge rows remain
* under the first-class QA / Challenge dimension.
* @param {Object} row row containing trackId and typeId
* @param {Object} dimensionLookup shared challenge dimension lookup
* @returns {Object} normalized track/type ids and names