Files
lolympus-tournament-support/apps/api/src/modules/tournament-code/tournament-code.scheduler.ts
T

100 lines
3.0 KiB
TypeScript

import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { TournamentResultService } from '../tournament-result/tournament-result.service';
import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service';
import { TournamentCodeService } from './tournament-code.service';
@Injectable()
export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(TournamentCodeScheduler.name);
private attachTimer?: NodeJS.Timeout;
private expireTimer?: NodeJS.Timeout;
private refillTimer?: NodeJS.Timeout;
constructor(
private readonly tournamentCodeService: TournamentCodeService,
private readonly autoProvisionService: TournamentCodeAutoProvisionService,
private readonly tournamentResultService: TournamentResultService,
) {}
public onModuleInit() {
this.attachTimer = setInterval(() => {
void this.attachPending();
}, 30_000);
this.expireTimer = setInterval(() => {
void this.markExpired();
}, 60 * 60 * 1000);
if (isAutoProvisionEnabled()) {
this.refillTimer = setInterval(() => {
void this.ensureVendorPool();
}, 5 * 60 * 1000);
}
this.attachTimer.unref?.();
this.expireTimer.unref?.();
this.refillTimer?.unref?.();
void this.attachPending();
void this.markExpired();
if (isAutoProvisionEnabled()) {
void this.ensureVendorPool();
}
}
public onModuleDestroy() {
if (this.attachTimer) clearInterval(this.attachTimer);
if (this.expireTimer) clearInterval(this.expireTimer);
if (this.refillTimer) clearInterval(this.refillTimer);
}
private async attachPending() {
try {
const matches =
await this.tournamentCodeService.attachPendingMatchDocuments();
if (matches.length > 0) {
this.logger.debug(
`Attached tournament codes for ${matches.length} matches.`,
);
for (const match of matches) {
await this.tournamentResultService.scheduleInitialPoll(match);
}
}
} catch (error) {
this.logger.warn(
`Failed to attach pending tournament codes: ${
error instanceof Error ? error.message : error
}`,
);
}
}
private async markExpired() {
try {
await this.tournamentCodeService.markExpired();
} catch (error) {
this.logger.warn(
`Failed to mark expired tournament codes: ${
error instanceof Error ? error.message : error
}`,
);
}
}
private async ensureVendorPool() {
try {
await this.autoProvisionService.ensurePool();
} catch (error) {
this.logger.warn(
`Failed to auto-provision tournament codes: ${
error instanceof Error ? error.message : error
}`,
);
}
}
}
function isAutoProvisionEnabled(): boolean {
const raw = process.env.TOURNAMENT_CODE_AUTO_PROVISION_ENABLED
?.trim()
.toLowerCase();
return raw !== 'false' && raw !== '0' && raw !== 'off';
}