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