Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3a76fd8c88 | ||
|
|
3357d4c9c8 | ||
|
|
2d1c33f1e9 | ||
|
|
03358cab4f | ||
|
|
e188828423 |
No files matched your search
+2
-2
@@ -31,7 +31,7 @@ COPY apps/web/package.json apps/web/package.json
|
|||||||
|
|
||||||
RUN pnpm install --prod --frozen-lockfile --filter api... --filter lolympus-tournament-support
|
RUN pnpm install --prod --frozen-lockfile --filter api... --filter lolympus-tournament-support
|
||||||
|
|
||||||
FROM gcr.io/distroless/nodejs24-debian13:nonroot AS runtime
|
FROM gcr.io/distroless/nodejs26-debian13:nonroot AS runtime
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
@@ -45,7 +45,7 @@ COPY --chown=nonroot:nonroot apps/api/newrelic.cjs ./apps/api/newrelic.cjs
|
|||||||
COPY --from=build --chown=nonroot:nonroot /app/apps/api/dist ./apps/api/dist
|
COPY --from=build --chown=nonroot:nonroot /app/apps/api/dist ./apps/api/dist
|
||||||
COPY --chown=nonroot:nonroot apps/project.env ./project.env
|
COPY --chown=nonroot:nonroot apps/project.env ./project.env
|
||||||
|
|
||||||
EXPOSE 10712
|
EXPOSE 3000
|
||||||
|
|
||||||
ENV NEW_RELIC_HOME=/app/apps/api \
|
ENV NEW_RELIC_HOME=/app/apps/api \
|
||||||
NEW_RELIC_APP_NAME=lolympus \
|
NEW_RELIC_APP_NAME=lolympus \
|
||||||
|
|||||||
@@ -1,11 +1,28 @@
|
|||||||
import {
|
import {
|
||||||
|
buildDoubleEliminationGameSlots,
|
||||||
buildDoubleEliminationBracket,
|
buildDoubleEliminationBracket,
|
||||||
cancelDoubleEliminationBracketMatch,
|
cancelDoubleEliminationBracketMatch,
|
||||||
completeDoubleEliminationBracketMatch,
|
completeDoubleEliminationBracketMatch,
|
||||||
|
resolveDoubleEliminationSeriesWinner,
|
||||||
reshuffleDoubleEliminationSeeds,
|
reshuffleDoubleEliminationSeeds,
|
||||||
swapDoubleEliminationSeeds,
|
swapDoubleEliminationSeeds,
|
||||||
} from './double-elimination.util';
|
} from './double-elimination.util';
|
||||||
|
|
||||||
|
function mongooseSubdocumentLike<T extends object>(value: T): T {
|
||||||
|
const wrapper = {
|
||||||
|
toObject: () => value,
|
||||||
|
} as T & { toObject: () => T };
|
||||||
|
|
||||||
|
for (const [key, entryValue] of Object.entries(value)) {
|
||||||
|
Object.defineProperty(wrapper, key, {
|
||||||
|
enumerable: false,
|
||||||
|
get: () => entryValue,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return wrapper;
|
||||||
|
}
|
||||||
|
|
||||||
describe('double-elimination util', () => {
|
describe('double-elimination util', () => {
|
||||||
it('builds a 4-team bracket with winner, loser, and grand final matches', () => {
|
it('builds a 4-team bracket with winner, loser, and grand final matches', () => {
|
||||||
const bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
|
const bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||||
@@ -15,14 +32,136 @@ describe('double-elimination util', () => {
|
|||||||
expect(bracket.bracketMatches.map((match) => match.bracketMatchId)).toEqual(
|
expect(bracket.bracketMatches.map((match) => match.bracketMatchId)).toEqual(
|
||||||
['WB_R1_M1', 'WB_R1_M2', 'WB_FINAL', 'LB_R1_M1', 'LB_FINAL', 'GF'],
|
['WB_R1_M1', 'WB_R1_M2', 'WB_FINAL', 'LB_R1_M1', 'LB_FINAL', 'GF'],
|
||||||
);
|
);
|
||||||
expect(bracket.bracketMatches.find((match) => match.bracketMatchId === 'WB_R1_M1'))
|
expect(
|
||||||
.toMatchObject({
|
bracket.bracketMatches.find(
|
||||||
teamAIndex: 1,
|
(match) => match.bracketMatchId === 'WB_R1_M1',
|
||||||
teamBIndex: 4,
|
),
|
||||||
winnerAdvancesTo: { bracketMatchId: 'WB_FINAL', position: 'A' },
|
).toMatchObject({
|
||||||
loserAdvancesTo: { bracketMatchId: 'LB_R1_M1', position: 'A' },
|
teamAIndex: 1,
|
||||||
state: 'ready',
|
teamBIndex: 4,
|
||||||
});
|
winnerAdvancesTo: { bracketMatchId: 'WB_FINAL', position: 'A' },
|
||||||
|
loserAdvancesTo: { bracketMatchId: 'LB_R1_M1', position: 'A' },
|
||||||
|
state: 'ready',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('assigns extensible series rules to winner-bracket matches', () => {
|
||||||
|
const bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||||
|
resetFinalEnabled: true,
|
||||||
|
winnerBracketGameCount: 5,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(
|
||||||
|
bracket.bracketMatches
|
||||||
|
.filter((match) => match.bracketSide === 'winner')
|
||||||
|
.map((match) => ({
|
||||||
|
bracketMatchId: match.bracketMatchId,
|
||||||
|
gameCount: match.gameCount,
|
||||||
|
requiredWins: match.requiredWins,
|
||||||
|
})),
|
||||||
|
).toEqual([
|
||||||
|
{ bracketMatchId: 'WB_R1_M1', gameCount: 5, requiredWins: 3 },
|
||||||
|
{ bracketMatchId: 'WB_R1_M2', gameCount: 5, requiredWins: 3 },
|
||||||
|
{ bracketMatchId: 'WB_FINAL', gameCount: 5, requiredWins: 3 },
|
||||||
|
]);
|
||||||
|
expect(
|
||||||
|
bracket.bracketMatches.find(
|
||||||
|
(match) => match.bracketMatchId === 'LB_R1_M1',
|
||||||
|
),
|
||||||
|
).toMatchObject({ gameCount: 1, requiredWins: 1 });
|
||||||
|
expect(
|
||||||
|
bracket.bracketMatches.find((match) => match.bracketMatchId === 'GF'),
|
||||||
|
).toMatchObject({ gameCount: 1, requiredWins: 1 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('expands bracket match series into game slots', () => {
|
||||||
|
const bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||||
|
resetFinalEnabled: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(
|
||||||
|
buildDoubleEliminationGameSlots(bracket.bracketMatches).slice(0, 7),
|
||||||
|
).toEqual([
|
||||||
|
expect.objectContaining({
|
||||||
|
gameNumber: 1,
|
||||||
|
seriesGameNumber: 1,
|
||||||
|
bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_R1_M1' }),
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
gameNumber: 2,
|
||||||
|
seriesGameNumber: 2,
|
||||||
|
bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_R1_M1' }),
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
gameNumber: 3,
|
||||||
|
seriesGameNumber: 3,
|
||||||
|
bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_R1_M1' }),
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
gameNumber: 4,
|
||||||
|
seriesGameNumber: 1,
|
||||||
|
bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_R1_M2' }),
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
gameNumber: 5,
|
||||||
|
seriesGameNumber: 2,
|
||||||
|
bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_R1_M2' }),
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
gameNumber: 6,
|
||||||
|
seriesGameNumber: 3,
|
||||||
|
bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_R1_M2' }),
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
gameNumber: 7,
|
||||||
|
seriesGameNumber: 1,
|
||||||
|
bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_FINAL' }),
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requires the configured number of wins before resolving a series winner', () => {
|
||||||
|
const bracketMatch = buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||||
|
resetFinalEnabled: true,
|
||||||
|
}).bracketMatches.find((match) => match.bracketMatchId === 'WB_R1_M1');
|
||||||
|
|
||||||
|
expect(
|
||||||
|
resolveDoubleEliminationSeriesWinner(
|
||||||
|
{ teamAIndex: 1, teamBIndex: 4, teamAWins: 1, teamBWins: 0 },
|
||||||
|
bracketMatch!,
|
||||||
|
),
|
||||||
|
).toBeUndefined();
|
||||||
|
expect(
|
||||||
|
resolveDoubleEliminationSeriesWinner(
|
||||||
|
{ teamAIndex: 1, teamBIndex: 4, teamAWins: 2, teamBWins: 1 },
|
||||||
|
bracketMatch!,
|
||||||
|
),
|
||||||
|
).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('completes a hydrated Mongoose-style bracket without losing subdocument fields', () => {
|
||||||
|
const bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||||
|
resetFinalEnabled: false,
|
||||||
|
});
|
||||||
|
const hydratedLikeBracket = {
|
||||||
|
...bracket,
|
||||||
|
seeds: bracket.seeds.map(mongooseSubdocumentLike),
|
||||||
|
bracketMatches: bracket.bracketMatches.map(mongooseSubdocumentLike),
|
||||||
|
events: bracket.events.map(mongooseSubdocumentLike),
|
||||||
|
};
|
||||||
|
|
||||||
|
const next = completeDoubleEliminationBracketMatch(hydratedLikeBracket, {
|
||||||
|
bracketMatchId: 'WB_R1_M1',
|
||||||
|
winnerTeamIndex: 1,
|
||||||
|
completedBy: 'riot-result',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(
|
||||||
|
next.bracketMatches.find((match) => match.bracketMatchId === 'WB_FINAL'),
|
||||||
|
).toMatchObject({ teamAIndex: 1 });
|
||||||
|
expect(
|
||||||
|
next.bracketMatches.find((match) => match.bracketMatchId === 'LB_R1_M1'),
|
||||||
|
).toMatchObject({ teamAIndex: 4 });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('moves winners and losers through a 4-team bracket and records top 3', () => {
|
it('moves winners and losers through a 4-team bracket and records top 3', () => {
|
||||||
@@ -43,10 +182,16 @@ describe('double-elimination util', () => {
|
|||||||
completedAt: new Date('2026-06-01T10:30:00.000Z'),
|
completedAt: new Date('2026-06-01T10:30:00.000Z'),
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(bracket.bracketMatches.find((match) => match.bracketMatchId === 'WB_FINAL'))
|
expect(
|
||||||
.toMatchObject({ teamAIndex: 1, teamBIndex: 2, state: 'ready' });
|
bracket.bracketMatches.find(
|
||||||
expect(bracket.bracketMatches.find((match) => match.bracketMatchId === 'LB_R1_M1'))
|
(match) => match.bracketMatchId === 'WB_FINAL',
|
||||||
.toMatchObject({ teamAIndex: 4, teamBIndex: 3, state: 'ready' });
|
),
|
||||||
|
).toMatchObject({ teamAIndex: 1, teamBIndex: 2, state: 'ready' });
|
||||||
|
expect(
|
||||||
|
bracket.bracketMatches.find(
|
||||||
|
(match) => match.bracketMatchId === 'LB_R1_M1',
|
||||||
|
),
|
||||||
|
).toMatchObject({ teamAIndex: 4, teamBIndex: 3, state: 'ready' });
|
||||||
|
|
||||||
bracket = completeDoubleEliminationBracketMatch(bracket, {
|
bracket = completeDoubleEliminationBracketMatch(bracket, {
|
||||||
bracketMatchId: 'WB_FINAL',
|
bracketMatchId: 'WB_FINAL',
|
||||||
@@ -97,14 +242,17 @@ describe('double-elimination util', () => {
|
|||||||
|
|
||||||
expect(bracket.resetFinalCreated).toBe(true);
|
expect(bracket.resetFinalCreated).toBe(true);
|
||||||
expect(bracket.placements).toEqual({ thirdTeamIndex: 3 });
|
expect(bracket.placements).toEqual({ thirdTeamIndex: 3 });
|
||||||
expect(bracket.bracketMatches.find((match) => match.bracketMatchId === 'GF_RESET'))
|
expect(
|
||||||
.toMatchObject({
|
bracket.bracketMatches.find(
|
||||||
gameNumber: 7,
|
(match) => match.bracketMatchId === 'GF_RESET',
|
||||||
bracketSide: 'reset-final',
|
),
|
||||||
teamAIndex: 1,
|
).toMatchObject({
|
||||||
teamBIndex: 2,
|
gameNumber: 7,
|
||||||
state: 'ready',
|
bracketSide: 'reset-final',
|
||||||
});
|
teamAIndex: 1,
|
||||||
|
teamBIndex: 2,
|
||||||
|
state: 'ready',
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('rejects completion cancellation when downstream matches are already completed', () => {
|
it('rejects completion cancellation when downstream matches are already completed', () => {
|
||||||
|
|||||||
@@ -43,6 +43,8 @@ export interface DoubleEliminationWalkover {
|
|||||||
export interface DoubleEliminationBracketMatch {
|
export interface DoubleEliminationBracketMatch {
|
||||||
bracketMatchId: string;
|
bracketMatchId: string;
|
||||||
gameNumber: number;
|
gameNumber: number;
|
||||||
|
gameCount: number;
|
||||||
|
requiredWins: number;
|
||||||
bracketSide: DoubleEliminationBracketSide;
|
bracketSide: DoubleEliminationBracketSide;
|
||||||
roundNumber: number;
|
roundNumber: number;
|
||||||
matchNumber: number;
|
matchNumber: number;
|
||||||
@@ -95,6 +97,27 @@ export interface DoubleEliminationBracket {
|
|||||||
|
|
||||||
export interface BuildDoubleEliminationBracketOptions {
|
export interface BuildDoubleEliminationBracketOptions {
|
||||||
resetFinalEnabled: boolean;
|
resetFinalEnabled: boolean;
|
||||||
|
winnerBracketGameCount?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DoubleEliminationSeriesRule {
|
||||||
|
gameCount: number;
|
||||||
|
requiredWins: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DoubleEliminationGameSlot {
|
||||||
|
gameNumber: number;
|
||||||
|
seriesGameNumber: number;
|
||||||
|
seriesGameCount: number;
|
||||||
|
seriesRequiredWins: number;
|
||||||
|
bracketMatch: DoubleEliminationBracketMatch;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DoubleEliminationSeriesScore {
|
||||||
|
teamAIndex: number;
|
||||||
|
teamBIndex: number;
|
||||||
|
teamAWins: number;
|
||||||
|
teamBWins: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CompleteDoubleEliminationBracketMatchParams {
|
export interface CompleteDoubleEliminationBracketMatchParams {
|
||||||
@@ -127,8 +150,8 @@ export function buildDoubleEliminationBracket(
|
|||||||
seeds,
|
seeds,
|
||||||
bracketMatches:
|
bracketMatches:
|
||||||
seededTeamIndexes.length === 4
|
seededTeamIndexes.length === 4
|
||||||
? buildFourTeamBracketMatches()
|
? buildFourTeamBracketMatches(options)
|
||||||
: buildEightTeamBracketMatches(),
|
: buildEightTeamBracketMatches(options),
|
||||||
placements: {},
|
placements: {},
|
||||||
events: [
|
events: [
|
||||||
{
|
{
|
||||||
@@ -142,6 +165,73 @@ export function buildDoubleEliminationBracket(
|
|||||||
return bracket;
|
return bracket;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function resolveDoubleEliminationSeriesRule(
|
||||||
|
params: {
|
||||||
|
bracketSide: DoubleEliminationBracketSide;
|
||||||
|
bracketMatchId: string;
|
||||||
|
roundNumber: number;
|
||||||
|
},
|
||||||
|
options: { winnerBracketGameCount?: number } = {},
|
||||||
|
): DoubleEliminationSeriesRule {
|
||||||
|
if (params.bracketSide === 'winner') {
|
||||||
|
return seriesRule(options.winnerBracketGameCount ?? 3);
|
||||||
|
}
|
||||||
|
return seriesRule(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildDoubleEliminationGameSlots(
|
||||||
|
bracketMatches: DoubleEliminationBracketMatch[],
|
||||||
|
): DoubleEliminationGameSlot[] {
|
||||||
|
const slots: DoubleEliminationGameSlot[] = [];
|
||||||
|
let gameNumber = 1;
|
||||||
|
for (const bracketMatch of bracketMatches) {
|
||||||
|
const seriesGameCount = normalizeSeriesGameCount(bracketMatch.gameCount);
|
||||||
|
const seriesRequiredWins =
|
||||||
|
bracketMatch.requiredWins ?? requiredWinsForGameCount(seriesGameCount);
|
||||||
|
for (
|
||||||
|
let seriesGameNumber = 1;
|
||||||
|
seriesGameNumber <= seriesGameCount;
|
||||||
|
seriesGameNumber += 1
|
||||||
|
) {
|
||||||
|
slots.push({
|
||||||
|
gameNumber,
|
||||||
|
seriesGameNumber,
|
||||||
|
seriesGameCount,
|
||||||
|
seriesRequiredWins,
|
||||||
|
bracketMatch,
|
||||||
|
});
|
||||||
|
gameNumber += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return slots;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveDoubleEliminationSeriesWinner(
|
||||||
|
series: DoubleEliminationSeriesScore | undefined,
|
||||||
|
bracketMatch: Pick<
|
||||||
|
DoubleEliminationBracketMatch,
|
||||||
|
'requiredWins' | 'teamAIndex' | 'teamBIndex'
|
||||||
|
>,
|
||||||
|
): number | undefined {
|
||||||
|
if (!series) return undefined;
|
||||||
|
const requiredWins = bracketMatch.requiredWins ?? 1;
|
||||||
|
if (
|
||||||
|
bracketMatch.teamAIndex &&
|
||||||
|
series.teamAWins >= requiredWins &&
|
||||||
|
series.teamAWins > series.teamBWins
|
||||||
|
) {
|
||||||
|
return bracketMatch.teamAIndex;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
bracketMatch.teamBIndex &&
|
||||||
|
series.teamBWins >= requiredWins &&
|
||||||
|
series.teamBWins > series.teamAWins
|
||||||
|
) {
|
||||||
|
return bracketMatch.teamBIndex;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
export function reshuffleDoubleEliminationSeeds(
|
export function reshuffleDoubleEliminationSeeds(
|
||||||
bracket: DoubleEliminationBracket,
|
bracket: DoubleEliminationBracket,
|
||||||
rng: () => number = Math.random,
|
rng: () => number = Math.random,
|
||||||
@@ -245,10 +335,13 @@ export function cancelDoubleEliminationBracketMatch(
|
|||||||
bracketMatch.bracketMatchId,
|
bracketMatch.bracketMatchId,
|
||||||
);
|
);
|
||||||
const completedDescendant = next.bracketMatches.find(
|
const completedDescendant = next.bracketMatches.find(
|
||||||
(match) => descendants.has(match.bracketMatchId) && match.state === 'completed',
|
(match) =>
|
||||||
|
descendants.has(match.bracketMatchId) && match.state === 'completed',
|
||||||
);
|
);
|
||||||
if (completedDescendant) {
|
if (completedDescendant) {
|
||||||
throw new Error('Cannot cancel because a downstream bracket match is completed.');
|
throw new Error(
|
||||||
|
'Cannot cancel because a downstream bracket match is completed.',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (bracketMatch.bracketMatchId === 'GF') {
|
if (bracketMatch.bracketMatchId === 'GF') {
|
||||||
@@ -263,10 +356,20 @@ export function cancelDoubleEliminationBracketMatch(
|
|||||||
(match) => match.bracketMatchId === descendantId,
|
(match) => match.bracketMatchId === descendantId,
|
||||||
);
|
);
|
||||||
if (!descendant) continue;
|
if (!descendant) continue;
|
||||||
if (referencesBracketMatch(descendant.teamASource, bracketMatch.bracketMatchId)) {
|
if (
|
||||||
|
referencesBracketMatch(
|
||||||
|
descendant.teamASource,
|
||||||
|
bracketMatch.bracketMatchId,
|
||||||
|
)
|
||||||
|
) {
|
||||||
descendant.teamAIndex = undefined;
|
descendant.teamAIndex = undefined;
|
||||||
}
|
}
|
||||||
if (referencesBracketMatch(descendant.teamBSource, bracketMatch.bracketMatchId)) {
|
if (
|
||||||
|
referencesBracketMatch(
|
||||||
|
descendant.teamBSource,
|
||||||
|
bracketMatch.bracketMatchId,
|
||||||
|
)
|
||||||
|
) {
|
||||||
descendant.teamBIndex = undefined;
|
descendant.teamBIndex = undefined;
|
||||||
}
|
}
|
||||||
descendant.winnerTeamIndex = undefined;
|
descendant.winnerTeamIndex = undefined;
|
||||||
@@ -351,9 +454,12 @@ function completeGrandFinal(
|
|||||||
grandFinal.winnerTeamIndex !== winnerBracketTeamIndex
|
grandFinal.winnerTeamIndex !== winnerBracketTeamIndex
|
||||||
) {
|
) {
|
||||||
bracket.resetFinalCreated = true;
|
bracket.resetFinalCreated = true;
|
||||||
|
const resetRule = seriesRule(1);
|
||||||
bracket.bracketMatches.push({
|
bracket.bracketMatches.push({
|
||||||
bracketMatchId: 'GF_RESET',
|
bracketMatchId: 'GF_RESET',
|
||||||
gameNumber: nextGameNumber(bracket),
|
gameNumber: nextGameNumber(bracket),
|
||||||
|
gameCount: resetRule.gameCount,
|
||||||
|
requiredWins: resetRule.requiredWins,
|
||||||
bracketSide: 'reset-final',
|
bracketSide: 'reset-final',
|
||||||
roundNumber: 1,
|
roundNumber: 1,
|
||||||
matchNumber: 1,
|
matchNumber: 1,
|
||||||
@@ -418,118 +524,122 @@ function applySeedTeams(bracket: DoubleEliminationBracket): void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildFourTeamBracketMatches(): DoubleEliminationBracketMatch[] {
|
function buildFourTeamBracketMatches(
|
||||||
|
options: BuildDoubleEliminationBracketOptions,
|
||||||
|
): DoubleEliminationBracketMatch[] {
|
||||||
return [
|
return [
|
||||||
bracketMatch('WB_R1_M1', 1, 'winner', 1, 1, {
|
bracketMatch('WB_R1_M1', 1, 'winner', 1, 1, options, {
|
||||||
teamASource: seedSource(1),
|
teamASource: seedSource(1),
|
||||||
teamBSource: seedSource(4),
|
teamBSource: seedSource(4),
|
||||||
winnerAdvancesTo: destination('WB_FINAL', 'A'),
|
winnerAdvancesTo: destination('WB_FINAL', 'A'),
|
||||||
loserAdvancesTo: destination('LB_R1_M1', 'A'),
|
loserAdvancesTo: destination('LB_R1_M1', 'A'),
|
||||||
}),
|
}),
|
||||||
bracketMatch('WB_R1_M2', 2, 'winner', 1, 2, {
|
bracketMatch('WB_R1_M2', 2, 'winner', 1, 2, options, {
|
||||||
teamASource: seedSource(2),
|
teamASource: seedSource(2),
|
||||||
teamBSource: seedSource(3),
|
teamBSource: seedSource(3),
|
||||||
winnerAdvancesTo: destination('WB_FINAL', 'B'),
|
winnerAdvancesTo: destination('WB_FINAL', 'B'),
|
||||||
loserAdvancesTo: destination('LB_R1_M1', 'B'),
|
loserAdvancesTo: destination('LB_R1_M1', 'B'),
|
||||||
}),
|
}),
|
||||||
bracketMatch('WB_FINAL', 3, 'winner', 2, 1, {
|
bracketMatch('WB_FINAL', 3, 'winner', 2, 1, options, {
|
||||||
teamASource: winnerSource('WB_R1_M1'),
|
teamASource: winnerSource('WB_R1_M1'),
|
||||||
teamBSource: winnerSource('WB_R1_M2'),
|
teamBSource: winnerSource('WB_R1_M2'),
|
||||||
winnerAdvancesTo: destination('GF', 'A'),
|
winnerAdvancesTo: destination('GF', 'A'),
|
||||||
loserAdvancesTo: destination('LB_FINAL', 'B'),
|
loserAdvancesTo: destination('LB_FINAL', 'B'),
|
||||||
}),
|
}),
|
||||||
bracketMatch('LB_R1_M1', 4, 'loser', 1, 1, {
|
bracketMatch('LB_R1_M1', 4, 'loser', 1, 1, options, {
|
||||||
teamASource: loserSource('WB_R1_M1'),
|
teamASource: loserSource('WB_R1_M1'),
|
||||||
teamBSource: loserSource('WB_R1_M2'),
|
teamBSource: loserSource('WB_R1_M2'),
|
||||||
winnerAdvancesTo: destination('LB_FINAL', 'A'),
|
winnerAdvancesTo: destination('LB_FINAL', 'A'),
|
||||||
}),
|
}),
|
||||||
bracketMatch('LB_FINAL', 5, 'loser', 2, 1, {
|
bracketMatch('LB_FINAL', 5, 'loser', 2, 1, options, {
|
||||||
teamASource: winnerSource('LB_R1_M1'),
|
teamASource: winnerSource('LB_R1_M1'),
|
||||||
teamBSource: loserSource('WB_FINAL'),
|
teamBSource: loserSource('WB_FINAL'),
|
||||||
winnerAdvancesTo: destination('GF', 'B'),
|
winnerAdvancesTo: destination('GF', 'B'),
|
||||||
}),
|
}),
|
||||||
bracketMatch('GF', 6, 'grand-final', 1, 1, {
|
bracketMatch('GF', 6, 'grand-final', 1, 1, options, {
|
||||||
teamASource: winnerSource('WB_FINAL'),
|
teamASource: winnerSource('WB_FINAL'),
|
||||||
teamBSource: winnerSource('LB_FINAL'),
|
teamBSource: winnerSource('LB_FINAL'),
|
||||||
}),
|
}),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildEightTeamBracketMatches(): DoubleEliminationBracketMatch[] {
|
function buildEightTeamBracketMatches(
|
||||||
|
options: BuildDoubleEliminationBracketOptions,
|
||||||
|
): DoubleEliminationBracketMatch[] {
|
||||||
return [
|
return [
|
||||||
bracketMatch('WB_R1_M1', 1, 'winner', 1, 1, {
|
bracketMatch('WB_R1_M1', 1, 'winner', 1, 1, options, {
|
||||||
teamASource: seedSource(1),
|
teamASource: seedSource(1),
|
||||||
teamBSource: seedSource(8),
|
teamBSource: seedSource(8),
|
||||||
winnerAdvancesTo: destination('WB_R2_M1', 'A'),
|
winnerAdvancesTo: destination('WB_R2_M1', 'A'),
|
||||||
loserAdvancesTo: destination('LB_R1_M1', 'A'),
|
loserAdvancesTo: destination('LB_R1_M1', 'A'),
|
||||||
}),
|
}),
|
||||||
bracketMatch('WB_R1_M2', 2, 'winner', 1, 2, {
|
bracketMatch('WB_R1_M2', 2, 'winner', 1, 2, options, {
|
||||||
teamASource: seedSource(4),
|
teamASource: seedSource(4),
|
||||||
teamBSource: seedSource(5),
|
teamBSource: seedSource(5),
|
||||||
winnerAdvancesTo: destination('WB_R2_M1', 'B'),
|
winnerAdvancesTo: destination('WB_R2_M1', 'B'),
|
||||||
loserAdvancesTo: destination('LB_R1_M1', 'B'),
|
loserAdvancesTo: destination('LB_R1_M1', 'B'),
|
||||||
}),
|
}),
|
||||||
bracketMatch('WB_R1_M3', 3, 'winner', 1, 3, {
|
bracketMatch('WB_R1_M3', 3, 'winner', 1, 3, options, {
|
||||||
teamASource: seedSource(2),
|
teamASource: seedSource(2),
|
||||||
teamBSource: seedSource(7),
|
teamBSource: seedSource(7),
|
||||||
winnerAdvancesTo: destination('WB_R2_M2', 'A'),
|
winnerAdvancesTo: destination('WB_R2_M2', 'A'),
|
||||||
loserAdvancesTo: destination('LB_R1_M2', 'A'),
|
loserAdvancesTo: destination('LB_R1_M2', 'A'),
|
||||||
}),
|
}),
|
||||||
bracketMatch('WB_R1_M4', 4, 'winner', 1, 4, {
|
bracketMatch('WB_R1_M4', 4, 'winner', 1, 4, options, {
|
||||||
teamASource: seedSource(3),
|
teamASource: seedSource(3),
|
||||||
teamBSource: seedSource(6),
|
teamBSource: seedSource(6),
|
||||||
winnerAdvancesTo: destination('WB_R2_M2', 'B'),
|
winnerAdvancesTo: destination('WB_R2_M2', 'B'),
|
||||||
loserAdvancesTo: destination('LB_R1_M2', 'B'),
|
loserAdvancesTo: destination('LB_R1_M2', 'B'),
|
||||||
}),
|
}),
|
||||||
bracketMatch('WB_R2_M1', 5, 'winner', 2, 1, {
|
bracketMatch('WB_R2_M1', 5, 'winner', 2, 1, options, {
|
||||||
teamASource: winnerSource('WB_R1_M1'),
|
teamASource: winnerSource('WB_R1_M1'),
|
||||||
teamBSource: winnerSource('WB_R1_M2'),
|
teamBSource: winnerSource('WB_R1_M2'),
|
||||||
winnerAdvancesTo: destination('WB_FINAL', 'A'),
|
winnerAdvancesTo: destination('WB_FINAL', 'A'),
|
||||||
loserAdvancesTo: destination('LB_R2_M2', 'B'),
|
loserAdvancesTo: destination('LB_R2_M2', 'B'),
|
||||||
}),
|
}),
|
||||||
bracketMatch('WB_R2_M2', 6, 'winner', 2, 2, {
|
bracketMatch('WB_R2_M2', 6, 'winner', 2, 2, options, {
|
||||||
teamASource: winnerSource('WB_R1_M3'),
|
teamASource: winnerSource('WB_R1_M3'),
|
||||||
teamBSource: winnerSource('WB_R1_M4'),
|
teamBSource: winnerSource('WB_R1_M4'),
|
||||||
winnerAdvancesTo: destination('WB_FINAL', 'B'),
|
winnerAdvancesTo: destination('WB_FINAL', 'B'),
|
||||||
loserAdvancesTo: destination('LB_R2_M1', 'B'),
|
loserAdvancesTo: destination('LB_R2_M1', 'B'),
|
||||||
}),
|
}),
|
||||||
bracketMatch('WB_FINAL', 7, 'winner', 3, 1, {
|
bracketMatch('WB_FINAL', 7, 'winner', 3, 1, options, {
|
||||||
teamASource: winnerSource('WB_R2_M1'),
|
teamASource: winnerSource('WB_R2_M1'),
|
||||||
teamBSource: winnerSource('WB_R2_M2'),
|
teamBSource: winnerSource('WB_R2_M2'),
|
||||||
winnerAdvancesTo: destination('GF', 'A'),
|
winnerAdvancesTo: destination('GF', 'A'),
|
||||||
loserAdvancesTo: destination('LB_FINAL', 'B'),
|
loserAdvancesTo: destination('LB_FINAL', 'B'),
|
||||||
}),
|
}),
|
||||||
bracketMatch('LB_R1_M1', 8, 'loser', 1, 1, {
|
bracketMatch('LB_R1_M1', 8, 'loser', 1, 1, options, {
|
||||||
teamASource: loserSource('WB_R1_M1'),
|
teamASource: loserSource('WB_R1_M1'),
|
||||||
teamBSource: loserSource('WB_R1_M2'),
|
teamBSource: loserSource('WB_R1_M2'),
|
||||||
winnerAdvancesTo: destination('LB_R2_M1', 'A'),
|
winnerAdvancesTo: destination('LB_R2_M1', 'A'),
|
||||||
}),
|
}),
|
||||||
bracketMatch('LB_R1_M2', 9, 'loser', 1, 2, {
|
bracketMatch('LB_R1_M2', 9, 'loser', 1, 2, options, {
|
||||||
teamASource: loserSource('WB_R1_M3'),
|
teamASource: loserSource('WB_R1_M3'),
|
||||||
teamBSource: loserSource('WB_R1_M4'),
|
teamBSource: loserSource('WB_R1_M4'),
|
||||||
winnerAdvancesTo: destination('LB_R2_M2', 'A'),
|
winnerAdvancesTo: destination('LB_R2_M2', 'A'),
|
||||||
}),
|
}),
|
||||||
bracketMatch('LB_R2_M1', 10, 'loser', 2, 1, {
|
bracketMatch('LB_R2_M1', 10, 'loser', 2, 1, options, {
|
||||||
teamASource: winnerSource('LB_R1_M1'),
|
teamASource: winnerSource('LB_R1_M1'),
|
||||||
teamBSource: loserSource('WB_R2_M2'),
|
teamBSource: loserSource('WB_R2_M2'),
|
||||||
winnerAdvancesTo: destination('LB_R3_M1', 'A'),
|
winnerAdvancesTo: destination('LB_R3_M1', 'A'),
|
||||||
}),
|
}),
|
||||||
bracketMatch('LB_R2_M2', 11, 'loser', 2, 2, {
|
bracketMatch('LB_R2_M2', 11, 'loser', 2, 2, options, {
|
||||||
teamASource: winnerSource('LB_R1_M2'),
|
teamASource: winnerSource('LB_R1_M2'),
|
||||||
teamBSource: loserSource('WB_R2_M1'),
|
teamBSource: loserSource('WB_R2_M1'),
|
||||||
winnerAdvancesTo: destination('LB_R3_M1', 'B'),
|
winnerAdvancesTo: destination('LB_R3_M1', 'B'),
|
||||||
}),
|
}),
|
||||||
bracketMatch('LB_R3_M1', 12, 'loser', 3, 1, {
|
bracketMatch('LB_R3_M1', 12, 'loser', 3, 1, options, {
|
||||||
teamASource: winnerSource('LB_R2_M1'),
|
teamASource: winnerSource('LB_R2_M1'),
|
||||||
teamBSource: winnerSource('LB_R2_M2'),
|
teamBSource: winnerSource('LB_R2_M2'),
|
||||||
winnerAdvancesTo: destination('LB_FINAL', 'A'),
|
winnerAdvancesTo: destination('LB_FINAL', 'A'),
|
||||||
}),
|
}),
|
||||||
bracketMatch('LB_FINAL', 13, 'loser', 4, 1, {
|
bracketMatch('LB_FINAL', 13, 'loser', 4, 1, options, {
|
||||||
teamASource: winnerSource('LB_R3_M1'),
|
teamASource: winnerSource('LB_R3_M1'),
|
||||||
teamBSource: loserSource('WB_FINAL'),
|
teamBSource: loserSource('WB_FINAL'),
|
||||||
winnerAdvancesTo: destination('GF', 'B'),
|
winnerAdvancesTo: destination('GF', 'B'),
|
||||||
}),
|
}),
|
||||||
bracketMatch('GF', 14, 'grand-final', 1, 1, {
|
bracketMatch('GF', 14, 'grand-final', 1, 1, options, {
|
||||||
teamASource: winnerSource('WB_FINAL'),
|
teamASource: winnerSource('WB_FINAL'),
|
||||||
teamBSource: winnerSource('LB_FINAL'),
|
teamBSource: winnerSource('LB_FINAL'),
|
||||||
}),
|
}),
|
||||||
@@ -542,11 +652,18 @@ function bracketMatch(
|
|||||||
bracketSide: DoubleEliminationBracketSide,
|
bracketSide: DoubleEliminationBracketSide,
|
||||||
roundNumber: number,
|
roundNumber: number,
|
||||||
matchNumber: number,
|
matchNumber: number,
|
||||||
|
options: BuildDoubleEliminationBracketOptions,
|
||||||
params: Partial<DoubleEliminationBracketMatch>,
|
params: Partial<DoubleEliminationBracketMatch>,
|
||||||
): DoubleEliminationBracketMatch {
|
): DoubleEliminationBracketMatch {
|
||||||
|
const rule = resolveDoubleEliminationSeriesRule(
|
||||||
|
{ bracketMatchId, bracketSide, roundNumber },
|
||||||
|
options,
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
bracketMatchId,
|
bracketMatchId,
|
||||||
gameNumber,
|
gameNumber,
|
||||||
|
gameCount: params.gameCount ?? rule.gameCount,
|
||||||
|
requiredWins: params.requiredWins ?? rule.requiredWins,
|
||||||
bracketSide,
|
bracketSide,
|
||||||
roundNumber,
|
roundNumber,
|
||||||
matchNumber,
|
matchNumber,
|
||||||
@@ -617,7 +734,14 @@ function requireBracketMatch(
|
|||||||
const bracketMatch = bracket.bracketMatches.find(
|
const bracketMatch = bracket.bracketMatches.find(
|
||||||
(match) => match.bracketMatchId === bracketMatchId,
|
(match) => match.bracketMatchId === bracketMatchId,
|
||||||
);
|
);
|
||||||
if (!bracketMatch) throw new Error('Bracket match not found.');
|
if (!bracketMatch) {
|
||||||
|
throw new Error(
|
||||||
|
`Bracket match not found: ${bracketMatchId}. Available: ${bracket.bracketMatches
|
||||||
|
.map((match) => match.bracketMatchId)
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(', ')}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
return bracketMatch;
|
return bracketMatch;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -627,43 +751,81 @@ function assertSeedChangeAllowed(bracket: DoubleEliminationBracket): void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function assertSupportedTeamCount(teamCount: number): asserts teamCount is 4 | 8 {
|
function assertSupportedTeamCount(
|
||||||
|
teamCount: number,
|
||||||
|
): asserts teamCount is 4 | 8 {
|
||||||
if (teamCount !== 4 && teamCount !== 8) {
|
if (teamCount !== 4 && teamCount !== 8) {
|
||||||
throw new Error('Double elimination supports only 4 or 8 teams.');
|
throw new Error('Double elimination supports only 4 or 8 teams.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function nextGameNumber(bracket: DoubleEliminationBracket): number {
|
function nextGameNumber(bracket: DoubleEliminationBracket): number {
|
||||||
return Math.max(...bracket.bracketMatches.map((match) => match.gameNumber)) + 1;
|
return (
|
||||||
|
Math.max(...bracket.bracketMatches.map((match) => match.gameNumber)) + 1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function seriesRule(gameCount: number): DoubleEliminationSeriesRule {
|
||||||
|
const normalizedGameCount = normalizeSeriesGameCount(gameCount);
|
||||||
|
return {
|
||||||
|
gameCount: normalizedGameCount,
|
||||||
|
requiredWins: requiredWinsForGameCount(normalizedGameCount),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeSeriesGameCount(gameCount: number | undefined): number {
|
||||||
|
if (!Number.isInteger(gameCount) || !gameCount || gameCount < 1) return 1;
|
||||||
|
return gameCount % 2 === 0 ? gameCount + 1 : gameCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
function requiredWinsForGameCount(gameCount: number): number {
|
||||||
|
return Math.floor(gameCount / 2) + 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
function cloneBracket(
|
function cloneBracket(
|
||||||
bracket: DoubleEliminationBracket,
|
bracket: DoubleEliminationBracket,
|
||||||
): DoubleEliminationBracket {
|
): DoubleEliminationBracket {
|
||||||
|
const plainBracket = toPlainObject(bracket);
|
||||||
return {
|
return {
|
||||||
...bracket,
|
...plainBracket,
|
||||||
seeds: bracket.seeds.map((seed) => ({ ...seed })),
|
seeds: plainBracket.seeds.map((seed) => ({ ...toPlainObject(seed) })),
|
||||||
bracketMatches: bracket.bracketMatches.map((match) => ({
|
bracketMatches: plainBracket.bracketMatches.map((rawMatch) => {
|
||||||
...match,
|
const match = toPlainObject(rawMatch);
|
||||||
teamASource: match.teamASource ? { ...match.teamASource } : undefined,
|
return {
|
||||||
teamBSource: match.teamBSource ? { ...match.teamBSource } : undefined,
|
...match,
|
||||||
winnerAdvancesTo: match.winnerAdvancesTo
|
teamASource: match.teamASource
|
||||||
? { ...match.winnerAdvancesTo }
|
? { ...toPlainObject(match.teamASource) }
|
||||||
: undefined,
|
: undefined,
|
||||||
loserAdvancesTo: match.loserAdvancesTo
|
teamBSource: match.teamBSource
|
||||||
? { ...match.loserAdvancesTo }
|
? { ...toPlainObject(match.teamBSource) }
|
||||||
: undefined,
|
: undefined,
|
||||||
walkover: match.walkover ? { ...match.walkover } : undefined,
|
winnerAdvancesTo: match.winnerAdvancesTo
|
||||||
|
? { ...toPlainObject(match.winnerAdvancesTo) }
|
||||||
|
: undefined,
|
||||||
|
loserAdvancesTo: match.loserAdvancesTo
|
||||||
|
? { ...toPlainObject(match.loserAdvancesTo) }
|
||||||
|
: undefined,
|
||||||
|
walkover: match.walkover
|
||||||
|
? { ...toPlainObject(match.walkover) }
|
||||||
|
: undefined,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
placements: { ...toPlainObject(plainBracket.placements) },
|
||||||
|
events: plainBracket.events.map((event) => ({
|
||||||
|
...toPlainObject(event),
|
||||||
})),
|
})),
|
||||||
placements: { ...bracket.placements },
|
|
||||||
events: bracket.events.map((event) => ({ ...event })),
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function shuffleInPlace<T>(
|
function toPlainObject<T>(value: T): T {
|
||||||
items: T[],
|
const candidate = value as { toObject?: () => T };
|
||||||
rng: () => number = Math.random,
|
if (candidate && typeof candidate.toObject === 'function') {
|
||||||
): T[] {
|
return candidate.toObject();
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function shuffleInPlace<T>(items: T[], rng: () => number = Math.random): T[] {
|
||||||
for (let index = items.length - 1; index > 0; index -= 1) {
|
for (let index = items.length - 1; index > 0; index -= 1) {
|
||||||
const swapIndex = Math.floor(rng() * (index + 1));
|
const swapIndex = Math.floor(rng() * (index + 1));
|
||||||
[items[index], items[swapIndex]] = [items[swapIndex], items[index]];
|
[items[index], items[swapIndex]] = [items[swapIndex], items[index]];
|
||||||
|
|||||||
+58
-12
@@ -347,20 +347,22 @@ describe('migrateTournamentCodeUniqueIndexes', () => {
|
|||||||
indexesDropped: 3,
|
indexesDropped: 3,
|
||||||
matchesUpdated: 1,
|
matchesUpdated: 1,
|
||||||
});
|
});
|
||||||
expect(collections.tournamentCode.find((code) => code._id === 'code-2')).toMatchObject({
|
expect(
|
||||||
|
collections.tournamentCode.find((code) => code._id === 'code-2'),
|
||||||
|
).toMatchObject({
|
||||||
code: 'B',
|
code: 'B',
|
||||||
releasedAt: now,
|
releasedAt: now,
|
||||||
state: 'released',
|
state: 'released',
|
||||||
});
|
});
|
||||||
expect(collections.tournamentCode.find((code) => code._id === 'code-2')).not.toHaveProperty(
|
expect(
|
||||||
'matchId',
|
collections.tournamentCode.find((code) => code._id === 'code-2'),
|
||||||
);
|
).not.toHaveProperty('matchId');
|
||||||
expect(collections.tournamentCode.find((code) => code._id === 'code-4')).not.toHaveProperty(
|
expect(
|
||||||
'riotMatchId',
|
collections.tournamentCode.find((code) => code._id === 'code-4'),
|
||||||
);
|
).not.toHaveProperty('riotMatchId');
|
||||||
expect(collections.tournamentCode.find((code) => code._id === 'code-5')).not.toHaveProperty(
|
expect(
|
||||||
'riotMatchId',
|
collections.tournamentCode.find((code) => code._id === 'code-5'),
|
||||||
);
|
).not.toHaveProperty('riotMatchId');
|
||||||
expect(collections.match[0].tournamentCodeIds).toEqual(['code-1']);
|
expect(collections.match[0].tournamentCodeIds).toEqual(['code-1']);
|
||||||
expect(indexes).toEqual(
|
expect(indexes).toEqual(
|
||||||
expect.arrayContaining([
|
expect.arrayContaining([
|
||||||
@@ -375,7 +377,9 @@ describe('migrateTournamentCodeUniqueIndexes', () => {
|
|||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
key: { matchId: 1, bracketMatchId: 1 },
|
key: { matchId: 1, bracketMatchId: 1 },
|
||||||
name: 'matchId_1_bracketMatchId_1',
|
name: 'matchId_1_bracketMatchId_1',
|
||||||
unique: true,
|
partialFilterExpression: expect.objectContaining({
|
||||||
|
state: { $in: ['reserved', 'used'] },
|
||||||
|
}),
|
||||||
}),
|
}),
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
key: { riotMatchId: 1 },
|
key: { riotMatchId: 1 },
|
||||||
@@ -421,7 +425,6 @@ describe('migrateTournamentCodeUniqueIndexes', () => {
|
|||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
key: { matchId: 1, bracketMatchId: 1 },
|
key: { matchId: 1, bracketMatchId: 1 },
|
||||||
name: 'matchId_1_bracketMatchId_1',
|
name: 'matchId_1_bracketMatchId_1',
|
||||||
unique: true,
|
|
||||||
}),
|
}),
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
key: { riotMatchId: 1 },
|
key: { riotMatchId: 1 },
|
||||||
@@ -501,6 +504,49 @@ describe('migrateTournamentCodeUniqueIndexes', () => {
|
|||||||
expect(JSON.stringify(collections.match)).toBe(beforeMatches);
|
expect(JSON.stringify(collections.match)).toBe(beforeMatches);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('allows multiple active codes for the same double-elimination bracket match', async () => {
|
||||||
|
const { db, collections } = createDb({
|
||||||
|
codes: [
|
||||||
|
{
|
||||||
|
_id: 'code-1',
|
||||||
|
matchId: 'match-1',
|
||||||
|
gameNumber: 1,
|
||||||
|
bracketMatchId: 'WB_R1_M1',
|
||||||
|
state: 'reserved',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
_id: 'code-2',
|
||||||
|
matchId: 'match-1',
|
||||||
|
gameNumber: 2,
|
||||||
|
bracketMatchId: 'WB_R1_M1',
|
||||||
|
state: 'reserved',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
matches: [{ _id: 'match-1', tournamentCodeIds: ['code-1', 'code-2'] }],
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await migrateTournamentCodeUniqueIndexes(db, {
|
||||||
|
dryRun: false,
|
||||||
|
createIndexes: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.stats).toMatchObject({
|
||||||
|
duplicateBracketMatchGroups: 0,
|
||||||
|
duplicateCodesReleased: 0,
|
||||||
|
duplicateCodesToRelease: 0,
|
||||||
|
});
|
||||||
|
expect(collections.tournamentCode).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
expect.objectContaining({ _id: 'code-1', state: 'reserved' }),
|
||||||
|
expect.objectContaining({ _id: 'code-2', state: 'reserved' }),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
expect(collections.match[0].tournamentCodeIds).toEqual([
|
||||||
|
'code-1',
|
||||||
|
'code-2',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
it('unsets blank riot match ids without treating them as duplicate releases', async () => {
|
it('unsets blank riot match ids without treating them as duplicate releases', async () => {
|
||||||
const { db, collections } = createDb({
|
const { db, collections } = createDb({
|
||||||
codes: [
|
codes: [
|
||||||
|
|||||||
+14
-7
@@ -151,7 +151,13 @@ export interface TournamentCodeUniqueIndexMigrationResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface TournamentCodeUniqueIndexMigrationProgress {
|
export interface TournamentCodeUniqueIndexMigrationProgress {
|
||||||
action?: 'alreadyCorrect' | 'create' | 'created' | 'drop' | 'dropped' | 'list';
|
action?:
|
||||||
|
| 'alreadyCorrect'
|
||||||
|
| 'create'
|
||||||
|
| 'created'
|
||||||
|
| 'drop'
|
||||||
|
| 'dropped'
|
||||||
|
| 'list';
|
||||||
phase:
|
phase:
|
||||||
| 'scanMatches'
|
| 'scanMatches'
|
||||||
| 'scanTournamentCodes'
|
| 'scanTournamentCodes'
|
||||||
@@ -205,7 +211,6 @@ const DESIRED_TOURNAMENT_CODE_INDEXES: DesiredIndex[] = [
|
|||||||
key: { matchId: 1, bracketMatchId: 1 },
|
key: { matchId: 1, bracketMatchId: 1 },
|
||||||
options: {
|
options: {
|
||||||
name: 'matchId_1_bracketMatchId_1',
|
name: 'matchId_1_bracketMatchId_1',
|
||||||
unique: true,
|
|
||||||
partialFilterExpression: {
|
partialFilterExpression: {
|
||||||
matchId: { $exists: true },
|
matchId: { $exists: true },
|
||||||
bracketMatchId: { $exists: true },
|
bracketMatchId: { $exists: true },
|
||||||
@@ -414,7 +419,6 @@ function findDuplicateGroups(
|
|||||||
): DuplicateGroup[] {
|
): DuplicateGroup[] {
|
||||||
return [
|
return [
|
||||||
...duplicateGroupsFor(docs, referencedCodeIds, 'gameNumber'),
|
...duplicateGroupsFor(docs, referencedCodeIds, 'gameNumber'),
|
||||||
...duplicateGroupsFor(docs, referencedCodeIds, 'bracketMatchId'),
|
|
||||||
...duplicateGroupsFor(docs, referencedCodeIds, 'riotMatchId'),
|
...duplicateGroupsFor(docs, referencedCodeIds, 'riotMatchId'),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -514,7 +518,8 @@ function summarizeCode(doc: TournamentCodeDoc): TournamentCodeDuplicateSummary {
|
|||||||
bracketMatchId:
|
bracketMatchId:
|
||||||
doc.bracketMatchId === undefined ? undefined : String(doc.bracketMatchId),
|
doc.bracketMatchId === undefined ? undefined : String(doc.bracketMatchId),
|
||||||
code: doc.code === undefined ? undefined : String(doc.code),
|
code: doc.code === undefined ? undefined : String(doc.code),
|
||||||
gameNumber: doc.gameNumber === undefined ? undefined : String(doc.gameNumber),
|
gameNumber:
|
||||||
|
doc.gameNumber === undefined ? undefined : String(doc.gameNumber),
|
||||||
id: stringifyId(doc._id) ?? '',
|
id: stringifyId(doc._id) ?? '',
|
||||||
matchId: doc.matchId === undefined ? undefined : stringifyId(doc.matchId),
|
matchId: doc.matchId === undefined ? undefined : stringifyId(doc.matchId),
|
||||||
riotMatchId:
|
riotMatchId:
|
||||||
@@ -576,7 +581,9 @@ function compareCodePriority(
|
|||||||
const rightDate = latestTimestamp(right);
|
const rightDate = latestTimestamp(right);
|
||||||
if (leftDate !== rightDate) return rightDate - leftDate;
|
if (leftDate !== rightDate) return rightDate - leftDate;
|
||||||
|
|
||||||
return (stringifyId(left._id) ?? '').localeCompare(stringifyId(right._id) ?? '');
|
return (stringifyId(left._id) ?? '').localeCompare(
|
||||||
|
stringifyId(right._id) ?? '',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function stateRank(state: unknown): number {
|
function stateRank(state: unknown): number {
|
||||||
@@ -715,8 +722,8 @@ function isNamespaceNotFoundError(error: unknown): boolean {
|
|||||||
};
|
};
|
||||||
return Boolean(
|
return Boolean(
|
||||||
candidate?.code === 26 ||
|
candidate?.code === 26 ||
|
||||||
candidate?.codeName === 'NamespaceNotFound' ||
|
candidate?.codeName === 'NamespaceNotFound' ||
|
||||||
candidate?.message?.includes('ns does not exist'),
|
candidate?.message?.includes('ns does not exist'),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+94
@@ -0,0 +1,94 @@
|
|||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { buildRepairPlan } from './repair-double-elimination-series-rules';
|
||||||
|
import type { MatchDocument, TournamentCodeDocument } from '../schema';
|
||||||
|
|
||||||
|
function createMatch(overrides: Partial<MatchDocument>): MatchDocument {
|
||||||
|
return {
|
||||||
|
_id: new mongoose.Types.ObjectId(),
|
||||||
|
gameCount: 3,
|
||||||
|
tournamentCodeIds: [],
|
||||||
|
doubleElimination: {
|
||||||
|
teamCount: 8,
|
||||||
|
resetFinalEnabled: false,
|
||||||
|
resetFinalCreated: false,
|
||||||
|
seeds: [],
|
||||||
|
bracketMatches: [],
|
||||||
|
placements: {},
|
||||||
|
events: [],
|
||||||
|
},
|
||||||
|
...overrides,
|
||||||
|
} as unknown as MatchDocument;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createCode(
|
||||||
|
overrides: Partial<TournamentCodeDocument>,
|
||||||
|
): TournamentCodeDocument {
|
||||||
|
return {
|
||||||
|
_id: new mongoose.Types.ObjectId(),
|
||||||
|
code: 'CODE',
|
||||||
|
state: 'reserved',
|
||||||
|
...overrides,
|
||||||
|
} as unknown as TournamentCodeDocument;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('repair-double-elimination-series-rules buildRepairPlan', () => {
|
||||||
|
it('plans missing ready series slots even when result games already exist', () => {
|
||||||
|
const match = createMatch({
|
||||||
|
result: {
|
||||||
|
riotMatchIds: ['KR_1'],
|
||||||
|
games: [
|
||||||
|
{
|
||||||
|
gameNumber: 1,
|
||||||
|
bracketMatchId: 'WB_R2_M1',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
seriesResults: [],
|
||||||
|
},
|
||||||
|
doubleElimination: {
|
||||||
|
teamCount: 8,
|
||||||
|
resetFinalEnabled: false,
|
||||||
|
resetFinalCreated: false,
|
||||||
|
seeds: [],
|
||||||
|
bracketMatches: [
|
||||||
|
{
|
||||||
|
bracketMatchId: 'WB_R2_M1',
|
||||||
|
gameNumber: 1,
|
||||||
|
gameCount: 3,
|
||||||
|
requiredWins: 2,
|
||||||
|
bracketSide: 'winner',
|
||||||
|
roundNumber: 2,
|
||||||
|
matchNumber: 1,
|
||||||
|
state: 'ready',
|
||||||
|
teamAIndex: 4,
|
||||||
|
teamBIndex: 6,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
placements: {},
|
||||||
|
events: [],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const existingFirstSetCode = createCode({
|
||||||
|
bracketMatchId: 'WB_R2_M1',
|
||||||
|
gameNumber: 1,
|
||||||
|
});
|
||||||
|
|
||||||
|
const plan = buildRepairPlan(match, [existingFirstSetCode], 3);
|
||||||
|
|
||||||
|
expect(plan.ruleRepairSkippedReason).toBe('result-games-exist');
|
||||||
|
expect(plan.codeUpdates).toEqual([]);
|
||||||
|
expect(plan.missingReadySlots).toEqual([
|
||||||
|
{
|
||||||
|
bracketMatchId: 'WB_R2_M1',
|
||||||
|
gameNumber: 2,
|
||||||
|
seriesGameNumber: 2,
|
||||||
|
seriesGameCount: 3,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
bracketMatchId: 'WB_R2_M1',
|
||||||
|
gameNumber: 3,
|
||||||
|
seriesGameNumber: 3,
|
||||||
|
seriesGameCount: 3,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
+470
@@ -0,0 +1,470 @@
|
|||||||
|
import 'reflect-metadata';
|
||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { ConfigModule } from '@nestjs/config';
|
||||||
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { readFile } from 'node:fs/promises';
|
||||||
|
import { resolve } from 'node:path';
|
||||||
|
import {
|
||||||
|
buildDoubleEliminationGameSlots,
|
||||||
|
type DoubleEliminationBracketMatch,
|
||||||
|
} from '../../../double-elimination/double-elimination.util';
|
||||||
|
import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../../../tournament-code/tournament-code.constants';
|
||||||
|
import { ConnectionService } from '../connection.service';
|
||||||
|
import type { MatchDocument, TournamentCodeDocument } from '../schema';
|
||||||
|
import { SecretModule } from '../../secret/secret.module';
|
||||||
|
|
||||||
|
interface CliOptions {
|
||||||
|
dryRun: boolean;
|
||||||
|
matchId?: mongoose.Types.ObjectId;
|
||||||
|
nodeEnv: string;
|
||||||
|
winnerGameCount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CodeUpdatePlan {
|
||||||
|
codeId: mongoose.Types.ObjectId;
|
||||||
|
code: string;
|
||||||
|
bracketMatchId: string;
|
||||||
|
currentGameNumber: number | undefined;
|
||||||
|
nextGameNumber: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MissingReadySlotPlan {
|
||||||
|
bracketMatchId: string;
|
||||||
|
gameNumber: number;
|
||||||
|
seriesGameNumber: number;
|
||||||
|
seriesGameCount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MatchRepairPlan {
|
||||||
|
codeUpdates: CodeUpdatePlan[];
|
||||||
|
currentGameCount: number;
|
||||||
|
matchId: mongoose.Types.ObjectId;
|
||||||
|
missingReadySlots: MissingReadySlotPlan[];
|
||||||
|
nextGameCount: number;
|
||||||
|
nextBracketMatches: DoubleEliminationBracketMatch[];
|
||||||
|
ruleRepairSkippedReason?: string;
|
||||||
|
skippedReason?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
ConfigModule.forRoot({
|
||||||
|
isGlobal: true,
|
||||||
|
envFilePath: [
|
||||||
|
resolve(__dirname, '../../../../../../project.env'),
|
||||||
|
resolve(process.cwd(), '../project.env'),
|
||||||
|
resolve(process.cwd(), 'apps/project.env'),
|
||||||
|
resolve(process.cwd(), 'project.env'),
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
SecretModule,
|
||||||
|
],
|
||||||
|
providers: [ConnectionService],
|
||||||
|
})
|
||||||
|
class RepairModule {}
|
||||||
|
|
||||||
|
async function loadMachineEnvFile() {
|
||||||
|
const homeDir = process.env.HOME ?? process.env.USERPROFILE;
|
||||||
|
if (!homeDir) return;
|
||||||
|
|
||||||
|
const machineEnvFile = resolve(homeDir, 'source/global-env-vars.txt');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const file = await readFile(machineEnvFile, 'utf8');
|
||||||
|
for (const rawLine of file.split(/\r?\n/)) {
|
||||||
|
const line = rawLine.trim();
|
||||||
|
if (!line || line.startsWith('#')) continue;
|
||||||
|
const matched = line.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
|
||||||
|
if (!matched) continue;
|
||||||
|
const [, key, rawValue] = matched;
|
||||||
|
process.env[key] = rawValue.replace(/^["']|["']$/g, '');
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Local machine env is optional for one-off migrations.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseArgs(argv: string[]): CliOptions {
|
||||||
|
let dryRun = true;
|
||||||
|
let matchId: mongoose.Types.ObjectId | undefined;
|
||||||
|
let nodeEnv = process.env.NODE_ENV ?? 'dev';
|
||||||
|
let winnerGameCount = 3;
|
||||||
|
|
||||||
|
for (let index = 0; index < argv.length; index += 1) {
|
||||||
|
const arg = argv[index];
|
||||||
|
if (arg === '--apply') {
|
||||||
|
dryRun = false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (arg === '--dry-run') {
|
||||||
|
dryRun = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (arg === '--env') {
|
||||||
|
const value = argv[index + 1];
|
||||||
|
if (!value) throw new Error('--env requires dev, staging, or prod.');
|
||||||
|
nodeEnv = value;
|
||||||
|
index += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (arg.startsWith('--env=')) {
|
||||||
|
nodeEnv = arg.slice('--env='.length);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (arg === '--match-id') {
|
||||||
|
matchId = parseObjectId(argv[index + 1], '--match-id');
|
||||||
|
index += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (arg.startsWith('--match-id=')) {
|
||||||
|
matchId = parseObjectId(arg.slice('--match-id='.length), '--match-id');
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (arg === '--winner-game-count') {
|
||||||
|
winnerGameCount = parseOddPositiveInteger(
|
||||||
|
argv[index + 1],
|
||||||
|
'--winner-game-count',
|
||||||
|
);
|
||||||
|
index += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (arg.startsWith('--winner-game-count=')) {
|
||||||
|
winnerGameCount = parseOddPositiveInteger(
|
||||||
|
arg.slice('--winner-game-count='.length),
|
||||||
|
'--winner-game-count',
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (arg === '--help' || arg === '-h') {
|
||||||
|
printHelp();
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
throw new Error(`Unknown argument: ${arg}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!['dev', 'staging', 'prod'].includes(nodeEnv)) {
|
||||||
|
throw new Error('--env must be dev, staging, or prod.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return { dryRun, matchId, nodeEnv, winnerGameCount };
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseObjectId(value: string | undefined, label: string) {
|
||||||
|
if (!value || !mongoose.isValidObjectId(value)) {
|
||||||
|
throw new Error(`${label} requires a valid ObjectId.`);
|
||||||
|
}
|
||||||
|
return new mongoose.Types.ObjectId(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseOddPositiveInteger(value: string | undefined, label: string) {
|
||||||
|
const parsed = Number(value);
|
||||||
|
if (!Number.isInteger(parsed) || parsed < 1 || parsed % 2 === 0) {
|
||||||
|
throw new Error(`${label} requires a positive odd integer.`);
|
||||||
|
}
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
function printHelp() {
|
||||||
|
console.log(`Usage:
|
||||||
|
pnpm --filter api exec ts-node src/modules/global/database/migrations/repair-double-elimination-series-rules.ts --match-id <id> --dry-run
|
||||||
|
pnpm --filter api exec ts-node src/modules/global/database/migrations/repair-double-elimination-series-rules.ts --match-id <id> --env prod --apply
|
||||||
|
|
||||||
|
Options:
|
||||||
|
--match-id <id> Optional match ObjectId. If omitted, scans all double-elimination matches.
|
||||||
|
--winner-game-count <n> Winner-bracket series size. Must be odd. Default: 3.
|
||||||
|
--dry-run Print the repair plan without writing. Default.
|
||||||
|
--apply Apply match and tournament code updates.
|
||||||
|
--env <env> dev | staging | prod. Default: NODE_ENV or dev.
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function requiredWinsFor(gameCount: number): number {
|
||||||
|
return Math.floor(gameCount / 2) + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
function codeSlotKey(
|
||||||
|
bracketMatchId: string | undefined,
|
||||||
|
gameNumber: number | undefined,
|
||||||
|
): string | undefined {
|
||||||
|
if (!bracketMatchId || typeof gameNumber !== 'number') return undefined;
|
||||||
|
return `${bracketMatchId}:${gameNumber}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildActiveCodeSlotKeys(
|
||||||
|
codes: TournamentCodeDocument[],
|
||||||
|
codeUpdates: CodeUpdatePlan[] = [],
|
||||||
|
): Set<string> {
|
||||||
|
const updateByCodeId = new Map(
|
||||||
|
codeUpdates.map((update) => [update.codeId.toString(), update]),
|
||||||
|
);
|
||||||
|
const activeSlotKeys = new Set<string>();
|
||||||
|
|
||||||
|
for (const code of codes) {
|
||||||
|
if (code.state !== 'reserved' && code.state !== 'used') continue;
|
||||||
|
const update = updateByCodeId.get(code._id.toString());
|
||||||
|
const key = codeSlotKey(
|
||||||
|
update?.bracketMatchId ?? code.bracketMatchId,
|
||||||
|
update?.nextGameNumber ?? code.gameNumber,
|
||||||
|
);
|
||||||
|
if (key) activeSlotKeys.add(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
return activeSlotKeys;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildMissingReadySlots(
|
||||||
|
bracketMatches: DoubleEliminationBracketMatch[],
|
||||||
|
codes: TournamentCodeDocument[],
|
||||||
|
codeUpdates: CodeUpdatePlan[] = [],
|
||||||
|
): MissingReadySlotPlan[] {
|
||||||
|
const activeSlotKeys = buildActiveCodeSlotKeys(codes, codeUpdates);
|
||||||
|
|
||||||
|
return buildDoubleEliminationGameSlots(bracketMatches)
|
||||||
|
.filter((slot) => slot.bracketMatch.state === 'ready')
|
||||||
|
.filter(
|
||||||
|
(slot) =>
|
||||||
|
!activeSlotKeys.has(
|
||||||
|
`${slot.bracketMatch.bracketMatchId}:${slot.gameNumber}`,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.map((slot) => ({
|
||||||
|
bracketMatchId: slot.bracketMatch.bracketMatchId,
|
||||||
|
gameNumber: slot.gameNumber,
|
||||||
|
seriesGameNumber: slot.seriesGameNumber,
|
||||||
|
seriesGameCount: slot.seriesGameCount,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildRepairPlan(
|
||||||
|
match: MatchDocument,
|
||||||
|
codes: TournamentCodeDocument[],
|
||||||
|
winnerGameCount: number,
|
||||||
|
): MatchRepairPlan {
|
||||||
|
const currentGameCount = match.gameCount;
|
||||||
|
const resultGames = match.result?.games ?? [];
|
||||||
|
const currentBracketMatches = [
|
||||||
|
...(match.doubleElimination?.bracketMatches ?? []),
|
||||||
|
];
|
||||||
|
if (resultGames.length > 0) {
|
||||||
|
return {
|
||||||
|
codeUpdates: [],
|
||||||
|
currentGameCount,
|
||||||
|
matchId: match._id,
|
||||||
|
missingReadySlots: buildMissingReadySlots(currentBracketMatches, codes),
|
||||||
|
nextBracketMatches: currentBracketMatches,
|
||||||
|
nextGameCount: currentGameCount,
|
||||||
|
ruleRepairSkippedReason: 'result-games-exist',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextBracketMatches = currentBracketMatches.map((bracketMatch) => {
|
||||||
|
const gameCount =
|
||||||
|
bracketMatch.bracketSide === 'winner' ? winnerGameCount : 1;
|
||||||
|
return {
|
||||||
|
...bracketMatch,
|
||||||
|
gameCount,
|
||||||
|
requiredWins: requiredWinsFor(gameCount),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
const firstSlotByBracketMatchId = new Map(
|
||||||
|
buildDoubleEliminationGameSlots(nextBracketMatches)
|
||||||
|
.filter((slot) => slot.seriesGameNumber === 1)
|
||||||
|
.map((slot) => [slot.bracketMatch.bracketMatchId, slot]),
|
||||||
|
);
|
||||||
|
const codeUpdates = codes
|
||||||
|
.filter((code) => code.bracketMatchId)
|
||||||
|
.map((code) => {
|
||||||
|
const slot = firstSlotByBracketMatchId.get(code.bracketMatchId!);
|
||||||
|
if (!slot) return null;
|
||||||
|
if (code.gameNumber === slot.gameNumber) return null;
|
||||||
|
return {
|
||||||
|
codeId: code._id,
|
||||||
|
code: code.code,
|
||||||
|
bracketMatchId: code.bracketMatchId!,
|
||||||
|
currentGameNumber: code.gameNumber,
|
||||||
|
nextGameNumber: slot.gameNumber,
|
||||||
|
} satisfies CodeUpdatePlan;
|
||||||
|
})
|
||||||
|
.filter((entry): entry is CodeUpdatePlan => Boolean(entry));
|
||||||
|
const missingReadySlots = buildMissingReadySlots(
|
||||||
|
nextBracketMatches,
|
||||||
|
codes,
|
||||||
|
codeUpdates,
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
codeUpdates,
|
||||||
|
currentGameCount,
|
||||||
|
matchId: match._id,
|
||||||
|
missingReadySlots,
|
||||||
|
nextGameCount: Math.max(currentGameCount ?? 1, winnerGameCount),
|
||||||
|
nextBracketMatches,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function printPlan(plan: MatchRepairPlan) {
|
||||||
|
console.log(`match=${plan.matchId.toString()}`);
|
||||||
|
if (plan.skippedReason) {
|
||||||
|
console.log(` skipped=${plan.skippedReason}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (plan.ruleRepairSkippedReason) {
|
||||||
|
console.log(` ruleRepairSkipped=${plan.ruleRepairSkippedReason}`);
|
||||||
|
} else {
|
||||||
|
console.log(
|
||||||
|
` gameCount: ${plan.currentGameCount} -> ${plan.nextGameCount}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
console.log(
|
||||||
|
` bracketMatches=${plan.nextBracketMatches.length} codeUpdates=${plan.codeUpdates.length} missingReadySlots=${plan.missingReadySlots.length}`,
|
||||||
|
);
|
||||||
|
for (const update of plan.codeUpdates) {
|
||||||
|
console.log(
|
||||||
|
` code ${update.code} ${update.bracketMatchId}: ${update.currentGameNumber ?? 'unset'} -> ${update.nextGameNumber}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for (const slot of plan.missingReadySlots) {
|
||||||
|
console.log(
|
||||||
|
` missing ${slot.bracketMatchId}: game ${slot.gameNumber} (${slot.seriesGameNumber}/${slot.seriesGameCount})`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function applyPlan(
|
||||||
|
match: MatchDocument,
|
||||||
|
plan: MatchRepairPlan,
|
||||||
|
TournamentCodeModel: mongoose.Model<any>,
|
||||||
|
session: mongoose.ClientSession,
|
||||||
|
) {
|
||||||
|
if (plan.skippedReason) return;
|
||||||
|
for (const update of plan.codeUpdates) {
|
||||||
|
await TournamentCodeModel.updateOne(
|
||||||
|
{ _id: update.codeId },
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
gameNumber: update.nextGameNumber,
|
||||||
|
bracketMatchId: update.bracketMatchId,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ session },
|
||||||
|
).exec();
|
||||||
|
}
|
||||||
|
const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS);
|
||||||
|
const reservedIds: mongoose.Types.ObjectId[] = [];
|
||||||
|
for (const slot of plan.missingReadySlots) {
|
||||||
|
const existingSlotCode = await TournamentCodeModel.exists({
|
||||||
|
matchId: match._id,
|
||||||
|
gameNumber: slot.gameNumber,
|
||||||
|
bracketMatchId: slot.bracketMatchId,
|
||||||
|
state: { $in: ['reserved', 'used'] },
|
||||||
|
})
|
||||||
|
.session(session)
|
||||||
|
.exec();
|
||||||
|
if (existingSlotCode) continue;
|
||||||
|
|
||||||
|
const code = await TournamentCodeModel.findOneAndUpdate(
|
||||||
|
{
|
||||||
|
state: 'available',
|
||||||
|
region: 'kr',
|
||||||
|
mapType: 'SUMMONERS_RIFT',
|
||||||
|
teamSize: 5,
|
||||||
|
expiresAt: { $gt: expiresAfter },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
state: 'reserved',
|
||||||
|
matchId: match._id,
|
||||||
|
gameNumber: slot.gameNumber,
|
||||||
|
bracketMatchId: slot.bracketMatchId,
|
||||||
|
reservedAt: new Date(),
|
||||||
|
},
|
||||||
|
$unset: { releasedAt: 1 },
|
||||||
|
},
|
||||||
|
{ sort: { expiresAt: 1 }, returnDocument: 'after', session },
|
||||||
|
).exec();
|
||||||
|
if (!code) break;
|
||||||
|
reservedIds.push(code._id);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (reservedIds.length > 0) {
|
||||||
|
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
|
||||||
|
match.tournamentCodeIds.push(...reservedIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!plan.ruleRepairSkippedReason) {
|
||||||
|
match.gameCount = plan.nextGameCount;
|
||||||
|
if (match.doubleElimination) {
|
||||||
|
match.doubleElimination.bracketMatches = plan.nextBracketMatches;
|
||||||
|
match.markModified('doubleElimination');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (reservedIds.length > 0 || !plan.ruleRepairSkippedReason) {
|
||||||
|
await match.save({ session });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const options = parseArgs(process.argv.slice(2));
|
||||||
|
process.env.NODE_ENV = options.nodeEnv;
|
||||||
|
process.env.SECRET_SOURCE = process.env.SECRET_SOURCE || 'infisical';
|
||||||
|
await loadMachineEnvFile();
|
||||||
|
|
||||||
|
const app = await NestFactory.createApplicationContext(RepairModule, {
|
||||||
|
logger: ['log', 'warn', 'error'],
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const connectionService = app.get(ConnectionService);
|
||||||
|
const MatchModel = await connectionService.getModel('match');
|
||||||
|
const TournamentCodeModel =
|
||||||
|
await connectionService.getModel('tournamentCode');
|
||||||
|
const matches = await MatchModel.find({
|
||||||
|
gameMode: 'double-elimination',
|
||||||
|
...(options.matchId ? { _id: options.matchId } : {}),
|
||||||
|
}).exec();
|
||||||
|
|
||||||
|
const plans: Array<{ match: MatchDocument; plan: MatchRepairPlan }> = [];
|
||||||
|
for (const match of matches) {
|
||||||
|
const codes = await TournamentCodeModel.find({
|
||||||
|
_id: { $in: match.tournamentCodeIds ?? [] },
|
||||||
|
}).exec();
|
||||||
|
const plan = buildRepairPlan(match, codes, options.winnerGameCount);
|
||||||
|
plans.push({ match, plan });
|
||||||
|
printPlan(plan);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.dryRun) {
|
||||||
|
console.log(
|
||||||
|
'No writes were made. Re-run with --apply to update MongoDB.',
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const session = await (
|
||||||
|
await connectionService.getConnection()
|
||||||
|
).startSession();
|
||||||
|
try {
|
||||||
|
await session.withTransaction(async () => {
|
||||||
|
for (const { match, plan } of plans) {
|
||||||
|
await applyPlan(match, plan, TournamentCodeModel, session);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
await session.endSession();
|
||||||
|
}
|
||||||
|
console.log(
|
||||||
|
`Applied ${plans.filter(({ plan }) => !plan.skippedReason).length} match repairs.`,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await app.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (require.main === module) {
|
||||||
|
main().catch((error) => {
|
||||||
|
console.error(error);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -598,6 +598,8 @@ export interface DoubleEliminationWalkover {
|
|||||||
export interface DoubleEliminationBracketMatch {
|
export interface DoubleEliminationBracketMatch {
|
||||||
bracketMatchId: string;
|
bracketMatchId: string;
|
||||||
gameNumber: number;
|
gameNumber: number;
|
||||||
|
gameCount: number;
|
||||||
|
requiredWins: number;
|
||||||
bracketSide: DoubleEliminationBracketSide;
|
bracketSide: DoubleEliminationBracketSide;
|
||||||
roundNumber: number;
|
roundNumber: number;
|
||||||
matchNumber: number;
|
matchNumber: number;
|
||||||
@@ -1516,7 +1518,6 @@ TournamentCodeSchema.index(
|
|||||||
TournamentCodeSchema.index(
|
TournamentCodeSchema.index(
|
||||||
{ matchId: 1, bracketMatchId: 1 },
|
{ matchId: 1, bracketMatchId: 1 },
|
||||||
{
|
{
|
||||||
unique: true,
|
|
||||||
partialFilterExpression: {
|
partialFilterExpression: {
|
||||||
matchId: { $exists: true },
|
matchId: { $exists: true },
|
||||||
bracketMatchId: { $exists: true },
|
bracketMatchId: { $exists: true },
|
||||||
@@ -1679,6 +1680,8 @@ const DoubleEliminationBracketMatchSubSchema =
|
|||||||
{
|
{
|
||||||
bracketMatchId: { type: String, required: true },
|
bracketMatchId: { type: String, required: true },
|
||||||
gameNumber: { type: Number, required: true, min: 1 },
|
gameNumber: { type: Number, required: true, min: 1 },
|
||||||
|
gameCount: { type: Number, required: true, min: 1, default: 1 },
|
||||||
|
requiredWins: { type: Number, required: true, min: 1, default: 1 },
|
||||||
bracketSide: {
|
bracketSide: {
|
||||||
type: String,
|
type: String,
|
||||||
enum: DOUBLE_ELIMINATION_BRACKET_SIDES,
|
enum: DOUBLE_ELIMINATION_BRACKET_SIDES,
|
||||||
@@ -1750,35 +1753,34 @@ const DoubleEliminationEventSubSchema = new Schema<DoubleEliminationEvent>(
|
|||||||
{ _id: false },
|
{ _id: false },
|
||||||
);
|
);
|
||||||
|
|
||||||
const DoubleEliminationBracketSubSchema =
|
const DoubleEliminationBracketSubSchema = new Schema<DoubleEliminationBracket>(
|
||||||
new Schema<DoubleEliminationBracket>(
|
{
|
||||||
{
|
teamCount: { type: Number, enum: [4, 8], required: true },
|
||||||
teamCount: { type: Number, enum: [4, 8], required: true },
|
resetFinalEnabled: { type: Boolean, required: true, default: false },
|
||||||
resetFinalEnabled: { type: Boolean, required: true, default: false },
|
resetFinalCreated: { type: Boolean, required: true, default: false },
|
||||||
resetFinalCreated: { type: Boolean, required: true, default: false },
|
seeds: {
|
||||||
seeds: {
|
type: [DoubleEliminationSeedSubSchema],
|
||||||
type: [DoubleEliminationSeedSubSchema],
|
required: true,
|
||||||
required: true,
|
default: [],
|
||||||
default: [],
|
|
||||||
},
|
|
||||||
bracketMatches: {
|
|
||||||
type: [DoubleEliminationBracketMatchSubSchema],
|
|
||||||
required: true,
|
|
||||||
default: [],
|
|
||||||
},
|
|
||||||
placements: {
|
|
||||||
type: DoubleEliminationPlacementsSubSchema,
|
|
||||||
required: true,
|
|
||||||
default: () => ({}),
|
|
||||||
},
|
|
||||||
events: {
|
|
||||||
type: [DoubleEliminationEventSubSchema],
|
|
||||||
required: true,
|
|
||||||
default: [],
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
{ _id: false },
|
bracketMatches: {
|
||||||
);
|
type: [DoubleEliminationBracketMatchSubSchema],
|
||||||
|
required: true,
|
||||||
|
default: [],
|
||||||
|
},
|
||||||
|
placements: {
|
||||||
|
type: DoubleEliminationPlacementsSubSchema,
|
||||||
|
required: true,
|
||||||
|
default: () => ({}),
|
||||||
|
},
|
||||||
|
events: {
|
||||||
|
type: [DoubleEliminationEventSubSchema],
|
||||||
|
required: true,
|
||||||
|
default: [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ _id: false },
|
||||||
|
);
|
||||||
|
|
||||||
const MatchResultSubSchema = new Schema<MatchResult>(
|
const MatchResultSubSchema = new Schema<MatchResult>(
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -491,7 +491,7 @@ describe('MatchService', () => {
|
|||||||
expect(createdPayloads[0]).toMatchObject({
|
expect(createdPayloads[0]).toMatchObject({
|
||||||
communityId,
|
communityId,
|
||||||
maxParticipants: 20,
|
maxParticipants: 20,
|
||||||
gameCount: 1,
|
gameCount: 5,
|
||||||
gameMode: 'double-elimination',
|
gameMode: 'double-elimination',
|
||||||
roundRobinMaxRounds: undefined,
|
roundRobinMaxRounds: undefined,
|
||||||
doubleElimination: {
|
doubleElimination: {
|
||||||
@@ -519,7 +519,9 @@ describe('MatchService', () => {
|
|||||||
gameMode: 'double-elimination',
|
gameMode: 'double-elimination',
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
).rejects.toThrow('Double elimination supports only 20 or 40 participants.');
|
).rejects.toThrow(
|
||||||
|
'Double elimination supports only 20 or 40 participants.',
|
||||||
|
);
|
||||||
expect(MatchModel.create).not.toHaveBeenCalled();
|
expect(MatchModel.create).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ const MATCH_SHORT_CODE_GENERATION_ATTEMPTS = 20;
|
|||||||
const DEFAULT_MATCH_LIST_LIMIT = 50;
|
const DEFAULT_MATCH_LIST_LIMIT = 50;
|
||||||
const MAX_MATCH_LIST_LIMIT = 200;
|
const MAX_MATCH_LIST_LIMIT = 200;
|
||||||
const DOUBLE_ELIMINATION_PARTICIPANT_COUNTS = [20, 40] as const;
|
const DOUBLE_ELIMINATION_PARTICIPANT_COUNTS = [20, 40] as const;
|
||||||
|
const DEFAULT_DOUBLE_ELIMINATION_SERIES_GAME_COUNT = 3;
|
||||||
|
|
||||||
interface DoubleEliminationConfigInput {
|
interface DoubleEliminationConfigInput {
|
||||||
doubleEliminationResetFinalEnabled?: boolean;
|
doubleEliminationResetFinalEnabled?: boolean;
|
||||||
@@ -109,21 +110,18 @@ interface DoubleEliminationAdminParams {
|
|||||||
actorUserId: mongoose.Types.ObjectId;
|
actorUserId: mongoose.Types.ObjectId;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface SwapDoubleEliminationSeedsParams
|
interface SwapDoubleEliminationSeedsParams extends DoubleEliminationAdminParams {
|
||||||
extends DoubleEliminationAdminParams {
|
|
||||||
leftSeedNumber: number;
|
leftSeedNumber: number;
|
||||||
rightSeedNumber: number;
|
rightSeedNumber: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ApplyDoubleEliminationWalkoverParams
|
interface ApplyDoubleEliminationWalkoverParams extends DoubleEliminationAdminParams {
|
||||||
extends DoubleEliminationAdminParams {
|
|
||||||
bracketMatchId: string;
|
bracketMatchId: string;
|
||||||
winnerTeamIndex: number;
|
winnerTeamIndex: number;
|
||||||
reason?: string;
|
reason?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface CancelDoubleEliminationActionParams
|
interface CancelDoubleEliminationActionParams extends DoubleEliminationAdminParams {
|
||||||
extends DoubleEliminationAdminParams {
|
|
||||||
bracketMatchId: string;
|
bracketMatchId: string;
|
||||||
reason?: string;
|
reason?: string;
|
||||||
}
|
}
|
||||||
@@ -529,9 +527,9 @@ export class MatchService {
|
|||||||
return await this.throwJoinFailure(MatchModel, params.matchId, user);
|
return await this.throwJoinFailure(MatchModel, params.matchId, user);
|
||||||
}
|
}
|
||||||
|
|
||||||
private normalizeMatchConfig<T extends Partial<Match> & DoubleEliminationConfigInput>(
|
private normalizeMatchConfig<
|
||||||
input: T,
|
T extends Partial<Match> & DoubleEliminationConfigInput,
|
||||||
): Partial<Match> {
|
>(input: T): Partial<Match> {
|
||||||
const patch = this.stripMatchConfigInput(input);
|
const patch = this.stripMatchConfigInput(input);
|
||||||
const gameMode = (patch.gameMode ?? 'pair') as MatchGameMode;
|
const gameMode = (patch.gameMode ?? 'pair') as MatchGameMode;
|
||||||
const maxParticipants = patch.maxParticipants ?? 10;
|
const maxParticipants = patch.maxParticipants ?? 10;
|
||||||
@@ -550,7 +548,9 @@ export class MatchService {
|
|||||||
...patch,
|
...patch,
|
||||||
gameMode,
|
gameMode,
|
||||||
maxParticipants,
|
maxParticipants,
|
||||||
gameCount: 1,
|
gameCount: this.normalizeDoubleEliminationSeriesGameCount(
|
||||||
|
patch.gameCount ?? DEFAULT_DOUBLE_ELIMINATION_SERIES_GAME_COUNT,
|
||||||
|
),
|
||||||
roundRobinMaxRounds: undefined,
|
roundRobinMaxRounds: undefined,
|
||||||
gameSchedule: [],
|
gameSchedule: [],
|
||||||
doubleElimination: {
|
doubleElimination: {
|
||||||
@@ -575,13 +575,20 @@ export class MatchService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private stripMatchConfigInput<T extends Partial<Match> & DoubleEliminationConfigInput>(
|
private stripMatchConfigInput<
|
||||||
input: T,
|
T extends Partial<Match> & DoubleEliminationConfigInput,
|
||||||
): Partial<Match> {
|
>(input: T): Partial<Match> {
|
||||||
const { doubleEliminationResetFinalEnabled: _ignored, ...patch } = input;
|
const { doubleEliminationResetFinalEnabled: _ignored, ...patch } = input;
|
||||||
return patch;
|
return patch;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private normalizeDoubleEliminationSeriesGameCount(gameCount: number): number {
|
||||||
|
if (!Number.isInteger(gameCount) || gameCount < 1) {
|
||||||
|
return DEFAULT_DOUBLE_ELIMINATION_SERIES_GAME_COUNT;
|
||||||
|
}
|
||||||
|
return gameCount % 2 === 0 ? gameCount + 1 : gameCount;
|
||||||
|
}
|
||||||
|
|
||||||
private async loadDoubleEliminationMatch(params: {
|
private async loadDoubleEliminationMatch(params: {
|
||||||
matchId: mongoose.Types.ObjectId;
|
matchId: mongoose.Types.ObjectId;
|
||||||
communityId: mongoose.Types.ObjectId;
|
communityId: mongoose.Types.ObjectId;
|
||||||
@@ -836,7 +843,10 @@ export class MatchService {
|
|||||||
private async throwJoinFailure(
|
private async throwJoinFailure(
|
||||||
MatchModel: mongoose.Model<Match>,
|
MatchModel: mongoose.Model<Match>,
|
||||||
matchId: mongoose.Types.ObjectId,
|
matchId: mongoose.Types.ObjectId,
|
||||||
user: { _id: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId },
|
user: {
|
||||||
|
_id: mongoose.Types.ObjectId;
|
||||||
|
communityId: mongoose.Types.ObjectId;
|
||||||
|
},
|
||||||
): Promise<never> {
|
): Promise<never> {
|
||||||
const match = await MatchModel.findById(matchId);
|
const match = await MatchModel.findById(matchId);
|
||||||
if (!match) throw new NotFoundException('Match not found.');
|
if (!match) throw new NotFoundException('Match not found.');
|
||||||
@@ -864,7 +874,10 @@ export class MatchService {
|
|||||||
private async throwCancelJoinFailure(
|
private async throwCancelJoinFailure(
|
||||||
MatchModel: mongoose.Model<Match>,
|
MatchModel: mongoose.Model<Match>,
|
||||||
matchId: mongoose.Types.ObjectId,
|
matchId: mongoose.Types.ObjectId,
|
||||||
user: { _id: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId },
|
user: {
|
||||||
|
_id: mongoose.Types.ObjectId;
|
||||||
|
communityId: mongoose.Types.ObjectId;
|
||||||
|
},
|
||||||
): Promise<never> {
|
): Promise<never> {
|
||||||
const match = await MatchModel.findById(matchId);
|
const match = await MatchModel.findById(matchId);
|
||||||
if (!match) throw new NotFoundException('Match not found.');
|
if (!match) throw new NotFoundException('Match not found.');
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
} from '../global/database/schema';
|
} from '../global/database/schema';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import { TournamentCodeService } from './tournament-code.service';
|
import { TournamentCodeService } from './tournament-code.service';
|
||||||
|
import { buildDoubleEliminationBracket } from '../double-elimination/double-elimination.util';
|
||||||
|
|
||||||
type TournamentCodeServiceInternals = TournamentCodeService & {
|
type TournamentCodeServiceInternals = TournamentCodeService & {
|
||||||
resolveRequiredSlots(match: MatchDocument): number;
|
resolveRequiredSlots(match: MatchDocument): number;
|
||||||
@@ -229,6 +230,7 @@ describe('TournamentCodeService round-robin scheduling', () => {
|
|||||||
const service = createService();
|
const service = createService();
|
||||||
const match = createMatch({
|
const match = createMatch({
|
||||||
gameMode: 'double-elimination',
|
gameMode: 'double-elimination',
|
||||||
|
gameCount: 3,
|
||||||
teams: Array.from({ length: 4 }, (_, index) => ({
|
teams: Array.from({ length: 4 }, (_, index) => ({
|
||||||
teamIndex: index + 1,
|
teamIndex: index + 1,
|
||||||
})),
|
})),
|
||||||
@@ -252,6 +254,70 @@ describe('TournamentCodeService round-robin scheduling', () => {
|
|||||||
(bracketMatch) => bracketMatch.state === 'ready',
|
(bracketMatch) => bracketMatch.state === 'ready',
|
||||||
),
|
),
|
||||||
).toHaveLength(2);
|
).toHaveLength(2);
|
||||||
|
expect(
|
||||||
|
match.doubleElimination?.bracketMatches.find(
|
||||||
|
(bracketMatch) => bracketMatch.bracketMatchId === 'WB_R1_M1',
|
||||||
|
),
|
||||||
|
).toMatchObject({ gameCount: 3, requiredWins: 2 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('expands double-elimination winner bracket series into code slots', async () => {
|
||||||
|
const TournamentCodeModel = {
|
||||||
|
find: jest.fn().mockReturnValue({
|
||||||
|
exec: jest.fn().mockResolvedValue([]),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
const service = new TournamentCodeService(
|
||||||
|
{ getModel: jest.fn().mockResolvedValue(TournamentCodeModel) } as never,
|
||||||
|
createAuctionRedisService() as never,
|
||||||
|
) as unknown as TournamentCodeServiceInternals;
|
||||||
|
const match = createMatch({
|
||||||
|
gameMode: 'double-elimination',
|
||||||
|
gameCount: 3,
|
||||||
|
teams: Array.from({ length: 4 }, (_, index) => ({
|
||||||
|
teamIndex: index + 1,
|
||||||
|
})),
|
||||||
|
doubleElimination: buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||||
|
resetFinalEnabled: true,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const slots = await service.buildSlots(match);
|
||||||
|
|
||||||
|
expect(slots.slice(0, 6)).toEqual([
|
||||||
|
expect.objectContaining({
|
||||||
|
gameNumber: 1,
|
||||||
|
seriesGameNumber: 1,
|
||||||
|
seriesGameCount: 3,
|
||||||
|
seriesRequiredWins: 2,
|
||||||
|
bracketMatchId: 'WB_R1_M1',
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
gameNumber: 2,
|
||||||
|
seriesGameNumber: 2,
|
||||||
|
bracketMatchId: 'WB_R1_M1',
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
gameNumber: 3,
|
||||||
|
seriesGameNumber: 3,
|
||||||
|
bracketMatchId: 'WB_R1_M1',
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
gameNumber: 4,
|
||||||
|
seriesGameNumber: 1,
|
||||||
|
bracketMatchId: 'WB_R1_M2',
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
gameNumber: 5,
|
||||||
|
seriesGameNumber: 2,
|
||||||
|
bracketMatchId: 'WB_R1_M2',
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
gameNumber: 6,
|
||||||
|
seriesGameNumber: 3,
|
||||||
|
bracketMatchId: 'WB_R1_M2',
|
||||||
|
}),
|
||||||
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('creates a limited round-robin schedule grouped by playable rounds', () => {
|
it('creates a limited round-robin schedule grouped by playable rounds', () => {
|
||||||
@@ -374,7 +440,7 @@ describe('TournamentCodeService round-robin scheduling', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('TournamentCodeService bulk upload', () => {
|
describe('TournamentCodeService bulk upload', () => {
|
||||||
it('defines unique slot and riot match indexes for multi-instance safety', () => {
|
it('defines slot and riot match indexes for multi-instance safety', () => {
|
||||||
const indexes = TournamentCodeSchema.indexes();
|
const indexes = TournamentCodeSchema.indexes();
|
||||||
|
|
||||||
expect(indexes).toContainEqual([
|
expect(indexes).toContainEqual([
|
||||||
@@ -391,7 +457,6 @@ describe('TournamentCodeService bulk upload', () => {
|
|||||||
expect(indexes).toContainEqual([
|
expect(indexes).toContainEqual([
|
||||||
{ matchId: 1, bracketMatchId: 1 },
|
{ matchId: 1, bracketMatchId: 1 },
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
unique: true,
|
|
||||||
partialFilterExpression: {
|
partialFilterExpression: {
|
||||||
matchId: { $exists: true },
|
matchId: { $exists: true },
|
||||||
bracketMatchId: { $exists: true },
|
bracketMatchId: { $exists: true },
|
||||||
|
|||||||
@@ -8,13 +8,13 @@ import {
|
|||||||
import { randomUUID } from 'crypto';
|
import { randomUUID } from 'crypto';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import {
|
import {
|
||||||
|
buildDoubleEliminationGameSlots,
|
||||||
buildDoubleEliminationBracket,
|
buildDoubleEliminationBracket,
|
||||||
findNextReadyDoubleEliminationBracketMatches,
|
type DoubleEliminationGameSlot,
|
||||||
} from '../double-elimination/double-elimination.util';
|
} from '../double-elimination/double-elimination.util';
|
||||||
import { AuctionRedisService } from '../auction/redis/auction-redis.service';
|
import { AuctionRedisService } from '../auction/redis/auction-redis.service';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
import type {
|
import type {
|
||||||
DoubleEliminationBracketMatch,
|
|
||||||
MatchGameAssignment,
|
MatchGameAssignment,
|
||||||
MatchDocument,
|
MatchDocument,
|
||||||
TournamentCode,
|
TournamentCode,
|
||||||
@@ -358,9 +358,9 @@ export class TournamentCodeService {
|
|||||||
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||||
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
|
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
|
||||||
this.ensureGameSchedule(match);
|
this.ensureGameSchedule(match);
|
||||||
const doubleEliminationBracketMatch =
|
const doubleEliminationSlot =
|
||||||
(match.gameMode ?? 'pair') === 'double-elimination'
|
(match.gameMode ?? 'pair') === 'double-elimination'
|
||||||
? this.resolveDoubleEliminationBracketMatchByGameNumber(
|
? this.resolveDoubleEliminationGameSlotByGameNumber(
|
||||||
match,
|
match,
|
||||||
params.gameNumber,
|
params.gameNumber,
|
||||||
)
|
)
|
||||||
@@ -376,11 +376,7 @@ export class TournamentCodeService {
|
|||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
(match.result?.games ?? []).some(
|
(match.result?.games ?? []).some(
|
||||||
(game) =>
|
(game) => game.gameNumber === params.gameNumber,
|
||||||
game.gameNumber === params.gameNumber ||
|
|
||||||
(doubleEliminationBracketMatch?.bracketMatchId &&
|
|
||||||
game.bracketMatchId ===
|
|
||||||
doubleEliminationBracketMatch.bracketMatchId),
|
|
||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
@@ -393,8 +389,12 @@ export class TournamentCodeService {
|
|||||||
TournamentCodeModel.findOne({
|
TournamentCodeModel.findOne({
|
||||||
_id: { $in: match.tournamentCodeIds },
|
_id: { $in: match.tournamentCodeIds },
|
||||||
matchId: match._id,
|
matchId: match._id,
|
||||||
...(doubleEliminationBracketMatch
|
...(doubleEliminationSlot
|
||||||
? { bracketMatchId: doubleEliminationBracketMatch.bracketMatchId }
|
? {
|
||||||
|
gameNumber: params.gameNumber,
|
||||||
|
bracketMatchId:
|
||||||
|
doubleEliminationSlot.bracketMatch.bracketMatchId,
|
||||||
|
}
|
||||||
: { gameNumber: params.gameNumber }),
|
: { gameNumber: params.gameNumber }),
|
||||||
}),
|
}),
|
||||||
session,
|
session,
|
||||||
@@ -444,9 +444,10 @@ export class TournamentCodeService {
|
|||||||
state: 'reserved',
|
state: 'reserved',
|
||||||
matchId: match._id,
|
matchId: match._id,
|
||||||
gameNumber: params.gameNumber,
|
gameNumber: params.gameNumber,
|
||||||
...(doubleEliminationBracketMatch
|
...(doubleEliminationSlot
|
||||||
? {
|
? {
|
||||||
bracketMatchId: doubleEliminationBracketMatch.bracketMatchId,
|
bracketMatchId:
|
||||||
|
doubleEliminationSlot.bracketMatch.bracketMatchId,
|
||||||
}
|
}
|
||||||
: {}),
|
: {}),
|
||||||
reservedAt: new Date(),
|
reservedAt: new Date(),
|
||||||
@@ -470,8 +471,8 @@ export class TournamentCodeService {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
gameNumber: params.gameNumber,
|
gameNumber: params.gameNumber,
|
||||||
...(doubleEliminationBracketMatch
|
...(doubleEliminationSlot
|
||||||
? this.toDoubleEliminationSlotBase(doubleEliminationBracketMatch)
|
? this.toDoubleEliminationSlotBase(doubleEliminationSlot)
|
||||||
: {}),
|
: {}),
|
||||||
roundNumber: this.resolveRoundNumberForGameNumber(
|
roundNumber: this.resolveRoundNumberForGameNumber(
|
||||||
match,
|
match,
|
||||||
@@ -735,9 +736,9 @@ export class TournamentCodeService {
|
|||||||
};
|
};
|
||||||
return Boolean(
|
return Boolean(
|
||||||
candidate?.hasErrorLabel?.('TransientTransactionError') ||
|
candidate?.hasErrorLabel?.('TransientTransactionError') ||
|
||||||
candidate?.hasErrorLabel?.('UnknownTransactionCommitResult') ||
|
candidate?.hasErrorLabel?.('UnknownTransactionCommitResult') ||
|
||||||
candidate?.code === 112 ||
|
candidate?.code === 112 ||
|
||||||
candidate?.codeName === 'WriteConflict',
|
candidate?.codeName === 'WriteConflict',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -768,9 +769,9 @@ export class TournamentCodeService {
|
|||||||
TournamentCodeModel: mongoose.Model<TournamentCode>,
|
TournamentCodeModel: mongoose.Model<TournamentCode>,
|
||||||
session: mongoose.ClientSession,
|
session: mongoose.ClientSession,
|
||||||
): Promise<MatchDocument> {
|
): Promise<MatchDocument> {
|
||||||
const readyBracketMatches = findNextReadyDoubleEliminationBracketMatches(
|
const readySlots = buildDoubleEliminationGameSlots(
|
||||||
match.doubleElimination,
|
match.doubleElimination?.bracketMatches ?? [],
|
||||||
);
|
).filter((slot) => slot.bracketMatch.state === 'ready');
|
||||||
const existingCodes =
|
const existingCodes =
|
||||||
match.tournamentCodeIds.length > 0
|
match.tournamentCodeIds.length > 0
|
||||||
? await this.execQuery<TournamentCodeDocument[]>(
|
? await this.execQuery<TournamentCodeDocument[]>(
|
||||||
@@ -782,22 +783,22 @@ export class TournamentCodeService {
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
: [];
|
: [];
|
||||||
const byBracketMatchId = new Map(
|
const byGameNumber = new Map(
|
||||||
existingCodes
|
existingCodes
|
||||||
.filter(
|
.filter(
|
||||||
(code) =>
|
(code) =>
|
||||||
code.bracketMatchId &&
|
typeof code.gameNumber === 'number' &&
|
||||||
(code.state === 'reserved' || code.state === 'used'),
|
(code.state === 'reserved' || code.state === 'used'),
|
||||||
)
|
)
|
||||||
.map((code) => [code.bracketMatchId as string, code]),
|
.map((code) => [code.gameNumber as number, code]),
|
||||||
);
|
);
|
||||||
const expiresAfter = new Date(
|
const expiresAfter = new Date(
|
||||||
Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS,
|
Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS,
|
||||||
);
|
);
|
||||||
const reservedIds: mongoose.Types.ObjectId[] = [];
|
const reservedIds: mongoose.Types.ObjectId[] = [];
|
||||||
|
|
||||||
for (const bracketMatch of readyBracketMatches) {
|
for (const slot of readySlots) {
|
||||||
if (byBracketMatchId.has(bracketMatch.bracketMatchId)) continue;
|
if (byGameNumber.has(slot.gameNumber)) continue;
|
||||||
const code = await TournamentCodeModel.findOneAndUpdate(
|
const code = await TournamentCodeModel.findOneAndUpdate(
|
||||||
{
|
{
|
||||||
state: 'available',
|
state: 'available',
|
||||||
@@ -810,8 +811,8 @@ export class TournamentCodeService {
|
|||||||
$set: {
|
$set: {
|
||||||
state: 'reserved',
|
state: 'reserved',
|
||||||
matchId: match._id,
|
matchId: match._id,
|
||||||
gameNumber: bracketMatch.gameNumber,
|
gameNumber: slot.gameNumber,
|
||||||
bracketMatchId: bracketMatch.bracketMatchId,
|
bracketMatchId: slot.bracketMatch.bracketMatchId,
|
||||||
reservedAt: new Date(),
|
reservedAt: new Date(),
|
||||||
},
|
},
|
||||||
$unset: { releasedAt: 1 },
|
$unset: { releasedAt: 1 },
|
||||||
@@ -820,7 +821,7 @@ export class TournamentCodeService {
|
|||||||
).exec();
|
).exec();
|
||||||
if (!code) break;
|
if (!code) break;
|
||||||
reservedIds.push(code._id);
|
reservedIds.push(code._id);
|
||||||
byBracketMatchId.set(bracketMatch.bracketMatchId, code);
|
byGameNumber.set(slot.gameNumber, code);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (reservedIds.length > 0) {
|
if (reservedIds.length > 0) {
|
||||||
@@ -841,6 +842,7 @@ export class TournamentCodeService {
|
|||||||
this.ensureGameSchedule(match);
|
this.ensureGameSchedule(match);
|
||||||
const bracketMatches = match.doubleElimination?.bracketMatches ?? [];
|
const bracketMatches = match.doubleElimination?.bracketMatches ?? [];
|
||||||
if (bracketMatches.length === 0) return [];
|
if (bracketMatches.length === 0) return [];
|
||||||
|
const slots = buildDoubleEliminationGameSlots(bracketMatches);
|
||||||
const TournamentCodeModel =
|
const TournamentCodeModel =
|
||||||
await this.connectionService.getModel('tournamentCode');
|
await this.connectionService.getModel('tournamentCode');
|
||||||
const ids = match.tournamentCodeIds ?? [];
|
const ids = match.tournamentCodeIds ?? [];
|
||||||
@@ -848,21 +850,21 @@ export class TournamentCodeService {
|
|||||||
ids.length > 0
|
ids.length > 0
|
||||||
? await TournamentCodeModel.find({ _id: { $in: ids } }).exec()
|
? await TournamentCodeModel.find({ _id: { $in: ids } }).exec()
|
||||||
: [];
|
: [];
|
||||||
const byBracketMatchId = new Map(
|
const byGameNumber = new Map(
|
||||||
codes
|
codes
|
||||||
.filter(
|
.filter(
|
||||||
(code) =>
|
(code) =>
|
||||||
code.bracketMatchId &&
|
typeof code.gameNumber === 'number' &&
|
||||||
code.state !== 'released' &&
|
code.state !== 'released' &&
|
||||||
code.state !== 'voided',
|
code.state !== 'voided',
|
||||||
)
|
)
|
||||||
.map((code) => [code.bracketMatchId as string, code]),
|
.map((code) => [code.gameNumber as number, code]),
|
||||||
);
|
);
|
||||||
|
|
||||||
return bracketMatches.map((bracketMatch) => {
|
return slots.map((slot) => {
|
||||||
const code = byBracketMatchId.get(bracketMatch.bracketMatchId);
|
const code = byGameNumber.get(slot.gameNumber);
|
||||||
return {
|
return {
|
||||||
...this.toDoubleEliminationSlotBase(bracketMatch),
|
...this.toDoubleEliminationSlotBase(slot),
|
||||||
code: code?.code ?? null,
|
code: code?.code ?? null,
|
||||||
expiresAt: code?.expiresAt.toISOString() ?? null,
|
expiresAt: code?.expiresAt.toISOString() ?? null,
|
||||||
state: code?.state ?? 'pending',
|
state: code?.state ?? 'pending',
|
||||||
@@ -872,10 +874,17 @@ export class TournamentCodeService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private toDoubleEliminationSlotBase(
|
private toDoubleEliminationSlotBase(
|
||||||
bracketMatch: DoubleEliminationBracketMatch,
|
slot: DoubleEliminationGameSlot,
|
||||||
): Omit<TournamentCodeSlotView, 'code' | 'expiresAt' | 'state' | 'riotMatchId'> {
|
): Omit<
|
||||||
|
TournamentCodeSlotView,
|
||||||
|
'code' | 'expiresAt' | 'state' | 'riotMatchId'
|
||||||
|
> {
|
||||||
|
const bracketMatch = slot.bracketMatch;
|
||||||
return {
|
return {
|
||||||
gameNumber: bracketMatch.gameNumber,
|
gameNumber: slot.gameNumber,
|
||||||
|
seriesGameNumber: slot.seriesGameNumber,
|
||||||
|
seriesGameCount: slot.seriesGameCount,
|
||||||
|
seriesRequiredWins: slot.seriesRequiredWins,
|
||||||
bracketMatchId: bracketMatch.bracketMatchId,
|
bracketMatchId: bracketMatch.bracketMatchId,
|
||||||
bracketSide: bracketMatch.bracketSide,
|
bracketSide: bracketMatch.bracketSide,
|
||||||
roundNumber: bracketMatch.roundNumber,
|
roundNumber: bracketMatch.roundNumber,
|
||||||
@@ -890,7 +899,9 @@ export class TournamentCodeService {
|
|||||||
const gameMode = match.gameMode ?? 'pair';
|
const gameMode = match.gameMode ?? 'pair';
|
||||||
|
|
||||||
if (gameMode === 'double-elimination') {
|
if (gameMode === 'double-elimination') {
|
||||||
return match.doubleElimination?.bracketMatches.length ?? 0;
|
return buildDoubleEliminationGameSlots(
|
||||||
|
match.doubleElimination?.bracketMatches ?? [],
|
||||||
|
).length;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (gameMode === 'round-robin') {
|
if (gameMode === 'round-robin') {
|
||||||
@@ -917,13 +928,13 @@ export class TournamentCodeService {
|
|||||||
const gameMode = match.gameMode ?? 'pair';
|
const gameMode = match.gameMode ?? 'pair';
|
||||||
|
|
||||||
if (gameMode === 'double-elimination') {
|
if (gameMode === 'double-elimination') {
|
||||||
const bracketMatch = this.resolveDoubleEliminationBracketMatchByGameNumber(
|
const slot = this.resolveDoubleEliminationGameSlotByGameNumber(
|
||||||
match,
|
match,
|
||||||
gameNumber,
|
gameNumber,
|
||||||
);
|
);
|
||||||
return {
|
return {
|
||||||
teamAIndex: bracketMatch?.teamAIndex ?? 1,
|
teamAIndex: slot?.bracketMatch.teamAIndex ?? 1,
|
||||||
teamBIndex: bracketMatch?.teamBIndex ?? 2,
|
teamBIndex: slot?.bracketMatch.teamBIndex ?? 2,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -984,20 +995,21 @@ export class TournamentCodeService {
|
|||||||
match.doubleElimination = buildDoubleEliminationBracket(
|
match.doubleElimination = buildDoubleEliminationBracket(
|
||||||
shuffledTeamIndexes,
|
shuffledTeamIndexes,
|
||||||
{
|
{
|
||||||
resetFinalEnabled:
|
resetFinalEnabled: match.doubleElimination?.resetFinalEnabled ?? false,
|
||||||
match.doubleElimination?.resetFinalEnabled ?? false,
|
winnerBracketGameCount:
|
||||||
|
match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
match.markModified?.('doubleElimination');
|
match.markModified?.('doubleElimination');
|
||||||
}
|
}
|
||||||
|
|
||||||
private resolveDoubleEliminationBracketMatchByGameNumber(
|
private resolveDoubleEliminationGameSlotByGameNumber(
|
||||||
match: MatchDocument,
|
match: MatchDocument,
|
||||||
gameNumber: number,
|
gameNumber: number,
|
||||||
): DoubleEliminationBracketMatch | undefined {
|
): DoubleEliminationGameSlot | undefined {
|
||||||
return match.doubleElimination?.bracketMatches.find(
|
return buildDoubleEliminationGameSlots(
|
||||||
(bracketMatch) => bracketMatch.gameNumber === gameNumber,
|
match.doubleElimination?.bracketMatches ?? [],
|
||||||
);
|
).find((slot) => slot.gameNumber === gameNumber);
|
||||||
}
|
}
|
||||||
|
|
||||||
private shuffleTeamIndexes(teamIndexes: number[]): number[] {
|
private shuffleTeamIndexes(teamIndexes: number[]): number[] {
|
||||||
|
|||||||
@@ -24,6 +24,9 @@ export interface BulkUploadTournamentCodesResponse {
|
|||||||
|
|
||||||
export interface TournamentCodeSlotView {
|
export interface TournamentCodeSlotView {
|
||||||
gameNumber: number;
|
gameNumber: number;
|
||||||
|
seriesGameNumber?: number;
|
||||||
|
seriesGameCount?: number;
|
||||||
|
seriesRequiredWins?: number;
|
||||||
bracketMatchId?: string;
|
bracketMatchId?: string;
|
||||||
bracketSide?: string;
|
bracketSide?: string;
|
||||||
roundNumber?: number;
|
roundNumber?: number;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import type { MatchDocument } from '../global/database/schema';
|
|||||||
import { DistributedLockService } from '../global/redis/distributed-lock.service';
|
import { DistributedLockService } from '../global/redis/distributed-lock.service';
|
||||||
import type { RiotMatchDto } from '../riot/riot.types';
|
import type { RiotMatchDto } from '../riot/riot.types';
|
||||||
import { TournamentResultService } from './tournament-result.service';
|
import { TournamentResultService } from './tournament-result.service';
|
||||||
|
import { buildDoubleEliminationBracket } from '../double-elimination/double-elimination.util';
|
||||||
|
|
||||||
type TournamentResultServiceInternals = TournamentResultService & {
|
type TournamentResultServiceInternals = TournamentResultService & {
|
||||||
nextPollDelayMs(elapsedMs: number): number | null;
|
nextPollDelayMs(elapsedMs: number): number | null;
|
||||||
@@ -14,6 +15,11 @@ type TournamentResultServiceInternals = TournamentResultService & {
|
|||||||
buildSeriesResults(
|
buildSeriesResults(
|
||||||
games: NonNullable<MatchDocument['result']>['games'],
|
games: NonNullable<MatchDocument['result']>['games'],
|
||||||
): NonNullable<MatchDocument['result']>['seriesResults'];
|
): NonNullable<MatchDocument['result']>['seriesResults'];
|
||||||
|
advanceDoubleEliminationIfNeeded(
|
||||||
|
match: MatchDocument,
|
||||||
|
gameResult: NonNullable<MatchDocument['result']>['games'][number],
|
||||||
|
completedBy: 'riot-result' | 'walkover',
|
||||||
|
): string | undefined;
|
||||||
};
|
};
|
||||||
|
|
||||||
function createService() {
|
function createService() {
|
||||||
@@ -38,23 +44,27 @@ function createDistributedLockService() {
|
|||||||
options.lockExpirationDurationMilliseconds,
|
options.lockExpirationDurationMilliseconds,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
runWithRenewedLock: jest.fn().mockImplementation(async (options, operation) =>
|
runWithRenewedLock: jest
|
||||||
operation({
|
.fn()
|
||||||
lockKey: options.lockKey,
|
.mockImplementation(async (options, operation) =>
|
||||||
lockOwnershipToken: 'lock-owner',
|
operation({
|
||||||
lockExpirationDurationMilliseconds:
|
lockKey: options.lockKey,
|
||||||
options.lockExpirationDurationMilliseconds,
|
lockOwnershipToken: 'lock-owner',
|
||||||
}),
|
lockExpirationDurationMilliseconds:
|
||||||
),
|
options.lockExpirationDurationMilliseconds,
|
||||||
|
}),
|
||||||
|
),
|
||||||
} as unknown as jest.Mocked<DistributedLockService>;
|
} as unknown as jest.Mocked<DistributedLockService>;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface MatchOverrides {
|
interface MatchOverrides {
|
||||||
gameCount?: number;
|
gameCount?: number;
|
||||||
gameMode?: 'pair' | 'bracket' | 'round-robin';
|
gameMode?: 'pair' | 'bracket' | 'round-robin' | 'double-elimination';
|
||||||
roundRobinMaxRounds?: number;
|
roundRobinMaxRounds?: number;
|
||||||
participants?: Array<{ excluded?: boolean }>;
|
participants?: Array<{ excluded?: boolean }>;
|
||||||
teams?: Array<{ teamIndex: number }>;
|
teams?: Array<{ teamIndex: number }>;
|
||||||
|
doubleElimination?: MatchDocument['doubleElimination'];
|
||||||
|
result?: MatchDocument['result'];
|
||||||
gameSchedule?: Array<{
|
gameSchedule?: Array<{
|
||||||
gameNumber: number;
|
gameNumber: number;
|
||||||
roundNumber?: number;
|
roundNumber?: number;
|
||||||
@@ -70,6 +80,7 @@ function createMatch(overrides: MatchOverrides): MatchDocument {
|
|||||||
participants: [],
|
participants: [],
|
||||||
teams: [],
|
teams: [],
|
||||||
gameSchedule: [],
|
gameSchedule: [],
|
||||||
|
result: undefined,
|
||||||
...overrides,
|
...overrides,
|
||||||
} as unknown as MatchDocument;
|
} as unknown as MatchDocument;
|
||||||
}
|
}
|
||||||
@@ -177,6 +188,96 @@ describe('TournamentResultService round-robin scheduling', () => {
|
|||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('maps double-elimination series game numbers to bracket matches', () => {
|
||||||
|
const service = createService();
|
||||||
|
const match = createMatch({
|
||||||
|
gameMode: 'double-elimination',
|
||||||
|
doubleElimination: buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||||
|
resetFinalEnabled: true,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(service.resolveRequiredGameSlots(match)).toBe(12);
|
||||||
|
expect(service.resolveSeriesRefForGameNumber(match, 1)).toEqual({
|
||||||
|
teamAIndex: 1,
|
||||||
|
teamBIndex: 4,
|
||||||
|
});
|
||||||
|
expect(service.resolveSeriesRefForGameNumber(match, 4)).toEqual({
|
||||||
|
teamAIndex: 2,
|
||||||
|
teamBIndex: 3,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('advances double-elimination only after a team reaches required series wins', () => {
|
||||||
|
const service = createService();
|
||||||
|
const game = {
|
||||||
|
gameNumber: 1,
|
||||||
|
bracketMatchId: 'WB_R1_M1',
|
||||||
|
riotMatchId: 'KR_1',
|
||||||
|
blueTeamIndex: 1,
|
||||||
|
redTeamIndex: 4,
|
||||||
|
winnerTeamIndex: 1,
|
||||||
|
winnerSide: 'blue',
|
||||||
|
gameCreation: 1,
|
||||||
|
gameDuration: 1800,
|
||||||
|
participants: [],
|
||||||
|
} as NonNullable<MatchDocument['result']>['games'][number];
|
||||||
|
const match = createMatch({
|
||||||
|
gameMode: 'double-elimination',
|
||||||
|
doubleElimination: buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||||
|
resetFinalEnabled: true,
|
||||||
|
}),
|
||||||
|
result: {
|
||||||
|
riotMatchIds: ['KR_1'],
|
||||||
|
games: [game],
|
||||||
|
seriesResults: [
|
||||||
|
{
|
||||||
|
bracketMatchId: 'WB_R1_M1',
|
||||||
|
teamAIndex: 1,
|
||||||
|
teamBIndex: 4,
|
||||||
|
teamAWins: 1,
|
||||||
|
teamBWins: 0,
|
||||||
|
winnerTeamIndex: 1,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
} as MatchOverrides);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
service.advanceDoubleEliminationIfNeeded(match, game, 'riot-result'),
|
||||||
|
).toBeUndefined();
|
||||||
|
const firstGameBracketMatch = match.doubleElimination?.bracketMatches.find(
|
||||||
|
(entry) => entry.bracketMatchId === 'WB_R1_M1',
|
||||||
|
);
|
||||||
|
expect(firstGameBracketMatch).toMatchObject({ state: 'ready' });
|
||||||
|
expect(firstGameBracketMatch?.winnerTeamIndex).toBeUndefined();
|
||||||
|
|
||||||
|
match.result!.seriesResults = [
|
||||||
|
{
|
||||||
|
bracketMatchId: 'WB_R1_M1',
|
||||||
|
teamAIndex: 1,
|
||||||
|
teamBIndex: 4,
|
||||||
|
teamAWins: 2,
|
||||||
|
teamBWins: 0,
|
||||||
|
winnerTeamIndex: 1,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
expect(
|
||||||
|
service.advanceDoubleEliminationIfNeeded(match, game, 'riot-result'),
|
||||||
|
).toBe('WB_R1_M1');
|
||||||
|
expect(
|
||||||
|
match.doubleElimination?.bracketMatches.find(
|
||||||
|
(entry) => entry.bracketMatchId === 'WB_R1_M1',
|
||||||
|
),
|
||||||
|
).toMatchObject({ state: 'completed', winnerTeamIndex: 1 });
|
||||||
|
expect(
|
||||||
|
match.doubleElimination?.bracketMatches.find(
|
||||||
|
(entry) => entry.bracketMatchId === 'WB_FINAL',
|
||||||
|
),
|
||||||
|
).toMatchObject({ teamAIndex: 1 });
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('TournamentResultService tournament code polling', () => {
|
describe('TournamentResultService tournament code polling', () => {
|
||||||
|
|||||||
@@ -6,7 +6,10 @@ import {
|
|||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import {
|
import {
|
||||||
|
buildDoubleEliminationGameSlots,
|
||||||
completeDoubleEliminationBracketMatch,
|
completeDoubleEliminationBracketMatch,
|
||||||
|
resolveDoubleEliminationSeriesWinner,
|
||||||
|
type DoubleEliminationGameSlot,
|
||||||
} from '../double-elimination/double-elimination.util';
|
} from '../double-elimination/double-elimination.util';
|
||||||
import { MatchStatsService } from '../community-stats/match-stats.service';
|
import { MatchStatsService } from '../community-stats/match-stats.service';
|
||||||
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
||||||
@@ -220,19 +223,20 @@ export class TournamentResultService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async processPollJob(job: PollTournamentResultJob): Promise<void> {
|
public async processPollJob(job: PollTournamentResultJob): Promise<void> {
|
||||||
const didProcessPollJob = await this.distributedLockService.runWithRenewedLock(
|
const didProcessPollJob =
|
||||||
{
|
await this.distributedLockService.runWithRenewedLock(
|
||||||
lockKey: this.tournamentResultPollProcessingLockKey(job.matchId),
|
{
|
||||||
lockExpirationDurationMilliseconds:
|
lockKey: this.tournamentResultPollProcessingLockKey(job.matchId),
|
||||||
TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_EXPIRATION_DURATION_MILLISECONDS,
|
lockExpirationDurationMilliseconds:
|
||||||
lockRenewalIntervalMilliseconds:
|
TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_EXPIRATION_DURATION_MILLISECONDS,
|
||||||
TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_RENEWAL_INTERVAL_MILLISECONDS,
|
lockRenewalIntervalMilliseconds:
|
||||||
},
|
TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_RENEWAL_INTERVAL_MILLISECONDS,
|
||||||
async () => {
|
},
|
||||||
await this.processPollJobWhileLockOwned(job);
|
async () => {
|
||||||
return true;
|
await this.processPollJobWhileLockOwned(job);
|
||||||
},
|
return true;
|
||||||
);
|
},
|
||||||
|
);
|
||||||
|
|
||||||
if (didProcessPollJob) return;
|
if (didProcessPollJob) return;
|
||||||
this.logger.debug(
|
this.logger.debug(
|
||||||
@@ -391,7 +395,17 @@ export class TournamentResultService {
|
|||||||
await code.save();
|
await code.save();
|
||||||
|
|
||||||
this.upsertGameResult(match, gameResult);
|
this.upsertGameResult(match, gameResult);
|
||||||
this.advanceDoubleEliminationIfNeeded(match, gameResult, 'riot-result');
|
const completedBracketMatchId = this.advanceDoubleEliminationIfNeeded(
|
||||||
|
match,
|
||||||
|
gameResult,
|
||||||
|
'riot-result',
|
||||||
|
);
|
||||||
|
if (completedBracketMatchId) {
|
||||||
|
await this.releaseUnusedReservedDoubleEliminationCodes(
|
||||||
|
match,
|
||||||
|
completedBracketMatchId,
|
||||||
|
);
|
||||||
|
}
|
||||||
if (match.status === 'team-built') {
|
if (match.status === 'team-built') {
|
||||||
match.status = 'in-progress';
|
match.status = 'in-progress';
|
||||||
}
|
}
|
||||||
@@ -426,7 +440,17 @@ export class TournamentResultService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.upsertGameResult(match, gameResult);
|
this.upsertGameResult(match, gameResult);
|
||||||
this.advanceDoubleEliminationIfNeeded(match, gameResult, 'riot-result');
|
const completedBracketMatchId = this.advanceDoubleEliminationIfNeeded(
|
||||||
|
match,
|
||||||
|
gameResult,
|
||||||
|
'riot-result',
|
||||||
|
);
|
||||||
|
if (completedBracketMatchId) {
|
||||||
|
await this.releaseUnusedReservedDoubleEliminationCodes(
|
||||||
|
match,
|
||||||
|
completedBracketMatchId,
|
||||||
|
);
|
||||||
|
}
|
||||||
await this.markTournamentCodeUsedForManualResult(
|
await this.markTournamentCodeUsedForManualResult(
|
||||||
match,
|
match,
|
||||||
gameResult,
|
gameResult,
|
||||||
@@ -719,19 +743,17 @@ export class TournamentResultService {
|
|||||||
const usedGameNumbers = new Set(
|
const usedGameNumbers = new Set(
|
||||||
(match.result?.games ?? []).map((game) => game.gameNumber),
|
(match.result?.games ?? []).map((game) => game.gameNumber),
|
||||||
);
|
);
|
||||||
const usedBracketMatchIds = new Set(
|
|
||||||
(match.result?.games ?? [])
|
|
||||||
.map((game) => game.bracketMatchId)
|
|
||||||
.filter((id): id is string => Boolean(id)),
|
|
||||||
);
|
|
||||||
const assignments: ManualGameAssignment[] = [];
|
const assignments: ManualGameAssignment[] = [];
|
||||||
if ((match.gameMode ?? 'pair') === 'double-elimination') {
|
if ((match.gameMode ?? 'pair') === 'double-elimination') {
|
||||||
for (const bracketMatch of match.doubleElimination?.bracketMatches ?? []) {
|
for (const slot of buildDoubleEliminationGameSlots(
|
||||||
|
match.doubleElimination?.bracketMatches ?? [],
|
||||||
|
)) {
|
||||||
|
const bracketMatch = slot.bracketMatch;
|
||||||
if (bracketMatch.state !== 'ready') continue;
|
if (bracketMatch.state !== 'ready') continue;
|
||||||
if (usedBracketMatchIds.has(bracketMatch.bracketMatchId)) continue;
|
if (usedGameNumbers.has(slot.gameNumber)) continue;
|
||||||
if (!bracketMatch.teamAIndex || !bracketMatch.teamBIndex) continue;
|
if (!bracketMatch.teamAIndex || !bracketMatch.teamBIndex) continue;
|
||||||
assignments.push({
|
assignments.push({
|
||||||
gameNumber: bracketMatch.gameNumber,
|
gameNumber: slot.gameNumber,
|
||||||
bracketMatchId: bracketMatch.bracketMatchId,
|
bracketMatchId: bracketMatch.bracketMatchId,
|
||||||
teamAIndex: bracketMatch.teamAIndex,
|
teamAIndex: bracketMatch.teamAIndex,
|
||||||
teamBIndex: bracketMatch.teamBIndex,
|
teamBIndex: bracketMatch.teamBIndex,
|
||||||
@@ -836,14 +858,27 @@ export class TournamentResultService {
|
|||||||
match: MatchDocument,
|
match: MatchDocument,
|
||||||
gameResult: MatchGameResult,
|
gameResult: MatchGameResult,
|
||||||
completedBy: 'riot-result' | 'walkover',
|
completedBy: 'riot-result' | 'walkover',
|
||||||
): void {
|
): string | undefined {
|
||||||
if ((match.gameMode ?? 'pair') !== 'double-elimination') return;
|
if ((match.gameMode ?? 'pair') !== 'double-elimination') return undefined;
|
||||||
if (!match.doubleElimination || !gameResult.bracketMatchId) return;
|
if (!match.doubleElimination || !gameResult.bracketMatchId)
|
||||||
|
return undefined;
|
||||||
|
const bracketMatch = match.doubleElimination.bracketMatches.find(
|
||||||
|
(entry) => entry.bracketMatchId === gameResult.bracketMatchId,
|
||||||
|
);
|
||||||
|
if (!bracketMatch || bracketMatch.state !== 'ready') return undefined;
|
||||||
|
const seriesResult = match.result?.seriesResults?.find(
|
||||||
|
(entry) => entry.bracketMatchId === gameResult.bracketMatchId,
|
||||||
|
);
|
||||||
|
const winnerTeamIndex = resolveDoubleEliminationSeriesWinner(
|
||||||
|
seriesResult,
|
||||||
|
bracketMatch,
|
||||||
|
);
|
||||||
|
if (!winnerTeamIndex) return undefined;
|
||||||
match.doubleElimination = completeDoubleEliminationBracketMatch(
|
match.doubleElimination = completeDoubleEliminationBracketMatch(
|
||||||
match.doubleElimination,
|
match.doubleElimination,
|
||||||
{
|
{
|
||||||
bracketMatchId: gameResult.bracketMatchId,
|
bracketMatchId: gameResult.bracketMatchId,
|
||||||
winnerTeamIndex: gameResult.winnerTeamIndex,
|
winnerTeamIndex,
|
||||||
completedBy,
|
completedBy,
|
||||||
completedAt: new Date(gameResult.gameCreation),
|
completedAt: new Date(gameResult.gameCreation),
|
||||||
},
|
},
|
||||||
@@ -853,14 +888,15 @@ export class TournamentResultService {
|
|||||||
match.doubleElimination!.placements.firstTeamIndex;
|
match.doubleElimination!.placements.firstTeamIndex;
|
||||||
}
|
}
|
||||||
match.markModified?.('doubleElimination');
|
match.markModified?.('doubleElimination');
|
||||||
|
return gameResult.bracketMatchId;
|
||||||
}
|
}
|
||||||
|
|
||||||
private isDoubleEliminationComplete(match: MatchDocument): boolean {
|
private isDoubleEliminationComplete(match: MatchDocument): boolean {
|
||||||
const placements = match.doubleElimination?.placements;
|
const placements = match.doubleElimination?.placements;
|
||||||
return Boolean(
|
return Boolean(
|
||||||
placements?.firstTeamIndex &&
|
placements?.firstTeamIndex &&
|
||||||
placements.secondTeamIndex &&
|
placements.secondTeamIndex &&
|
||||||
placements.thirdTeamIndex,
|
placements.thirdTeamIndex,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -883,9 +919,10 @@ export class TournamentResultService {
|
|||||||
match: MatchDocument,
|
match: MatchDocument,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
if ((match.gameMode ?? 'pair') !== 'double-elimination') return;
|
if ((match.gameMode ?? 'pair') !== 'double-elimination') return;
|
||||||
const readyBracketMatches = (match.doubleElimination?.bracketMatches ?? [])
|
const readySlots = buildDoubleEliminationGameSlots(
|
||||||
.filter((bracketMatch) => bracketMatch.state === 'ready');
|
match.doubleElimination?.bracketMatches ?? [],
|
||||||
if (readyBracketMatches.length === 0) return;
|
).filter((slot) => slot.bracketMatch.state === 'ready');
|
||||||
|
if (readySlots.length === 0) return;
|
||||||
|
|
||||||
const MatchModel = await this.connectionService.getModel('match');
|
const MatchModel = await this.connectionService.getModel('match');
|
||||||
const TournamentCodeModel =
|
const TournamentCodeModel =
|
||||||
@@ -896,20 +933,22 @@ export class TournamentResultService {
|
|||||||
_id: { $in: match.tournamentCodeIds },
|
_id: { $in: match.tournamentCodeIds },
|
||||||
}).exec()
|
}).exec()
|
||||||
: [];
|
: [];
|
||||||
const existingByBracketMatchId = new Map(
|
const existingByGameNumber = new Map(
|
||||||
existingCodes
|
existingCodes
|
||||||
.filter(
|
.filter(
|
||||||
(code) =>
|
(code) =>
|
||||||
code.bracketMatchId &&
|
typeof code.gameNumber === 'number' &&
|
||||||
(code.state === 'reserved' || code.state === 'used'),
|
(code.state === 'reserved' || code.state === 'used'),
|
||||||
)
|
)
|
||||||
.map((code) => [code.bracketMatchId as string, code]),
|
.map((code) => [code.gameNumber as number, code]),
|
||||||
);
|
);
|
||||||
const reservedIds: mongoose.Types.ObjectId[] = [];
|
const reservedIds: mongoose.Types.ObjectId[] = [];
|
||||||
const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS);
|
const expiresAfter = new Date(
|
||||||
|
Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS,
|
||||||
|
);
|
||||||
|
|
||||||
for (const bracketMatch of readyBracketMatches) {
|
for (const slot of readySlots) {
|
||||||
if (existingByBracketMatchId.has(bracketMatch.bracketMatchId)) continue;
|
if (existingByGameNumber.has(slot.gameNumber)) continue;
|
||||||
const code = await TournamentCodeModel.findOneAndUpdate(
|
const code = await TournamentCodeModel.findOneAndUpdate(
|
||||||
{
|
{
|
||||||
state: 'available',
|
state: 'available',
|
||||||
@@ -922,8 +961,8 @@ export class TournamentResultService {
|
|||||||
$set: {
|
$set: {
|
||||||
state: 'reserved',
|
state: 'reserved',
|
||||||
matchId: match._id,
|
matchId: match._id,
|
||||||
gameNumber: bracketMatch.gameNumber,
|
gameNumber: slot.gameNumber,
|
||||||
bracketMatchId: bracketMatch.bracketMatchId,
|
bracketMatchId: slot.bracketMatch.bracketMatchId,
|
||||||
reservedAt: new Date(),
|
reservedAt: new Date(),
|
||||||
},
|
},
|
||||||
$unset: { releasedAt: 1 },
|
$unset: { releasedAt: 1 },
|
||||||
@@ -960,9 +999,10 @@ export class TournamentResultService {
|
|||||||
await TournamentCodeModel.updateOne(
|
await TournamentCodeModel.updateOne(
|
||||||
{
|
{
|
||||||
matchId: match._id,
|
matchId: match._id,
|
||||||
|
gameNumber: gameResult.gameNumber,
|
||||||
...(gameResult.bracketMatchId
|
...(gameResult.bracketMatchId
|
||||||
? { bracketMatchId: gameResult.bracketMatchId }
|
? { bracketMatchId: gameResult.bracketMatchId }
|
||||||
: { gameNumber: gameResult.gameNumber }),
|
: {}),
|
||||||
state: { $in: ['reserved', 'released'] },
|
state: { $in: ['reserved', 'released'] },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -980,6 +1020,45 @@ export class TournamentResultService {
|
|||||||
).exec();
|
).exec();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async releaseUnusedReservedDoubleEliminationCodes(
|
||||||
|
match: MatchDocument,
|
||||||
|
bracketMatchId: string,
|
||||||
|
): Promise<void> {
|
||||||
|
const ids = match.tournamentCodeIds ?? [];
|
||||||
|
if (ids.length === 0) return;
|
||||||
|
const usedGameNumbers = new Set(
|
||||||
|
(match.result?.games ?? [])
|
||||||
|
.filter((game) => game.bracketMatchId === bracketMatchId)
|
||||||
|
.map((game) => game.gameNumber),
|
||||||
|
);
|
||||||
|
const TournamentCodeModel =
|
||||||
|
await this.connectionService.getModel('tournamentCode');
|
||||||
|
const codes = await TournamentCodeModel.find({
|
||||||
|
_id: { $in: ids },
|
||||||
|
matchId: match._id,
|
||||||
|
bracketMatchId,
|
||||||
|
state: 'reserved',
|
||||||
|
gameNumber: { $nin: [...usedGameNumbers] },
|
||||||
|
}).exec();
|
||||||
|
if (codes.length === 0) return;
|
||||||
|
const releasedIds = codes.map((code) => code._id.toString());
|
||||||
|
await TournamentCodeModel.updateMany(
|
||||||
|
{ _id: { $in: codes.map((code) => code._id) } },
|
||||||
|
{
|
||||||
|
$set: { state: 'released', releasedAt: new Date() },
|
||||||
|
$unset: {
|
||||||
|
matchId: 1,
|
||||||
|
gameNumber: 1,
|
||||||
|
bracketMatchId: 1,
|
||||||
|
reservedAt: 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
).exec();
|
||||||
|
match.tournamentCodeIds = ids.filter(
|
||||||
|
(id) => !releasedIds.includes(id.toString()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
private buildSeriesResults(
|
private buildSeriesResults(
|
||||||
games: MatchGameResult[],
|
games: MatchGameResult[],
|
||||||
): NonNullable<MatchDocument['result']>['seriesResults'] {
|
): NonNullable<MatchDocument['result']>['seriesResults'] {
|
||||||
@@ -1009,9 +1088,7 @@ export class TournamentResultService {
|
|||||||
|
|
||||||
return [...bySeries.values()].sort(
|
return [...bySeries.values()].sort(
|
||||||
(left, right) =>
|
(left, right) =>
|
||||||
(left.bracketMatchId ?? '').localeCompare(
|
(left.bracketMatchId ?? '').localeCompare(right.bracketMatchId ?? '') ||
|
||||||
right.bracketMatchId ?? '',
|
|
||||||
) ||
|
|
||||||
left.teamAIndex - right.teamAIndex ||
|
left.teamAIndex - right.teamAIndex ||
|
||||||
left.teamBIndex - right.teamBIndex,
|
left.teamBIndex - right.teamBIndex,
|
||||||
);
|
);
|
||||||
@@ -1024,13 +1101,14 @@ export class TournamentResultService {
|
|||||||
const gameMode = match.gameMode ?? 'pair';
|
const gameMode = match.gameMode ?? 'pair';
|
||||||
|
|
||||||
if (gameMode === 'double-elimination') {
|
if (gameMode === 'double-elimination') {
|
||||||
const bracketMatch = match.doubleElimination?.bracketMatches.find(
|
const slot = this.resolveDoubleEliminationGameSlotByGameNumber(
|
||||||
(entry) => entry.gameNumber === gameNumber,
|
match,
|
||||||
|
gameNumber,
|
||||||
);
|
);
|
||||||
return bracketMatch
|
return slot
|
||||||
? {
|
? {
|
||||||
teamAIndex: bracketMatch.teamAIndex ?? 1,
|
teamAIndex: slot.bracketMatch.teamAIndex ?? 1,
|
||||||
teamBIndex: bracketMatch.teamBIndex ?? 2,
|
teamBIndex: slot.bracketMatch.teamBIndex ?? 2,
|
||||||
}
|
}
|
||||||
: {
|
: {
|
||||||
teamAIndex: 1,
|
teamAIndex: 1,
|
||||||
@@ -1071,10 +1149,21 @@ export class TournamentResultService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private resolveDoubleEliminationGameSlotByGameNumber(
|
||||||
|
match: MatchDocument,
|
||||||
|
gameNumber: number,
|
||||||
|
): DoubleEliminationGameSlot | undefined {
|
||||||
|
return buildDoubleEliminationGameSlots(
|
||||||
|
match.doubleElimination?.bracketMatches ?? [],
|
||||||
|
).find((slot) => slot.gameNumber === gameNumber);
|
||||||
|
}
|
||||||
|
|
||||||
private resolveRequiredGameSlots(match: MatchDocument): number {
|
private resolveRequiredGameSlots(match: MatchDocument): number {
|
||||||
const gameMode = match.gameMode ?? 'pair';
|
const gameMode = match.gameMode ?? 'pair';
|
||||||
if (gameMode === 'double-elimination') {
|
if (gameMode === 'double-elimination') {
|
||||||
return match.doubleElimination?.bracketMatches.length ?? 0;
|
return buildDoubleEliminationGameSlots(
|
||||||
|
match.doubleElimination?.bracketMatches ?? [],
|
||||||
|
).length;
|
||||||
}
|
}
|
||||||
if (gameMode === 'round-robin') {
|
if (gameMode === 'round-robin') {
|
||||||
if ((match.gameSchedule?.length ?? 0) > 0) {
|
if ((match.gameSchedule?.length ?? 0) > 0) {
|
||||||
@@ -1210,7 +1299,9 @@ export class TournamentResultService {
|
|||||||
: matchOrId._id.toString();
|
: matchOrId._id.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
private tournamentResultPollProcessingLockKey(matchIdentifier: string): string {
|
private tournamentResultPollProcessingLockKey(
|
||||||
|
matchIdentifier: string,
|
||||||
|
): string {
|
||||||
return `distributed-lock:tournament-result:process-poll-job:match:${matchIdentifier}`;
|
return `distributed-lock:tournament-result:process-poll-job:match:${matchIdentifier}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -147,6 +147,9 @@ export type TournamentCodeSlotState = TournamentCodeState | 'pending';
|
|||||||
|
|
||||||
export interface TournamentCodeSlotView {
|
export interface TournamentCodeSlotView {
|
||||||
gameNumber: number;
|
gameNumber: number;
|
||||||
|
seriesGameNumber?: number;
|
||||||
|
seriesGameCount?: number;
|
||||||
|
seriesRequiredWins?: number;
|
||||||
bracketMatchId?: string;
|
bracketMatchId?: string;
|
||||||
bracketSide?: string;
|
bracketSide?: string;
|
||||||
roundNumber?: number;
|
roundNumber?: number;
|
||||||
@@ -257,6 +260,8 @@ export interface ApiDoubleEliminationWalkover {
|
|||||||
export interface ApiDoubleEliminationBracketMatch {
|
export interface ApiDoubleEliminationBracketMatch {
|
||||||
bracketMatchId: string;
|
bracketMatchId: string;
|
||||||
gameNumber: number;
|
gameNumber: number;
|
||||||
|
gameCount: number;
|
||||||
|
requiredWins: number;
|
||||||
bracketSide: 'winner' | 'loser' | 'grand-final' | 'reset-final';
|
bracketSide: 'winner' | 'loser' | 'grand-final' | 'reset-final';
|
||||||
roundNumber: number;
|
roundNumber: number;
|
||||||
matchNumber: number;
|
matchNumber: number;
|
||||||
|
|||||||
@@ -1535,6 +1535,9 @@ function TournamentCodeList({
|
|||||||
<div className="mb-1.5 flex items-center justify-between gap-2">
|
<div className="mb-1.5 flex items-center justify-between gap-2">
|
||||||
<span className="shrink-0 text-xs font-bold text-base-content/45">
|
<span className="shrink-0 text-xs font-bold text-base-content/45">
|
||||||
{slot.gameNumber}경기
|
{slot.gameNumber}경기
|
||||||
|
{slot.seriesGameCount && slot.seriesGameCount > 1
|
||||||
|
? ` · ${slot.seriesGameNumber ?? 1}/${slot.seriesGameCount}세트`
|
||||||
|
: ""}
|
||||||
</span>
|
</span>
|
||||||
{shouldShowTeamLabel && (
|
{shouldShowTeamLabel && (
|
||||||
<span className="min-w-0 truncate text-xs text-base-content/30">
|
<span className="min-w-0 truncate text-xs text-base-content/30">
|
||||||
@@ -2582,14 +2585,6 @@ function formatDoubleEliminationMatchState(
|
|||||||
return "대기";
|
return "대기";
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatDoubleEliminationCompletionType(
|
|
||||||
completedBy?: ApiDoubleEliminationBracketMatch["completedBy"],
|
|
||||||
) {
|
|
||||||
if (completedBy === "walkover") return "부전승";
|
|
||||||
if (completedBy === "riot-result") return "결과 반영";
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function DoubleEliminationBracketSection({
|
function DoubleEliminationBracketSection({
|
||||||
match,
|
match,
|
||||||
canManage,
|
canManage,
|
||||||
@@ -2984,9 +2979,6 @@ function DoubleEliminationBracketCard({
|
|||||||
canManage &&
|
canManage &&
|
||||||
bracketMatch.state === "ready" &&
|
bracketMatch.state === "ready" &&
|
||||||
Boolean(bracketMatch.teamAIndex && bracketMatch.teamBIndex);
|
Boolean(bracketMatch.teamAIndex && bracketMatch.teamBIndex);
|
||||||
const completionTypeLabel = formatDoubleEliminationCompletionType(
|
|
||||||
bracketMatch.completedBy,
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
@@ -3007,6 +2999,11 @@ function DoubleEliminationBracketCard({
|
|||||||
<span className="shrink-0 text-xs font-black text-base-content/70">
|
<span className="shrink-0 text-xs font-black text-base-content/70">
|
||||||
{bracketMatch.gameNumber}경기
|
{bracketMatch.gameNumber}경기
|
||||||
</span>
|
</span>
|
||||||
|
{bracketMatch.gameCount > 1 && (
|
||||||
|
<span className="shrink-0 text-xs font-black text-primary/70">
|
||||||
|
BO{bracketMatch.gameCount} · {bracketMatch.requiredWins}선승
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
<span className="truncate font-mono text-xs font-medium text-base-content/30">
|
<span className="truncate font-mono text-xs font-medium text-base-content/30">
|
||||||
{bracketMatch.bracketMatchId}
|
{bracketMatch.bracketMatchId}
|
||||||
</span>
|
</span>
|
||||||
@@ -3061,25 +3058,16 @@ function DoubleEliminationBracketCard({
|
|||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{(completionTypeLabel || canManage) && (
|
{canManage && (
|
||||||
<div className="mt-auto flex min-w-0 items-center justify-between gap-1">
|
<div className="mt-auto flex min-w-0 justify-end">
|
||||||
<div className="flex min-w-0 items-center gap-1">
|
<DoubleEliminationBracketCardActions
|
||||||
{completionTypeLabel && (
|
bracketMatch={bracketMatch}
|
||||||
<span className="shrink-0 border border-accent/25 bg-accent/10 px-1 text-xs font-black text-accent-content">
|
canApplyWalkover={canApplyWalkover}
|
||||||
{completionTypeLabel}
|
busy={busy}
|
||||||
</span>
|
onWalkover={onWalkover}
|
||||||
)}
|
onCancelWalkover={onCancelWalkover}
|
||||||
</div>
|
onCancelResult={onCancelResult}
|
||||||
{canManage && (
|
/>
|
||||||
<DoubleEliminationBracketCardActions
|
|
||||||
bracketMatch={bracketMatch}
|
|
||||||
canApplyWalkover={canApplyWalkover}
|
|
||||||
busy={busy}
|
|
||||||
onWalkover={onWalkover}
|
|
||||||
onCancelWalkover={onCancelWalkover}
|
|
||||||
onCancelResult={onCancelResult}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -52,6 +52,12 @@ function normalizeRoundRobinMaxRounds(
|
|||||||
return Math.max(1, Math.min(fullRoundCount, Math.floor(value)));
|
return Math.max(1, Math.min(fullRoundCount, Math.floor(value)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function normalizeSeriesGameCount(value: number | undefined) {
|
||||||
|
if (!value || !Number.isFinite(value) || value < 1) return 3;
|
||||||
|
const integer = Math.floor(value);
|
||||||
|
return integer % 2 === 0 ? integer + 1 : integer;
|
||||||
|
}
|
||||||
|
|
||||||
function RequiredBadge() {
|
function RequiredBadge() {
|
||||||
return (
|
return (
|
||||||
<span className="ml-1 inline-flex items-center border border-primary/20 bg-primary/5 px-1.5 py-0.5 text-xs font-bold text-primary">
|
<span className="ml-1 inline-flex items-center border border-primary/20 bg-primary/5 px-1.5 py-0.5 text-xs font-bold text-primary">
|
||||||
@@ -350,14 +356,15 @@ export default function MatchAdminPage() {
|
|||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
min={1}
|
min={1}
|
||||||
disabled={form.gameMode === 'double-elimination'}
|
step={form.gameMode === 'double-elimination' ? 2 : 1}
|
||||||
value={form.gameMode === 'double-elimination' ? 1 : form.gameCount}
|
value={form.gameCount}
|
||||||
onChange={(event) => setForm((current) => ({ ...current, gameCount: Number(event.target.value) }))}
|
onChange={(event) => setForm((current) => ({ ...current, gameCount: Number(event.target.value) }))}
|
||||||
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
|
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
|
||||||
/>
|
/>
|
||||||
{form.gameMode === 'double-elimination' && (
|
{form.gameMode === 'double-elimination' && (
|
||||||
<span className="mt-1 block text-xs text-base-content/30">
|
<span className="mt-1 block text-xs text-base-content/30">
|
||||||
더블 엘리미네이션은 단판으로 진행됩니다.
|
승자조는 현재 3판 2선승으로 진행됩니다. 추후 5판 3선승도 같은
|
||||||
|
구조로 지원합니다.
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</label>
|
</label>
|
||||||
@@ -377,7 +384,9 @@ export default function MatchAdminPage() {
|
|||||||
? 20
|
? 20
|
||||||
: current.maxParticipants,
|
: current.maxParticipants,
|
||||||
gameCount:
|
gameCount:
|
||||||
gameMode === 'double-elimination' ? 1 : current.gameCount,
|
gameMode === 'double-elimination'
|
||||||
|
? normalizeSeriesGameCount(current.gameCount)
|
||||||
|
: current.gameCount,
|
||||||
}));
|
}));
|
||||||
}}
|
}}
|
||||||
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
|
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
|
||||||
|
|||||||
Reference in new issue
Block a user