import { Injectable, Logger, OnModuleDestroy, OnModuleInit, } from '@nestjs/common'; import { DistributedLockService } from '../global/redis/distributed-lock.service'; import { TournamentResultService } from '../tournament-result/tournament-result.service'; import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service'; import { TournamentCodeService } from './tournament-code.service'; const ATTACH_PENDING_CODES_TO_MATCHES_LOCK_KEY = 'distributed-lock:tournament-code:scheduler:attach-pending-codes-to-matches'; const MARK_EXPIRED_ASSIGNED_CODES_LOCK_KEY = 'distributed-lock:tournament-code:scheduler:mark-expired-assigned-codes'; const ENSURE_VENDOR_CODE_POOL_LOCK_KEY = 'distributed-lock:tournament-code:scheduler:ensure-vendor-code-pool'; const SCHEDULER_LOCK_EXPIRATION_DURATION_MILLISECONDS = 10 * 60_000; const SCHEDULER_LOCK_RENEWAL_INTERVAL_MILLISECONDS = 2 * 60_000; @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, private readonly distributedLockService: DistributedLockService, ) {} 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 { await this.distributedLockService.runWithRenewedLock( { lockKey: ATTACH_PENDING_CODES_TO_MATCHES_LOCK_KEY, lockExpirationDurationMilliseconds: SCHEDULER_LOCK_EXPIRATION_DURATION_MILLISECONDS, lockRenewalIntervalMilliseconds: SCHEDULER_LOCK_RENEWAL_INTERVAL_MILLISECONDS, }, async () => { 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.distributedLockService.runWithRenewedLock( { lockKey: MARK_EXPIRED_ASSIGNED_CODES_LOCK_KEY, lockExpirationDurationMilliseconds: SCHEDULER_LOCK_EXPIRATION_DURATION_MILLISECONDS, lockRenewalIntervalMilliseconds: SCHEDULER_LOCK_RENEWAL_INTERVAL_MILLISECONDS, }, async () => { const result = await this.tournamentCodeService.markExpired(); for (const matchId of result.affectedMatchIds) { try { await this.tournamentResultService.scheduleInitialPoll(matchId); } catch (error) { this.logger.warn( `Failed to reconcile Competition codes after expiring a code for Match ${matchId.toString()}: ${ error instanceof Error ? error.message : error }`, ); } } }, ); } catch (error) { this.logger.warn( `Failed to mark expired tournament codes: ${ error instanceof Error ? error.message : error }`, ); } } private async ensureVendorPool() { try { await this.distributedLockService.runWithRenewedLock( { lockKey: ENSURE_VENDOR_CODE_POOL_LOCK_KEY, lockExpirationDurationMilliseconds: SCHEDULER_LOCK_EXPIRATION_DURATION_MILLISECONDS, lockRenewalIntervalMilliseconds: SCHEDULER_LOCK_RENEWAL_INTERVAL_MILLISECONDS, }, async () => { 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'; }