refactor: harden competition persistence type boundaries

This commit is contained in:
dahyeon committed 2026-07-12 20:18:48 +00:00
1 parent ec92494211
commit 7ea2002975
7 files changed
+127 -62

No files matched your search

@@ -293,7 +293,7 @@ function competitionStatsSource(
},
];
});
const startedAt = new Date(String(rawGame.startedAt ?? ''));
const startedAt = dateFromUnknown(rawGame.startedAt);
return [
{
gameNumber: finiteNumber(rawGame.displayNumber) ?? gameIndex + 1,
@@ -339,18 +339,18 @@ function competitionStatsSource(
function identifier(value: unknown): string | undefined {
if (typeof value === 'string' && value.length > 0) return value;
if (
typeof value === 'object' &&
value !== null &&
'toString' in value &&
typeof value.toString === 'function'
) {
const result = value.toString();
return result === '[object Object]' ? undefined : result;
}
if (value instanceof mongoose.Types.ObjectId) return value.toHexString();
return undefined;
}
function dateFromUnknown(value: unknown): Date {
if (value instanceof Date) return new Date(value.getTime());
if (typeof value === 'string' || typeof value === 'number') {
return new Date(value);
}
return new Date(Number.NaN);
}
function finiteNumber(value: unknown): number | undefined {
return typeof value === 'number' && Number.isFinite(value)
? value
@@ -161,7 +161,7 @@ export class CompetitionBootstrapService {
}
await session.commitTransaction();
return competition as CompetitionDocument;
return competition;
} catch (error) {
await session.abortTransaction().catch(() => undefined);
if (
@@ -91,6 +91,13 @@ interface CommandEnvelope {
payload: Readonly<Record<string, unknown>>;
}
interface AssignmentRecord {
seriesId: PersistenceId;
gameSlotId: PersistenceId;
tournamentCodeId: PersistenceId;
state: string;
}
@Injectable()
export class CompetitionCommandService {
constructor(private readonly connectionService: ConnectionService) {}
@@ -170,7 +177,7 @@ export class CompetitionCommandService {
.exec(),
AssignmentModel.find({ competitionId: command.competitionId })
.lean()
.exec(),
.exec() as Promise<AssignmentRecord[]>,
]);
const revisionCheck = await CompetitionModel.findById(command.competitionId)
.lean()
@@ -259,7 +266,7 @@ export class CompetitionCommandService {
AssignmentModel.find({ competitionId: command.competitionId })
.session(session)
.lean()
.exec(),
.exec() as Promise<AssignmentRecord[]>,
]);
const input = reversalInput(
competition,
@@ -589,7 +596,7 @@ export class CompetitionCommandService {
private async applyReversalAssignments(
competitionId: PersistenceId,
preview: SeriesReversalPreview,
assignments: Array<Record<string, any>>,
assignments: AssignmentRecord[],
commandId: string,
recordedAt: Date,
session: mongoose.ClientSession,
@@ -739,7 +746,11 @@ function buildOutbox(
updatedCompetition: unknown,
recordedAt: Date,
): Readonly<Record<string, unknown>> {
const facts = Array.isArray(fact) ? fact : [fact];
const facts: readonly Readonly<Record<string, unknown>>[] = Array.isArray(
fact,
)
? fact
: [fact];
return {
eventId: `${commandId}:competition-projected`,
competitionId,
@@ -861,7 +872,7 @@ function reversalInput(
competition: Pick<Competition, 'revision' | 'seriesGraph'>,
command: PreviewSeriesReversalCommand,
facts: readonly unknown[],
assignments: readonly Record<string, any>[],
assignments: readonly AssignmentRecord[],
) {
return {
competitionId: idString(command.competitionId),
@@ -12,10 +12,11 @@ import {
} from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type { Competition } from './competition.schema';
import type { Competition, CompetitionFact } from './competition.schema';
import { CompetitionBootstrapService } from './competition-bootstrap.service';
type PersistenceId = string | mongoose.Types.ObjectId;
type CompetitionRecord = Competition & { _id: mongoose.Types.ObjectId };
export interface CompetitionScope {
communityId: mongoose.Types.ObjectId;
@@ -35,7 +36,9 @@ export class CompetitionQueryService {
) {}
/** Resolve the one-to-one aggregate, lazily freezing a completed team build. */
public async getCompetition(scope: CompetitionScope): Promise<any> {
public async getCompetition(
scope: CompetitionScope,
): Promise<CompetitionRecord> {
const CompetitionModel =
await this.connectionService.getModel('competition');
const existing = await CompetitionModel.findOne({
@@ -44,7 +47,7 @@ export class CompetitionQueryService {
})
.lean()
.exec();
if (existing) return existing;
if (existing) return existing as CompetitionRecord;
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findOne({
@@ -203,37 +206,47 @@ export class CompetitionQueryService {
nextCursor:
rows.length > limit && last
? encodeCursor({
revision: last.revision,
ordinalWithinRevision: last.ordinalWithinRevision,
id: idString(last._id),
revision: requiredNumber(last.revision, 'revision'),
ordinalWithinRevision: requiredNumber(
last.ordinalWithinRevision,
'ordinalWithinRevision',
),
id: requiredId(last._id, '_id'),
})
: null,
};
}
}
function presentFact(source: Record<string, any>): CompetitionFactView {
function presentFact(
source: CompetitionFact & { _id: mongoose.Types.ObjectId },
): 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,
id: requiredId(source._id, '_id') as never,
competitionId: requiredId(source.competitionId, 'competitionId') as never,
revision: requiredNumber(source.revision, 'revision'),
ordinalWithinRevision: requiredNumber(
source.ordinalWithinRevision,
'ordinalWithinRevision',
),
commandId: requiredString(source.commandId, 'commandId') as never,
schemaVersion: requiredNumber(source.schemaVersion, 'schemaVersion'),
actor: toWire(source.actor) as never,
occurredAt: isoDate(source.occurredAt),
recordedAt: isoDate(source.recordedAt),
...(source.causationId ? { causationId: String(source.causationId) } : {}),
...(typeof source.causationId === 'string' && source.causationId.length > 0
? { causationId: 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,
gameId: requiredId(source.gameId, 'gameId') as never,
seriesId: requiredId(source.seriesId, 'seriesId') as never,
gameSlotId: requiredId(source.gameSlotId, 'gameSlotId') as never,
ordinal: requiredNumber(source.ordinal, 'ordinal'),
startedAt: isoDate(source.startedAt ?? source.occurredAt),
durationSeconds: numberValue(source.durationSeconds ?? 0),
participants: toWire(source.participants ?? []) as never,
@@ -244,26 +257,32 @@ function presentFact(source: Record<string, any>): CompetitionFactView {
return {
...common,
type: 'game-voided',
gameAcceptedFactId: idString(source.gameAcceptedFactId) as never,
reason: String(source.reason),
gameAcceptedFactId: requiredId(
source.gameAcceptedFactId,
'gameAcceptedFactId',
) as never,
reason: requiredString(source.reason, 'reason'),
};
case 'series-adjudicated':
return {
...common,
type: 'series-adjudicated',
seriesId: idString(source.seriesId) as never,
seriesId: requiredId(source.seriesId, 'seriesId') as never,
decision: toWire(source.decision) as never,
reason: String(source.reason),
reason: requiredString(source.reason, 'reason'),
};
case 'adjudication-reversed':
return {
...common,
type: 'adjudication-reversed',
adjudicationFactId: idString(source.adjudicationFactId) as never,
reason: String(source.reason),
adjudicationFactId: requiredId(
source.adjudicationFactId,
'adjudicationFactId',
) as never,
reason: requiredString(source.reason, 'reason'),
};
default:
throw new Error(`Unsupported Competition fact type: ${source.type}`);
throw new Error('Unsupported Competition fact type.');
}
}
@@ -279,7 +298,9 @@ function encodeCursor(cursor: FactCursor): string {
function decodeCursor(value: string): FactCursor {
try {
const parsed = JSON.parse(Buffer.from(value, 'base64url').toString('utf8'));
const parsed: unknown = JSON.parse(
Buffer.from(value, 'base64url').toString('utf8'),
);
if (
!isRecord(parsed) ||
!Number.isInteger(parsed.revision) ||
@@ -315,8 +336,10 @@ function idString(value: PersistenceId): string {
: String(value);
}
function isoDate(value: Date | string): string {
return value instanceof Date ? value.toISOString() : String(value);
function isoDate(value: unknown): string {
if (value instanceof Date) return value.toISOString();
if (typeof value === 'string') return value;
throw new Error('Competition fact contains an invalid date.');
}
function numberValue(value: unknown): number {
@@ -338,3 +361,18 @@ function toWire(value: unknown): unknown {
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function requiredId(value: unknown, field: string): string {
if (value instanceof mongoose.Types.ObjectId) return value.toHexString();
return requiredString(value, field);
}
function requiredString(value: unknown, field: string): string {
if (typeof value === 'string' && value.length > 0) return value;
throw new Error(`Competition fact contains an invalid ${field}.`);
}
function requiredNumber(value: unknown, field: string): number {
if (typeof value === 'number' && Number.isFinite(value)) return value;
throw new Error(`Competition fact contains an invalid ${field}.`);
}
@@ -56,7 +56,7 @@ type ReversalFact =
interface ReversalAssignment {
seriesId: string;
gameSlotId: string;
state: 'reserved' | 'used' | 'released' | 'voided' | string;
state: string;
}
export interface ReversalPreviewInput {
@@ -1469,9 +1469,24 @@ function canonicalize(value: unknown): string {
function opaqueString(value: unknown): string {
if (typeof value === 'string') return value.trim();
if (hasHexString(value)) {
const rendered = value.toHexString();
if (typeof rendered === 'string') return rendered.trim();
}
if (typeof value === 'number' || typeof value === 'boolean') {
return String(value);
}
if (value === undefined || value === null) return '';
const rendered = String(value);
return rendered === '[object Object]' ? '' : rendered;
return '';
}
function hasHexString(value: unknown): value is { toHexString(): unknown } {
return (
value !== null &&
typeof value === 'object' &&
'toHexString' in value &&
typeof value.toHexString === 'function'
);
}
function positiveInteger(value: unknown): number | undefined {
@@ -329,7 +329,7 @@ async function hydrateLegacyMatch(
.limit(0),
);
const result = isRecord(match.result) ? match.result : undefined;
const games = Array.isArray(result?.games) ? result.games : [];
const games = arrayOf(result?.games);
const riotMatchIds = uniqueStrings(
games.map((game) => (isRecord(game) ? game.riotMatchId : undefined)),
);
@@ -854,13 +854,9 @@ function optionalIdString(value: unknown): string | undefined {
function idString(value: unknown): string {
if (value instanceof mongoose.Types.ObjectId) return value.toHexString();
if (
value &&
typeof value === 'object' &&
'toHexString' in value &&
typeof value.toHexString === 'function'
) {
return String(value.toHexString());
if (hasHexString(value)) {
const rendered = value.toHexString();
if (typeof rendered === 'string') return rendered;
}
return String(value);
}
@@ -906,13 +902,9 @@ function canonicalJson(value: unknown): string {
function canonicalValue(value: unknown): unknown {
if (value instanceof mongoose.Types.ObjectId) return value.toHexString();
if (value instanceof Date) return value.toISOString();
if (
value &&
typeof value === 'object' &&
'toHexString' in value &&
typeof value.toHexString === 'function'
) {
return String(value.toHexString());
if (hasHexString(value)) {
const rendered = value.toHexString();
if (typeof rendered === 'string') return rendered;
}
if (Array.isArray(value)) return value.map(canonicalValue);
if (isRecord(value)) {
@@ -925,3 +917,12 @@ function canonicalValue(value: unknown): unknown {
}
return value;
}
function hasHexString(value: unknown): value is { toHexString(): unknown } {
return (
value !== null &&
typeof value === 'object' &&
'toHexString' in value &&
typeof value.toHexString === 'function'
);
}