refactor: import historical results as competition facts
This commit is contained in:
1 parent
6aa2cb9009
commit
7db97c540b
4 files changed
+1222
-77
No files matched your search
@@ -0,0 +1,716 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/require-await, @typescript-eslint/unbound-method */
|
||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
import type { CompetitionBootstrapService } from '../competition/competition-bootstrap.service';
|
||||||
|
import type { CompetitionCommandService } from '../competition/competition-command.service';
|
||||||
|
import type { MatchStatsService } from '../community-stats/match-stats.service';
|
||||||
|
import type { CommunityStatsService } from '../community-stats/community-stats.service';
|
||||||
|
import type { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import type { DistributedLockService } from '../global/redis/distributed-lock.service';
|
||||||
|
import type { RedisService } from '../global/redis/redis.service';
|
||||||
|
import type { RiotMatchService } from '../riot/riot-match.service';
|
||||||
|
import type { RiotMatchDto } from '../riot/riot.types';
|
||||||
|
import { LegacyImportService } from './legacy-import.service';
|
||||||
|
import type { LegacyUserSnapshot, UserByPuuidMap } from './match-builder.util';
|
||||||
|
import type { LegacyImportMemberJob } from './legacy-import.types';
|
||||||
|
|
||||||
|
const ServiceConstructor = LegacyImportService as unknown as new (
|
||||||
|
...dependencies: unknown[]
|
||||||
|
) => LegacyImportService;
|
||||||
|
|
||||||
|
describe('Legacy import Competition result cutover', () => {
|
||||||
|
it('has no production Match.result writer', () => {
|
||||||
|
const source = readFileSync(
|
||||||
|
require.resolve('./legacy-import.service'),
|
||||||
|
'utf8',
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(source).not.toMatch(/\b(?:match|update)\.result\s*=/u);
|
||||||
|
expect(source).not.toMatch(/\bresult\s*:\s*\{\s*winnerTeamIndex/u);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates a paired Competition and accepts Riot evidence without writing Match.result', async () => {
|
||||||
|
const fixture = createImportFixture();
|
||||||
|
const competitionFactModel = {
|
||||||
|
exists: jest.fn().mockResolvedValue(null),
|
||||||
|
};
|
||||||
|
const matchModel = {
|
||||||
|
findOneAndUpdate: jest.fn().mockReturnValue(execResult(fixture.match)),
|
||||||
|
updateOne: jest.fn().mockReturnValue(execResult({ modifiedCount: 1 })),
|
||||||
|
};
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn(async (name: string) => {
|
||||||
|
if (name === 'competitionFact') return competitionFactModel;
|
||||||
|
if (name === 'match') return matchModel;
|
||||||
|
throw new Error(`Unexpected model ${name}`);
|
||||||
|
}),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const bootstrapService = {
|
||||||
|
bootstrap: jest.fn().mockResolvedValue(fixture.competition),
|
||||||
|
} as unknown as jest.Mocked<CompetitionBootstrapService>;
|
||||||
|
const commandService = {
|
||||||
|
acceptGame: jest.fn().mockResolvedValue({
|
||||||
|
competition: {
|
||||||
|
...fixture.competition,
|
||||||
|
revision: 1,
|
||||||
|
phase: 'completed',
|
||||||
|
},
|
||||||
|
commandId: 'command-1',
|
||||||
|
revision: 1,
|
||||||
|
replayed: false,
|
||||||
|
}),
|
||||||
|
} as unknown as jest.Mocked<CompetitionCommandService>;
|
||||||
|
const matchStatsService = {
|
||||||
|
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
|
||||||
|
} as unknown as jest.Mocked<MatchStatsService>;
|
||||||
|
const service = createService({
|
||||||
|
connectionService,
|
||||||
|
matchStatsService,
|
||||||
|
bootstrapService,
|
||||||
|
commandService,
|
||||||
|
runWithLock: async (_options, operation) => operation(),
|
||||||
|
});
|
||||||
|
jest
|
||||||
|
.spyOn(
|
||||||
|
service as unknown as {
|
||||||
|
ensureRiotMatchPersisted: (
|
||||||
|
riotMatchId: string,
|
||||||
|
region: string,
|
||||||
|
) => Promise<RiotMatchDto>;
|
||||||
|
},
|
||||||
|
'ensureRiotMatchPersisted',
|
||||||
|
)
|
||||||
|
.mockResolvedValue(fixture.detail);
|
||||||
|
|
||||||
|
const outcome = await importSingleMatch(
|
||||||
|
service,
|
||||||
|
fixture.detail.metadata.matchId,
|
||||||
|
fixture.job,
|
||||||
|
fixture.userByPuuid,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(outcome).toBe('imported');
|
||||||
|
expect(matchModel.findOneAndUpdate).toHaveBeenCalledWith(
|
||||||
|
{ _id: expect.any(mongoose.Types.ObjectId) },
|
||||||
|
{
|
||||||
|
$setOnInsert: expect.not.objectContaining({
|
||||||
|
result: expect.anything(),
|
||||||
|
doubleElimination: expect.anything(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
expect.objectContaining({ upsert: true, returnDocument: 'after' }),
|
||||||
|
);
|
||||||
|
expect(bootstrapService.bootstrap).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
gameMode: 'pair',
|
||||||
|
gameCount: 1,
|
||||||
|
teams: expect.arrayContaining([
|
||||||
|
expect.objectContaining({ teamIndex: 1 }),
|
||||||
|
expect.objectContaining({ teamIndex: 2 }),
|
||||||
|
]),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(commandService.acceptGame).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
competitionId: fixture.competition._id.toString(),
|
||||||
|
expectedRevision: 0,
|
||||||
|
evidence: expect.objectContaining({
|
||||||
|
type: 'riot',
|
||||||
|
riotMatchId: fixture.detail.metadata.matchId,
|
||||||
|
payloadHash: expect.stringMatching(/^[a-f0-9]{64}$/u),
|
||||||
|
}),
|
||||||
|
mapping: expect.objectContaining({
|
||||||
|
blueTeamId: fixture.blueTeamId.toString(),
|
||||||
|
redTeamId: fixture.redTeamId.toString(),
|
||||||
|
winnerTeamId: fixture.blueTeamId.toString(),
|
||||||
|
algorithmVersion: 'roster-overlap-v1',
|
||||||
|
mappingVersion: 1,
|
||||||
|
confidence: 1,
|
||||||
|
diagnostics: {
|
||||||
|
trustedOverlap: 10,
|
||||||
|
normalOverlap: 10,
|
||||||
|
reversedOverlap: 0,
|
||||||
|
},
|
||||||
|
participantAssignments: expect.any(Array),
|
||||||
|
snapshot: expect.any(Object),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(matchModel.updateOne).toHaveBeenCalledWith(
|
||||||
|
{ _id: fixture.match._id },
|
||||||
|
{ $set: { status: 'finished' } },
|
||||||
|
);
|
||||||
|
expect(matchStatsService.buildAndUpsert).toHaveBeenCalledWith(
|
||||||
|
fixture.match._id,
|
||||||
|
{ sourceRevision: 1 },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('detects duplicates from accepted Competition fact evidence before fetching Riot data', async () => {
|
||||||
|
const fixture = createImportFixture();
|
||||||
|
const competitionFactModel = {
|
||||||
|
exists: jest
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValue({ _id: new mongoose.Types.ObjectId() }),
|
||||||
|
};
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn(async (name: string) => {
|
||||||
|
if (name === 'competitionFact') return competitionFactModel;
|
||||||
|
throw new Error(`Unexpected model ${name}`);
|
||||||
|
}),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const service = createService({
|
||||||
|
connectionService,
|
||||||
|
runWithLock: async (_options, operation) => operation(),
|
||||||
|
});
|
||||||
|
const ensureRiotMatchPersisted = jest
|
||||||
|
.spyOn(
|
||||||
|
service as unknown as {
|
||||||
|
ensureRiotMatchPersisted: () => Promise<RiotMatchDto>;
|
||||||
|
},
|
||||||
|
'ensureRiotMatchPersisted',
|
||||||
|
)
|
||||||
|
.mockResolvedValue(fixture.detail);
|
||||||
|
|
||||||
|
const outcome = await importSingleMatch(
|
||||||
|
service,
|
||||||
|
fixture.detail.metadata.matchId,
|
||||||
|
fixture.job,
|
||||||
|
fixture.userByPuuid,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(outcome).toBe('duplicate');
|
||||||
|
expect(competitionFactModel.exists).toHaveBeenCalledWith({
|
||||||
|
type: 'game-accepted',
|
||||||
|
'evidence.type': 'riot',
|
||||||
|
'evidence.riotMatchId': fixture.detail.metadata.matchId,
|
||||||
|
});
|
||||||
|
expect(ensureRiotMatchPersisted).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lists new legacy imports from Competition projection when Match.result is absent', async () => {
|
||||||
|
const fixture = createImportFixture();
|
||||||
|
const canonicalCompetition = {
|
||||||
|
...fixture.competition,
|
||||||
|
revision: 1,
|
||||||
|
phase: 'completed',
|
||||||
|
projection: {
|
||||||
|
phase: 'completed',
|
||||||
|
series: [
|
||||||
|
{
|
||||||
|
...fixture.competition.projection.series[0],
|
||||||
|
status: 'completed',
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
slot: 'A',
|
||||||
|
teamId: fixture.blueTeamId,
|
||||||
|
gameWins: 1,
|
||||||
|
},
|
||||||
|
{ slot: 'B', teamId: fixture.redTeamId, gameWins: 0 },
|
||||||
|
],
|
||||||
|
outcome: {
|
||||||
|
type: 'played',
|
||||||
|
winnerTeamId: fixture.blueTeamId,
|
||||||
|
loserTeamId: fixture.redTeamId,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
gameSlots: [],
|
||||||
|
games: [
|
||||||
|
{
|
||||||
|
seriesId: fixture.competition.projection.series[0].seriesId,
|
||||||
|
winnerTeamId: fixture.blueTeamId,
|
||||||
|
evidence: {
|
||||||
|
type: 'riot',
|
||||||
|
riotMatchId: fixture.detail.metadata.matchId,
|
||||||
|
},
|
||||||
|
participants: fixture.match.participants.map(({ userId }) => ({
|
||||||
|
userId,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const matchModel = {
|
||||||
|
find: jest.fn().mockReturnValue({
|
||||||
|
sort: jest.fn().mockReturnValue({
|
||||||
|
limit: jest.fn().mockReturnValue(execResult([fixture.match])),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
const competitionModel = {
|
||||||
|
find: jest.fn().mockReturnValue({
|
||||||
|
lean: jest.fn().mockReturnValue(execResult([canonicalCompetition])),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
const riotMatchModel = {
|
||||||
|
find: jest.fn().mockReturnValue({
|
||||||
|
lean: jest.fn().mockReturnValue(
|
||||||
|
execResult([
|
||||||
|
{
|
||||||
|
matchId: fixture.detail.metadata.matchId,
|
||||||
|
raw: fixture.detail,
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn((name: string) => {
|
||||||
|
if (name === 'match') return Promise.resolve(matchModel);
|
||||||
|
if (name === 'competition') return Promise.resolve(competitionModel);
|
||||||
|
if (name === 'riotMatch') return Promise.resolve(riotMatchModel);
|
||||||
|
return Promise.reject(new Error(`Unexpected model ${name}`));
|
||||||
|
}),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const service = createService({ connectionService });
|
||||||
|
jest
|
||||||
|
.spyOn(
|
||||||
|
service as unknown as {
|
||||||
|
buildUserByPuuidMap: () => Promise<UserByPuuidMap>;
|
||||||
|
},
|
||||||
|
'buildUserByPuuidMap',
|
||||||
|
)
|
||||||
|
.mockResolvedValue(fixture.userByPuuid);
|
||||||
|
|
||||||
|
const page = await service.listLegacyMatches({
|
||||||
|
communityId: fixture.match.communityId,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(page.matches).toEqual([
|
||||||
|
expect.objectContaining({
|
||||||
|
matchId: fixture.match._id.toString(),
|
||||||
|
riotMatchId: fixture.detail.metadata.matchId,
|
||||||
|
memberCount: 10,
|
||||||
|
externalCount: 0,
|
||||||
|
teamAIndex: 1,
|
||||||
|
teamBIndex: 2,
|
||||||
|
teamAWins: 1,
|
||||||
|
teamBWins: 0,
|
||||||
|
winnerTeamIndex: 1,
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('cascades admin deletion through Competition facts and read models', async () => {
|
||||||
|
const fixture = createImportFixture();
|
||||||
|
const competitionFactModel = deleteManyModel();
|
||||||
|
const competitionOutboxModel = deleteManyModel();
|
||||||
|
const assignmentModel = deleteManyModel();
|
||||||
|
const competitionModel = {
|
||||||
|
...deleteManyModel(),
|
||||||
|
find: jest.fn().mockReturnValue({
|
||||||
|
select: jest.fn().mockReturnValue({
|
||||||
|
lean: jest
|
||||||
|
.fn()
|
||||||
|
.mockReturnValue(execResult([{ _id: fixture.competition._id }])),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
const matchModel = {
|
||||||
|
find: jest.fn().mockReturnValue({
|
||||||
|
select: jest
|
||||||
|
.fn()
|
||||||
|
.mockReturnValue(execResult([{ _id: fixture.match._id }])),
|
||||||
|
}),
|
||||||
|
deleteMany: jest.fn().mockReturnValue(execResult({ deletedCount: 1 })),
|
||||||
|
};
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn((name: string) => {
|
||||||
|
const models: Record<string, unknown> = {
|
||||||
|
match: matchModel,
|
||||||
|
competition: competitionModel,
|
||||||
|
competitionFact: competitionFactModel,
|
||||||
|
competitionOutbox: competitionOutboxModel,
|
||||||
|
tournamentCodeAssignment: assignmentModel,
|
||||||
|
};
|
||||||
|
const model = models[name];
|
||||||
|
return model
|
||||||
|
? Promise.resolve(model)
|
||||||
|
: Promise.reject(new Error(`Unexpected model ${name}`));
|
||||||
|
}),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const matchStatsService = {
|
||||||
|
removeByMatches: jest.fn().mockResolvedValue(undefined),
|
||||||
|
} as unknown as jest.Mocked<MatchStatsService>;
|
||||||
|
const communityStatsService = {
|
||||||
|
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
|
||||||
|
} as unknown as jest.Mocked<CommunityStatsService>;
|
||||||
|
const service = createService({
|
||||||
|
connectionService,
|
||||||
|
matchStatsService,
|
||||||
|
communityStatsService,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await service.bulkDeleteLegacyMatches({
|
||||||
|
communityId: fixture.match.communityId,
|
||||||
|
body: { matchIds: [fixture.match._id.toString()] },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toEqual({ deleted: 1 });
|
||||||
|
for (const model of [
|
||||||
|
competitionFactModel,
|
||||||
|
competitionOutboxModel,
|
||||||
|
assignmentModel,
|
||||||
|
]) {
|
||||||
|
expect(model.deleteMany).toHaveBeenCalledWith({
|
||||||
|
competitionId: { $in: [fixture.competition._id] },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
expect(competitionModel.deleteMany).toHaveBeenCalledWith({
|
||||||
|
_id: { $in: [fixture.competition._id] },
|
||||||
|
});
|
||||||
|
expect(matchStatsService.removeByMatches).toHaveBeenCalledWith([
|
||||||
|
fixture.match._id,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rebuilds a historical legacy Match into Competition facts without rewriting Match.result', async () => {
|
||||||
|
const fixture = createImportFixture();
|
||||||
|
const historicalMatch = {
|
||||||
|
...fixture.match,
|
||||||
|
legacyImported: true,
|
||||||
|
result: {
|
||||||
|
riotMatchIds: [fixture.detail.metadata.matchId],
|
||||||
|
games: [
|
||||||
|
{
|
||||||
|
riotMatchId: fixture.detail.metadata.matchId,
|
||||||
|
participants: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
seriesResults: [],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const matchModel = {
|
||||||
|
find: jest.fn().mockReturnValue(execResult([historicalMatch])),
|
||||||
|
updateOne: jest.fn().mockReturnValue(execResult({ modifiedCount: 1 })),
|
||||||
|
};
|
||||||
|
const competitionModel = {
|
||||||
|
find: jest.fn().mockReturnValue({
|
||||||
|
lean: jest.fn().mockReturnValue(execResult([])),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
const riotMatchModel = {
|
||||||
|
find: jest.fn().mockReturnValue({
|
||||||
|
lean: jest.fn().mockReturnValue(
|
||||||
|
execResult([
|
||||||
|
{
|
||||||
|
matchId: fixture.detail.metadata.matchId,
|
||||||
|
raw: fixture.detail,
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn(async (name: string) => {
|
||||||
|
if (name === 'match') return matchModel;
|
||||||
|
if (name === 'competition') return competitionModel;
|
||||||
|
if (name === 'riotMatch') return riotMatchModel;
|
||||||
|
throw new Error(`Unexpected model ${name}`);
|
||||||
|
}),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const bootstrapService = {
|
||||||
|
bootstrap: jest.fn().mockResolvedValue(fixture.competition),
|
||||||
|
} as unknown as jest.Mocked<CompetitionBootstrapService>;
|
||||||
|
const commandService = {
|
||||||
|
acceptGame: jest.fn().mockResolvedValue({
|
||||||
|
competition: {
|
||||||
|
...fixture.competition,
|
||||||
|
revision: 1,
|
||||||
|
phase: 'completed',
|
||||||
|
},
|
||||||
|
commandId: 'command-1',
|
||||||
|
revision: 1,
|
||||||
|
replayed: false,
|
||||||
|
}),
|
||||||
|
} as unknown as jest.Mocked<CompetitionCommandService>;
|
||||||
|
const matchStatsService = {
|
||||||
|
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
|
||||||
|
} as unknown as jest.Mocked<MatchStatsService>;
|
||||||
|
const service = createService({
|
||||||
|
connectionService,
|
||||||
|
matchStatsService,
|
||||||
|
bootstrapService,
|
||||||
|
commandService,
|
||||||
|
});
|
||||||
|
jest
|
||||||
|
.spyOn(
|
||||||
|
service as unknown as {
|
||||||
|
buildUserByPuuidMap: () => Promise<UserByPuuidMap>;
|
||||||
|
},
|
||||||
|
'buildUserByPuuidMap',
|
||||||
|
)
|
||||||
|
.mockResolvedValue(fixture.userByPuuid);
|
||||||
|
|
||||||
|
const result = await service.rebuildLegacyMatches({
|
||||||
|
communityId: fixture.match.communityId,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toMatchObject({ scanned: 1, rebuilt: 1 });
|
||||||
|
for (const [, update] of matchModel.updateOne.mock.calls) {
|
||||||
|
expect(update).toEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
$set: expect.not.objectContaining({ result: expect.anything() }),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
expect(bootstrapService.bootstrap).toHaveBeenCalledTimes(1);
|
||||||
|
expect(commandService.acceptGame).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
actor: { type: 'system' },
|
||||||
|
evidence: expect.objectContaining({
|
||||||
|
type: 'riot',
|
||||||
|
riotMatchId: fixture.detail.metadata.matchId,
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(matchStatsService.buildAndUpsert).toHaveBeenCalledWith(
|
||||||
|
fixture.match._id,
|
||||||
|
{ sourceRevision: 1 },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function createService(
|
||||||
|
options: {
|
||||||
|
connectionService?: ConnectionService;
|
||||||
|
communityStatsService?: CommunityStatsService;
|
||||||
|
matchStatsService?: MatchStatsService;
|
||||||
|
bootstrapService?: CompetitionBootstrapService;
|
||||||
|
commandService?: CompetitionCommandService;
|
||||||
|
runWithLock?: (
|
||||||
|
options: Record<string, unknown>,
|
||||||
|
operation: () => Promise<unknown>,
|
||||||
|
) => Promise<unknown>;
|
||||||
|
} = {},
|
||||||
|
): LegacyImportService {
|
||||||
|
const distributedLockService = {
|
||||||
|
runWithLock:
|
||||||
|
options.runWithLock ??
|
||||||
|
(async (
|
||||||
|
_options: Record<string, unknown>,
|
||||||
|
operation: () => Promise<unknown>,
|
||||||
|
) => operation()),
|
||||||
|
} as unknown as DistributedLockService;
|
||||||
|
return new ServiceConstructor(
|
||||||
|
options.connectionService ?? ({} as ConnectionService),
|
||||||
|
{} as RedisService,
|
||||||
|
{} as RiotMatchService,
|
||||||
|
options.communityStatsService ??
|
||||||
|
({
|
||||||
|
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
|
||||||
|
} as unknown as CommunityStatsService),
|
||||||
|
options.matchStatsService ?? ({} as MatchStatsService),
|
||||||
|
distributedLockService,
|
||||||
|
options.bootstrapService ?? ({} as CompetitionBootstrapService),
|
||||||
|
options.commandService ?? ({} as CompetitionCommandService),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function importSingleMatch(
|
||||||
|
service: LegacyImportService,
|
||||||
|
riotMatchId: string,
|
||||||
|
job: LegacyImportMemberJob,
|
||||||
|
userByPuuid: UserByPuuidMap,
|
||||||
|
): Promise<string> {
|
||||||
|
return (
|
||||||
|
service as unknown as {
|
||||||
|
importSingleMatch: (
|
||||||
|
riotMatchId: string,
|
||||||
|
job: LegacyImportMemberJob,
|
||||||
|
userByPuuid: UserByPuuidMap,
|
||||||
|
) => Promise<string>;
|
||||||
|
}
|
||||||
|
).importSingleMatch(riotMatchId, job, userByPuuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
function createImportFixture() {
|
||||||
|
const communityId = new mongoose.Types.ObjectId();
|
||||||
|
const triggeredBy = new mongoose.Types.ObjectId();
|
||||||
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
|
const competitionId = new mongoose.Types.ObjectId();
|
||||||
|
const seriesId = new mongoose.Types.ObjectId();
|
||||||
|
const gameSlotId = new mongoose.Types.ObjectId();
|
||||||
|
const blueTeamId = new mongoose.Types.ObjectId();
|
||||||
|
const redTeamId = new mongoose.Types.ObjectId();
|
||||||
|
const users = Array.from({ length: 10 }, (_, index) => ({
|
||||||
|
userId: new mongoose.Types.ObjectId(),
|
||||||
|
puuid: `puuid-${index + 1}`,
|
||||||
|
}));
|
||||||
|
const userByPuuid: UserByPuuidMap = new Map(
|
||||||
|
users.map(({ userId, puuid }, index) => [
|
||||||
|
puuid,
|
||||||
|
{
|
||||||
|
userId,
|
||||||
|
account: {
|
||||||
|
puuid,
|
||||||
|
gameName: `player-${index + 1}`,
|
||||||
|
tagLine: 'KR1',
|
||||||
|
profileIconId: index + 1,
|
||||||
|
tiers: [],
|
||||||
|
isPrimary: true,
|
||||||
|
},
|
||||||
|
displayName: `player-${index + 1}`,
|
||||||
|
preferredPositions: [],
|
||||||
|
} as LegacyUserSnapshot,
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
const participants = users.map(({ puuid }, index) => ({
|
||||||
|
puuid,
|
||||||
|
participantId: index + 1,
|
||||||
|
teamId: index < 5 ? 100 : 200,
|
||||||
|
championId: index + 1,
|
||||||
|
teamPosition: ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'][index % 5],
|
||||||
|
kills: index < 5 ? 10 : 2,
|
||||||
|
deaths: index < 5 ? 2 : 10,
|
||||||
|
assists: index < 5 ? 8 : 3,
|
||||||
|
win: index < 5,
|
||||||
|
}));
|
||||||
|
const detail = {
|
||||||
|
metadata: {
|
||||||
|
dataVersion: '2',
|
||||||
|
matchId: 'KR_legacy_1',
|
||||||
|
participants: users.map(({ puuid }) => puuid),
|
||||||
|
},
|
||||||
|
info: {
|
||||||
|
gameCreation: Date.parse('2026-07-12T10:00:00.000Z'),
|
||||||
|
gameEndTimestamp: Date.parse('2026-07-12T10:30:00.000Z'),
|
||||||
|
gameDuration: 1_800,
|
||||||
|
mapId: 11,
|
||||||
|
tournamentCode: 'LEGACY-CODE',
|
||||||
|
participants,
|
||||||
|
teams: [
|
||||||
|
{ teamId: 100, win: true },
|
||||||
|
{ teamId: 200, win: false },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
} as unknown as RiotMatchDto;
|
||||||
|
const match = {
|
||||||
|
_id: matchId,
|
||||||
|
communityId,
|
||||||
|
title: 'legacy',
|
||||||
|
description: 'Legacy import (자동 생성)',
|
||||||
|
mapId: 11,
|
||||||
|
status: 'team-built',
|
||||||
|
scheduledAt: new Date(detail.info.gameCreation),
|
||||||
|
maxParticipants: 10,
|
||||||
|
gameCount: 1,
|
||||||
|
gameMode: 'pair',
|
||||||
|
tournamentCodeIds: [],
|
||||||
|
gameSchedule: [],
|
||||||
|
teamBuiltAt: new Date(detail.info.gameCreation),
|
||||||
|
hostUserId: triggeredBy,
|
||||||
|
participants: users.map(({ userId, puuid }, index) => ({
|
||||||
|
userId,
|
||||||
|
puuid,
|
||||||
|
gameName: `player-${index + 1}`,
|
||||||
|
tagLine: 'KR1',
|
||||||
|
profileIconId: index + 1,
|
||||||
|
preferredPositions: [],
|
||||||
|
joinedAt: new Date(detail.info.gameCreation),
|
||||||
|
})),
|
||||||
|
teams: [
|
||||||
|
{
|
||||||
|
teamIndex: 1,
|
||||||
|
name: '1팀',
|
||||||
|
members: users.slice(0, 5).map(({ userId }, index) => ({
|
||||||
|
userId,
|
||||||
|
assignedPosition: ['TOP', 'JGL', 'MID', 'ADC', 'SUP'][index],
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
teamIndex: 2,
|
||||||
|
name: '2팀',
|
||||||
|
members: users.slice(5).map(({ userId }, index) => ({
|
||||||
|
userId,
|
||||||
|
assignedPosition: ['TOP', 'JGL', 'MID', 'ADC', 'SUP'][index],
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
prizes: [],
|
||||||
|
notices: [],
|
||||||
|
schedule: [],
|
||||||
|
};
|
||||||
|
const competition = {
|
||||||
|
_id: competitionId,
|
||||||
|
matchId,
|
||||||
|
communityId,
|
||||||
|
revision: 0,
|
||||||
|
phase: 'ready',
|
||||||
|
teams: [
|
||||||
|
{
|
||||||
|
teamId: blueTeamId,
|
||||||
|
legacyTeamIndex: 1,
|
||||||
|
displayOrder: 1,
|
||||||
|
seedNumber: 1,
|
||||||
|
name: '1팀',
|
||||||
|
members: users.slice(0, 5).map(({ userId }) => ({ userId })),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
teamId: redTeamId,
|
||||||
|
legacyTeamIndex: 2,
|
||||||
|
displayOrder: 2,
|
||||||
|
seedNumber: 2,
|
||||||
|
name: '2팀',
|
||||||
|
members: users.slice(5).map(({ userId }) => ({ userId })),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
projection: {
|
||||||
|
phase: 'ready',
|
||||||
|
series: [
|
||||||
|
{
|
||||||
|
seriesId,
|
||||||
|
status: 'ready',
|
||||||
|
entries: [
|
||||||
|
{ slot: 'A', teamId: blueTeamId, gameWins: 0 },
|
||||||
|
{ slot: 'B', teamId: redTeamId, gameWins: 0 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
gameSlots: [
|
||||||
|
{
|
||||||
|
id: gameSlotId,
|
||||||
|
seriesId,
|
||||||
|
ordinal: 1,
|
||||||
|
displayNumber: 1,
|
||||||
|
status: 'ready',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
games: [],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const job: LegacyImportMemberJob = {
|
||||||
|
kind: 'legacy-import-member',
|
||||||
|
jobId: 'member-job-1',
|
||||||
|
parentJobId: 'legacy-job-1',
|
||||||
|
communityId: communityId.toString(),
|
||||||
|
userId: users[0].userId.toString(),
|
||||||
|
puuid: users[0].puuid,
|
||||||
|
startTime: 1,
|
||||||
|
endTime: 2,
|
||||||
|
triggeredBy: triggeredBy.toString(),
|
||||||
|
region: 'asia',
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
detail,
|
||||||
|
match,
|
||||||
|
competition,
|
||||||
|
blueTeamId,
|
||||||
|
redTeamId,
|
||||||
|
job,
|
||||||
|
userByPuuid,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function execResult<T>(value: T) {
|
||||||
|
return { exec: jest.fn().mockResolvedValue(value) };
|
||||||
|
}
|
||||||
|
|
||||||
|
function deleteManyModel() {
|
||||||
|
return {
|
||||||
|
deleteMany: jest
|
||||||
|
.fn()
|
||||||
|
.mockReturnValue(execResult({ acknowledged: true, deletedCount: 1 })),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,11 +1,12 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
|
import { CompetitionModule } from '../competition/competition.module';
|
||||||
import { CommunityStatsModule } from '../community-stats/community-stats.module';
|
import { CommunityStatsModule } from '../community-stats/community-stats.module';
|
||||||
import { RiotModule } from '../riot/riot.module';
|
import { RiotModule } from '../riot/riot.module';
|
||||||
import { LegacyImportController } from './legacy-import.controller';
|
import { LegacyImportController } from './legacy-import.controller';
|
||||||
import { LegacyImportService } from './legacy-import.service';
|
import { LegacyImportService } from './legacy-import.service';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [RiotModule, CommunityStatsModule],
|
imports: [RiotModule, CommunityStatsModule, CompetitionModule],
|
||||||
controllers: [LegacyImportController],
|
controllers: [LegacyImportController],
|
||||||
providers: [LegacyImportService],
|
providers: [LegacyImportService],
|
||||||
exports: [LegacyImportService],
|
exports: [LegacyImportService],
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
|
import { CompetitionBootstrapService } from '../competition/competition-bootstrap.service';
|
||||||
|
import { CompetitionCommandService } from '../competition/competition-command.service';
|
||||||
import { MatchStatsService } from '../community-stats/match-stats.service';
|
import { MatchStatsService } from '../community-stats/match-stats.service';
|
||||||
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
@@ -66,6 +68,8 @@ describe('LegacyImportService member job completion', () => {
|
|||||||
communityStatsService,
|
communityStatsService,
|
||||||
{} as MatchStatsService,
|
{} as MatchStatsService,
|
||||||
distributedLockService,
|
distributedLockService,
|
||||||
|
{} as CompetitionBootstrapService,
|
||||||
|
{} as CompetitionCommandService,
|
||||||
);
|
);
|
||||||
const job: LegacyImportMemberJob = {
|
const job: LegacyImportMemberJob = {
|
||||||
kind: 'legacy-import-member',
|
kind: 'legacy-import-member',
|
||||||
|
|||||||
@@ -5,8 +5,16 @@ import {
|
|||||||
Logger,
|
Logger,
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { randomUUID } from 'crypto';
|
import { createHash, randomUUID } from 'node:crypto';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
|
import {
|
||||||
|
CompetitionBootstrapService,
|
||||||
|
type CompetitionBootstrapMatch,
|
||||||
|
} from '../competition/competition-bootstrap.service';
|
||||||
|
import {
|
||||||
|
CompetitionCommandService,
|
||||||
|
type CompetitionCommandActor,
|
||||||
|
} from '../competition/competition-command.service';
|
||||||
import { MatchStatsService } from '../community-stats/match-stats.service';
|
import { MatchStatsService } from '../community-stats/match-stats.service';
|
||||||
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
@@ -17,6 +25,7 @@ import {
|
|||||||
import type {
|
import type {
|
||||||
LegacyImportJobDocument,
|
LegacyImportJobDocument,
|
||||||
Match,
|
Match,
|
||||||
|
MatchDocument,
|
||||||
RiotMatch as StoredRiotMatch,
|
RiotMatch as StoredRiotMatch,
|
||||||
UserDocument,
|
UserDocument,
|
||||||
} from '../global/database/schema';
|
} from '../global/database/schema';
|
||||||
@@ -25,7 +34,11 @@ import { RIOT_JOB_LOW_STREAM } from '../riot-job-queue/riot-job-queue.types';
|
|||||||
import { RiotMatchService } from '../riot/riot-match.service';
|
import { RiotMatchService } from '../riot/riot-match.service';
|
||||||
import type { RiotMatchDto, RiotRegionalRoute } from '../riot/riot.types';
|
import type { RiotMatchDto, RiotRegionalRoute } from '../riot/riot.types';
|
||||||
import {
|
import {
|
||||||
buildGameResult,
|
resolveReadyCompetitionSlot,
|
||||||
|
type CompetitionResultSnapshot,
|
||||||
|
} from '../tournament-result/competition-result.adapter';
|
||||||
|
import type { MatchPuuidLookup } from '../tournament-result/team-mapping.util';
|
||||||
|
import {
|
||||||
buildParticipantsSnapshot,
|
buildParticipantsSnapshot,
|
||||||
buildTeams,
|
buildTeams,
|
||||||
buildUserByPuuidMap,
|
buildUserByPuuidMap,
|
||||||
@@ -50,6 +63,10 @@ const MATCH_IMPORT_LOCK_TTL_SECONDS = 60;
|
|||||||
const MATCH_ID_PAGE_SIZE = 100;
|
const MATCH_ID_PAGE_SIZE = 100;
|
||||||
|
|
||||||
type ImportOutcome = 'imported' | 'duplicate' | 'skipped' | 'error';
|
type ImportOutcome = 'imported' | 'duplicate' | 'skipped' | 'error';
|
||||||
|
type ResultlessMatchPatch = Omit<
|
||||||
|
Partial<Match>,
|
||||||
|
'result' | 'doubleElimination'
|
||||||
|
>;
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class LegacyImportService {
|
export class LegacyImportService {
|
||||||
@@ -62,6 +79,8 @@ export class LegacyImportService {
|
|||||||
private readonly communityStatsService: CommunityStatsService,
|
private readonly communityStatsService: CommunityStatsService,
|
||||||
private readonly matchStatsService: MatchStatsService,
|
private readonly matchStatsService: MatchStatsService,
|
||||||
private readonly distributedLockService: DistributedLockService,
|
private readonly distributedLockService: DistributedLockService,
|
||||||
|
private readonly competitionBootstrapService: CompetitionBootstrapService,
|
||||||
|
private readonly competitionCommandService: CompetitionCommandService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public async previewMembers(params: {
|
public async previewMembers(params: {
|
||||||
@@ -154,7 +173,7 @@ export class LegacyImportService {
|
|||||||
startTime: Math.floor(window.startTime.getTime() / 1000),
|
startTime: Math.floor(window.startTime.getTime() / 1000),
|
||||||
endTime: Math.floor(window.endTime.getTime() / 1000),
|
endTime: Math.floor(window.endTime.getTime() / 1000),
|
||||||
triggeredBy: params.triggeredBy.toString(),
|
triggeredBy: params.triggeredBy.toString(),
|
||||||
region: (community.riotRegion ?? 'asia') as RiotRegionalRoute,
|
region: community.riotRegion ?? 'asia',
|
||||||
};
|
};
|
||||||
await this.redisService.appendStream(
|
await this.redisService.appendStream(
|
||||||
RIOT_JOB_LOW_STREAM,
|
RIOT_JOB_LOW_STREAM,
|
||||||
@@ -302,8 +321,19 @@ export class LegacyImportService {
|
|||||||
.limit(limit + 1)
|
.limit(limit + 1)
|
||||||
.exec();
|
.exec();
|
||||||
const visible = matches.slice(0, limit);
|
const visible = matches.slice(0, limit);
|
||||||
const riotMatchIds = visible
|
const competitionByMatchId = await this.loadCompetitionByMatchId(
|
||||||
.map((match) => match.result?.games[0]?.riotMatchId)
|
visible.map(({ _id }) => _id),
|
||||||
|
);
|
||||||
|
const summaryByMatchId = new Map(
|
||||||
|
visible.map((match) => [
|
||||||
|
match._id.toString(),
|
||||||
|
summarizeCompetitionResult(
|
||||||
|
competitionByMatchId.get(match._id.toString()),
|
||||||
|
) ?? summarizeLegacyMatchResult(match),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
const riotMatchIds = [...summaryByMatchId.values()]
|
||||||
|
.map(({ riotMatchId }) => riotMatchId)
|
||||||
.filter((matchId): matchId is string => Boolean(matchId));
|
.filter((matchId): matchId is string => Boolean(matchId));
|
||||||
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
||||||
const rawDocs = await RiotMatchModel.find({
|
const rawDocs = await RiotMatchModel.find({
|
||||||
@@ -317,23 +347,23 @@ export class LegacyImportService {
|
|||||||
const userByPuuid = await this.buildUserByPuuidMap(params.communityId);
|
const userByPuuid = await this.buildUserByPuuidMap(params.communityId);
|
||||||
return {
|
return {
|
||||||
matches: visible.map((match) => {
|
matches: visible.map((match) => {
|
||||||
const riotMatchId = match.result?.games[0]?.riotMatchId ?? null;
|
const summary = summaryByMatchId.get(match._id.toString())!;
|
||||||
|
const riotMatchId = summary.riotMatchId;
|
||||||
const raw = riotMatchId ? rawById.get(riotMatchId) : undefined;
|
const raw = riotMatchId ? rawById.get(riotMatchId) : undefined;
|
||||||
const memberCount = match.result?.games[0]?.participants.length ?? 0;
|
|
||||||
return {
|
return {
|
||||||
matchId: match._id.toString(),
|
matchId: match._id.toString(),
|
||||||
title: match.title,
|
title: match.title,
|
||||||
scheduledAt: match.scheduledAt.toISOString(),
|
scheduledAt: match.scheduledAt.toISOString(),
|
||||||
riotMatchId,
|
riotMatchId,
|
||||||
memberCount,
|
memberCount: summary.memberCount,
|
||||||
externalCount: raw
|
externalCount: raw
|
||||||
? resolveExternalCount(raw, userByPuuid)
|
? resolveExternalCount(raw, userByPuuid)
|
||||||
: Math.max(0, 10 - memberCount),
|
: Math.max(0, 10 - summary.memberCount),
|
||||||
teamAIndex: match.result?.seriesResults?.[0]?.teamAIndex ?? 1,
|
teamAIndex: summary.teamAIndex,
|
||||||
teamBIndex: match.result?.seriesResults?.[0]?.teamBIndex ?? 2,
|
teamBIndex: summary.teamBIndex,
|
||||||
teamAWins: match.result?.seriesResults?.[0]?.teamAWins ?? 0,
|
teamAWins: summary.teamAWins,
|
||||||
teamBWins: match.result?.seriesResults?.[0]?.teamBWins ?? 0,
|
teamBWins: summary.teamBWins,
|
||||||
winnerTeamIndex: match.result?.winnerTeamIndex,
|
winnerTeamIndex: summary.winnerTeamIndex,
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
nextCursor:
|
nextCursor:
|
||||||
@@ -362,6 +392,41 @@ export class LegacyImportService {
|
|||||||
const targetIds = targets.map((match) => match._id);
|
const targetIds = targets.map((match) => match._id);
|
||||||
if (targetIds.length === 0) return { deleted: 0 };
|
if (targetIds.length === 0) return { deleted: 0 };
|
||||||
|
|
||||||
|
const [
|
||||||
|
CompetitionModel,
|
||||||
|
CompetitionFactModel,
|
||||||
|
CompetitionOutboxModel,
|
||||||
|
AssignmentModel,
|
||||||
|
] = await Promise.all([
|
||||||
|
this.connectionService.getModel('competition'),
|
||||||
|
this.connectionService.getModel('competitionFact'),
|
||||||
|
this.connectionService.getModel('competitionOutbox'),
|
||||||
|
this.connectionService.getModel('tournamentCodeAssignment'),
|
||||||
|
]);
|
||||||
|
const competitions = await CompetitionModel.find({
|
||||||
|
matchId: { $in: targetIds },
|
||||||
|
})
|
||||||
|
.select({ _id: 1 })
|
||||||
|
.lean()
|
||||||
|
.exec();
|
||||||
|
const competitionIds = competitions.map(({ _id }) => _id);
|
||||||
|
if (competitionIds.length > 0) {
|
||||||
|
await Promise.all([
|
||||||
|
CompetitionFactModel.deleteMany({
|
||||||
|
competitionId: { $in: competitionIds },
|
||||||
|
}).exec(),
|
||||||
|
CompetitionOutboxModel.deleteMany({
|
||||||
|
competitionId: { $in: competitionIds },
|
||||||
|
}).exec(),
|
||||||
|
AssignmentModel.deleteMany({
|
||||||
|
competitionId: { $in: competitionIds },
|
||||||
|
}).exec(),
|
||||||
|
]);
|
||||||
|
await CompetitionModel.deleteMany({
|
||||||
|
_id: { $in: competitionIds },
|
||||||
|
}).exec();
|
||||||
|
}
|
||||||
|
|
||||||
const result = await MatchModel.deleteMany({
|
const result = await MatchModel.deleteMany({
|
||||||
_id: { $in: targetIds },
|
_id: { $in: targetIds },
|
||||||
communityId: params.communityId,
|
communityId: params.communityId,
|
||||||
@@ -380,12 +445,19 @@ export class LegacyImportService {
|
|||||||
communityId: params.communityId,
|
communityId: params.communityId,
|
||||||
legacyImported: true,
|
legacyImported: true,
|
||||||
}).exec();
|
}).exec();
|
||||||
const riotMatchIds = matches
|
const competitionByMatchId = await this.loadCompetitionByMatchId(
|
||||||
.map(
|
matches.map(({ _id }) => _id),
|
||||||
(match) =>
|
);
|
||||||
match.result?.games[0]?.riotMatchId ??
|
const summaryByMatchId = new Map(
|
||||||
match.result?.riotMatchIds?.[0],
|
matches.map((match) => [
|
||||||
)
|
match._id.toString(),
|
||||||
|
summarizeCompetitionResult(
|
||||||
|
competitionByMatchId.get(match._id.toString()),
|
||||||
|
) ?? summarizeLegacyMatchResult(match),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
const riotMatchIds = [...summaryByMatchId.values()]
|
||||||
|
.map(({ riotMatchId }) => riotMatchId)
|
||||||
.filter((matchId): matchId is string => Boolean(matchId));
|
.filter((matchId): matchId is string => Boolean(matchId));
|
||||||
|
|
||||||
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
||||||
@@ -409,14 +481,17 @@ export class LegacyImportService {
|
|||||||
};
|
};
|
||||||
|
|
||||||
for (const match of matches) {
|
for (const match of matches) {
|
||||||
const riotMatchId =
|
const existingCompetition = competitionByMatchId.get(
|
||||||
match.result?.games[0]?.riotMatchId ?? match.result?.riotMatchIds?.[0];
|
match._id.toString(),
|
||||||
|
);
|
||||||
|
const summary = summaryByMatchId.get(match._id.toString())!;
|
||||||
|
const riotMatchId = summary.riotMatchId;
|
||||||
const raw = riotMatchId ? rawById.get(riotMatchId) : undefined;
|
const raw = riotMatchId ? rawById.get(riotMatchId) : undefined;
|
||||||
const title = this.normalizeLegacyTitle(
|
const title = this.normalizeLegacyTitle(
|
||||||
match.title,
|
match.title,
|
||||||
raw?.info.gameCreation ?? match.scheduledAt.getTime(),
|
raw?.info.gameCreation ?? match.scheduledAt.getTime(),
|
||||||
);
|
);
|
||||||
const update: Partial<Match> = {};
|
const update: ResultlessMatchPatch = {};
|
||||||
if (title !== match.title) {
|
if (title !== match.title) {
|
||||||
update.title = title;
|
update.title = title;
|
||||||
result.normalizedTitles += 1;
|
result.normalizedTitles += 1;
|
||||||
@@ -429,43 +504,41 @@ export class LegacyImportService {
|
|||||||
{ _id: match._id },
|
{ _id: match._id },
|
||||||
{ $set: update },
|
{ $set: update },
|
||||||
).exec();
|
).exec();
|
||||||
await this.matchStatsService.buildAndUpsert(match._id);
|
await this.rebuildMatchStats(
|
||||||
|
match._id,
|
||||||
|
competitionRevision(existingCompetition),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const participants = buildParticipantsSnapshot(raw, userByPuuid);
|
const participants = buildParticipantsSnapshot(raw, userByPuuid);
|
||||||
const gameResult = buildGameResult(raw, userByPuuid, 1);
|
const teams = buildTeams(raw, userByPuuid);
|
||||||
if (!gameResult || participants.length === 0) {
|
const counts = countKnownParticipants(raw, userByPuuid);
|
||||||
|
if (
|
||||||
|
!hasDecisiveRiotWinner(raw) ||
|
||||||
|
!hasTrustedCompetitionRoster(counts, participants, teams)
|
||||||
|
) {
|
||||||
result.skippedNoKnownParticipants += 1;
|
result.skippedNoKnownParticipants += 1;
|
||||||
if (Object.keys(update).length > 0) {
|
if (Object.keys(update).length > 0) {
|
||||||
await MatchModel.updateOne(
|
await MatchModel.updateOne(
|
||||||
{ _id: match._id },
|
{ _id: match._id },
|
||||||
{ $set: update },
|
{ $set: update },
|
||||||
).exec();
|
).exec();
|
||||||
await this.matchStatsService.buildAndUpsert(match._id);
|
await this.rebuildMatchStats(
|
||||||
|
match._id,
|
||||||
|
competitionRevision(existingCompetition),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const winnerTeamIndex = gameResult.winnerTeamIndex;
|
|
||||||
update.mapId = raw.info.mapId ?? match.mapId;
|
update.mapId = raw.info.mapId ?? match.mapId;
|
||||||
update.participants = participants;
|
update.participants = participants;
|
||||||
update.teams = buildTeams(raw, userByPuuid);
|
update.teams = teams;
|
||||||
update.result = {
|
update.gameMode = 'pair';
|
||||||
winnerTeamIndex,
|
update.gameCount = 1;
|
||||||
riotMatchIds: [riotMatchId],
|
update.teamBuiltAt = match.teamBuiltAt ?? new Date(raw.info.gameCreation);
|
||||||
games: [gameResult],
|
|
||||||
seriesResults: [
|
|
||||||
{
|
|
||||||
teamAIndex: 1,
|
|
||||||
teamBIndex: 2,
|
|
||||||
teamAWins: winnerTeamIndex === 1 ? 1 : 0,
|
|
||||||
teamBWins: winnerTeamIndex === 2 ? 1 : 0,
|
|
||||||
winnerTeamIndex,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
|
|
||||||
await MatchModel.updateOne(
|
await MatchModel.updateOne(
|
||||||
{
|
{
|
||||||
@@ -475,7 +548,30 @@ export class LegacyImportService {
|
|||||||
},
|
},
|
||||||
{ $set: update },
|
{ $set: update },
|
||||||
).exec();
|
).exec();
|
||||||
await this.matchStatsService.buildAndUpsert(match._id);
|
let sourceRevision = competitionRevision(existingCompetition);
|
||||||
|
if (!summarizeCompetitionResult(existingCompetition)) {
|
||||||
|
const updatedMatch = {
|
||||||
|
...toPlainRecord(match),
|
||||||
|
...update,
|
||||||
|
_id: match._id,
|
||||||
|
communityId: match.communityId,
|
||||||
|
} as unknown as MatchDocument;
|
||||||
|
sourceRevision =
|
||||||
|
(await this.acceptRiotCompetitionFact({
|
||||||
|
match: updatedMatch,
|
||||||
|
detail: raw,
|
||||||
|
actor: { type: 'system' },
|
||||||
|
})) ?? undefined;
|
||||||
|
}
|
||||||
|
if (sourceRevision === undefined) {
|
||||||
|
result.skippedNoKnownParticipants += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
await MatchModel.updateOne(
|
||||||
|
{ _id: match._id },
|
||||||
|
{ $set: { status: 'finished' } },
|
||||||
|
).exec();
|
||||||
|
await this.rebuildMatchStats(match._id, sourceRevision);
|
||||||
result.rebuilt += 1;
|
result.rebuilt += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -486,6 +582,44 @@ export class LegacyImportService {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async loadCompetitionByMatchId(
|
||||||
|
matchIds: mongoose.Types.ObjectId[],
|
||||||
|
): Promise<Map<string, unknown>> {
|
||||||
|
if (matchIds.length === 0) return new Map();
|
||||||
|
const CompetitionModel =
|
||||||
|
await this.connectionService.getModel('competition');
|
||||||
|
const competitions = await CompetitionModel.find({
|
||||||
|
matchId: { $in: matchIds },
|
||||||
|
})
|
||||||
|
.lean()
|
||||||
|
.exec();
|
||||||
|
return new Map(
|
||||||
|
competitions.map((competition) => [
|
||||||
|
competition.matchId.toString(),
|
||||||
|
competition,
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private rebuildMatchStats(
|
||||||
|
matchId: mongoose.Types.ObjectId,
|
||||||
|
sourceRevision?: number,
|
||||||
|
): Promise<void> {
|
||||||
|
return this.matchStatsService
|
||||||
|
.buildAndUpsert(matchId, {
|
||||||
|
...(sourceRevision === undefined ? {} : { sourceRevision }),
|
||||||
|
})
|
||||||
|
.catch((error: unknown) => {
|
||||||
|
this.logger.warn(
|
||||||
|
`Failed to rebuild legacy Match stats ${matchId.toString()}${
|
||||||
|
sourceRevision === undefined
|
||||||
|
? ''
|
||||||
|
: ` at Competition revision ${sourceRevision}`
|
||||||
|
}: ${error instanceof Error ? error.message : String(error)}`,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private async collectMatchIds(
|
private async collectMatchIds(
|
||||||
job: LegacyImportMemberJob,
|
job: LegacyImportMemberJob,
|
||||||
): Promise<Set<string>> {
|
): Promise<Set<string>> {
|
||||||
@@ -521,9 +655,12 @@ export class LegacyImportService {
|
|||||||
MATCH_IMPORT_LOCK_TTL_SECONDS * 1000,
|
MATCH_IMPORT_LOCK_TTL_SECONDS * 1000,
|
||||||
},
|
},
|
||||||
async () => {
|
async () => {
|
||||||
const MatchModel = await this.connectionService.getModel('match');
|
const CompetitionFactModel =
|
||||||
const existing = await MatchModel.exists({
|
await this.connectionService.getModel('competitionFact');
|
||||||
'result.games.riotMatchId': riotMatchId,
|
const existing = await CompetitionFactModel.exists({
|
||||||
|
type: 'game-accepted',
|
||||||
|
'evidence.type': 'riot',
|
||||||
|
'evidence.riotMatchId': riotMatchId,
|
||||||
});
|
});
|
||||||
if (existing) return 'duplicate';
|
if (existing) return 'duplicate';
|
||||||
|
|
||||||
@@ -533,43 +670,31 @@ export class LegacyImportService {
|
|||||||
);
|
);
|
||||||
if (!detail.info.tournamentCode) return 'skipped';
|
if (!detail.info.tournamentCode) return 'skipped';
|
||||||
const counts = countKnownParticipants(detail, userByPuuid);
|
const counts = countKnownParticipants(detail, userByPuuid);
|
||||||
if (counts.total === 0) return 'skipped';
|
const participants = buildParticipantsSnapshot(detail, userByPuuid);
|
||||||
|
const teams = buildTeams(detail, userByPuuid);
|
||||||
const gameResult = buildGameResult(detail, userByPuuid, 1);
|
if (
|
||||||
if (!gameResult || gameResult.participants.length === 0) {
|
!hasDecisiveRiotWinner(detail) ||
|
||||||
|
!hasTrustedCompetitionRoster(counts, participants, teams)
|
||||||
|
) {
|
||||||
return 'skipped';
|
return 'skipped';
|
||||||
}
|
}
|
||||||
|
|
||||||
const winnerTeamIndex = gameResult.winnerTeamIndex;
|
const matchPayload: ResultlessMatchPatch = {
|
||||||
const matchPayload: Partial<Match> = {
|
|
||||||
communityId: new mongoose.Types.ObjectId(job.communityId),
|
communityId: new mongoose.Types.ObjectId(job.communityId),
|
||||||
title: this.formatLegacyDate(detail.info.gameCreation),
|
title: this.formatLegacyDate(detail.info.gameCreation),
|
||||||
description: 'Legacy import (자동 생성)',
|
description: 'Legacy import (자동 생성)',
|
||||||
mapId: detail.info.mapId ?? 11,
|
mapId: detail.info.mapId ?? 11,
|
||||||
status: 'finished',
|
status: 'team-built',
|
||||||
scheduledAt: new Date(detail.info.gameCreation),
|
scheduledAt: new Date(detail.info.gameCreation),
|
||||||
maxParticipants: 10,
|
maxParticipants: 10,
|
||||||
gameCount: 1,
|
gameCount: 1,
|
||||||
gameMode: 'pair',
|
gameMode: 'pair',
|
||||||
tournamentCodeIds: [],
|
tournamentCodeIds: [],
|
||||||
|
gameSchedule: [],
|
||||||
teamBuiltAt: new Date(detail.info.gameCreation),
|
teamBuiltAt: new Date(detail.info.gameCreation),
|
||||||
hostUserId: new mongoose.Types.ObjectId(job.triggeredBy),
|
hostUserId: new mongoose.Types.ObjectId(job.triggeredBy),
|
||||||
participants: buildParticipantsSnapshot(detail, userByPuuid),
|
participants,
|
||||||
teams: buildTeams(detail, userByPuuid),
|
teams,
|
||||||
result: {
|
|
||||||
winnerTeamIndex,
|
|
||||||
riotMatchIds: [riotMatchId],
|
|
||||||
games: [gameResult],
|
|
||||||
seriesResults: [
|
|
||||||
{
|
|
||||||
teamAIndex: 1,
|
|
||||||
teamBIndex: 2,
|
|
||||||
teamAWins: winnerTeamIndex === 1 ? 1 : 0,
|
|
||||||
teamBWins: winnerTeamIndex === 2 ? 1 : 0,
|
|
||||||
winnerTeamIndex,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
legacyImported: true,
|
legacyImported: true,
|
||||||
legacyImportSource: {
|
legacyImportSource: {
|
||||||
importedAt: new Date(),
|
importedAt: new Date(),
|
||||||
@@ -581,8 +706,36 @@ export class LegacyImportService {
|
|||||||
notices: [],
|
notices: [],
|
||||||
schedule: [],
|
schedule: [],
|
||||||
};
|
};
|
||||||
const match = await MatchModel.create(matchPayload);
|
const MatchModel = await this.connectionService.getModel('match');
|
||||||
await this.matchStatsService.buildAndUpsert(match._id);
|
const match = await MatchModel.findOneAndUpdate(
|
||||||
|
{
|
||||||
|
_id: deterministicObjectId(`legacy-import:match:${riotMatchId}`),
|
||||||
|
},
|
||||||
|
{ $setOnInsert: matchPayload },
|
||||||
|
{
|
||||||
|
upsert: true,
|
||||||
|
returnDocument: 'after',
|
||||||
|
setDefaultsOnInsert: true,
|
||||||
|
runValidators: true,
|
||||||
|
},
|
||||||
|
).exec();
|
||||||
|
if (!match)
|
||||||
|
throw new Error('Legacy Match upsert returned no document.');
|
||||||
|
|
||||||
|
const sourceRevision = await this.acceptRiotCompetitionFact({
|
||||||
|
match,
|
||||||
|
detail,
|
||||||
|
actor: {
|
||||||
|
type: 'migration',
|
||||||
|
migrationRunId: job.parentJobId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (sourceRevision === null) return 'skipped';
|
||||||
|
await MatchModel.updateOne(
|
||||||
|
{ _id: match._id },
|
||||||
|
{ $set: { status: 'finished' } },
|
||||||
|
).exec();
|
||||||
|
await this.rebuildMatchStats(match._id, sourceRevision);
|
||||||
return 'imported';
|
return 'imported';
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -598,6 +751,42 @@ export class LegacyImportService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async acceptRiotCompetitionFact(params: {
|
||||||
|
match: MatchDocument;
|
||||||
|
detail: RiotMatchDto;
|
||||||
|
actor: CompetitionCommandActor;
|
||||||
|
}): Promise<number | null> {
|
||||||
|
const competitionDocument =
|
||||||
|
await this.competitionBootstrapService.bootstrap(
|
||||||
|
params.match as unknown as CompetitionBootstrapMatch,
|
||||||
|
);
|
||||||
|
const competition = toCompetitionResultSnapshot(competitionDocument);
|
||||||
|
const mapped = resolveReadyCompetitionSlot({
|
||||||
|
competition,
|
||||||
|
detail: params.detail,
|
||||||
|
lookup: buildMatchPuuidLookup(params.match),
|
||||||
|
});
|
||||||
|
if (!mapped) return null;
|
||||||
|
|
||||||
|
const accepted = await this.competitionCommandService.acceptGame({
|
||||||
|
competitionId: competition.competitionId,
|
||||||
|
expectedRevision: competition.revision,
|
||||||
|
idempotencyKey: `legacy-import:riot:${params.detail.metadata.matchId}`,
|
||||||
|
actor: params.actor,
|
||||||
|
occurredAt: mapped.occurredAt,
|
||||||
|
gameId: mapped.gameId,
|
||||||
|
seriesId: mapped.seriesId,
|
||||||
|
gameSlotId: mapped.gameSlotId,
|
||||||
|
ordinal: mapped.ordinal,
|
||||||
|
evidence: mapped.evidence,
|
||||||
|
mapping: mapped.mapping,
|
||||||
|
startedAt: mapped.startedAt,
|
||||||
|
durationSeconds: mapped.durationSeconds,
|
||||||
|
participants: mapped.normalizedParticipants,
|
||||||
|
});
|
||||||
|
return accepted.revision;
|
||||||
|
}
|
||||||
|
|
||||||
private async ensureRiotMatchPersisted(
|
private async ensureRiotMatchPersisted(
|
||||||
riotMatchId: string,
|
riotMatchId: string,
|
||||||
region: RiotRegionalRoute,
|
region: RiotRegionalRoute,
|
||||||
@@ -679,13 +868,18 @@ export class LegacyImportService {
|
|||||||
const updated = await LegacyImportJobModel.findOne({
|
const updated = await LegacyImportJobModel.findOne({
|
||||||
jobId: job.parentJobId,
|
jobId: job.parentJobId,
|
||||||
})
|
})
|
||||||
.select({ processedMembers: 1, totalMembers: 1, state: 1, completedAt: 1 })
|
.select({
|
||||||
|
processedMembers: 1,
|
||||||
|
totalMembers: 1,
|
||||||
|
state: 1,
|
||||||
|
completedAt: 1,
|
||||||
|
})
|
||||||
.lean()
|
.lean()
|
||||||
.exec();
|
.exec();
|
||||||
const completed = Boolean(
|
const completed = Boolean(
|
||||||
updated &&
|
updated &&
|
||||||
updated.state !== 'cancelled' &&
|
updated.state !== 'cancelled' &&
|
||||||
updated.processedMembers >= updated.totalMembers,
|
updated.processedMembers >= updated.totalMembers,
|
||||||
);
|
);
|
||||||
if (completed) {
|
if (completed) {
|
||||||
await LegacyImportJobModel.updateOne(
|
await LegacyImportJobModel.updateOne(
|
||||||
@@ -741,7 +935,7 @@ export class LegacyImportService {
|
|||||||
.catch((error: unknown) => {
|
.catch((error: unknown) => {
|
||||||
this.logger.warn(
|
this.logger.warn(
|
||||||
`Failed to release legacy import lock ${lockOwnership.lockKey}: ${
|
`Failed to release legacy import lock ${lockOwnership.lockKey}: ${
|
||||||
error instanceof Error ? error.message : error
|
error instanceof Error ? error.message : String(error)
|
||||||
}`,
|
}`,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -903,3 +1097,233 @@ function isRiotMatchDto(value: unknown): value is RiotMatchDto {
|
|||||||
'info' in value,
|
'info' in value,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface LegacyResultSummary {
|
||||||
|
riotMatchId: string | null;
|
||||||
|
memberCount: number;
|
||||||
|
teamAIndex: number;
|
||||||
|
teamBIndex: number;
|
||||||
|
teamAWins: number;
|
||||||
|
teamBWins: number;
|
||||||
|
winnerTeamIndex?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function summarizeCompetitionResult(
|
||||||
|
value: unknown,
|
||||||
|
): LegacyResultSummary | null {
|
||||||
|
if (!value) return null;
|
||||||
|
const competition = toPlainRecord(value);
|
||||||
|
const projection = toRecord(competition.projection);
|
||||||
|
const games = toArray(projection.games).map(toRecord);
|
||||||
|
const game = games.find((candidate) => {
|
||||||
|
const evidence = toRecord(candidate.evidence);
|
||||||
|
return evidence.type === 'riot' && typeof evidence.riotMatchId === 'string';
|
||||||
|
});
|
||||||
|
if (!game) return null;
|
||||||
|
const evidence = toRecord(game.evidence);
|
||||||
|
const series = toArray(projection.series)
|
||||||
|
.map(toRecord)
|
||||||
|
.find(
|
||||||
|
(candidate) => idString(candidate.seriesId) === idString(game.seriesId),
|
||||||
|
);
|
||||||
|
const entries = toArray(series?.entries).map(toRecord);
|
||||||
|
const teamIndexById = new Map(
|
||||||
|
toArray(competition.teams).map((teamValue) => {
|
||||||
|
const team = toRecord(teamValue);
|
||||||
|
return [
|
||||||
|
idString(team.teamId),
|
||||||
|
optionalNumber(team.legacyTeamIndex) ?? numberValue(team.displayOrder),
|
||||||
|
];
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const teamA = entries.find((entry) => entry.slot === 'A');
|
||||||
|
const teamB = entries.find((entry) => entry.slot === 'B');
|
||||||
|
const teamAId = idString(teamA?.teamId);
|
||||||
|
const teamBId = idString(teamB?.teamId);
|
||||||
|
const winnerTeamId =
|
||||||
|
idString(toRecord(series?.outcome).winnerTeamId) ||
|
||||||
|
idString(game.winnerTeamId);
|
||||||
|
return {
|
||||||
|
riotMatchId: String(evidence.riotMatchId),
|
||||||
|
memberCount: toArray(game.participants).filter(
|
||||||
|
(participant) => idString(toRecord(participant).userId).length > 0,
|
||||||
|
).length,
|
||||||
|
teamAIndex: teamIndexById.get(teamAId) ?? 1,
|
||||||
|
teamBIndex: teamIndexById.get(teamBId) ?? 2,
|
||||||
|
teamAWins: numberValue(teamA?.gameWins),
|
||||||
|
teamBWins: numberValue(teamB?.gameWins),
|
||||||
|
...(teamIndexById.has(winnerTeamId)
|
||||||
|
? { winnerTeamIndex: teamIndexById.get(winnerTeamId) }
|
||||||
|
: {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function summarizeLegacyMatchResult(match: MatchDocument): LegacyResultSummary {
|
||||||
|
const series = match.result?.seriesResults?.[0];
|
||||||
|
const game = match.result?.games?.[0];
|
||||||
|
return {
|
||||||
|
riotMatchId: game?.riotMatchId ?? match.result?.riotMatchIds?.[0] ?? null,
|
||||||
|
memberCount: game?.participants.length ?? 0,
|
||||||
|
teamAIndex: series?.teamAIndex ?? 1,
|
||||||
|
teamBIndex: series?.teamBIndex ?? 2,
|
||||||
|
teamAWins: series?.teamAWins ?? 0,
|
||||||
|
teamBWins: series?.teamBWins ?? 0,
|
||||||
|
...(match.result?.winnerTeamIndex === undefined
|
||||||
|
? {}
|
||||||
|
: { winnerTeamIndex: match.result.winnerTeamIndex }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function competitionRevision(value: unknown): number | undefined {
|
||||||
|
return value ? optionalNumber(toPlainRecord(value).revision) : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasDecisiveRiotWinner(detail: RiotMatchDto): boolean {
|
||||||
|
return (
|
||||||
|
detail.info.teams.filter(
|
||||||
|
({ teamId, win }) => win && (teamId === 100 || teamId === 200),
|
||||||
|
).length === 1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasTrustedCompetitionRoster(
|
||||||
|
counts: { team100: number; team200: number; total: number },
|
||||||
|
participants: Match['participants'],
|
||||||
|
teams: Match['teams'],
|
||||||
|
): boolean {
|
||||||
|
if (
|
||||||
|
counts.total < 6 ||
|
||||||
|
counts.team100 !== counts.team200 ||
|
||||||
|
counts.team100 === 0 ||
|
||||||
|
teams.length !== 2 ||
|
||||||
|
teams.some((team) => team.members.length !== counts.team100)
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const userIds = participants.map(({ userId }) => userId.toString());
|
||||||
|
return (
|
||||||
|
userIds.length === counts.total && new Set(userIds).size === userIds.length
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildMatchPuuidLookup(match: MatchDocument): MatchPuuidLookup {
|
||||||
|
const puuidByUserId = new Map<string, string>();
|
||||||
|
const userIdByPuuid = new Map<string, mongoose.Types.ObjectId>();
|
||||||
|
for (const participant of match.participants) {
|
||||||
|
if (!participant.puuid) continue;
|
||||||
|
puuidByUserId.set(participant.userId.toString(), participant.puuid);
|
||||||
|
userIdByPuuid.set(participant.puuid, participant.userId);
|
||||||
|
}
|
||||||
|
return { puuidByUserId, userIdByPuuid };
|
||||||
|
}
|
||||||
|
|
||||||
|
function toCompetitionResultSnapshot(
|
||||||
|
value: unknown,
|
||||||
|
): CompetitionResultSnapshot {
|
||||||
|
const raw = toPlainRecord(value);
|
||||||
|
const projection = toRecord(raw.projection);
|
||||||
|
return {
|
||||||
|
competitionId: idString(raw._id),
|
||||||
|
revision: numberValue(raw.revision),
|
||||||
|
phase: String(raw.phase) as CompetitionResultSnapshot['phase'],
|
||||||
|
teams: toArray(raw.teams).map((teamValue) => {
|
||||||
|
const team = toRecord(teamValue);
|
||||||
|
return {
|
||||||
|
teamId: idString(team.teamId),
|
||||||
|
members: toArray(team.members).map((memberValue) => ({
|
||||||
|
userId: idString(toRecord(memberValue).userId),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
projection: {
|
||||||
|
phase: String(
|
||||||
|
projection.phase,
|
||||||
|
) as CompetitionResultSnapshot['projection']['phase'],
|
||||||
|
series: toArray(projection.series).map((seriesValue) => {
|
||||||
|
const series = toRecord(seriesValue);
|
||||||
|
return {
|
||||||
|
seriesId: idString(series.seriesId),
|
||||||
|
status: String(
|
||||||
|
series.status,
|
||||||
|
) as CompetitionResultSnapshot['projection']['series'][number]['status'],
|
||||||
|
entries: toArray(series.entries).map((entryValue) => {
|
||||||
|
const entry = toRecord(entryValue);
|
||||||
|
return {
|
||||||
|
slot: String(entry.slot) as 'A' | 'B',
|
||||||
|
teamId: entry.teamId == null ? null : idString(entry.teamId),
|
||||||
|
gameWins: numberValue(entry.gameWins),
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
gameSlots: toArray(projection.gameSlots).map((slotValue) => {
|
||||||
|
const slot = toRecord(slotValue);
|
||||||
|
return {
|
||||||
|
id: idString(slot.id),
|
||||||
|
seriesId: idString(slot.seriesId),
|
||||||
|
ordinal: numberValue(slot.ordinal),
|
||||||
|
displayNumber: numberValue(slot.displayNumber),
|
||||||
|
status: String(
|
||||||
|
slot.status,
|
||||||
|
) as CompetitionResultSnapshot['projection']['gameSlots'][number]['status'],
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
games: toArray(projection.games).map((gameValue) => {
|
||||||
|
const evidence = toRecord(toRecord(gameValue).evidence);
|
||||||
|
return {
|
||||||
|
evidence: {
|
||||||
|
type: typeof evidence.type === 'string' ? evidence.type : undefined,
|
||||||
|
riotMatchId:
|
||||||
|
typeof evidence.riotMatchId === 'string'
|
||||||
|
? evidence.riotMatchId
|
||||||
|
: undefined,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function toPlainRecord(value: unknown): Record<string, unknown> {
|
||||||
|
if (
|
||||||
|
value &&
|
||||||
|
typeof value === 'object' &&
|
||||||
|
'toObject' in value &&
|
||||||
|
typeof value.toObject === 'function'
|
||||||
|
) {
|
||||||
|
const document = value as { toObject: () => unknown };
|
||||||
|
return toRecord(document.toObject());
|
||||||
|
}
|
||||||
|
return toRecord(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function toRecord(value: unknown): Record<string, unknown> {
|
||||||
|
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
||||||
|
? (value as Record<string, unknown>)
|
||||||
|
: {};
|
||||||
|
}
|
||||||
|
|
||||||
|
function toArray(value: unknown): unknown[] {
|
||||||
|
return Array.isArray(value) ? value : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
function idString(value: unknown): string {
|
||||||
|
if (value instanceof mongoose.Types.ObjectId) return value.toString();
|
||||||
|
return typeof value === 'string' ? value : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function numberValue(value: unknown): number {
|
||||||
|
return typeof value === 'number' && Number.isFinite(value) ? value : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function optionalNumber(value: unknown): number | undefined {
|
||||||
|
return typeof value === 'number' && Number.isFinite(value)
|
||||||
|
? value
|
||||||
|
: undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function deterministicObjectId(key: string): mongoose.Types.ObjectId {
|
||||||
|
return new mongoose.Types.ObjectId(
|
||||||
|
createHash('sha256').update(key).digest('hex').slice(0, 24),
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in new issue
Block a user