@icpctools/contest-api 0.0.0-stage → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/contest-api.d.ts +120 -0
- package/dist/contest-api.js +795 -0
- package/dist/contest-api.js.map +1 -0
- package/dist/contest-time-util.d.ts +24 -0
- package/dist/contest-time-util.js +182 -0
- package/dist/contest-time-util.js.map +1 -0
- package/dist/contest-types.d.ts +315 -0
- package/dist/contest-types.js +12 -0
- package/dist/contest-types.js.map +1 -0
- package/dist/contest-util.d.ts +21 -0
- package/dist/contest-util.js +195 -0
- package/dist/contest-util.js.map +1 -0
- package/dist/contests.d.ts +16 -0
- package/dist/contests.js +72 -0
- package/dist/contests.js.map +1 -0
- package/dist/fetch-utils.d.ts +2 -0
- package/dist/fetch-utils.js +14 -0
- package/dist/fetch-utils.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/package.json +36 -3
- package/src/contest-api.ts +924 -0
- package/src/contest-time-util.ts +219 -0
- package/src/contest-types.ts +381 -0
- package/src/contest-util.ts +230 -0
- package/src/contests.ts +78 -0
- package/src/fetch-utils.ts +18 -0
- package/src/index.ts +5 -0
- package/README.md +0 -3
|
@@ -0,0 +1,924 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Contest API for getting data from a single contest. There are two basic ways of
|
|
3
|
+
* using it: calling loadXxx() on individual contest endpoints, or using
|
|
4
|
+
* watch() to connect to an event feed. After doing either, call getXxx() to get
|
|
5
|
+
* contest data.
|
|
6
|
+
*/
|
|
7
|
+
import { fetchOptions } from './fetch-utils.js';
|
|
8
|
+
import type {
|
|
9
|
+
Access,
|
|
10
|
+
Account,
|
|
11
|
+
Award,
|
|
12
|
+
Clarification,
|
|
13
|
+
Commentary,
|
|
14
|
+
Contest,
|
|
15
|
+
ContestState,
|
|
16
|
+
ContestType,
|
|
17
|
+
FileReference,
|
|
18
|
+
Group,
|
|
19
|
+
Id,
|
|
20
|
+
Judgement,
|
|
21
|
+
JudgementType,
|
|
22
|
+
Language,
|
|
23
|
+
MapInfo,
|
|
24
|
+
Notification,
|
|
25
|
+
Organization,
|
|
26
|
+
Person,
|
|
27
|
+
Problem,
|
|
28
|
+
Run,
|
|
29
|
+
Scoreboard,
|
|
30
|
+
StartStatus,
|
|
31
|
+
Submission,
|
|
32
|
+
Team,
|
|
33
|
+
Version
|
|
34
|
+
} from './contest-types.js';
|
|
35
|
+
|
|
36
|
+
export interface Credentials {
|
|
37
|
+
user?: string;
|
|
38
|
+
password?: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export type ContestEvent = {
|
|
42
|
+
type: ContestType;
|
|
43
|
+
id?: Id;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
export type ContestListener = (event: ContestEvent) => void;
|
|
47
|
+
|
|
48
|
+
export type ContestModifier = (event: Notification) => boolean;
|
|
49
|
+
|
|
50
|
+
class InitialLoadGate {
|
|
51
|
+
// hard backstop: release after this long even if the feed is still busy
|
|
52
|
+
private static readonly MAX_WAIT_MS = 10000;
|
|
53
|
+
// release once the feed has been idle this long (historical burst drained)
|
|
54
|
+
private static readonly IDLE_MS = 500;
|
|
55
|
+
|
|
56
|
+
private loaded: boolean = false;
|
|
57
|
+
private queue: (() => void)[] = [];
|
|
58
|
+
private timeoutId?: ReturnType<typeof setTimeout>;
|
|
59
|
+
private idleTimeoutId?: ReturnType<typeof setTimeout>;
|
|
60
|
+
|
|
61
|
+
async wait(): Promise<void> {
|
|
62
|
+
if (this.loaded) {
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// start hard timeout backstop on first call
|
|
67
|
+
if (!this.timeoutId) {
|
|
68
|
+
this.timeoutId = setTimeout(() => {
|
|
69
|
+
if (this.loaded) {
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
console.log('Initial contest load timeout reached');
|
|
73
|
+
this.release();
|
|
74
|
+
}, InitialLoadGate.MAX_WAIT_MS);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return new Promise<void>((resolve) => {
|
|
78
|
+
this.queue.push(resolve);
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Called for each processed notification during startup. The initial event
|
|
83
|
+
// feed sends all historical data as a burst; once it goes idle for IDLE_MS
|
|
84
|
+
// we assume the burst has drained and release the gate. Resetting the timer
|
|
85
|
+
// on every event means we keep waiting as long as data is still arriving.
|
|
86
|
+
touch(): void {
|
|
87
|
+
if (this.loaded) {
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
if (this.idleTimeoutId) {
|
|
91
|
+
clearTimeout(this.idleTimeoutId);
|
|
92
|
+
}
|
|
93
|
+
this.idleTimeoutId = setTimeout(() => {
|
|
94
|
+
this.release();
|
|
95
|
+
}, InitialLoadGate.IDLE_MS);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
release(): void {
|
|
99
|
+
this.loaded = true;
|
|
100
|
+
if (this.timeoutId) {
|
|
101
|
+
clearTimeout(this.timeoutId);
|
|
102
|
+
this.timeoutId = undefined;
|
|
103
|
+
}
|
|
104
|
+
if (this.idleTimeoutId) {
|
|
105
|
+
clearTimeout(this.idleTimeoutId);
|
|
106
|
+
this.idleTimeoutId = undefined;
|
|
107
|
+
}
|
|
108
|
+
// release all waiting threads
|
|
109
|
+
while (this.queue.length > 0) {
|
|
110
|
+
const resolve = this.queue.shift();
|
|
111
|
+
resolve?.();
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const initialLoadGate = new InitialLoadGate();
|
|
117
|
+
|
|
118
|
+
export class ContestAPI {
|
|
119
|
+
private version?: Version;
|
|
120
|
+
private contest?: Contest;
|
|
121
|
+
private access?: Access;
|
|
122
|
+
private state?: ContestState;
|
|
123
|
+
private organizations?: Organization[];
|
|
124
|
+
private groups?: Group[];
|
|
125
|
+
private teams?: Team[];
|
|
126
|
+
private persons?: Person[];
|
|
127
|
+
private accounts?: Account[];
|
|
128
|
+
private account?: Account;
|
|
129
|
+
private languages?: Language[];
|
|
130
|
+
private judgementTypes?: JudgementType[];
|
|
131
|
+
private problems?: Problem[];
|
|
132
|
+
private submissions?: Submission[];
|
|
133
|
+
private judgements?: Judgement[];
|
|
134
|
+
private runs?: Run[];
|
|
135
|
+
private clarifications?: Clarification[];
|
|
136
|
+
private commentary?: Commentary[];
|
|
137
|
+
private awards?: Award[];
|
|
138
|
+
private startStatus?: StartStatus[];
|
|
139
|
+
private scoreboard?: Scoreboard;
|
|
140
|
+
private mapInfo?: MapInfo;
|
|
141
|
+
|
|
142
|
+
private id: string;
|
|
143
|
+
private contestURL: string;
|
|
144
|
+
private baseURL: string;
|
|
145
|
+
private serverURL: string;
|
|
146
|
+
private proxyURL?: string;
|
|
147
|
+
private credentials?: Credentials;
|
|
148
|
+
|
|
149
|
+
private timeDelta = [];
|
|
150
|
+
|
|
151
|
+
private watching: boolean = false;
|
|
152
|
+
|
|
153
|
+
// throttle timer for reloading the scoreboard after relevant events
|
|
154
|
+
private scoreboardReloadTimeout: ReturnType<typeof setTimeout> | undefined;
|
|
155
|
+
private static readonly SCOREBOARD_RELOAD_THROTTLE_MS = 500;
|
|
156
|
+
|
|
157
|
+
private unknownTypes: string[] = [];
|
|
158
|
+
|
|
159
|
+
private contestListeners: ContestListener[] = [];
|
|
160
|
+
private contestModifiers: ContestModifier[] = [];
|
|
161
|
+
|
|
162
|
+
private shouldReconnect: boolean = false;
|
|
163
|
+
|
|
164
|
+
constructor(contestURL: string, credentials?: Credentials, proxyURL?: string) {
|
|
165
|
+
if (!contestURL.endsWith('/')) {
|
|
166
|
+
contestURL += '/';
|
|
167
|
+
}
|
|
168
|
+
this.contestURL = contestURL;
|
|
169
|
+
this.credentials = credentials;
|
|
170
|
+
this.proxyURL = proxyURL;
|
|
171
|
+
|
|
172
|
+
const bInd = this.contestURL.indexOf('/api/contests/');
|
|
173
|
+
this.id = this.contestURL.substring(bInd + 14, this.contestURL.length - 1);
|
|
174
|
+
|
|
175
|
+
// base url, e.g. http://example.com/api/
|
|
176
|
+
this.baseURL = this.contestURL.substring(0, bInd + 5);
|
|
177
|
+
|
|
178
|
+
// server url, e.g. http://example.com
|
|
179
|
+
const sInd = this.contestURL.indexOf('//');
|
|
180
|
+
const sInd2 = this.contestURL.indexOf('/', sInd + 2);
|
|
181
|
+
this.serverURL = this.contestURL.substring(0, sInd2);
|
|
182
|
+
|
|
183
|
+
//console.log('Contest URL: ' + this.contestURL);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
getURL(type: string, id?: string): string {
|
|
187
|
+
if (id == null) {
|
|
188
|
+
if (type === 'contest') {
|
|
189
|
+
return this.contestURL;
|
|
190
|
+
} else if (type === 'version') {
|
|
191
|
+
return this.baseURL;
|
|
192
|
+
}
|
|
193
|
+
return this.contestURL + type;
|
|
194
|
+
}
|
|
195
|
+
return this.contestURL + type + '/' + id;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
199
|
+
async loadObject(type: ContestType): Promise<any> {
|
|
200
|
+
const startTime = performance.now();
|
|
201
|
+
const url = this.getURL(type);
|
|
202
|
+
try {
|
|
203
|
+
const response = await fetch(url, fetchOptions(this.credentials));
|
|
204
|
+
if (!response.ok) {
|
|
205
|
+
throw new Error(`HTTP error ${response.status} loading ${url}: ${response.statusText}`);
|
|
206
|
+
}
|
|
207
|
+
const body = await response.text();
|
|
208
|
+
const obj = JSON.parse(body, (_key, value) => {
|
|
209
|
+
return value === null ? undefined : value;
|
|
210
|
+
});
|
|
211
|
+
const endTime = performance.now();
|
|
212
|
+
console.log(`Fetched ${url} in ${(endTime - startTime).toFixed(1)}ms`);
|
|
213
|
+
this.processFileReferences(obj);
|
|
214
|
+
return obj;
|
|
215
|
+
} catch (error: unknown) {
|
|
216
|
+
if (error instanceof Error) {
|
|
217
|
+
throw new Error(`Error loading ${url}: ${error.message}`, { cause: error });
|
|
218
|
+
}
|
|
219
|
+
throw new Error(`Unexpected error loading ${url}: ${error}`, { cause: error });
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async loadVersion(force?: boolean): Promise<void> {
|
|
224
|
+
if (force || !this.version) {
|
|
225
|
+
this.version = await this.loadObject('version');
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async loadContest(force?: boolean): Promise<void> {
|
|
230
|
+
if (force || !this.contest) {
|
|
231
|
+
this.contest = await this.loadObject('contest');
|
|
232
|
+
this.fireChange({ type: 'contest' });
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
async loadAccess(force?: boolean): Promise<void> {
|
|
237
|
+
if (force || !this.access) {
|
|
238
|
+
this.access = await this.loadObject('access');
|
|
239
|
+
this.fireChange({ type: 'access' });
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
async loadState(force?: boolean): Promise<void> {
|
|
244
|
+
if (force || !this.state) {
|
|
245
|
+
this.state = await this.loadObject('state');
|
|
246
|
+
this.fireChange({ type: 'state' });
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async loadStartStatus(force?: boolean): Promise<void> {
|
|
251
|
+
if (force || !this.startStatus) {
|
|
252
|
+
this.startStatus = await this.loadObject('start-status');
|
|
253
|
+
this.fireChange({ type: 'start-status' });
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
async loadLanguages(force?: boolean): Promise<void> {
|
|
258
|
+
if (force || !this.languages) {
|
|
259
|
+
this.languages = await this.loadObject('languages');
|
|
260
|
+
this.fireChange({ type: 'languages' });
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async loadJudgementTypes(force?: boolean): Promise<void> {
|
|
265
|
+
if (force || !this.judgementTypes) {
|
|
266
|
+
this.judgementTypes = await this.loadObject('judgement-types');
|
|
267
|
+
this.fireChange({ type: 'judgement-types' });
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
private sortProblems(problems2: Problem[]): Problem[] {
|
|
272
|
+
return problems2.sort((a, b) => (a.ordinal > b.ordinal ? 1 : b.ordinal > a.ordinal ? -1 : 0));
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
async loadProblems(force?: boolean): Promise<void> {
|
|
276
|
+
if (force || !this.problems) {
|
|
277
|
+
this.problems = this.sortProblems(await this.loadObject('problems'));
|
|
278
|
+
this.fireChange({ type: 'problems' });
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
async loadGroups(force?: boolean): Promise<void> {
|
|
283
|
+
if (force || !this.groups) {
|
|
284
|
+
this.groups = await this.loadObject('groups');
|
|
285
|
+
this.fireChange({ type: 'groups' });
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
async loadOrganizations(force?: boolean): Promise<void> {
|
|
290
|
+
if (force || !this.organizations) {
|
|
291
|
+
this.organizations = await this.loadObject('organizations');
|
|
292
|
+
this.fireChange({ type: 'organizations' });
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
private sortTeams(teams2: Team[]): Team[] {
|
|
297
|
+
// sort by team id
|
|
298
|
+
return teams2.sort((a, b) => {
|
|
299
|
+
// try parsing as number first
|
|
300
|
+
const an = parseInt(a.id);
|
|
301
|
+
const bn = parseInt(b.id);
|
|
302
|
+
if (!Number.isNaN(an) && !Number.isNaN(bn)) {
|
|
303
|
+
return an - bn;
|
|
304
|
+
}
|
|
305
|
+
// otherwise compare by locale
|
|
306
|
+
return a.id.localeCompare(b.id);
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async loadTeams(force?: boolean): Promise<void> {
|
|
311
|
+
if (force || !this.teams) {
|
|
312
|
+
this.teams = this.sortTeams(await this.loadObject('teams'));
|
|
313
|
+
this.fireChange({ type: 'teams' });
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
async loadPersons(force?: boolean): Promise<void> {
|
|
318
|
+
if (force || !this.persons) {
|
|
319
|
+
this.persons = await this.loadObject('persons');
|
|
320
|
+
this.fireChange({ type: 'persons' });
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
async loadAccounts(force?: boolean): Promise<void> {
|
|
325
|
+
if (force || !this.accounts) {
|
|
326
|
+
this.accounts = await this.loadObject('accounts');
|
|
327
|
+
this.fireChange({ type: 'accounts' });
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
async loadAccount(force?: boolean): Promise<void> {
|
|
332
|
+
if (force || !this.account) {
|
|
333
|
+
this.account = await this.loadObject('account');
|
|
334
|
+
this.fireChange({ type: 'account' });
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
async loadSubmissions(force?: boolean): Promise<void> {
|
|
339
|
+
if (force || !this.submissions) {
|
|
340
|
+
this.submissions = await this.loadObject('submissions');
|
|
341
|
+
this.fireChange({ type: 'submissions' });
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
async loadJudgements(force?: boolean): Promise<void> {
|
|
346
|
+
if (force || !this.judgements) {
|
|
347
|
+
this.judgements = await this.loadObject('judgements');
|
|
348
|
+
this.fireChange({ type: 'judgements' });
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
async loadRuns(force?: boolean): Promise<void> {
|
|
353
|
+
if (force || !this.runs) {
|
|
354
|
+
this.runs = await this.loadObject('runs');
|
|
355
|
+
this.fireChange({ type: 'runs' });
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
async loadClarifications(force?: boolean): Promise<void> {
|
|
360
|
+
if (force || !this.clarifications) {
|
|
361
|
+
this.clarifications = await this.loadObject('clarifications');
|
|
362
|
+
this.fireChange({ type: 'clarifications' });
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
async loadCommentary(force?: boolean): Promise<void> {
|
|
367
|
+
if (force || !this.commentary) {
|
|
368
|
+
this.commentary = await this.loadObject('commentary');
|
|
369
|
+
this.fireChange({ type: 'commentary' });
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
async loadScoreboard(force?: boolean): Promise<void> {
|
|
374
|
+
if (force || !this.scoreboard) {
|
|
375
|
+
const scoreboard2: Scoreboard = await this.loadObject('scoreboard');
|
|
376
|
+
scoreboard2.rows.sort((a, b) => {
|
|
377
|
+
return a.rank - b.rank;
|
|
378
|
+
});
|
|
379
|
+
|
|
380
|
+
this.scoreboard = scoreboard2;
|
|
381
|
+
this.fireChange({ type: 'scoreboard' });
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
async loadAwards(force?: boolean): Promise<void> {
|
|
386
|
+
if (force || !this.awards) {
|
|
387
|
+
this.awards = await this.loadObject('awards');
|
|
388
|
+
this.fireChange({ type: 'awards' });
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
async loadMapInfo(force?: boolean): Promise<void> {
|
|
393
|
+
if (force || !this.mapInfo) {
|
|
394
|
+
this.mapInfo = await this.loadObject('map-info');
|
|
395
|
+
this.fireChange({ type: 'map-info' });
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
getContestURL(): string {
|
|
400
|
+
return this.contestURL;
|
|
401
|
+
}
|
|
402
|
+
getVersion(): Version | undefined {
|
|
403
|
+
return this.version;
|
|
404
|
+
}
|
|
405
|
+
getContest(): Contest | undefined {
|
|
406
|
+
return this.contest;
|
|
407
|
+
}
|
|
408
|
+
getAccess() {
|
|
409
|
+
return this.access;
|
|
410
|
+
}
|
|
411
|
+
getState(): ContestState | undefined {
|
|
412
|
+
return this.state;
|
|
413
|
+
}
|
|
414
|
+
getStartStatus() {
|
|
415
|
+
return this.startStatus;
|
|
416
|
+
}
|
|
417
|
+
getLanguages(): Language[] {
|
|
418
|
+
return this.languages || [];
|
|
419
|
+
}
|
|
420
|
+
getJudgementTypes(): JudgementType[] {
|
|
421
|
+
return this.judgementTypes || [];
|
|
422
|
+
}
|
|
423
|
+
getProblems(): Problem[] {
|
|
424
|
+
return this.problems || [];
|
|
425
|
+
}
|
|
426
|
+
getGroups(): Group[] {
|
|
427
|
+
return this.groups || [];
|
|
428
|
+
}
|
|
429
|
+
getTeams(): Team[] {
|
|
430
|
+
return this.teams || [];
|
|
431
|
+
}
|
|
432
|
+
getOrganizations(): Organization[] {
|
|
433
|
+
return this.organizations || [];
|
|
434
|
+
}
|
|
435
|
+
getPersons(): Person[] {
|
|
436
|
+
return this.persons || [];
|
|
437
|
+
}
|
|
438
|
+
getAccounts(): Account[] {
|
|
439
|
+
return this.accounts || [];
|
|
440
|
+
}
|
|
441
|
+
getAccount(): Account | undefined {
|
|
442
|
+
return this.account;
|
|
443
|
+
}
|
|
444
|
+
getSubmissions(): Submission[] {
|
|
445
|
+
return this.submissions || [];
|
|
446
|
+
}
|
|
447
|
+
getJudgements(): Judgement[] {
|
|
448
|
+
return this.judgements || [];
|
|
449
|
+
}
|
|
450
|
+
getRuns(): Run[] {
|
|
451
|
+
return this.runs || [];
|
|
452
|
+
}
|
|
453
|
+
getClarifications(): Clarification[] {
|
|
454
|
+
return this.clarifications || [];
|
|
455
|
+
}
|
|
456
|
+
getCommentary(): Commentary[] {
|
|
457
|
+
return this.commentary || [];
|
|
458
|
+
}
|
|
459
|
+
getScoreboard(): Scoreboard | undefined {
|
|
460
|
+
return this.scoreboard;
|
|
461
|
+
}
|
|
462
|
+
getAwards(): Award[] {
|
|
463
|
+
return this.awards || [];
|
|
464
|
+
}
|
|
465
|
+
getMapInfo(): MapInfo | undefined {
|
|
466
|
+
return this.mapInfo;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
getTimeDelta() {
|
|
470
|
+
if (this.timeDelta.length == 0) return 0;
|
|
471
|
+
let total = 0;
|
|
472
|
+
this.timeDelta.forEach(function (item) {
|
|
473
|
+
total += item;
|
|
474
|
+
});
|
|
475
|
+
return total / this.timeDelta.length;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
resolveClientURL(ref: FileReference): string | undefined {
|
|
479
|
+
if (!ref || !ref.href) {
|
|
480
|
+
return undefined;
|
|
481
|
+
}
|
|
482
|
+
// If href is already absolute, return as-is
|
|
483
|
+
if (ref.href.startsWith('http://') || ref.href.startsWith('https://')) {
|
|
484
|
+
return ref.href;
|
|
485
|
+
}
|
|
486
|
+
// Prepend server-relative URLs
|
|
487
|
+
if (ref.href.startsWith('/')) {
|
|
488
|
+
if (this.proxyURL) {
|
|
489
|
+
return this.proxyURL + '/api' + ref.href;
|
|
490
|
+
}
|
|
491
|
+
return this.serverURL + ref.href;
|
|
492
|
+
}
|
|
493
|
+
// ... and base-relative URLs
|
|
494
|
+
if (this.proxyURL) {
|
|
495
|
+
return this.proxyURL + '/' + ref.href;
|
|
496
|
+
}
|
|
497
|
+
return this.baseURL + ref.href;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
private isFileReference(obj: unknown): obj is FileReference {
|
|
501
|
+
if (obj == null || !(typeof obj === 'object' && 'href' in obj && 'mime' in obj)) {
|
|
502
|
+
return false;
|
|
503
|
+
}
|
|
504
|
+
return true;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
private processFileReferences(obj: unknown) {
|
|
508
|
+
// We get either one object or an array of objects, handle both cases
|
|
509
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
510
|
+
let objs: any[];
|
|
511
|
+
if (Array.isArray(obj)) {
|
|
512
|
+
objs = obj;
|
|
513
|
+
} else {
|
|
514
|
+
objs = [obj];
|
|
515
|
+
}
|
|
516
|
+
for (const obj of objs) {
|
|
517
|
+
for (const key in obj) {
|
|
518
|
+
const prop = obj[key];
|
|
519
|
+
if (!Array.isArray(prop)) {
|
|
520
|
+
continue;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
for (const item of prop) {
|
|
524
|
+
if (this.isFileReference(item)) {
|
|
525
|
+
item.href = this.resolveClientURL(item) || item.href;
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
getAuth() {
|
|
533
|
+
return btoa(this.credentials?.user + ':' + this.credentials?.password);
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
private processNotificationSingleton(type: string, data: object) {
|
|
537
|
+
// update a 'singleton' object, e.g. contest, state
|
|
538
|
+
switch (type) {
|
|
539
|
+
case 'contest': {
|
|
540
|
+
const obj = data as Contest;
|
|
541
|
+
this.processFileReferences(obj);
|
|
542
|
+
this.contest = obj;
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
case 'state': {
|
|
546
|
+
this.state = data as ContestState;
|
|
547
|
+
return;
|
|
548
|
+
}
|
|
549
|
+
case 'map-info': {
|
|
550
|
+
this.mapInfo = data as MapInfo;
|
|
551
|
+
break;
|
|
552
|
+
}
|
|
553
|
+
default: {
|
|
554
|
+
if (!this.unknownTypes.includes(type)) {
|
|
555
|
+
console.log('Unknown singleton type in feed: ' + type);
|
|
556
|
+
this.unknownTypes.push(type);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
private processData(
|
|
563
|
+
id: Id | undefined,
|
|
564
|
+
arr: { id: Id }[] | undefined,
|
|
565
|
+
obj: { id: Id } | { id: Id }[] | undefined | null
|
|
566
|
+
): { id: Id }[] {
|
|
567
|
+
if (Array.isArray(obj)) {
|
|
568
|
+
if (id) {
|
|
569
|
+
console.log('Event can never have id and data array');
|
|
570
|
+
return arr ?? [];
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
obj.forEach((obj) => this.processFileReferences(obj));
|
|
574
|
+
return obj;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
if (!arr || arr.length === 0) {
|
|
578
|
+
// deletion on empty array
|
|
579
|
+
if (!obj) {
|
|
580
|
+
return [];
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
this.processFileReferences(obj);
|
|
584
|
+
return [obj];
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
// search for existing object to replace
|
|
588
|
+
let index = -1;
|
|
589
|
+
for (let i = 0; i < arr.length; i++) {
|
|
590
|
+
if (arr[i].id === id) {
|
|
591
|
+
index = i;
|
|
592
|
+
break;
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
// deletion
|
|
597
|
+
if (obj === undefined || obj === null) {
|
|
598
|
+
if (index >= 0) {
|
|
599
|
+
arr.splice(index, 1);
|
|
600
|
+
}
|
|
601
|
+
return arr;
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
// replacement
|
|
605
|
+
if (index >= 0) {
|
|
606
|
+
this.processFileReferences(obj);
|
|
607
|
+
arr[index] = obj;
|
|
608
|
+
return arr;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
// addition
|
|
612
|
+
this.processFileReferences(obj);
|
|
613
|
+
arr.push(obj);
|
|
614
|
+
return arr;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
processNotification(n: Notification): void {
|
|
618
|
+
if (!this.modify(n)) {
|
|
619
|
+
return;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
// keep the initial-load gate open as long as feed data is still arriving
|
|
623
|
+
initialLoadGate.touch();
|
|
624
|
+
|
|
625
|
+
if ((!n.id || n.type === 'contest') && !Array.isArray(n.data)) {
|
|
626
|
+
// no id and not an array: must be a 'singleton' object (e.g. state)
|
|
627
|
+
this.processNotificationSingleton(n.type, n.data ?? {});
|
|
628
|
+
this.fireChange({ type: n.type, id: n.id });
|
|
629
|
+
return;
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
const data = n.data as { id: Id } | null | undefined;
|
|
633
|
+
switch (n.type) {
|
|
634
|
+
case 'judgement-types': {
|
|
635
|
+
this.judgementTypes = this.processData(n.id, this.judgementTypes, data) as JudgementType[];
|
|
636
|
+
break;
|
|
637
|
+
}
|
|
638
|
+
case 'languages': {
|
|
639
|
+
this.languages = this.processData(n.id, this.languages, data) as Language[];
|
|
640
|
+
break;
|
|
641
|
+
}
|
|
642
|
+
case 'problems': {
|
|
643
|
+
this.problems = this.sortProblems(this.processData(n.id, this.problems, data) as Problem[]);
|
|
644
|
+
break;
|
|
645
|
+
}
|
|
646
|
+
case 'groups': {
|
|
647
|
+
this.groups = this.processData(n.id, this.groups, data) as Group[];
|
|
648
|
+
break;
|
|
649
|
+
}
|
|
650
|
+
case 'organizations': {
|
|
651
|
+
this.organizations = this.processData(n.id, this.organizations, data) as Organization[];
|
|
652
|
+
break;
|
|
653
|
+
}
|
|
654
|
+
case 'teams': {
|
|
655
|
+
this.teams = this.sortTeams(this.processData(n.id, this.teams, data) as Team[]);
|
|
656
|
+
break;
|
|
657
|
+
}
|
|
658
|
+
case 'persons': {
|
|
659
|
+
this.persons = this.processData(n.id, this.persons, data) as Person[];
|
|
660
|
+
break;
|
|
661
|
+
}
|
|
662
|
+
case 'accounts': {
|
|
663
|
+
this.accounts = this.processData(n.id, this.accounts, data) as Account[];
|
|
664
|
+
break;
|
|
665
|
+
}
|
|
666
|
+
case 'submissions': {
|
|
667
|
+
this.submissions = this.processData(n.id, this.submissions, data) as Submission[];
|
|
668
|
+
break;
|
|
669
|
+
}
|
|
670
|
+
case 'judgements': {
|
|
671
|
+
this.judgements = this.processData(n.id, this.judgements, data) as Judgement[];
|
|
672
|
+
break;
|
|
673
|
+
}
|
|
674
|
+
case 'runs': {
|
|
675
|
+
this.runs = this.processData(n.id, this.runs, data) as Run[];
|
|
676
|
+
break;
|
|
677
|
+
}
|
|
678
|
+
case 'clarifications': {
|
|
679
|
+
this.clarifications = this.processData(n.id, this.clarifications, data) as Clarification[];
|
|
680
|
+
break;
|
|
681
|
+
}
|
|
682
|
+
case 'awards': {
|
|
683
|
+
this.awards = this.processData(n.id, this.awards, data) as Award[];
|
|
684
|
+
break;
|
|
685
|
+
}
|
|
686
|
+
case 'commentary': {
|
|
687
|
+
this.commentary = this.processData(n.id, this.commentary, data) as Commentary[];
|
|
688
|
+
break;
|
|
689
|
+
}
|
|
690
|
+
case 'start-status': {
|
|
691
|
+
this.startStatus = this.processData(n.id, this.startStatus, data) as StartStatus[];
|
|
692
|
+
break;
|
|
693
|
+
}
|
|
694
|
+
default: {
|
|
695
|
+
if (!this.unknownTypes.includes(n.type)) {
|
|
696
|
+
console.log('Unknown type in feed: ' + n.type);
|
|
697
|
+
this.unknownTypes.push(n.type);
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
this.fireChange({ type: n.type, id: n.id });
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
private async *readLines(stream: ReadableStream<Uint8Array>): AsyncGenerator<string> {
|
|
706
|
+
const reader = stream.getReader();
|
|
707
|
+
const decoder = new TextDecoder();
|
|
708
|
+
let buffer = '';
|
|
709
|
+
try {
|
|
710
|
+
while (true) {
|
|
711
|
+
const { done, value } = await reader.read();
|
|
712
|
+
if (done) break;
|
|
713
|
+
buffer += decoder.decode(value, { stream: true });
|
|
714
|
+
const lines = buffer.split('\n');
|
|
715
|
+
buffer = lines.pop()!;
|
|
716
|
+
for (const line of lines) {
|
|
717
|
+
yield line.replace(/\r$/, '');
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
buffer += decoder.decode();
|
|
721
|
+
if (buffer.length > 0) {
|
|
722
|
+
yield buffer.replace(/\r$/, '');
|
|
723
|
+
}
|
|
724
|
+
} finally {
|
|
725
|
+
reader.releaseLock();
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
async connectToFeed(): Promise<boolean> {
|
|
730
|
+
const url = this.getURL('event-feed');
|
|
731
|
+
let connected = false;
|
|
732
|
+
try {
|
|
733
|
+
const opts = fetchOptions(this.credentials);
|
|
734
|
+
delete opts.signal; // no timeout for long-lived stream
|
|
735
|
+
const response = await fetch(url, opts);
|
|
736
|
+
if (!response.ok) {
|
|
737
|
+
throw new Error(`HTTP error ${response.status}: ${response.statusText}`);
|
|
738
|
+
}
|
|
739
|
+
if (!response.body) {
|
|
740
|
+
throw new Error('No response body');
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
for await (const line of this.readLines(response.body)) {
|
|
744
|
+
if (!connected) {
|
|
745
|
+
console.log('Connected to feed');
|
|
746
|
+
connected = true;
|
|
747
|
+
}
|
|
748
|
+
if (line.length > 0) {
|
|
749
|
+
const obj: Notification = JSON.parse(line, (_key, value) => {
|
|
750
|
+
return value === null ? undefined : value;
|
|
751
|
+
});
|
|
752
|
+
this.processNotification(obj);
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
console.log(`Event feed stream ended for ${url}`);
|
|
757
|
+
} catch (error: unknown) {
|
|
758
|
+
initialLoadGate.release();
|
|
759
|
+
|
|
760
|
+
if (error instanceof Error) {
|
|
761
|
+
console.error(`Error loading ${url}: ${error.message}`);
|
|
762
|
+
} else {
|
|
763
|
+
console.error(`Unexpected error loading ${url}: ${error}`);
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
return connected;
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
async readEventFeed(): Promise<void> {
|
|
770
|
+
console.log('Connecting to event feed');
|
|
771
|
+
|
|
772
|
+
let reconnectDelay: number = 1000;
|
|
773
|
+
const maxReconnectDelay = 30000; // max 30 seconds
|
|
774
|
+
|
|
775
|
+
while (this.shouldReconnect) {
|
|
776
|
+
// TODO should we reset here, or support event feed token?
|
|
777
|
+
if (await this.connectToFeed()) {
|
|
778
|
+
reconnectDelay = 1000;
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
if (this.state?.end_of_updates) {
|
|
782
|
+
this.shouldReconnect = false;
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
if (this.shouldReconnect) {
|
|
786
|
+
console.log(`Reconnecting to event feed in ${reconnectDelay / 1000}s...`);
|
|
787
|
+
await new Promise((resolve) => setTimeout(resolve, reconnectDelay));
|
|
788
|
+
reconnectDelay = Math.min(reconnectDelay * 2, maxReconnectDelay);
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
console.log('Done reading event feed');
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
private reset(): void {
|
|
796
|
+
this.version = undefined;
|
|
797
|
+
this.contest = undefined;
|
|
798
|
+
this.access = undefined;
|
|
799
|
+
this.state = undefined;
|
|
800
|
+
this.organizations = [];
|
|
801
|
+
this.groups = [];
|
|
802
|
+
this.teams = [];
|
|
803
|
+
this.persons = [];
|
|
804
|
+
this.accounts = [];
|
|
805
|
+
this.account = undefined;
|
|
806
|
+
this.languages = [];
|
|
807
|
+
this.judgementTypes = [];
|
|
808
|
+
this.problems = [];
|
|
809
|
+
this.submissions = [];
|
|
810
|
+
this.judgements = [];
|
|
811
|
+
this.runs = [];
|
|
812
|
+
this.clarifications = [];
|
|
813
|
+
this.commentary = [];
|
|
814
|
+
this.awards = [];
|
|
815
|
+
this.startStatus = [];
|
|
816
|
+
this.scoreboard = undefined;
|
|
817
|
+
this.mapInfo = undefined;
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
async watch(): Promise<void> {
|
|
821
|
+
if (this.watching) {
|
|
822
|
+
return;
|
|
823
|
+
}
|
|
824
|
+
this.watching = true;
|
|
825
|
+
console.log(`Watching ${this.id}`);
|
|
826
|
+
|
|
827
|
+
// reset the contest to empty arrays
|
|
828
|
+
this.reset();
|
|
829
|
+
|
|
830
|
+
// load the initial version, access, and scoreboard endpoints since they're not in the feed
|
|
831
|
+
await this.loadVersion(true);
|
|
832
|
+
await this.loadAccess(true);
|
|
833
|
+
await this.loadScoreboard(true);
|
|
834
|
+
|
|
835
|
+
// Enable reconnection and start reading the event feed
|
|
836
|
+
this.shouldReconnect = true;
|
|
837
|
+
|
|
838
|
+
this.readEventFeed().catch((error) => {
|
|
839
|
+
console.error(`Event feed error: ${error}`);
|
|
840
|
+
});
|
|
841
|
+
|
|
842
|
+
// wait for initial contest load (or timeout)
|
|
843
|
+
await initialLoadGate.wait();
|
|
844
|
+
|
|
845
|
+
console.log(`Done watching ${this.id}`);
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
unwatch(): void {
|
|
849
|
+
if (!this.watching) {
|
|
850
|
+
return;
|
|
851
|
+
}
|
|
852
|
+
this.watching = false;
|
|
853
|
+
this.shouldReconnect = false;
|
|
854
|
+
if (this.scoreboardReloadTimeout) {
|
|
855
|
+
clearTimeout(this.scoreboardReloadTimeout);
|
|
856
|
+
this.scoreboardReloadTimeout = undefined;
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
// Schedule a scoreboard reload, throttled so bursts of events trigger at most one reload
|
|
861
|
+
// per throttle window. If a reload is already pending we leave it, so a steady stream of
|
|
862
|
+
// events (faster than the window) still reloads regularly instead of being starved.
|
|
863
|
+
private scheduleScoreboardReload(): void {
|
|
864
|
+
if (this.scoreboardReloadTimeout) {
|
|
865
|
+
return;
|
|
866
|
+
}
|
|
867
|
+
this.scoreboardReloadTimeout = setTimeout(async () => {
|
|
868
|
+
this.scoreboardReloadTimeout = undefined;
|
|
869
|
+
try {
|
|
870
|
+
await this.loadScoreboard(true);
|
|
871
|
+
} catch (error: unknown) {
|
|
872
|
+
console.error(`Error reloading scoreboard: ${error}`);
|
|
873
|
+
}
|
|
874
|
+
}, ContestAPI.SCOREBOARD_RELOAD_THROTTLE_MS);
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
addContestListener(listener: ContestListener): void {
|
|
878
|
+
this.contestListeners.push(listener);
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
removeContestListener(listener: ContestListener): void {
|
|
882
|
+
const index = this.contestListeners.indexOf(listener);
|
|
883
|
+
if (index >= 0) {
|
|
884
|
+
this.contestListeners.splice(index, 1);
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
private fireChange(event: ContestEvent): void {
|
|
889
|
+
if (event.type === 'submissions' || event.type === 'judgements' || event.type === 'problems') {
|
|
890
|
+
this.scheduleScoreboardReload();
|
|
891
|
+
}
|
|
892
|
+
for (const listener of this.contestListeners) {
|
|
893
|
+
try {
|
|
894
|
+
listener(event);
|
|
895
|
+
} catch (error) {
|
|
896
|
+
console.error('Error in contest listener:', error);
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
addContestModifier(modifier: ContestModifier): void {
|
|
902
|
+
this.contestModifiers.push(modifier);
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
removeContestModifier(modifier: ContestModifier): void {
|
|
906
|
+
const index = this.contestModifiers.indexOf(modifier);
|
|
907
|
+
if (index >= 0) {
|
|
908
|
+
this.contestModifiers.splice(index, 1);
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
private modify(event: Notification): boolean {
|
|
913
|
+
for (const modifier of this.contestModifiers) {
|
|
914
|
+
try {
|
|
915
|
+
if (!modifier(event)) {
|
|
916
|
+
return false;
|
|
917
|
+
}
|
|
918
|
+
} catch (error) {
|
|
919
|
+
console.error('Error in contest modifier:', error);
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
return true;
|
|
923
|
+
}
|
|
924
|
+
}
|