forked from enkoder/beanstalk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.ts
404 lines (367 loc) · 10.8 KB
/
background.ts
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
import { trace as otel } from "@opentelemetry/api";
import objectHash from "object-hash";
import { g } from "./g.js";
import {
type ABREntryType,
type ABRTournamentType,
ABRTournamentTypeFilter,
abrToResult,
abrToTournament,
getEntries,
getTournamentsByType,
getTournamentsByUserId,
} from "./lib/abr.js";
import * as NRDB from "./lib/nrdb.js";
import { calculatePointDistribution } from "./lib/ranking.js";
import { trace } from "./lib/tracer.js";
import { Results } from "./models/results.js";
import { Seasons } from "./models/season.js";
import { Tournaments } from "./models/tournament.js";
import { Users } from "./models/user.js";
import type { Result, Tournament, User } from "./schema.js";
import type {
Env,
IngestResultQueueMessage,
IngestTournamentQueueMessage,
TriggerType,
} from "./types.d.js";
const DISALLOW_TOURNAMENT_ID = [
// circuit opener selected as circuit breaker
3694,
];
enum Queues {
IngestTournament = "ingest-tournament",
IngestTournamentDLQ = "ingest-tournament-dlq",
IngestResult = "ingest-result",
IngestResultDLQ = "ingest-result-dlq",
IngestCard = "ingest-card",
}
const SUPPORTED_TOURNAMENT_TYPES: ABRTournamentTypeFilter[] = [
ABRTournamentTypeFilter.CircuitOpener,
ABRTournamentTypeFilter.CircuitBreaker,
ABRTournamentTypeFilter.WorldsChampionship,
ABRTournamentTypeFilter.NationalChampionship,
ABRTournamentTypeFilter.IntercontinentalChampionship,
ABRTournamentTypeFilter.ContinentalChampionship,
];
export async function processScheduledEvent(event: ScheduledEvent, env: Env) {
switch (event.cron) {
// Every day at midnight
case "0 0 * * *":
await trace(
"publishAllTournamentIngest",
() => publishAllTournamentIngest(env, "cron"),
{ cron: event.cron, trigger: "cron" },
);
break;
}
}
export async function processQueueBatch(
batch: MessageBatch<ABRTournamentType | ABREntryType>,
env: Env,
) {
for (const message of batch.messages) {
switch (batch.queue) {
case Queues.IngestTournament: {
const ingestTournamentMessage =
message.body as IngestTournamentQueueMessage;
const tournament = ingestTournamentMessage.tournament;
if (DISALLOW_TOURNAMENT_ID.includes(tournament.id)) {
break;
}
await trace(
"handleTournamentIngest",
() => handleTournamentIngest(env, ingestTournamentMessage),
{
queue: Queues.IngestTournament,
tournament_title: tournament.title,
tournament_id: tournament.id,
},
);
break;
}
case Queues.IngestTournamentDLQ:
await trace(
"handleTournamentIngestDLQ",
() => handleTournamentIngestDLQ(message.body as ABRTournamentType),
{
queue: Queues.IngestTournamentDLQ,
},
);
break;
case Queues.IngestResult: {
const { tournament, entry } = message.body as IngestResultQueueMessage;
await trace(
"handleResultIngest",
() => handleResultIngest(env, tournament, entry),
{
queue: Queues.IngestResult,
tournament_id: tournament.id,
tournament_name: tournament.name,
tournament_type: tournament.type,
user_name: entry.user_name,
user_name_import: entry.user_import_name,
},
);
break;
}
case Queues.IngestResultDLQ: {
const { tournament, entry } = message.body as IngestResultQueueMessage;
await trace(
"handleResultIngestDLQ",
() => handleResultIngestDLQ(tournament, entry),
{
queue: Queues.IngestResultDLQ,
},
);
break;
}
case Queues.IngestCard: {
await trace(
"handleCardIngest",
() => handleCardIngest(env, message.body),
{
queue: Queues.IngestCard,
},
);
break;
}
}
}
}
export async function publishAllTournamentIngest(
env: Env,
trigger: TriggerType,
) {
const data = { publish: "tournament", trigger: trigger };
for (const type of SUPPORTED_TOURNAMENT_TYPES) {
try {
await publishIngestTournament(env, trigger, null, type);
console.log(
JSON.stringify({
tournament_type: type,
status: "success",
...data,
}),
);
} catch (e) {
g().sentry.captureException(e);
console.log(
JSON.stringify({
tournament_type: type,
status: "error",
...data,
}),
);
}
}
}
async function ingestEntry(
env: Env,
entry: ABREntryType,
tournamentId: number,
points: number,
): Promise<Result | null> {
// If there's a non-zero user_id then the user has claimed their spot in the tournament
let user: User | null = null;
let name: string = entry.user_id
? await NRDB.getNameFromId(entry.user_id)
: entry.user_name;
// name can be null and ID can be 0
if (!name && entry.user_import_name) {
name = entry.user_import_name;
}
if (entry.user_id) {
user = await Users.get(entry.user_id);
} else {
// It's possible the user's name is known, but they haven't claimed yet
user = await Users.getByName(name);
}
// first time here, let's make a new user for later
if (!user && entry.user_id) {
user = await Users.insert({
id: entry.user_id,
name: name,
});
}
if (!user) {
return null;
}
// TODO: types
const runner_card = JSON.parse(
await env.CARDS_KV.get(String(entry.runner_deck_identity_id)),
);
const corp_card = JSON.parse(
await env.CARDS_KV.get(String(entry.corp_deck_identity_id)),
);
const runner_deck_identity_name = runner_card.title;
const runner_deck_faction = runner_card.faction_code;
const corp_deck_identity_name = corp_card.title;
const corp_deck_faction = corp_card.faction_code;
// this is a partial, be sure to add the extra stuff that isn't coming from abr
return await Results.insert(
abrToResult(entry, {
tournament_id: tournamentId,
user_id: user.id,
points_earned: points,
runner_deck_identity_name: runner_deck_identity_name,
runner_deck_faction: runner_deck_faction,
corp_deck_identity_name: corp_deck_identity_name,
corp_deck_faction: corp_deck_faction,
}),
true,
);
}
async function handleResultIngest(
env: Env,
tournament: Tournament,
abrEntry: ABREntryType,
) {
let count = 0;
if (
tournament.type === "intercontinental championship" &&
tournament.season_id !== 0 &&
tournament.season_id !== null
) {
count = await Results.countUniqueAttendeesByType(
"continental championship",
tournament.season_id,
);
}
const { points } = calculatePointDistribution(
tournament.players_count,
tournament.type,
count,
);
const placementIndex = (abrEntry.rank_top || abrEntry.rank_swiss) - 1;
if (placementIndex < 0 || placementIndex >= points.length) {
g().sentry.captureException(
new Error(
`Somehow the placement (${placementIndex}) is out of rang of points (${points})`,
),
);
}
const loggedData = {
tournament_id: tournament.id,
tournament_name: tournament.name,
tournament_type: tournament.type,
user_name: abrEntry.user_name,
user_name_import: abrEntry.user_import_name,
};
const span = otel.getActiveSpan();
try {
const result = await ingestEntry(
env,
abrEntry,
tournament.id,
points[placementIndex],
);
if (!result) {
span.setAttribute("ingest_status", "skip");
console.log(
JSON.stringify({
status: "skip",
...loggedData,
}),
);
} else {
span.setAttribute("ingest_status", "success");
console.log(
JSON.stringify({
status: "success",
...loggedData,
}),
);
}
} catch (e) {
g().sentry.captureException(e);
span.setAttribute("ingest_status", "error");
console.log(
JSON.stringify({
status: "error",
...loggedData,
}),
);
throw e;
}
}
async function handleTournamentIngest(
env: Env,
message: IngestTournamentQueueMessage,
) {
const { tournament: abrTournament, trigger } = message;
const seasons = await Seasons.getFromTimestamp(abrTournament.date.toString());
const seasonId = seasons.length !== 0 ? seasons[0].id : null;
if (seasonId === null) {
return;
}
const entries = await getEntries(abrTournament.id);
const cutTo = entries.filter((e) => e.rank_top !== null).length;
const tournamentBlob = abrToTournament(abrTournament, seasonId, cutTo);
const fingerprint = objectHash({
tournament: tournamentBlob,
season_id: seasonId,
entries: entries,
});
let tournament = await Tournaments.get(tournamentBlob.id);
// Is this a new tournament we've never seen?
if (!tournament) {
tournament = await Tournaments.insert({
...tournamentBlob,
fingerprint: fingerprint,
});
} else {
if (trigger !== "api" && tournament.fingerprint === fingerprint) {
console.log(`skipping ${tournament.name} due to fingerprint match`);
return;
}
tournament = await Tournaments.update({
...tournamentBlob,
fingerprint: fingerprint,
});
}
for (const entry of entries) {
await env.INGEST_RESULT_Q.send({ tournament: tournament, entry: entry });
}
}
function handleTournamentIngestDLQ(tournament: ABRTournamentType) {
// TODO: actually do something here on ingest fail
const str = JSON.stringify(tournament, null, 4);
console.log(`handleTournamentIngestDLQ | ${str}`);
}
function handleResultIngestDLQ(tournament: Tournament, entry: ABREntryType) {
// TODO: actually do something here on ingest fail
const tournamentStr = JSON.stringify(tournament, null, 4);
const entryStr = JSON.stringify(entry, null, 4);
console.log(
`handleResultIngestDLQ | tournament=${tournamentStr} | entry=${entryStr}`,
);
}
export async function publishIngestTournament(
env: Env,
trigger: TriggerType,
userId?: number,
tournamentTypeFilter?: ABRTournamentTypeFilter,
) {
// fetch and insert the tournament row
let abrTournaments: ABRTournamentType[] = [];
if (userId) {
abrTournaments = await getTournamentsByUserId(userId);
} else if (tournamentTypeFilter) {
abrTournaments = await getTournamentsByType(tournamentTypeFilter);
}
// 100 is the limit for batch sizes
const chunkSize = 100;
for (let i = 0; i < abrTournaments.length; i += chunkSize) {
const chunkedTournaments = abrTournaments.slice(i, i + chunkSize);
await env.INGEST_TOURNAMENT_Q.sendBatch(
chunkedTournaments.map((t) => ({
body: { tournament: t, trigger: trigger },
contentType: "json",
})),
);
}
}
async function handleCardIngest(env: Env, card) {
await env.CARDS_KV.put(String(Number(card.code)), JSON.stringify(card));
}