feat: auto provision tournament codes
This commit is contained in:
1 parent
65bc214fb2
commit
bac29ac933
13 files changed
+1164
-117
No files matched your search
@@ -1225,7 +1225,6 @@ export const TournamentCodeSchema = new Schema<TournamentCode>(
|
||||
type: String,
|
||||
required: true,
|
||||
trim: true,
|
||||
uppercase: true,
|
||||
},
|
||||
region: { type: String, required: true, default: 'kr' },
|
||||
mapType: {
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import {
|
||||
SYSTEM_TOURNAMENT_CODE_UPLOADED_BY,
|
||||
TournamentCodeAutoProvisionService,
|
||||
} from './tournament-code-auto-provision.service';
|
||||
import { TournamentCodeService } from './tournament-code.service';
|
||||
import { TournamentCodeVendorService } from './tournament-code-vendor.service';
|
||||
|
||||
describe('TournamentCodeAutoProvisionService', () => {
|
||||
function createFixture(params?: {
|
||||
availableCounts?: number[];
|
||||
vendorCodes?: string[];
|
||||
}) {
|
||||
const availableCounts = [...(params?.availableCounts ?? [30])];
|
||||
const vendorCodes = [...(params?.vendorCodes ?? [])];
|
||||
const tournamentCodeService = {
|
||||
countUsableAvailable: jest.fn().mockImplementation(async () => {
|
||||
return availableCounts.shift() ?? 30;
|
||||
}),
|
||||
bulkUpload: jest.fn().mockResolvedValue({
|
||||
inserted: 1,
|
||||
duplicates: [],
|
||||
invalid: [],
|
||||
}),
|
||||
} as unknown as jest.Mocked<TournamentCodeService>;
|
||||
const vendorService = {
|
||||
fetchTournamentCode: jest.fn().mockImplementation(async () => {
|
||||
const code = vendorCodes.shift();
|
||||
if (!code) throw new Error('No vendor code');
|
||||
return code;
|
||||
}),
|
||||
} as unknown as jest.Mocked<TournamentCodeVendorService>;
|
||||
const service = new TournamentCodeAutoProvisionService(
|
||||
tournamentCodeService,
|
||||
vendorService,
|
||||
);
|
||||
jest
|
||||
.spyOn(
|
||||
service as unknown as { sleepBeforeVendorRequest(): Promise<void> },
|
||||
'sleepBeforeVendorRequest',
|
||||
)
|
||||
.mockResolvedValue(undefined);
|
||||
|
||||
return { service, tournamentCodeService, vendorService };
|
||||
}
|
||||
|
||||
it('does nothing when the usable pool already meets the target', async () => {
|
||||
const { service, tournamentCodeService, vendorService } = createFixture({
|
||||
availableCounts: [30],
|
||||
});
|
||||
|
||||
await expect(service.ensurePool()).resolves.toMatchObject({
|
||||
target: 30,
|
||||
before: 30,
|
||||
after: 30,
|
||||
requested: 0,
|
||||
inserted: 0,
|
||||
});
|
||||
expect(vendorService.fetchTournamentCode).not.toHaveBeenCalled();
|
||||
expect(tournamentCodeService.bulkUpload).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('requests vendor codes until the pool reaches 30', async () => {
|
||||
const { service, tournamentCodeService, vendorService } = createFixture({
|
||||
availableCounts: [28, 29, 30],
|
||||
vendorCodes: ['KR05090-aBc', 'KR05090-dEf'],
|
||||
});
|
||||
|
||||
const result = await service.ensurePool();
|
||||
|
||||
expect(result).toMatchObject({
|
||||
target: 30,
|
||||
before: 28,
|
||||
after: 30,
|
||||
requested: 2,
|
||||
inserted: 2,
|
||||
});
|
||||
expect(vendorService.fetchTournamentCode).toHaveBeenCalledTimes(2);
|
||||
expect(
|
||||
(
|
||||
service as unknown as {
|
||||
sleepBeforeVendorRequest: jest.Mock;
|
||||
}
|
||||
).sleepBeforeVendorRequest,
|
||||
).toHaveBeenCalledTimes(2);
|
||||
expect(tournamentCodeService.bulkUpload).toHaveBeenCalledWith({
|
||||
uploadedBy: SYSTEM_TOURNAMENT_CODE_UPLOADED_BY,
|
||||
codes: [
|
||||
expect.objectContaining({
|
||||
code: 'KR05090-aBc',
|
||||
source: 'deeplol-vendor',
|
||||
spectatorType: 'ALL',
|
||||
}),
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('shares an in-flight refill instead of starting overlapping vendor loops', async () => {
|
||||
const { service, vendorService } = createFixture({
|
||||
availableCounts: [29, 30],
|
||||
vendorCodes: ['KR05090-aBc'],
|
||||
});
|
||||
|
||||
const [left, right] = await Promise.all([
|
||||
service.ensurePool(),
|
||||
service.ensurePool(),
|
||||
]);
|
||||
|
||||
expect(left).toBe(right);
|
||||
expect(vendorService.fetchTournamentCode).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from './tournament-code.constants';
|
||||
import { TournamentCodeService } from './tournament-code.service';
|
||||
import {
|
||||
resolveVendorRequestDelayMs,
|
||||
TournamentCodeVendorService,
|
||||
} from './tournament-code-vendor.service';
|
||||
|
||||
const DEFAULT_POOL_TARGET = 30;
|
||||
const DEFAULT_VENDOR_CODE_EXPIRES_IN_MS = 14 * 24 * 60 * 60 * 1000;
|
||||
const MAX_REFILL_ATTEMPTS_MULTIPLIER = 2;
|
||||
|
||||
export const SYSTEM_TOURNAMENT_CODE_UPLOADED_BY = new mongoose.Types.ObjectId(
|
||||
'000000000000000000000000',
|
||||
);
|
||||
|
||||
export interface TournamentCodeAutoProvisionResult {
|
||||
target: number;
|
||||
before: number;
|
||||
after: number;
|
||||
requested: number;
|
||||
inserted: number;
|
||||
duplicates: number;
|
||||
invalid: number;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class TournamentCodeAutoProvisionService {
|
||||
private readonly logger = new Logger(TournamentCodeAutoProvisionService.name);
|
||||
private inFlight?: Promise<TournamentCodeAutoProvisionResult>;
|
||||
|
||||
constructor(
|
||||
private readonly tournamentCodeService: TournamentCodeService,
|
||||
private readonly vendorService: TournamentCodeVendorService,
|
||||
) {}
|
||||
|
||||
public async ensurePool(): Promise<TournamentCodeAutoProvisionResult> {
|
||||
if (this.inFlight) return this.inFlight;
|
||||
|
||||
this.inFlight = this.refillPool().finally(() => {
|
||||
this.inFlight = undefined;
|
||||
});
|
||||
return this.inFlight;
|
||||
}
|
||||
|
||||
public async sleepBeforeVendorRequest(): Promise<void> {
|
||||
await sleep(resolveVendorRequestDelayMs());
|
||||
}
|
||||
|
||||
private async refillPool(): Promise<TournamentCodeAutoProvisionResult> {
|
||||
const target = resolvePoolTarget();
|
||||
const before = await this.tournamentCodeService.countUsableAvailable();
|
||||
let after = before;
|
||||
let requested = 0;
|
||||
let inserted = 0;
|
||||
let duplicates = 0;
|
||||
let invalid = 0;
|
||||
|
||||
const maxAttempts = Math.max(
|
||||
1,
|
||||
(target - before) * MAX_REFILL_ATTEMPTS_MULTIPLIER,
|
||||
);
|
||||
|
||||
while (after < target && requested < maxAttempts) {
|
||||
await this.sleepBeforeVendorRequest();
|
||||
const code = await this.vendorService.fetchTournamentCode();
|
||||
requested += 1;
|
||||
|
||||
const uploadResult = await this.tournamentCodeService.bulkUpload({
|
||||
uploadedBy: SYSTEM_TOURNAMENT_CODE_UPLOADED_BY,
|
||||
codes: [
|
||||
{
|
||||
code,
|
||||
expiresAt: resolveVendorCodeExpiresAt().toISOString(),
|
||||
spectatorType: 'ALL',
|
||||
source: 'deeplol-vendor',
|
||||
notes: 'auto-provisioned from Deeplol vendor',
|
||||
},
|
||||
],
|
||||
});
|
||||
inserted += uploadResult.inserted;
|
||||
duplicates += uploadResult.duplicates.length;
|
||||
invalid += uploadResult.invalid.length;
|
||||
after = await this.tournamentCodeService.countUsableAvailable();
|
||||
}
|
||||
|
||||
if (inserted > 0 || before < target) {
|
||||
this.logger.log(
|
||||
`Tournament code pool refill: before=${before} after=${after} target=${target} requested=${requested} inserted=${inserted} duplicates=${duplicates} invalid=${invalid}`,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
target,
|
||||
before,
|
||||
after,
|
||||
requested,
|
||||
inserted,
|
||||
duplicates,
|
||||
invalid,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function resolvePoolTarget(): number {
|
||||
const configured = Number(process.env.TOURNAMENT_CODE_POOL_TARGET);
|
||||
return Number.isInteger(configured) && configured > 0
|
||||
? configured
|
||||
: DEFAULT_POOL_TARGET;
|
||||
}
|
||||
|
||||
function resolveVendorCodeExpiresAt(): Date {
|
||||
const configuredHours = Number(
|
||||
process.env.TOURNAMENT_CODE_VENDOR_EXPIRES_IN_HOURS,
|
||||
);
|
||||
const expiresInMs =
|
||||
Number.isFinite(configuredHours) && configuredHours > 0
|
||||
? configuredHours * 60 * 60 * 1000
|
||||
: DEFAULT_VENDOR_CODE_EXPIRES_IN_MS;
|
||||
return new Date(
|
||||
Date.now() + Math.max(expiresInMs, TOURNAMENT_CODE_EXPIRY_MARGIN_MS),
|
||||
);
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import {
|
||||
buildDeeplolTournamentCodeRequest,
|
||||
resolveVendorRequestDelayMs,
|
||||
TournamentCodeVendorService,
|
||||
} from './tournament-code-vendor.service';
|
||||
|
||||
describe('TournamentCodeVendorService', () => {
|
||||
const originalFetch = global.fetch;
|
||||
|
||||
afterEach(() => {
|
||||
global.fetch = originalFetch;
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('builds the Deeplol request URL and browser-like headers', () => {
|
||||
const request = buildDeeplolTournamentCodeRequest();
|
||||
|
||||
expect(request.url.toString()).toBe(
|
||||
'https://b2c-api.deeplol.gg/tournament/tournament_code?server_id=212&server_name=%EB%A1%A4%EB%A6%BC%ED%91%B8%EC%8A%A4&server_comment=LPS_%EB%82%B4%EC%A0%84&spectator_type=ALL&pick_type=TOURNAMENT_DRAFT&map_name=SUMMONERS_RIFT&platform_id=KR',
|
||||
);
|
||||
expect(request.headers).toMatchObject({
|
||||
accept: '*/*',
|
||||
'accept-encoding': 'gzip, deflate, br, zstd',
|
||||
'accept-language': 'ko,en;q=0.9,en-US;q=0.8',
|
||||
'cache-control': 'no-cache',
|
||||
host: 'b2c-api.deeplol.gg',
|
||||
origin: 'https://clash.deeplol.gg',
|
||||
pragma: 'no-cache',
|
||||
priority: 'u=1, i',
|
||||
referer: 'https://clash.deeplol.gg/',
|
||||
'sec-ch-ua':
|
||||
'"Microsoft Edge";v="149", "Chromium";v="149", "Not)A;Brand";v="24"',
|
||||
'sec-ch-ua-mobile': '?0',
|
||||
'sec-ch-ua-platform': '"Windows"',
|
||||
'sec-fetch-dest': 'empty',
|
||||
'sec-fetch-mode': 'cors',
|
||||
'sec-fetch-site': 'same-site',
|
||||
'user-agent':
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36 Edg/149.0.0.0',
|
||||
});
|
||||
expect(Object.keys(request.headers)).not.toContain(':authority');
|
||||
});
|
||||
|
||||
it('fetches the first tournament code from the vendor response', async () => {
|
||||
global.fetch = jest.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: jest.fn().mockResolvedValue({
|
||||
tournament_code_list: [
|
||||
'KR05090-85d64e26-0a7d-438b-9ada-11784e46add3',
|
||||
],
|
||||
}),
|
||||
});
|
||||
const service = new TournamentCodeVendorService();
|
||||
|
||||
await expect(service.fetchTournamentCode()).resolves.toBe(
|
||||
'KR05090-85d64e26-0a7d-438b-9ada-11784e46add3',
|
||||
);
|
||||
expect(global.fetch).toHaveBeenCalledWith(
|
||||
expect.stringContaining(
|
||||
'https://b2c-api.deeplol.gg/tournament/tournament_code?',
|
||||
),
|
||||
expect.objectContaining({
|
||||
method: 'GET',
|
||||
headers: expect.objectContaining({
|
||||
origin: 'https://clash.deeplol.gg',
|
||||
referer: 'https://clash.deeplol.gg/',
|
||||
}),
|
||||
signal: expect.any(AbortSignal),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects malformed vendor responses', async () => {
|
||||
global.fetch = jest.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: jest.fn().mockResolvedValue({
|
||||
tournament_code_list: [null],
|
||||
}),
|
||||
});
|
||||
const service = new TournamentCodeVendorService();
|
||||
|
||||
await expect(service.fetchTournamentCode()).rejects.toThrow(
|
||||
'Vendor tournament code response is malformed.',
|
||||
);
|
||||
});
|
||||
|
||||
it('generates mostly near-5-second delays with occasional extra delay', () => {
|
||||
expect(resolveVendorRequestDelayMs(() => 0.1)).toBe(5_050);
|
||||
expect(resolveVendorRequestDelayMs(() => 0.84)).toBe(5_420);
|
||||
expect(resolveVendorRequestDelayMs(() => 0.9)).toBe(8_700);
|
||||
expect(resolveVendorRequestDelayMs(() => 0)).toBeGreaterThanOrEqual(5_000);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
const DEFAULT_VENDOR_URL =
|
||||
'https://b2c-api.deeplol.gg/tournament/tournament_code';
|
||||
const DEFAULT_FETCH_TIMEOUT_MS = 10_000;
|
||||
const MIN_REQUEST_DELAY_MS = 5_000;
|
||||
|
||||
const DEFAULT_QUERY_PARAMS = {
|
||||
server_id: '212',
|
||||
server_name: '롤림푸스',
|
||||
server_comment: 'LPS_내전',
|
||||
spectator_type: 'ALL',
|
||||
pick_type: 'TOURNAMENT_DRAFT',
|
||||
map_name: 'SUMMONERS_RIFT',
|
||||
platform_id: 'KR',
|
||||
} as const;
|
||||
|
||||
const BROWSER_LIKE_HEADERS = {
|
||||
accept: '*/*',
|
||||
'accept-encoding': 'gzip, deflate, br, zstd',
|
||||
'accept-language': 'ko,en;q=0.9,en-US;q=0.8',
|
||||
'cache-control': 'no-cache',
|
||||
host: 'b2c-api.deeplol.gg',
|
||||
origin: 'https://clash.deeplol.gg',
|
||||
pragma: 'no-cache',
|
||||
priority: 'u=1, i',
|
||||
referer: 'https://clash.deeplol.gg/',
|
||||
'sec-ch-ua':
|
||||
'"Microsoft Edge";v="149", "Chromium";v="149", "Not)A;Brand";v="24"',
|
||||
'sec-ch-ua-mobile': '?0',
|
||||
'sec-ch-ua-platform': '"Windows"',
|
||||
'sec-fetch-dest': 'empty',
|
||||
'sec-fetch-mode': 'cors',
|
||||
'sec-fetch-site': 'same-site',
|
||||
'user-agent':
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36 Edg/149.0.0.0',
|
||||
} as const;
|
||||
|
||||
interface DeeplolTournamentCodeResponse {
|
||||
tournament_code_list?: unknown;
|
||||
}
|
||||
|
||||
export interface DeeplolTournamentCodeRequest {
|
||||
url: URL;
|
||||
headers: Record<string, string>;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class TournamentCodeVendorService {
|
||||
public async fetchTournamentCode(): Promise<string> {
|
||||
const request = buildDeeplolTournamentCodeRequest();
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => {
|
||||
controller.abort();
|
||||
}, resolveFetchTimeoutMs());
|
||||
|
||||
try {
|
||||
const response = await fetch(request.url.toString(), {
|
||||
method: 'GET',
|
||||
headers: request.headers,
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Vendor tournament code request failed (${response.status}).`,
|
||||
);
|
||||
}
|
||||
|
||||
const payload = (await response.json()) as DeeplolTournamentCodeResponse;
|
||||
return parseVendorTournamentCode(payload);
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function buildDeeplolTournamentCodeRequest(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): DeeplolTournamentCodeRequest {
|
||||
const url = new URL(
|
||||
env.TOURNAMENT_CODE_VENDOR_URL?.trim() || DEFAULT_VENDOR_URL,
|
||||
);
|
||||
const params = {
|
||||
server_id:
|
||||
env.TOURNAMENT_CODE_VENDOR_SERVER_ID ?? DEFAULT_QUERY_PARAMS.server_id,
|
||||
server_name:
|
||||
env.TOURNAMENT_CODE_VENDOR_SERVER_NAME ??
|
||||
DEFAULT_QUERY_PARAMS.server_name,
|
||||
server_comment:
|
||||
env.TOURNAMENT_CODE_VENDOR_SERVER_COMMENT ??
|
||||
DEFAULT_QUERY_PARAMS.server_comment,
|
||||
spectator_type:
|
||||
env.TOURNAMENT_CODE_VENDOR_SPECTATOR_TYPE ??
|
||||
DEFAULT_QUERY_PARAMS.spectator_type,
|
||||
pick_type:
|
||||
env.TOURNAMENT_CODE_VENDOR_PICK_TYPE ?? DEFAULT_QUERY_PARAMS.pick_type,
|
||||
map_name:
|
||||
env.TOURNAMENT_CODE_VENDOR_MAP_NAME ?? DEFAULT_QUERY_PARAMS.map_name,
|
||||
platform_id:
|
||||
env.TOURNAMENT_CODE_VENDOR_PLATFORM_ID ??
|
||||
DEFAULT_QUERY_PARAMS.platform_id,
|
||||
};
|
||||
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
url.searchParams.set(key, value);
|
||||
}
|
||||
|
||||
return {
|
||||
url,
|
||||
headers: {
|
||||
...BROWSER_LIKE_HEADERS,
|
||||
host: url.host,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveVendorRequestDelayMs(
|
||||
random: () => number = Math.random,
|
||||
): number {
|
||||
const roll = clampRandom(random());
|
||||
if (roll < 0.85) {
|
||||
return MIN_REQUEST_DELAY_MS + Math.round(roll * 500);
|
||||
}
|
||||
return MIN_REQUEST_DELAY_MS + 100 + Math.round(roll * 4_000);
|
||||
}
|
||||
|
||||
function parseVendorTournamentCode(
|
||||
payload: DeeplolTournamentCodeResponse,
|
||||
): string {
|
||||
const codes = payload.tournament_code_list;
|
||||
if (
|
||||
!Array.isArray(codes) ||
|
||||
typeof codes[0] !== 'string' ||
|
||||
!codes[0].trim()
|
||||
) {
|
||||
throw new Error('Vendor tournament code response is malformed.');
|
||||
}
|
||||
return codes[0].trim();
|
||||
}
|
||||
|
||||
function resolveFetchTimeoutMs(): number {
|
||||
const configured = Number(process.env.TOURNAMENT_CODE_VENDOR_TIMEOUT_MS);
|
||||
return Number.isFinite(configured) && configured > 0
|
||||
? configured
|
||||
: DEFAULT_FETCH_TIMEOUT_MS;
|
||||
}
|
||||
|
||||
function clampRandom(value: number): number {
|
||||
if (!Number.isFinite(value)) return 0;
|
||||
return Math.min(1, Math.max(0, value));
|
||||
}
|
||||
@@ -1,12 +1,19 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TournamentCodeController } from './tournament-code.controller';
|
||||
import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service';
|
||||
import { TournamentCodeReplacementController } from './tournament-code-replacement.controller';
|
||||
import { TournamentCodeScheduler } from './tournament-code.scheduler';
|
||||
import { TournamentCodeService } from './tournament-code.service';
|
||||
import { TournamentCodeVendorService } from './tournament-code-vendor.service';
|
||||
|
||||
@Module({
|
||||
controllers: [TournamentCodeController, TournamentCodeReplacementController],
|
||||
providers: [TournamentCodeService, TournamentCodeScheduler],
|
||||
providers: [
|
||||
TournamentCodeService,
|
||||
TournamentCodeVendorService,
|
||||
TournamentCodeAutoProvisionService,
|
||||
TournamentCodeScheduler,
|
||||
],
|
||||
exports: [TournamentCodeService],
|
||||
})
|
||||
export class TournamentCodeModule {}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service';
|
||||
import { TournamentCodeService } from './tournament-code.service';
|
||||
|
||||
@Injectable()
|
||||
@@ -6,8 +7,12 @@ 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) {}
|
||||
constructor(
|
||||
private readonly tournamentCodeService: TournamentCodeService,
|
||||
private readonly autoProvisionService: TournamentCodeAutoProvisionService,
|
||||
) {}
|
||||
|
||||
public onModuleInit() {
|
||||
this.attachTimer = setInterval(() => {
|
||||
@@ -16,16 +21,26 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
|
||||
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() {
|
||||
@@ -54,4 +69,23 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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';
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
import type { MatchDocument } from '../global/database/schema';
|
||||
import {
|
||||
TournamentCodeSchema,
|
||||
type MatchDocument,
|
||||
} from '../global/database/schema';
|
||||
import mongoose from 'mongoose';
|
||||
import { TournamentCodeService } from './tournament-code.service';
|
||||
|
||||
@@ -14,6 +17,7 @@ type TournamentCodeServiceInternals = TournamentCodeService & {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
gameNumber: number;
|
||||
}): Promise<unknown>;
|
||||
attachPendingMatches(communityId?: mongoose.Types.ObjectId): Promise<number>;
|
||||
};
|
||||
|
||||
function createService() {
|
||||
@@ -318,6 +322,89 @@ describe('TournamentCodeService round-robin scheduling', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('TournamentCodeService bulk upload', () => {
|
||||
it('preserves tournament code casing at the schema layer', async () => {
|
||||
const connection = mongoose.createConnection();
|
||||
try {
|
||||
const TournamentCodeModel = connection.model(
|
||||
'TournamentCodeCasingSpec',
|
||||
TournamentCodeSchema,
|
||||
);
|
||||
|
||||
const code = new TournamentCodeModel({
|
||||
code: ' AbC-12345 ',
|
||||
expiresAt: new Date(Date.now() + 60 * 60 * 1000),
|
||||
uploadedBy: new mongoose.Types.ObjectId(),
|
||||
});
|
||||
|
||||
expect(code.code).toBe('AbC-12345');
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('stores tournament codes with the exact casing from input', async () => {
|
||||
const insertMany = jest.fn().mockResolvedValue(undefined);
|
||||
const TournamentCodeModel = {
|
||||
find: jest.fn().mockReturnValue({
|
||||
select: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue([]),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
insertMany,
|
||||
};
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockResolvedValue(TournamentCodeModel),
|
||||
};
|
||||
const service = new TournamentCodeService(
|
||||
connectionService as never,
|
||||
) as unknown as TournamentCodeServiceInternals;
|
||||
service.attachPendingMatches = jest.fn().mockResolvedValue(0);
|
||||
|
||||
await service.bulkUpload({
|
||||
communityId: new mongoose.Types.ObjectId(),
|
||||
uploadedBy: new mongoose.Types.ObjectId(),
|
||||
codes: [
|
||||
{
|
||||
code: ' AbC-12345 ',
|
||||
expiresAt: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(insertMany).toHaveBeenCalledWith(
|
||||
[
|
||||
expect.objectContaining({
|
||||
code: 'AbC-12345',
|
||||
}),
|
||||
],
|
||||
{ ordered: false },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TournamentCodeService pool stats', () => {
|
||||
it('counts only available codes that are usable beyond the expiry margin', async () => {
|
||||
const countDocuments = jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue(12),
|
||||
});
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockResolvedValue({ countDocuments }),
|
||||
};
|
||||
const service = new TournamentCodeService(connectionService as never);
|
||||
|
||||
await expect(service.countUsableAvailable()).resolves.toBe(12);
|
||||
expect(countDocuments).toHaveBeenCalledWith({
|
||||
state: 'available',
|
||||
expiresAt: {
|
||||
$gt: expect.any(Date),
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('TournamentCodeService code replacement', () => {
|
||||
function queryResult<T>(value: T) {
|
||||
return { exec: jest.fn().mockResolvedValue(value) };
|
||||
|
||||
@@ -37,7 +37,7 @@ export class TournamentCodeService {
|
||||
constructor(private readonly connectionService: ConnectionService) {}
|
||||
|
||||
public async bulkUpload(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
communityId?: mongoose.Types.ObjectId;
|
||||
uploadedBy: mongoose.Types.ObjectId;
|
||||
codes: TournamentCodeUploadItem[];
|
||||
}): Promise<BulkUploadTournamentCodesResponse> {
|
||||
@@ -121,6 +121,17 @@ export class TournamentCodeService {
|
||||
};
|
||||
}
|
||||
|
||||
public async countUsableAvailable(): Promise<number> {
|
||||
const TournamentCodeModel =
|
||||
await this.connectionService.getModel('tournamentCode');
|
||||
return TournamentCodeModel.countDocuments({
|
||||
state: 'available',
|
||||
expiresAt: {
|
||||
$gt: new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS),
|
||||
},
|
||||
}).exec();
|
||||
}
|
||||
|
||||
public async list(params: {
|
||||
state?: TournamentCodeState;
|
||||
limit?: number;
|
||||
@@ -492,7 +503,7 @@ export class TournamentCodeService {
|
||||
}
|
||||
|
||||
private normalizeCode(code: string | undefined): string {
|
||||
return (code ?? '').trim().toUpperCase();
|
||||
return (code ?? '').trim();
|
||||
}
|
||||
|
||||
private replaceTournamentCodeId(
|
||||
|
||||
@@ -101,6 +101,180 @@ describe('TournamentResultService round-robin scheduling', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('TournamentResultService tournament code polling', () => {
|
||||
function queryResult<T>(value: T) {
|
||||
return { exec: jest.fn().mockResolvedValue(value) };
|
||||
}
|
||||
|
||||
function sortedQueryResult<T>(value: T) {
|
||||
return {
|
||||
sort: jest.fn().mockReturnValue(queryResult(value)),
|
||||
};
|
||||
}
|
||||
|
||||
function createPollFixture(params: {
|
||||
storedCode: string;
|
||||
riotTournamentCode: string;
|
||||
}) {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const codeId = new mongoose.Types.ObjectId();
|
||||
const users = Array.from({ length: 10 }, (_, index) => ({
|
||||
userId: new mongoose.Types.ObjectId(),
|
||||
puuid: `poll-puuid-${index + 1}`,
|
||||
}));
|
||||
const match = {
|
||||
_id: matchId,
|
||||
communityId,
|
||||
status: 'team-built',
|
||||
teamBuiltAt: new Date('2026-05-03T10:00:00.000Z'),
|
||||
gameCount: 1,
|
||||
gameMode: 'pair',
|
||||
tournamentCodeIds: [codeId],
|
||||
gameSchedule: [],
|
||||
resultPollState: {
|
||||
startedAt: new Date(),
|
||||
matchedCount: 0,
|
||||
expandedToAllPuuids: true,
|
||||
state: 'polling',
|
||||
},
|
||||
participants: users.map((user) => ({
|
||||
userId: user.userId,
|
||||
puuid: user.puuid,
|
||||
excluded: false,
|
||||
})),
|
||||
teams: [
|
||||
{
|
||||
teamIndex: 1,
|
||||
members: users.slice(0, 5).map((user) => ({ userId: user.userId })),
|
||||
},
|
||||
{
|
||||
teamIndex: 2,
|
||||
members: users.slice(5).map((user) => ({ userId: user.userId })),
|
||||
},
|
||||
],
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
} as unknown as MatchDocument & {
|
||||
save: jest.Mock;
|
||||
result?: MatchDocument['result'];
|
||||
};
|
||||
const code = {
|
||||
_id: codeId,
|
||||
code: params.storedCode,
|
||||
state: 'reserved',
|
||||
gameNumber: 1,
|
||||
riotMatchId: undefined,
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const detail = {
|
||||
metadata: {
|
||||
matchId: 'KR_9876543210',
|
||||
participants: users.map((user) => user.puuid),
|
||||
},
|
||||
info: {
|
||||
tournamentCode: params.riotTournamentCode,
|
||||
gameCreation: Date.parse('2026-05-03T10:30:00.000Z'),
|
||||
gameEndTimestamp: Date.parse('2026-05-03T11:00:00.000Z'),
|
||||
gameDuration: 1800,
|
||||
participants: users.map((user, index) => ({
|
||||
puuid: user.puuid,
|
||||
teamId: index < 5 ? 100 : 200,
|
||||
championId: 1,
|
||||
kills: 1,
|
||||
deaths: 1,
|
||||
assists: 1,
|
||||
win: index < 5,
|
||||
})),
|
||||
teams: [
|
||||
{ teamId: 100, win: true },
|
||||
{ teamId: 200, win: false },
|
||||
],
|
||||
},
|
||||
} as unknown as RiotMatchDto;
|
||||
const TournamentCodeModel = {
|
||||
find: jest
|
||||
.fn()
|
||||
.mockReturnValueOnce(sortedQueryResult([code]))
|
||||
.mockReturnValueOnce(sortedQueryResult([code])),
|
||||
exists: jest.fn().mockResolvedValue(null),
|
||||
};
|
||||
const RiotMatchModel = {
|
||||
findOne: jest.fn().mockReturnValue(queryResult(null)),
|
||||
updateOne: jest.fn().mockReturnValue(queryResult(undefined)),
|
||||
};
|
||||
const CommunityModel = {
|
||||
findById: jest.fn().mockReturnValue({
|
||||
select: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue(queryResult({ riotRegion: 'asia' })),
|
||||
}),
|
||||
}),
|
||||
};
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockImplementation(async (name: string) => {
|
||||
if (name === 'match') {
|
||||
return { findById: jest.fn().mockResolvedValue(match) };
|
||||
}
|
||||
if (name === 'tournamentCode') return TournamentCodeModel;
|
||||
if (name === 'community') return CommunityModel;
|
||||
if (name === 'riotMatch') return RiotMatchModel;
|
||||
throw new Error(`Unexpected model: ${name}`);
|
||||
}),
|
||||
};
|
||||
const riotMatchService = {
|
||||
getMatchIdsByPuuid: jest.fn().mockResolvedValue(['KR_9876543210']),
|
||||
getMatch: jest.fn().mockResolvedValue(detail),
|
||||
};
|
||||
const riotJobQueueService = {
|
||||
enqueueTournamentResultPoll: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const service = new TournamentResultService(
|
||||
connectionService as never,
|
||||
riotMatchService as never,
|
||||
riotJobQueueService as never,
|
||||
{ invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never,
|
||||
{ buildAndUpsert: jest.fn().mockResolvedValue(undefined) } as never,
|
||||
);
|
||||
|
||||
return { service, match, code };
|
||||
}
|
||||
|
||||
it('matches Riot tournament codes using exact casing', async () => {
|
||||
const { service, match, code } = createPollFixture({
|
||||
storedCode: 'AbC-12345',
|
||||
riotTournamentCode: 'AbC-12345',
|
||||
});
|
||||
|
||||
await service.processPollJob({
|
||||
matchId: match._id.toString(),
|
||||
attempt: 1,
|
||||
expandedToAllPuuids: true,
|
||||
});
|
||||
|
||||
expect(code.state).toBe('used');
|
||||
expect(code.riotMatchId).toBe('KR_9876543210');
|
||||
expect(code.save).toHaveBeenCalled();
|
||||
expect(match.result?.games).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('does not match tournament codes when casing differs', async () => {
|
||||
const { service, match, code } = createPollFixture({
|
||||
storedCode: 'ABC-12345',
|
||||
riotTournamentCode: 'abc-12345',
|
||||
});
|
||||
|
||||
await service.processPollJob({
|
||||
matchId: match._id.toString(),
|
||||
attempt: 1,
|
||||
expandedToAllPuuids: true,
|
||||
});
|
||||
|
||||
expect(code.state).toBe('reserved');
|
||||
expect(code.riotMatchId).toBeUndefined();
|
||||
expect(code.save).not.toHaveBeenCalled();
|
||||
expect(match.result?.games).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('TournamentResultService manual result collection', () => {
|
||||
function createManualFixture() {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
|
||||
@@ -262,7 +262,7 @@ export class TournamentResultService {
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const tournamentCode = detail.info.tournamentCode?.trim().toUpperCase();
|
||||
const tournamentCode = detail.info.tournamentCode?.trim();
|
||||
if (!tournamentCode) continue;
|
||||
|
||||
const code = unmatchedByCode.get(tournamentCode);
|
||||
|
||||
Reference in new issue
Block a user