From 2135af71073b6ba5caf47a45a0aac78c45fafc51 Mon Sep 17 00:00:00 2001 From: Park Dahyeon Date: Sun, 12 Jul 2026 18:49:37 +0000 Subject: [PATCH] feat: add competition persistence schemas --- .../competition/competition.schema.spec.ts | 135 +++++++ .../modules/competition/competition.schema.ts | 370 ++++++++++++++++++ .../api/src/modules/global/database/schema.ts | 35 ++ 3 files changed, 540 insertions(+) create mode 100644 apps/api/src/modules/competition/competition.schema.spec.ts create mode 100644 apps/api/src/modules/competition/competition.schema.ts diff --git a/apps/api/src/modules/competition/competition.schema.spec.ts b/apps/api/src/modules/competition/competition.schema.spec.ts new file mode 100644 index 00000000..bc72e78a --- /dev/null +++ b/apps/api/src/modules/competition/competition.schema.spec.ts @@ -0,0 +1,135 @@ +import { + CompetitionFactSchema, + CompetitionOutboxSchema, + CompetitionSchema, + TournamentCodeAssignmentSchema, + competitionModelDefinitions, +} from './competition.schema'; +import { + MatchSchema, + MatchStatsSchema, + tournamentModelDefinitions, +} from '../global/database/schema'; + +describe('Competition persistence schemas', () => { + it('registers every Competition-owned collection', () => { + expect( + competitionModelDefinitions.map(({ name, schemaName }) => ({ + name, + schemaName, + })), + ).toEqual([ + { name: 'competition', schemaName: 'competition' }, + { name: 'competitionFact', schemaName: 'competition_fact' }, + { name: 'competitionOutbox', schemaName: 'competition_outbox' }, + { + name: 'tournamentCodeAssignment', + schemaName: 'tournament_code_assignment', + }, + ]); + expect(tournamentModelDefinitions).toEqual( + expect.arrayContaining( + competitionModelDefinitions.map(({ name, schemaName }) => + expect.objectContaining({ name, schemaName }), + ), + ), + ); + }); + + it('links Match and stats projections to the Competition revision', () => { + expect(MatchSchema.path('competitionId')).toBeDefined(); + expect(MatchStatsSchema.path('sourceCompetitionId')).toBeDefined(); + expect(MatchStatsSchema.path('sourceRevision')).toBeDefined(); + expect(MatchStatsSchema.path('projectorVersion')).toBeDefined(); + expectIndexes(MatchSchema, [ + { + keys: { competitionId: 1 }, + options: { unique: true }, + }, + ]); + }); + + it('enforces one Competition per Match and monotonic revisions', () => { + expectIndexes(CompetitionSchema, [ + { + keys: { matchId: 1 }, + options: { unique: true }, + }, + { + keys: { communityId: 1, phase: 1, updatedAt: -1 }, + }, + ]); + }); + + it('makes fact ordering and command replay identities unique', () => { + expectIndexes(CompetitionFactSchema, [ + { + keys: { competitionId: 1, revision: 1, ordinalWithinRevision: 1 }, + options: { unique: true }, + }, + { + keys: { competitionId: 1, commandId: 1, ordinalWithinRevision: 1 }, + options: { unique: true }, + }, + { + keys: { 'evidence.riotMatchId': 1 }, + options: { unique: true }, + }, + ]); + }); + + it('prevents duplicate outbox events', () => { + expectIndexes(CompetitionOutboxSchema, [ + { + keys: { eventId: 1 }, + options: { unique: true }, + }, + { + keys: { state: 1, availableAt: 1 }, + }, + ]); + }); + + it('allows only one active assignment for a code or GameSlot', () => { + expectIndexes(TournamentCodeAssignmentSchema, [ + { + keys: { gameSlotId: 1 }, + options: { + unique: true, + partialFilterExpression: { state: { $in: ['reserved', 'used'] } }, + }, + }, + { + keys: { tournamentCodeId: 1 }, + options: { + unique: true, + partialFilterExpression: { state: { $in: ['reserved', 'used'] } }, + }, + }, + { + keys: { riotMatchId: 1 }, + options: { unique: true }, + }, + ]); + }); +}); + +function expectIndexes( + schema: { indexes(): Array<[Record, Record]> }, + expected: Array<{ + keys: Record; + options?: Record; + }>, +) { + const indexes = schema.indexes(); + for (const candidate of expected) { + expect(indexes).toEqual( + expect.arrayContaining([ + [ + candidate.keys, + expect.objectContaining(candidate.options ?? {}), + ], + ]), + ); + } +} diff --git a/apps/api/src/modules/competition/competition.schema.ts b/apps/api/src/modules/competition/competition.schema.ts new file mode 100644 index 00000000..659199a8 --- /dev/null +++ b/apps/api/src/modules/competition/competition.schema.ts @@ -0,0 +1,370 @@ +import mongoose, { HydratedDocument, Schema } from 'mongoose'; + +export const COMPETITION_PHASES = [ + 'ready', + 'running', + 'completed', + 'cancelled', +] as const; +export type CompetitionPhase = (typeof COMPETITION_PHASES)[number]; + +export const COMPETITION_FACT_TYPES = [ + 'game-accepted', + 'game-voided', + 'series-adjudicated', + 'adjudication-reversed', +] as const; +export type CompetitionFactType = (typeof COMPETITION_FACT_TYPES)[number]; + +export const COMPETITION_OUTBOX_STATES = [ + 'pending', + 'published', + 'failed', +] as const; +export type CompetitionOutboxState = + (typeof COMPETITION_OUTBOX_STATES)[number]; + +export const TOURNAMENT_CODE_ASSIGNMENT_STATES = [ + 'reserved', + 'used', + 'released', + 'voided', +] as const; +export type TournamentCodeAssignmentState = + (typeof TOURNAMENT_CODE_ASSIGNMENT_STATES)[number]; + +export interface CompetitionTeamMemberSnapshot { + userId: mongoose.Types.ObjectId; + displayName: string; + gameName?: string; + tagLine?: string; + profileIconId?: number; + assignedPosition?: string; + cost?: number; +} + +export interface CompetitionTeamSnapshot { + teamId: mongoose.Types.ObjectId; + legacyTeamIndex?: number; + displayOrder: number; + seedNumber: number; + name: string; + captainUserId?: mongoose.Types.ObjectId; + members: CompetitionTeamMemberSnapshot[]; +} + +export interface Competition { + matchId: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + schemaVersion: number; + projectorVersion: number; + revision: number; + phase: CompetitionPhase; + teams: CompetitionTeamSnapshot[]; + format: Record; + seriesGraph: Array>; + projection: Record; + createdAt: Date; + updatedAt: Date; +} + +export type CompetitionDocument = HydratedDocument; + +export interface CompetitionFact { + competitionId: mongoose.Types.ObjectId; + type: CompetitionFactType; + revision: number; + ordinalWithinRevision: number; + commandId: string; + idempotencyKey: string; + requestHash: string; + schemaVersion: number; + actor: Record; + occurredAt: Date; + recordedAt: Date; + causationId?: string; + gameId?: mongoose.Types.ObjectId; + seriesId?: mongoose.Types.ObjectId; + gameSlotId?: mongoose.Types.ObjectId; + ordinal?: number; + evidence?: Record; + mapping?: Record; + gameAcceptedFactId?: mongoose.Types.ObjectId; + adjudicationFactId?: mongoose.Types.ObjectId; + decision?: Record; + reason?: string; + createdAt: Date; + updatedAt: Date; +} + +export type CompetitionFactDocument = HydratedDocument; + +export interface CompetitionOutbox { + eventId: string; + competitionId: mongoose.Types.ObjectId; + revision: number; + commandId: string; + idempotencyKey: string; + requestHash: string; + type: string; + payload: Record; + state: CompetitionOutboxState; + attemptCount: number; + availableAt: Date; + publishedAt?: Date; + lastError?: string; + createdAt: Date; + updatedAt: Date; +} + +export type CompetitionOutboxDocument = HydratedDocument; + +export interface TournamentCodeAssignment { + competitionId: mongoose.Types.ObjectId; + seriesId: mongoose.Types.ObjectId; + gameSlotId: mongoose.Types.ObjectId; + tournamentCodeId: mongoose.Types.ObjectId; + state: TournamentCodeAssignmentState; + reservedAt: Date; + usedAt?: Date; + releasedAt?: Date; + voidedAt?: Date; + riotMatchId?: string; + commandId: string; + createdAt: Date; + updatedAt: Date; +} + +export type TournamentCodeAssignmentDocument = + HydratedDocument; + +const CompetitionTeamMemberSchema = new Schema( + { + userId: { type: Schema.Types.ObjectId, ref: 'user', required: true }, + displayName: { type: String, required: true }, + gameName: { type: String }, + tagLine: { type: String }, + profileIconId: { type: Number }, + assignedPosition: { type: String }, + cost: { type: Number }, + }, + { _id: false }, +); + +const CompetitionTeamSchema = new Schema( + { + teamId: { type: Schema.Types.ObjectId, required: true }, + legacyTeamIndex: { type: Number, min: 1 }, + displayOrder: { type: Number, required: true, min: 1 }, + seedNumber: { type: Number, required: true, min: 1 }, + name: { type: String, required: true }, + captainUserId: { type: Schema.Types.ObjectId, ref: 'user' }, + members: { + type: [CompetitionTeamMemberSchema], + required: true, + default: [], + }, + }, + { _id: false }, +); + +export const CompetitionSchema: mongoose.Schema = + new Schema( + { + matchId: { + type: Schema.Types.ObjectId, + ref: 'match', + required: true, + }, + communityId: { + type: Schema.Types.ObjectId, + ref: 'community', + required: true, + }, + schemaVersion: { type: Number, required: true, min: 1 }, + projectorVersion: { type: Number, required: true, min: 1 }, + revision: { type: Number, required: true, min: 0, default: 0 }, + phase: { + type: String, + enum: COMPETITION_PHASES, + required: true, + default: 'ready', + }, + teams: { type: [CompetitionTeamSchema], required: true }, + format: { type: Schema.Types.Mixed, required: true }, + seriesGraph: { type: Schema.Types.Mixed, required: true }, + projection: { type: Schema.Types.Mixed, required: true }, + }, + { timestamps: true, collection: 'competition' }, + ); + +CompetitionSchema.index({ matchId: 1 }, { unique: true }); +CompetitionSchema.index({ communityId: 1, phase: 1, updatedAt: -1 }); + +export const CompetitionFactSchema = new Schema( + { + competitionId: { + type: Schema.Types.ObjectId, + ref: 'competition', + required: true, + }, + type: { type: String, enum: COMPETITION_FACT_TYPES, required: true }, + revision: { type: Number, required: true, min: 1 }, + ordinalWithinRevision: { type: Number, required: true, min: 1 }, + commandId: { type: String, required: true }, + idempotencyKey: { type: String, required: true }, + requestHash: { type: String, required: true }, + schemaVersion: { type: Number, required: true, min: 1 }, + actor: { type: Schema.Types.Mixed, required: true }, + occurredAt: { type: Date, required: true }, + recordedAt: { type: Date, required: true }, + causationId: { type: String }, + gameId: { type: Schema.Types.ObjectId }, + seriesId: { type: Schema.Types.ObjectId }, + gameSlotId: { type: Schema.Types.ObjectId }, + ordinal: { type: Number, min: 1 }, + evidence: { type: Schema.Types.Mixed }, + mapping: { type: Schema.Types.Mixed }, + gameAcceptedFactId: { type: Schema.Types.ObjectId }, + adjudicationFactId: { type: Schema.Types.ObjectId }, + decision: { type: Schema.Types.Mixed }, + reason: { type: String }, + }, + { timestamps: true, collection: 'competition_fact' }, +); + +CompetitionFactSchema.index( + { competitionId: 1, revision: 1, ordinalWithinRevision: 1 }, + { unique: true }, +); +CompetitionFactSchema.index( + { competitionId: 1, commandId: 1, ordinalWithinRevision: 1 }, + { unique: true }, +); +CompetitionFactSchema.index( + { 'evidence.riotMatchId': 1 }, + { + unique: true, + partialFilterExpression: { + type: 'game-accepted', + 'evidence.riotMatchId': { $type: 'string' }, + }, + }, +); +CompetitionFactSchema.index({ competitionId: 1, seriesId: 1, recordedAt: 1 }); + +export const CompetitionOutboxSchema = new Schema( + { + eventId: { type: String, required: true }, + competitionId: { + type: Schema.Types.ObjectId, + ref: 'competition', + required: true, + }, + revision: { type: Number, required: true, min: 1 }, + commandId: { type: String, required: true }, + idempotencyKey: { type: String, required: true }, + requestHash: { type: String, required: true }, + type: { type: String, required: true }, + payload: { type: Schema.Types.Mixed, required: true }, + state: { + type: String, + enum: COMPETITION_OUTBOX_STATES, + required: true, + default: 'pending', + }, + attemptCount: { type: Number, required: true, min: 0, default: 0 }, + availableAt: { type: Date, required: true }, + publishedAt: { type: Date }, + lastError: { type: String }, + }, + { timestamps: true, collection: 'competition_outbox' }, +); + +CompetitionOutboxSchema.index({ eventId: 1 }, { unique: true }); +CompetitionOutboxSchema.index({ state: 1, availableAt: 1 }); +CompetitionOutboxSchema.index( + { competitionId: 1, idempotencyKey: 1 }, + { unique: true }, +); + +export const TournamentCodeAssignmentSchema = + new Schema( + { + competitionId: { + type: Schema.Types.ObjectId, + ref: 'competition', + required: true, + }, + seriesId: { type: Schema.Types.ObjectId, required: true }, + gameSlotId: { type: Schema.Types.ObjectId, required: true }, + tournamentCodeId: { + type: Schema.Types.ObjectId, + ref: 'tournamentCode', + required: true, + }, + state: { + type: String, + enum: TOURNAMENT_CODE_ASSIGNMENT_STATES, + required: true, + }, + reservedAt: { type: Date, required: true }, + usedAt: { type: Date }, + releasedAt: { type: Date }, + voidedAt: { type: Date }, + riotMatchId: { type: String }, + commandId: { type: String, required: true }, + }, + { timestamps: true, collection: 'tournament_code_assignment' }, + ); + +const activeAssignmentFilter = { state: { $in: ['reserved', 'used'] } }; +TournamentCodeAssignmentSchema.index( + { gameSlotId: 1 }, + { + unique: true, + partialFilterExpression: activeAssignmentFilter, + }, +); +TournamentCodeAssignmentSchema.index( + { tournamentCodeId: 1 }, + { + unique: true, + partialFilterExpression: activeAssignmentFilter, + }, +); +TournamentCodeAssignmentSchema.index( + { riotMatchId: 1 }, + { + unique: true, + partialFilterExpression: { riotMatchId: { $type: 'string' } }, + }, +); +TournamentCodeAssignmentSchema.index({ competitionId: 1, state: 1 }); + +export const competitionModelDefinitions: Array<{ + name: string; + schema: mongoose.Schema; + schemaName: string; +}> = [ + { + name: 'competition', + schema: CompetitionSchema, + schemaName: 'competition', + }, + { + name: 'competitionFact', + schema: CompetitionFactSchema, + schemaName: 'competition_fact', + }, + { + name: 'competitionOutbox', + schema: CompetitionOutboxSchema, + schemaName: 'competition_outbox', + }, + { + name: 'tournamentCodeAssignment', + schema: TournamentCodeAssignmentSchema, + schemaName: 'tournament_code_assignment', + }, +]; diff --git a/apps/api/src/modules/global/database/schema.ts b/apps/api/src/modules/global/database/schema.ts index 2a6169ba..34783ab9 100644 --- a/apps/api/src/modules/global/database/schema.ts +++ b/apps/api/src/modules/global/database/schema.ts @@ -3,6 +3,13 @@ import type { RiotPlatformRoute, RiotRegionalRoute, } from '../../riot/riot.types'; +import { + Competition, + CompetitionFact, + CompetitionOutbox, + TournamentCodeAssignment, + competitionModelDefinitions, +} from '../../competition/competition.schema'; import { ModelDefinition } from './types'; export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP'; @@ -672,6 +679,7 @@ export interface MatchScheduleItem { export interface Match extends MongooseTimestamps { communityId: mongoose.Types.ObjectId; + competitionId?: mongoose.Types.ObjectId; shortCode?: string; title: string; description: string; @@ -1021,6 +1029,9 @@ export interface MatchStatsTimelinePoint { export interface MatchStats extends MongooseTimestamps { matchId: mongoose.Types.ObjectId; + sourceCompetitionId?: mongoose.Types.ObjectId; + sourceRevision?: number; + projectorVersion?: number; communityId: mongoose.Types.ObjectId; scheduledAt: Date; gameCreationMin: number; @@ -1845,6 +1856,11 @@ export const MatchSchema = new Schema( ref: 'community', required: true, }, + competitionId: { + type: Schema.Types.ObjectId, + ref: 'competition', + required: false, + }, shortCode: { type: String, required: false, @@ -1936,6 +1952,13 @@ export const MatchSchema = new Schema( ); MatchSchema.index({ communityId: 1, scheduledAt: -1 }); +MatchSchema.index( + { competitionId: 1 }, + { + unique: true, + partialFilterExpression: { competitionId: { $type: 'objectId' } }, + }, +); MatchSchema.index({ communityId: 1, status: 1, scheduledAt: -1 }); MatchSchema.index( { communityId: 1, shortCode: 1 }, @@ -2389,6 +2412,13 @@ export const MatchStatsSchema: mongoose.Schema = new Schema( required: true, unique: true, }, + sourceCompetitionId: { + type: Schema.Types.ObjectId, + ref: 'competition', + required: false, + }, + sourceRevision: { type: Number, required: false, min: 0 }, + projectorVersion: { type: Number, required: false, min: 1 }, communityId: { type: Schema.Types.ObjectId, ref: 'community', @@ -2419,6 +2449,7 @@ MatchStatsSchema.index({ communityId: 1, userIds: 1, scheduledAt: -1 }); MatchStatsSchema.index({ communityId: 1, championIds: 1 }); export const tournamentModelDefinitions: ModelDefinition[] = [ + ...competitionModelDefinitions, { name: 'identity', schema: IdentitySchema, schemaName: 'identity' }, { name: 'community', schema: CommunitySchema, schemaName: 'community' }, { @@ -2468,6 +2499,10 @@ export const tournamentModelDefinitions: ModelDefinition[] = [ ]; export interface TournamentModelTypes { + competition: Competition; + competitionFact: CompetitionFact; + competitionOutbox: CompetitionOutbox; + tournamentCodeAssignment: TournamentCodeAssignment; identity: Identity; community: Community; dakaoInboundMessage: DakaoInboundMessage;