refactor: import historical results as competition facts

This commit is contained in:
dahyeon committed 2026-07-12 20:08:29 +00:00
1 parent 6aa2cb9009
commit 7db97c540b
4 files changed
+1222 -77

No files matched your search

@@ -5,8 +5,16 @@ import {
Logger,
NotFoundException,
} from '@nestjs/common';
import { randomUUID } from 'crypto';
import { createHash, randomUUID } from 'node:crypto';
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 { CommunityStatsService } from '../community-stats/community-stats.service';
import { ConnectionService } from '../global/database/connection.service';
@@ -17,6 +25,7 @@ import {
import type {
LegacyImportJobDocument,
Match,
MatchDocument,
RiotMatch as StoredRiotMatch,
UserDocument,
} 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 type { RiotMatchDto, RiotRegionalRoute } from '../riot/riot.types';
import {
buildGameResult,
resolveReadyCompetitionSlot,
type CompetitionResultSnapshot,
} from '../tournament-result/competition-result.adapter';
import type { MatchPuuidLookup } from '../tournament-result/team-mapping.util';
import {
buildParticipantsSnapshot,
buildTeams,
buildUserByPuuidMap,
@@ -50,6 +63,10 @@ const MATCH_IMPORT_LOCK_TTL_SECONDS = 60;
const MATCH_ID_PAGE_SIZE = 100;
type ImportOutcome = 'imported' | 'duplicate' | 'skipped' | 'error';
type ResultlessMatchPatch = Omit<
Partial<Match>,
'result' | 'doubleElimination'
>;
@Injectable()
export class LegacyImportService {
@@ -62,6 +79,8 @@ export class LegacyImportService {
private readonly communityStatsService: CommunityStatsService,
private readonly matchStatsService: MatchStatsService,
private readonly distributedLockService: DistributedLockService,
private readonly competitionBootstrapService: CompetitionBootstrapService,
private readonly competitionCommandService: CompetitionCommandService,
) {}
public async previewMembers(params: {
@@ -154,7 +173,7 @@ export class LegacyImportService {
startTime: Math.floor(window.startTime.getTime() / 1000),
endTime: Math.floor(window.endTime.getTime() / 1000),
triggeredBy: params.triggeredBy.toString(),
region: (community.riotRegion ?? 'asia') as RiotRegionalRoute,
region: community.riotRegion ?? 'asia',
};
await this.redisService.appendStream(
RIOT_JOB_LOW_STREAM,
@@ -302,8 +321,19 @@ export class LegacyImportService {
.limit(limit + 1)
.exec();
const visible = matches.slice(0, limit);
const riotMatchIds = visible
.map((match) => match.result?.games[0]?.riotMatchId)
const competitionByMatchId = await this.loadCompetitionByMatchId(
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));
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const rawDocs = await RiotMatchModel.find({
@@ -317,23 +347,23 @@ export class LegacyImportService {
const userByPuuid = await this.buildUserByPuuidMap(params.communityId);
return {
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 memberCount = match.result?.games[0]?.participants.length ?? 0;
return {
matchId: match._id.toString(),
title: match.title,
scheduledAt: match.scheduledAt.toISOString(),
riotMatchId,
memberCount,
memberCount: summary.memberCount,
externalCount: raw
? resolveExternalCount(raw, userByPuuid)
: Math.max(0, 10 - memberCount),
teamAIndex: match.result?.seriesResults?.[0]?.teamAIndex ?? 1,
teamBIndex: match.result?.seriesResults?.[0]?.teamBIndex ?? 2,
teamAWins: match.result?.seriesResults?.[0]?.teamAWins ?? 0,
teamBWins: match.result?.seriesResults?.[0]?.teamBWins ?? 0,
winnerTeamIndex: match.result?.winnerTeamIndex,
: Math.max(0, 10 - summary.memberCount),
teamAIndex: summary.teamAIndex,
teamBIndex: summary.teamBIndex,
teamAWins: summary.teamAWins,
teamBWins: summary.teamBWins,
winnerTeamIndex: summary.winnerTeamIndex,
};
}),
nextCursor:
@@ -362,6 +392,41 @@ export class LegacyImportService {
const targetIds = targets.map((match) => match._id);
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({
_id: { $in: targetIds },
communityId: params.communityId,
@@ -380,12 +445,19 @@ export class LegacyImportService {
communityId: params.communityId,
legacyImported: true,
}).exec();
const riotMatchIds = matches
.map(
(match) =>
match.result?.games[0]?.riotMatchId ??
match.result?.riotMatchIds?.[0],
)
const competitionByMatchId = await this.loadCompetitionByMatchId(
matches.map(({ _id }) => _id),
);
const summaryByMatchId = new Map(
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));
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
@@ -409,14 +481,17 @@ export class LegacyImportService {
};
for (const match of matches) {
const riotMatchId =
match.result?.games[0]?.riotMatchId ?? match.result?.riotMatchIds?.[0];
const existingCompetition = competitionByMatchId.get(
match._id.toString(),
);
const summary = summaryByMatchId.get(match._id.toString())!;
const riotMatchId = summary.riotMatchId;
const raw = riotMatchId ? rawById.get(riotMatchId) : undefined;
const title = this.normalizeLegacyTitle(
match.title,
raw?.info.gameCreation ?? match.scheduledAt.getTime(),
);
const update: Partial<Match> = {};
const update: ResultlessMatchPatch = {};
if (title !== match.title) {
update.title = title;
result.normalizedTitles += 1;
@@ -429,43 +504,41 @@ export class LegacyImportService {
{ _id: match._id },
{ $set: update },
).exec();
await this.matchStatsService.buildAndUpsert(match._id);
await this.rebuildMatchStats(
match._id,
competitionRevision(existingCompetition),
);
}
continue;
}
const participants = buildParticipantsSnapshot(raw, userByPuuid);
const gameResult = buildGameResult(raw, userByPuuid, 1);
if (!gameResult || participants.length === 0) {
const teams = buildTeams(raw, userByPuuid);
const counts = countKnownParticipants(raw, userByPuuid);
if (
!hasDecisiveRiotWinner(raw) ||
!hasTrustedCompetitionRoster(counts, participants, teams)
) {
result.skippedNoKnownParticipants += 1;
if (Object.keys(update).length > 0) {
await MatchModel.updateOne(
{ _id: match._id },
{ $set: update },
).exec();
await this.matchStatsService.buildAndUpsert(match._id);
await this.rebuildMatchStats(
match._id,
competitionRevision(existingCompetition),
);
}
continue;
}
const winnerTeamIndex = gameResult.winnerTeamIndex;
update.mapId = raw.info.mapId ?? match.mapId;
update.participants = participants;
update.teams = buildTeams(raw, userByPuuid);
update.result = {
winnerTeamIndex,
riotMatchIds: [riotMatchId],
games: [gameResult],
seriesResults: [
{
teamAIndex: 1,
teamBIndex: 2,
teamAWins: winnerTeamIndex === 1 ? 1 : 0,
teamBWins: winnerTeamIndex === 2 ? 1 : 0,
winnerTeamIndex,
},
],
};
update.teams = teams;
update.gameMode = 'pair';
update.gameCount = 1;
update.teamBuiltAt = match.teamBuiltAt ?? new Date(raw.info.gameCreation);
await MatchModel.updateOne(
{
@@ -475,7 +548,30 @@ export class LegacyImportService {
},
{ $set: update },
).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;
}
@@ -486,6 +582,44 @@ export class LegacyImportService {
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(
job: LegacyImportMemberJob,
): Promise<Set<string>> {
@@ -521,9 +655,12 @@ export class LegacyImportService {
MATCH_IMPORT_LOCK_TTL_SECONDS * 1000,
},
async () => {
const MatchModel = await this.connectionService.getModel('match');
const existing = await MatchModel.exists({
'result.games.riotMatchId': riotMatchId,
const CompetitionFactModel =
await this.connectionService.getModel('competitionFact');
const existing = await CompetitionFactModel.exists({
type: 'game-accepted',
'evidence.type': 'riot',
'evidence.riotMatchId': riotMatchId,
});
if (existing) return 'duplicate';
@@ -533,43 +670,31 @@ export class LegacyImportService {
);
if (!detail.info.tournamentCode) return 'skipped';
const counts = countKnownParticipants(detail, userByPuuid);
if (counts.total === 0) return 'skipped';
const gameResult = buildGameResult(detail, userByPuuid, 1);
if (!gameResult || gameResult.participants.length === 0) {
const participants = buildParticipantsSnapshot(detail, userByPuuid);
const teams = buildTeams(detail, userByPuuid);
if (
!hasDecisiveRiotWinner(detail) ||
!hasTrustedCompetitionRoster(counts, participants, teams)
) {
return 'skipped';
}
const winnerTeamIndex = gameResult.winnerTeamIndex;
const matchPayload: Partial<Match> = {
const matchPayload: ResultlessMatchPatch = {
communityId: new mongoose.Types.ObjectId(job.communityId),
title: this.formatLegacyDate(detail.info.gameCreation),
description: 'Legacy import (자동 생성)',
mapId: detail.info.mapId ?? 11,
status: 'finished',
status: 'team-built',
scheduledAt: new Date(detail.info.gameCreation),
maxParticipants: 10,
gameCount: 1,
gameMode: 'pair',
tournamentCodeIds: [],
gameSchedule: [],
teamBuiltAt: new Date(detail.info.gameCreation),
hostUserId: new mongoose.Types.ObjectId(job.triggeredBy),
participants: buildParticipantsSnapshot(detail, userByPuuid),
teams: buildTeams(detail, userByPuuid),
result: {
winnerTeamIndex,
riotMatchIds: [riotMatchId],
games: [gameResult],
seriesResults: [
{
teamAIndex: 1,
teamBIndex: 2,
teamAWins: winnerTeamIndex === 1 ? 1 : 0,
teamBWins: winnerTeamIndex === 2 ? 1 : 0,
winnerTeamIndex,
},
],
},
participants,
teams,
legacyImported: true,
legacyImportSource: {
importedAt: new Date(),
@@ -581,8 +706,36 @@ export class LegacyImportService {
notices: [],
schedule: [],
};
const match = await MatchModel.create(matchPayload);
await this.matchStatsService.buildAndUpsert(match._id);
const MatchModel = await this.connectionService.getModel('match');
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';
},
);
@@ -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(
riotMatchId: string,
region: RiotRegionalRoute,
@@ -679,13 +868,18 @@ export class LegacyImportService {
const updated = await LegacyImportJobModel.findOne({
jobId: job.parentJobId,
})
.select({ processedMembers: 1, totalMembers: 1, state: 1, completedAt: 1 })
.select({
processedMembers: 1,
totalMembers: 1,
state: 1,
completedAt: 1,
})
.lean()
.exec();
const completed = Boolean(
updated &&
updated.state !== 'cancelled' &&
updated.processedMembers >= updated.totalMembers,
updated.state !== 'cancelled' &&
updated.processedMembers >= updated.totalMembers,
);
if (completed) {
await LegacyImportJobModel.updateOne(
@@ -741,7 +935,7 @@ export class LegacyImportService {
.catch((error: unknown) => {
this.logger.warn(
`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,
);
}
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),
);
}