feat: add competition persistence schemas

This commit is contained in:
dahyeon committed 2026-07-12 18:49:37 +00:00
1 parent 05a83db886
commit 2135af7107
3 files changed
+540

No files matched your search

@@ -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<string, number>, Record<string, unknown>]> },
expected: Array<{
keys: Record<string, number>;
options?: Record<string, unknown>;
}>,
) {
const indexes = schema.indexes();
for (const candidate of expected) {
expect(indexes).toEqual(
expect.arrayContaining([
[
candidate.keys,
expect.objectContaining(candidate.options ?? {}),
],
]),
);
}
}
@@ -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<string, unknown>;
seriesGraph: Array<Record<string, unknown>>;
projection: Record<string, unknown>;
createdAt: Date;
updatedAt: Date;
}
export type CompetitionDocument = HydratedDocument<Competition>;
export interface CompetitionFact {
competitionId: mongoose.Types.ObjectId;
type: CompetitionFactType;
revision: number;
ordinalWithinRevision: number;
commandId: string;
idempotencyKey: string;
requestHash: string;
schemaVersion: number;
actor: Record<string, unknown>;
occurredAt: Date;
recordedAt: Date;
causationId?: string;
gameId?: mongoose.Types.ObjectId;
seriesId?: mongoose.Types.ObjectId;
gameSlotId?: mongoose.Types.ObjectId;
ordinal?: number;
evidence?: Record<string, unknown>;
mapping?: Record<string, unknown>;
gameAcceptedFactId?: mongoose.Types.ObjectId;
adjudicationFactId?: mongoose.Types.ObjectId;
decision?: Record<string, unknown>;
reason?: string;
createdAt: Date;
updatedAt: Date;
}
export type CompetitionFactDocument = HydratedDocument<CompetitionFact>;
export interface CompetitionOutbox {
eventId: string;
competitionId: mongoose.Types.ObjectId;
revision: number;
commandId: string;
idempotencyKey: string;
requestHash: string;
type: string;
payload: Record<string, unknown>;
state: CompetitionOutboxState;
attemptCount: number;
availableAt: Date;
publishedAt?: Date;
lastError?: string;
createdAt: Date;
updatedAt: Date;
}
export type CompetitionOutboxDocument = HydratedDocument<CompetitionOutbox>;
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<TournamentCodeAssignment>;
const CompetitionTeamMemberSchema = new Schema<CompetitionTeamMemberSnapshot>(
{
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<CompetitionTeamSnapshot>(
{
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<Competition> =
new Schema<Competition>(
{
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<CompetitionFact>(
{
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<CompetitionOutbox>(
{
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<TournamentCodeAssignment>(
{
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',
},
];
@@ -3,6 +3,13 @@ import type {
RiotPlatformRoute, RiotPlatformRoute,
RiotRegionalRoute, RiotRegionalRoute,
} from '../../riot/riot.types'; } from '../../riot/riot.types';
import {
Competition,
CompetitionFact,
CompetitionOutbox,
TournamentCodeAssignment,
competitionModelDefinitions,
} from '../../competition/competition.schema';
import { ModelDefinition } from './types'; import { ModelDefinition } from './types';
export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP'; export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
@@ -672,6 +679,7 @@ export interface MatchScheduleItem {
export interface Match extends MongooseTimestamps { export interface Match extends MongooseTimestamps {
communityId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId;
competitionId?: mongoose.Types.ObjectId;
shortCode?: string; shortCode?: string;
title: string; title: string;
description: string; description: string;
@@ -1021,6 +1029,9 @@ export interface MatchStatsTimelinePoint {
export interface MatchStats extends MongooseTimestamps { export interface MatchStats extends MongooseTimestamps {
matchId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId;
sourceCompetitionId?: mongoose.Types.ObjectId;
sourceRevision?: number;
projectorVersion?: number;
communityId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId;
scheduledAt: Date; scheduledAt: Date;
gameCreationMin: number; gameCreationMin: number;
@@ -1845,6 +1856,11 @@ export const MatchSchema = new Schema<Match>(
ref: 'community', ref: 'community',
required: true, required: true,
}, },
competitionId: {
type: Schema.Types.ObjectId,
ref: 'competition',
required: false,
},
shortCode: { shortCode: {
type: String, type: String,
required: false, required: false,
@@ -1936,6 +1952,13 @@ export const MatchSchema = new Schema<Match>(
); );
MatchSchema.index({ communityId: 1, scheduledAt: -1 }); 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, status: 1, scheduledAt: -1 });
MatchSchema.index( MatchSchema.index(
{ communityId: 1, shortCode: 1 }, { communityId: 1, shortCode: 1 },
@@ -2389,6 +2412,13 @@ export const MatchStatsSchema: mongoose.Schema<MatchStats> = new Schema(
required: true, required: true,
unique: 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: { communityId: {
type: Schema.Types.ObjectId, type: Schema.Types.ObjectId,
ref: 'community', ref: 'community',
@@ -2419,6 +2449,7 @@ MatchStatsSchema.index({ communityId: 1, userIds: 1, scheduledAt: -1 });
MatchStatsSchema.index({ communityId: 1, championIds: 1 }); MatchStatsSchema.index({ communityId: 1, championIds: 1 });
export const tournamentModelDefinitions: ModelDefinition[] = [ export const tournamentModelDefinitions: ModelDefinition[] = [
...competitionModelDefinitions,
{ name: 'identity', schema: IdentitySchema, schemaName: 'identity' }, { name: 'identity', schema: IdentitySchema, schemaName: 'identity' },
{ name: 'community', schema: CommunitySchema, schemaName: 'community' }, { name: 'community', schema: CommunitySchema, schemaName: 'community' },
{ {
@@ -2468,6 +2499,10 @@ export const tournamentModelDefinitions: ModelDefinition[] = [
]; ];
export interface TournamentModelTypes { export interface TournamentModelTypes {
competition: Competition;
competitionFact: CompetitionFact;
competitionOutbox: CompetitionOutbox;
tournamentCodeAssignment: TournamentCodeAssignment;
identity: Identity; identity: Identity;
community: Community; community: Community;
dakaoInboundMessage: DakaoInboundMessage; dakaoInboundMessage: DakaoInboundMessage;