forked from odota/core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuildMatch.ts
More file actions
309 lines (293 loc) · 9.33 KB
/
Copy pathbuildMatch.ts
File metadata and controls
309 lines (293 loc) · 9.33 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
import { heroes } from "dotaconstants";
import config from "../../config.ts";
import { computeMatchData, estimatePositions } from "./compute.ts";
import { buildReplayUrl, isTurbo } from "./utility.ts";
import redis, { redisCount } from "../store/redis.ts";
import db from "../store/db.ts";
import { benchmarks } from "./benchmarksUtil.ts";
import * as allFetchers from "../fetcher/allFetchers.ts";
import { getMatchBlob } from "./getMatchBlob.ts";
import { getStartOfBlockMinutes } from "./time.ts";
import { getMatchRankTier } from "./queries.ts";
import { isContributor } from "../../CONTRIBUTORS.ts";
const { metaFetcher } = allFetchers;
function extendPlayerData(
player: Player | ParsedPlayer,
match: Match | ParsedMatch,
): Player | ParsedPlayer {
// NOTE: This adds match specific properties into the player object, which leads to some unnecessary duplication in the output
// We do this right now to allow computeMatchData to work properly
const p: Partial<ParsedPlayerMatch> = {
...player,
radiant_win: match.radiant_win,
start_time: match.start_time,
duration: match.duration,
cluster: match.cluster,
lobby_type: match.lobby_type,
game_mode: match.game_mode,
is_contributor: Boolean(
player.account_id && isContributor(player.account_id),
),
};
computeMatchData(p as ParsedPlayerMatch);
// Note: Type is bad here, we're adding properties that shouldn't be there but changing will affect external API
return p as Player | ParsedPlayer;
}
type ProMatchInfo = {
radiant_team?: any;
dire_team?: any;
league?: any;
series_id?: number;
series_type?: number;
replay_salt?: number;
};
async function getProMatchInfo(match: Match): Promise<ProMatchInfo> {
const resultPromise = match.leagueid
? db
.first(["series_id", "series_type", "replay_salt"])
.from("matches")
.where({
match_id: match.match_id,
})
: Promise.resolve(undefined);
const leaguePromise = match.leagueid
? db.first().from("leagues").where({
leagueid: match.leagueid,
})
: Promise.resolve(undefined);
const radiantTeamPromise =
"radiant_team_id" in match
? db.first().from("teams").where({
team_id: match.radiant_team_id,
})
: Promise.resolve(undefined);
const direTeamPromise =
"dire_team_id" in match
? db.first().from("teams").where({
team_id: match.dire_team_id,
})
: Promise.resolve(undefined);
const [result, league, radiantTeam, direTeam] = await Promise.all([
resultPromise,
leaguePromise,
radiantTeamPromise,
direTeamPromise,
]);
const final: ProMatchInfo = {};
if (result) {
final.series_id = result.series_id;
final.series_type = result.series_type;
final.replay_salt = result.replay_salt;
}
if (league) {
final.league = league;
}
if (radiantTeam) {
final.radiant_team = radiantTeam;
}
if (direTeam) {
final.dire_team = direTeam;
}
return final;
}
/**
* Adds benchmark data to the players in a match
* */
export async function getPlayerBenchmarks(m: Match) {
const turbo = isTurbo(m);
// Bracket 1-8 from the average rank of the players, matching what the
// write side does in counts.ts (turbo only has global benchmarks)
const { avg } = turbo ? { avg: null } : await getMatchRankTier(db, m.players);
const bracket = avg ? Math.floor(avg / 10) : null;
return Promise.all(
m.players.map(async (p) => {
const result: Record<
string,
{ raw?: number; pct?: number; pct_bracket?: number }
> = {};
for (let metric of Object.keys(benchmarks)) {
result[metric] = {};
// Use data from previous epoch
let key = [
"benchmarks",
getStartOfBlockMinutes(
Number(config.BENCHMARK_RETENTION_MINUTES),
-1,
),
metric,
p.hero_id,
turbo ? "turbo" : "",
].join(":");
const backupKey = [
"benchmarks",
getStartOfBlockMinutes(Number(config.BENCHMARK_RETENTION_MINUTES), 0),
metric,
p.hero_id,
turbo ? "turbo" : "",
].join(":");
const raw = benchmarks[metric](m, p);
result[metric] = {
raw,
};
const exists = await redis.exists(key);
if (exists === 0) {
// No data, use backup key (current epoch)
key = backupKey;
}
const card = await redis.zcard(key);
if (raw !== undefined && raw !== null && !Number.isNaN(Number(raw))) {
const count = await redis.zcount(key, "0", raw);
// deaths_per_min is the one metric where lower is better, so its
// percentile is the share of players with a higher value
const pct =
metric === "deaths_per_min" ? 1 - count / card : count / card;
result[metric].pct = pct;
if (bracket) {
// Same distribution restricted to this match's rank bracket
const bracketKey = `${key}:${bracket}`;
const bracketCard = await redis.zcard(bracketKey);
if (bracketCard > 0) {
const bracketCount = await redis.zcount(bracketKey, "0", raw);
result[metric].pct_bracket =
metric === "deaths_per_min"
? 1 - bracketCount / bracketCard
: bracketCount / bracketCard;
}
}
}
}
return result;
}),
);
}
async function getPlayerDetails(match: Match | ParsedMatch) {
const accountIds = match.players.map((p) => p.account_id ?? null).filter(Boolean);
const { rows } = await db.raw(
`
SELECT players.account_id, personaname, name, last_login, rating, status, computed_mmr
FROM players
LEFT JOIN notable_players USING(account_id)
LEFT JOIN rank_tier USING(account_id)
LEFT JOIN player_computed_mmr USING(account_id)
LEFT JOIN subscriber USING(account_id)
WHERE players.account_id = ANY(?)
`,
[accountIds],
);
const rowsByAccountId = new Map<number | undefined, AnyDict>(rows.map((row: AnyDict) => [row.account_id, row]));
return match.players.map((p) => {
const row = rowsByAccountId.get(p.account_id);
return {
...p,
personaname: row?.personaname,
name: row?.name,
last_login: row?.last_login,
rank_tier: row?.rating,
computed_mmr: row?.computed_mmr,
is_subscriber: Boolean(row?.status),
};
});
}
async function getCosmetics(match: Match | ParsedMatch) {
if ("cosmetics" in match && match.cosmetics) {
return Promise.all(
Object.keys(match.cosmetics).map((itemId) =>
db.first().from("cosmetics").where({
item_id: itemId,
}),
),
);
}
return null;
}
async function getMeta(matchId: number | undefined) {
if (matchId) {
return metaFetcher.getOrFetchData(matchId, null);
}
return null;
}
export async function buildMatch(
matchId: number,
options: { meta?: boolean },
): Promise<Match | ParsedMatch | null> {
if (!matchId || !Number.isInteger(matchId) || matchId <= 0) {
return null;
}
// track distribution of matches requested
// const bucket = Math.floor(matchId / 1000000000);
// redisCount((bucket + '_match_req') as MetricName);
redisCount("build_match");
// Check for cache
const key = `match:${matchId}`;
const reply = await redis.get(key);
if (reply) {
redisCount("match_cache_hit");
return JSON.parse(reply);
}
// Attempt to fetch match and backfill what's needed
let [match, odData]: [
Match | ParsedMatch | null,
GetMatchDataMetadata | null,
] = await getMatchBlob(matchId, allFetchers);
if (!match) {
return null;
}
match.od_data = odData;
const [players, prodata, cosmetics, metadata, playerBenchmarks] =
await Promise.all([
getPlayerDetails(match),
getProMatchInfo(match),
getCosmetics(match),
getMeta(options.meta ? matchId : undefined),
getPlayerBenchmarks(match),
]);
let matchResult: Match | ParsedMatch = {
...match,
...prodata,
metadata,
players: players
.map((p) => extendPlayerData(p, match))
.map((p) => {
if (!cosmetics) {
return p;
}
const hero = heroes[String(p.hero_id) as keyof typeof heroes] || {};
const playerCosmetics = cosmetics
.filter(Boolean)
.filter(
(c) =>
match &&
"cosmetics" in match &&
match.cosmetics?.[c.item_id] === p.player_slot &&
(!c.used_by_heroes || c.used_by_heroes === hero.name),
);
return {
...p,
cosmetics: playerCosmetics,
};
})
.map((p, i) => {
return { ...p, benchmarks: playerBenchmarks[i] };
}),
replay_url: match.replay_salt
? buildReplayUrl(match.match_id, match.cluster, match.replay_salt)
: undefined,
};
computeMatchData(matchResult as ParsedPlayerMatch);
estimatePositions(matchResult.players as ParsedPlayerMatch[]);
// Save in cache
if (matchResult && config.ENABLE_MATCH_CACHE) {
await redis.setex(
key,
config.MATCH_CACHE_SECONDS,
JSON.stringify(matchResult),
);
}
// if (config.NODE_ENV === 'development' || config.NODE_ENV === 'test') {
// await fs.writeFile(
// './json/' + matchId + '_output.json',
// JSON.stringify(matchResult, null, 2),
// );
// }
return matchResult;
}