feat: expose revision-safe competition API

This commit is contained in:
dahyeon committed 2026-07-12 19:34:15 +00:00
1 parent f3286e7fd1
commit 55e5b8df70
11 files changed
+2443 -19

No files matched your search

@@ -0,0 +1,340 @@
import type {
CompetitionFactView,
CompetitionFactsResponse,
TeamCompetitionViewResponse,
} from '@lolympus/contracts';
import {
ConflictException,
ForbiddenException,
Injectable,
NotFoundException,
UnprocessableEntityException,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type { Competition } from './competition.schema';
import { CompetitionBootstrapService } from './competition-bootstrap.service';
type PersistenceId = string | mongoose.Types.ObjectId;
export interface CompetitionScope {
communityId: mongoose.Types.ObjectId;
matchId: mongoose.Types.ObjectId;
}
interface CompetitionProjectionSource {
series?: Array<Record<string, unknown>>;
gameSlots?: Array<Record<string, unknown>>;
}
@Injectable()
export class CompetitionQueryService {
constructor(
private readonly connectionService: ConnectionService,
private readonly bootstrapService: CompetitionBootstrapService,
) {}
/** Resolve the one-to-one aggregate, lazily freezing a completed team build. */
public async getCompetition(scope: CompetitionScope): Promise<any> {
const CompetitionModel =
await this.connectionService.getModel('competition');
const existing = await CompetitionModel.findOne({
matchId: scope.matchId,
communityId: scope.communityId,
})
.lean()
.exec();
if (existing) return existing;
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findOne({
_id: scope.matchId,
communityId: scope.communityId,
})
.lean()
.exec();
if (!match) throw new NotFoundException('Match not found.');
if (
match.status === 'recruiting' ||
!Array.isArray(match.teams) ||
match.teams.length < 2
) {
throw new ConflictException(
'Competition is unavailable until team building is complete.',
);
}
return this.bootstrapService.bootstrap(match as never);
}
public async getTeamView(
scope: CompetitionScope & { userId: mongoose.Types.ObjectId },
): Promise<TeamCompetitionViewResponse> {
const competition = (await this.getCompetition(scope)) as Competition & {
_id: PersistenceId;
};
const team = competition.teams.find(({ members }) =>
members.some(({ userId }) => sameId(userId, scope.userId)),
);
if (!team) {
throw new ForbiddenException(
'Only a Competition team member may access the team view.',
);
}
const projection = competition.projection as CompetitionProjectionSource;
const allSeries = Array.isArray(projection.series) ? projection.series : [];
const teamId = idString(team.teamId);
const activeSeries = allSeries.filter(
(series) =>
series.status !== 'completed' &&
series.status !== 'inactive' &&
Array.isArray(series.entries) &&
series.entries.some(
(entry) =>
isRecord(entry) &&
idString(entry.teamId as PersistenceId) === teamId,
),
);
const activeSeriesIds = new Set(
activeSeries.map((series) => idString(series.seriesId as PersistenceId)),
);
const gameSlots = (
Array.isArray(projection.gameSlots) ? projection.gameSlots : []
).filter((slot) =>
activeSeriesIds.has(idString(slot.seriesId as PersistenceId)),
);
const AssignmentModel = await this.connectionService.getModel(
'tournamentCodeAssignment',
);
const queriedAssignments = await AssignmentModel.find({
competitionId: competition._id,
seriesId: { $in: [...activeSeriesIds] },
state: { $in: ['reserved', 'used'] },
})
.lean()
.exec();
// Keep this defensive filter even when the persistence query is mocked or
// changed: an opponent-only assignment must never cross this boundary.
const assignments = queriedAssignments.filter((assignment) =>
activeSeriesIds.has(idString(assignment.seriesId)),
);
const codeIds = assignments.map(({ tournamentCodeId }) => tournamentCodeId);
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const codes = codeIds.length
? await TournamentCodeModel.find({ _id: { $in: codeIds } })
.lean()
.exec()
: [];
const codeById = new Map(codes.map((code) => [idString(code._id), code]));
const assignmentBySlot = new Map(
assignments.map((assignment) => [
idString(assignment.gameSlotId),
assignment,
]),
);
return {
competitionId: idString(competition._id) as never,
revision: competition.revision,
phase: competition.phase,
teamId: teamId as never,
activeSeries: toWire(activeSeries) as never,
tournamentCodes: gameSlots.map((slot) => {
const gameSlotId = idString(slot.id as PersistenceId);
const assignment = assignmentBySlot.get(gameSlotId);
const code = assignment
? codeById.get(idString(assignment.tournamentCodeId))
: undefined;
return {
gameSlotId: gameSlotId as never,
seriesId: idString(slot.seriesId as PersistenceId) as never,
ordinal: numberValue(slot.ordinal),
displayNumber: numberValue(slot.displayNumber),
state:
assignment?.state === 'reserved' || assignment?.state === 'used'
? assignment.state
: 'pending',
code: typeof code?.code === 'string' ? code.code : null,
expiresAt: code?.expiresAt ? isoDate(code.expiresAt) : null,
};
}),
};
}
public async listFacts(
scope: CompetitionScope & { cursor?: string; limit?: number },
): Promise<CompetitionFactsResponse> {
const competition = (await this.getCompetition(scope)) as Competition & {
_id: PersistenceId;
};
const limit = normalizeLimit(scope.limit);
const cursor = scope.cursor ? decodeCursor(scope.cursor) : undefined;
const cursorFilter = cursor
? {
$or: [
{ revision: { $gt: cursor.revision } },
{
revision: cursor.revision,
ordinalWithinRevision: { $gt: cursor.ordinalWithinRevision },
},
{
revision: cursor.revision,
ordinalWithinRevision: cursor.ordinalWithinRevision,
_id: { $gt: new mongoose.Types.ObjectId(cursor.id) },
},
],
}
: {};
const FactModel = await this.connectionService.getModel('competitionFact');
const rows = await FactModel.find({
competitionId: competition._id,
...cursorFilter,
})
.sort({ revision: 1, ordinalWithinRevision: 1, _id: 1 })
.limit(limit + 1)
.lean()
.exec();
const page = rows.slice(0, limit);
const last = page.at(-1);
return {
facts: page.map(presentFact),
nextCursor:
rows.length > limit && last
? encodeCursor({
revision: last.revision,
ordinalWithinRevision: last.ordinalWithinRevision,
id: idString(last._id),
})
: null,
};
}
}
function presentFact(source: Record<string, any>): CompetitionFactView {
const common = {
id: idString(source._id) as never,
competitionId: idString(source.competitionId) as never,
revision: source.revision,
ordinalWithinRevision: source.ordinalWithinRevision,
commandId: String(source.commandId) as never,
schemaVersion: source.schemaVersion,
actor: toWire(source.actor) as never,
occurredAt: isoDate(source.occurredAt),
recordedAt: isoDate(source.recordedAt),
...(source.causationId ? { causationId: String(source.causationId) } : {}),
};
switch (source.type) {
case 'game-accepted':
return {
...common,
type: 'game-accepted',
gameId: idString(source.gameId) as never,
seriesId: idString(source.seriesId) as never,
gameSlotId: idString(source.gameSlotId) as never,
ordinal: source.ordinal,
startedAt: isoDate(source.startedAt ?? source.occurredAt),
durationSeconds: numberValue(source.durationSeconds ?? 0),
participants: toWire(source.participants ?? []) as never,
evidence: toWire(source.evidence) as never,
mapping: toWire(source.mapping) as never,
};
case 'game-voided':
return {
...common,
type: 'game-voided',
gameAcceptedFactId: idString(source.gameAcceptedFactId) as never,
reason: String(source.reason),
};
case 'series-adjudicated':
return {
...common,
type: 'series-adjudicated',
seriesId: idString(source.seriesId) as never,
decision: toWire(source.decision) as never,
reason: String(source.reason),
};
case 'adjudication-reversed':
return {
...common,
type: 'adjudication-reversed',
adjudicationFactId: idString(source.adjudicationFactId) as never,
reason: String(source.reason),
};
default:
throw new Error(`Unsupported Competition fact type: ${source.type}`);
}
}
interface FactCursor {
revision: number;
ordinalWithinRevision: number;
id: string;
}
function encodeCursor(cursor: FactCursor): string {
return Buffer.from(JSON.stringify(cursor)).toString('base64url');
}
function decodeCursor(value: string): FactCursor {
try {
const parsed = JSON.parse(Buffer.from(value, 'base64url').toString('utf8'));
if (
!isRecord(parsed) ||
!Number.isInteger(parsed.revision) ||
!Number.isInteger(parsed.ordinalWithinRevision) ||
typeof parsed.id !== 'string' ||
!mongoose.isValidObjectId(parsed.id)
) {
throw new Error('malformed cursor');
}
return parsed as unknown as FactCursor;
} catch {
throw new UnprocessableEntityException('Invalid facts cursor.');
}
}
function normalizeLimit(value: number | undefined): number {
if (value === undefined) return 50;
if (!Number.isInteger(value) || value < 1 || value > 100) {
throw new UnprocessableEntityException(
'Facts page limit must be an integer from 1 through 100.',
);
}
return value;
}
function sameId(left: PersistenceId, right: PersistenceId): boolean {
return idString(left) === idString(right);
}
function idString(value: PersistenceId): string {
return value instanceof mongoose.Types.ObjectId
? value.toHexString()
: String(value);
}
function isoDate(value: Date | string): string {
return value instanceof Date ? value.toISOString() : String(value);
}
function numberValue(value: unknown): number {
return typeof value === 'number' ? value : Number(value);
}
function toWire(value: unknown): unknown {
if (value instanceof mongoose.Types.ObjectId) return value.toHexString();
if (value instanceof Date) return value.toISOString();
if (Array.isArray(value)) return value.map(toWire);
if (isRecord(value)) {
return Object.fromEntries(
Object.entries(value).map(([key, child]) => [key, toWire(child)]),
);
}
return value;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}