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