Compare commits

..
16 Commits
49 changed files with 3183 additions and 363 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
66
+17 -1
View File
@@ -86,7 +86,23 @@ pnpm dev:web
```bash ```bash
pnpm --filter api test pnpm --filter api test
pnpm --filter web build:test pnpm --filter web build:staging
``` ```
현재 정리된 기준으로 API 테스트와 웹 테스트 빌드를 통과합니다. 현재 정리된 기준으로 API 테스트와 웹 테스트 빌드를 통과합니다.
## Deployment branches
`main`은 항상 배포 가능한 trunk로 유지하고 dev 배포 기준으로 사용합니다.
빌드 번호는 `BUILD_NUMBER` 파일에서 1씩 증가시키며, 현재 시작 번호는 `66`입니다.
staging 검증이 필요할 때는 `release/66` 같은 임시 브랜치를 만들고,
검증이 끝나면 삭제합니다.
```bash
git push origin main:release/66
pnpm deploy:web:staging
```
staging Pages 배포 스크립트는 `CF_PAGES_STAGING_BRANCH`가 있으면 그 값을
사용하고, 없으면 최신 `release/*` 브랜치를 자동으로 선택합니다. 최신 기준은
브랜치가 가리키는 커밋 시각이며, 동률이면 브랜치명 내림차순입니다.
+2 -2
View File
@@ -11,10 +11,10 @@
"seed:dev": "ts-node src/seed.ts", "seed:dev": "ts-node src/seed.ts",
"seed:dakao-participant": "ts-node src/seed-dakao-participant.ts", "seed:dakao-participant": "ts-node src/seed-dakao-participant.ts",
"start:dev": "node -e \"process.env.NODE_ENV='dev'; require('./dist/main.js')\"", "start:dev": "node -e \"process.env.NODE_ENV='dev'; require('./dist/main.js')\"",
"start:test": "node -e \"process.env.NODE_ENV='test'; require('./dist/main.js')\"", "start:staging": "node -e \"process.env.NODE_ENV='staging'; require('./dist/main.js')\"",
"start:prod": "node -e \"process.env.NODE_ENV='prod'; require('./dist/main.js')\"", "start:prod": "node -e \"process.env.NODE_ENV='prod'; require('./dist/main.js')\"",
"pm2:dev": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:dev", "pm2:dev": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:dev",
"pm2:test": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:test", "pm2:staging": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:staging",
"pm2:prod": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:prod", "pm2:prod": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:prod",
"start:debug": "nest start --debug --watch", "start:debug": "nest start --debug --watch",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
+67
View File
@@ -0,0 +1,67 @@
import {
createCorsOrigin,
isAllowedCorsOrigin,
resolveWebOrigins,
} from './cors-origin';
describe('CORS origin resolution', () => {
it('allows Cloudflare Pages preview origins in dev and staging', () => {
const origin = 'https://807e0ea6.lolympus.pages.dev';
expect(isAllowedCorsOrigin(origin, 'dev')).toBe(true);
expect(isAllowedCorsOrigin(origin, 'staging')).toBe(true);
});
it('does not allow Cloudflare Pages preview origins in prod', () => {
expect(
isAllowedCorsOrigin('https://807e0ea6.lolympus.pages.dev', 'prod'),
).toBe(false);
});
it('rejects similar but unsafe Pages origins', () => {
expect(
isAllowedCorsOrigin('http://807e0ea6.lolympus.pages.dev', 'staging'),
).toBe(false);
expect(isAllowedCorsOrigin('https://lolympus.pages.dev', 'staging')).toBe(
false,
);
expect(
isAllowedCorsOrigin('https://a.b.lolympus.pages.dev', 'staging'),
).toBe(false);
expect(
isAllowedCorsOrigin(
'https://807e0ea6.lolympus.pages.dev.evil.com',
'staging',
),
).toBe(false);
});
it('keeps configured web origins allowed', () => {
expect(
isAllowedCorsOrigin('https://example.com', 'prod', [
'https://example.com',
]),
).toBe(true);
});
it('falls back to default web origins when WEB_ORIGIN is empty', () => {
expect(resolveWebOrigins('')).toContain('http://localhost:5173');
});
it('creates a Nest CORS callback from the same rules', (done) => {
const corsOrigin = createCorsOrigin('staging');
expect(corsOrigin).not.toBe(true);
if (corsOrigin === true) return;
corsOrigin('https://807e0ea6.lolympus.pages.dev', (error, allow) => {
expect(error).toBeNull();
expect(allow).toBe(true);
done();
});
});
it('keeps dev CORS permissive for local development', () => {
expect(createCorsOrigin('dev')).toBe(true);
});
});
+101
View File
@@ -0,0 +1,101 @@
import type { CustomOrigin } from '@nestjs/common/interfaces/external/cors-options.interface';
const DEFAULT_WEB_ORIGINS = [
'http://localhost:5173',
'http://126.dahyeon.us:5173',
'https://lolympus.dahyeon.us',
];
const PAGES_DEV_ORIGIN_HOST_PATTERN =
/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.lolympus\.pages\.dev$/i;
const PAGES_DEV_CORS_ENVIRONMENTS = new Set(['dev', 'staging']);
function parseOrigin(origin: string, allowPath: boolean): URL | null {
const trimmedOrigin = origin.trim();
if (trimmedOrigin.length === 0) return null;
try {
const url = new URL(trimmedOrigin);
if (
!allowPath &&
(url.pathname !== '/' || url.search !== '' || url.hash !== '')
) {
return null;
}
return url;
} catch {
return null;
}
}
function normalizeOrigin(origin: string, allowPath = false): string | null {
const url = parseOrigin(origin, allowPath);
if (!url) return null;
return `${url.protocol}//${url.host}`;
}
export function resolveWebOrigins(
webOrigin = process.env.WEB_ORIGIN,
): string[] {
const configuredOrigins = webOrigin
?.split(',')
.map((origin) => normalizeOrigin(origin, true))
.filter((origin): origin is string => origin !== null);
if (configuredOrigins && configuredOrigins.length > 0) {
return configuredOrigins;
}
return [...DEFAULT_WEB_ORIGINS];
}
export function isLolympusPagesDevOrigin(origin: string): boolean {
const url = parseOrigin(origin, false);
if (!url) return false;
return (
url.protocol === 'https:' &&
url.port === '' &&
PAGES_DEV_ORIGIN_HOST_PATTERN.test(url.hostname)
);
}
export function isAllowedCorsOrigin(
requestOrigin: string | undefined,
nodeEnv = process.env.NODE_ENV,
webOrigins = resolveWebOrigins(),
): boolean {
if (!requestOrigin) return false;
const normalizedRequestOrigin = normalizeOrigin(requestOrigin);
if (!normalizedRequestOrigin) return false;
const normalizedWebOrigins = webOrigins
.map((origin) => normalizeOrigin(origin, true))
.filter((origin): origin is string => origin !== null);
if (normalizedWebOrigins.includes(normalizedRequestOrigin)) {
return true;
}
return (
PAGES_DEV_CORS_ENVIRONMENTS.has(nodeEnv ?? '') &&
isLolympusPagesDevOrigin(requestOrigin)
);
}
export function createCorsOrigin(
nodeEnv = process.env.NODE_ENV,
webOrigin = process.env.WEB_ORIGIN,
): true | CustomOrigin {
if (nodeEnv === 'dev') return true;
const webOrigins = resolveWebOrigins(webOrigin);
return (requestOrigin, callback) => {
callback(null, isAllowedCorsOrigin(requestOrigin, nodeEnv, webOrigins));
};
}
+5 -10
View File
@@ -1,23 +1,18 @@
import { ValidationPipe } from '@nestjs/common'; import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core'; import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module'; import { AppModule } from './app.module';
import { createCorsOrigin } from './cors-origin';
async function bootstrap() { async function bootstrap() {
const app = await NestFactory.create(AppModule, { const app = await NestFactory.create(AppModule, {
rawBody: true, rawBody: true,
}); });
const isDev = process.env.NODE_ENV === 'dev'; const nodeEnv = process.env.NODE_ENV;
const webOrigins = process.env.WEB_ORIGIN?.split(',').map((origin) => const isDev = nodeEnv === 'dev';
origin.trim(),
) ?? [
'http://localhost:5173',
'http://126.dahyeon.us:5173',
'https://lolympus.dahyeon.us',
];
app.enableCors({ app.enableCors({
origin: isDev ? true : webOrigins, origin: createCorsOrigin(nodeEnv),
credentials: true, credentials: true,
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'], allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
}); });
@@ -31,4 +26,4 @@ async function bootstrap() {
); );
await app.listen(isDev ? 3000 : 10712); await app.listen(isDev ? 3000 : 10712);
} }
bootstrap(); void bootstrap();
@@ -16,6 +16,7 @@ import { IdentityService } from '../auth/identity.service';
import { JwtService } from '../auth/jwt.service'; import { JwtService } from '../auth/jwt.service';
import { ConnectionService } from '../global/database/connection.service'; import { ConnectionService } from '../global/database/connection.service';
import type { import type {
AuctionChatMessage,
AuctionDocument, AuctionDocument,
IdentityDocument, IdentityDocument,
Position, Position,
@@ -37,6 +38,11 @@ interface SoldPayload {
assignedPosition?: Position; assignedPosition?: Position;
} }
interface ChatMessagePayload {
message?: string;
displayName?: string;
}
@WebSocketGateway({ @WebSocketGateway({
namespace: '/auction', namespace: '/auction',
cors: { cors: {
@@ -100,6 +106,7 @@ export class AuctionGateway
const auction = await this.auctionService.getByMatchId( const auction = await this.auctionService.getByMatchId(
new mongoose.Types.ObjectId(payload.matchId), new mongoose.Types.ObjectId(payload.matchId),
); );
this.emitChatHistory(socket, auction);
this.broadcastState(payload.matchId, auction); this.broadcastState(payload.matchId, auction);
} catch (error) { } catch (error) {
this.emitKnownError(socket, error); this.emitKnownError(socket, error);
@@ -182,6 +189,34 @@ export class AuctionGateway
} }
} }
@SubscribeMessage('chat-message')
public async handleChatMessage(
@ConnectedSocket() socket: Socket,
@MessageBody() payload: ChatMessagePayload,
) {
const matchId = this.requireJoinedMatchId(socket);
if (!matchId) return;
if (typeof payload?.message !== 'string') {
this.emitError(socket, 'Chat message is required.');
return;
}
try {
const { message } = await this.auctionService.appendChatMessage({
matchId: new mongoose.Types.ObjectId(matchId),
userId: this.resolveSocketUserId(socket),
displayName: this.resolveChatDisplayName(socket, payload.displayName),
message: payload.message,
});
this.server
.to(matchId)
.emit('chat-message', this.serializeChatMessage(message));
} catch (error) {
this.emitKnownError(socket, error);
}
}
private requireJoinedMatchId(socket: Socket): string | null { private requireJoinedMatchId(socket: Socket): string | null {
const matchId = this.getSocketMatchId(socket); const matchId = this.getSocketMatchId(socket);
if (!matchId) { if (!matchId) {
@@ -219,6 +254,36 @@ export class AuctionGateway
return Array.isArray(header) ? header[0] : header; return Array.isArray(header) ? header[0] : header;
} }
private resolveSocketUserId(
socket: Socket,
): mongoose.Types.ObjectId | undefined {
return (socket.data.user as UserDocument | undefined)?._id;
}
private resolveChatDisplayName(
socket: Socket,
fallbackDisplayName?: string,
): string {
const user = socket.data.user as UserDocument | undefined;
const primaryRiotAccount =
user?.riotAccounts.find((entry) => entry.isPrimary) ??
user?.riotAccounts[0];
if (primaryRiotAccount?.gameName) {
return primaryRiotAccount.tagLine
? `${primaryRiotAccount.gameName}#${primaryRiotAccount.tagLine}`
: primaryRiotAccount.gameName;
}
if (user?.kakaoTalkNickname) return user.kakaoTalkNickname;
if (user?.discordNickname) return user.discordNickname;
const identity = socket.data.identity as IdentityDocument | undefined;
if (identity?.displayName) return identity.displayName;
if (identity?.email) return identity.email;
return fallbackDisplayName ?? '관전자';
}
private async authenticateSocket(socket: Socket): Promise<void> { private async authenticateSocket(socket: Socket): Promise<void> {
const fallback = await this.authService.resolveDevUserById( const fallback = await this.authService.resolveDevUserById(
this.readHandshakeUserId(socket), this.readHandshakeUserId(socket),
@@ -299,6 +364,14 @@ export class AuctionGateway
this.syncRoomTimer(matchId, auction); this.syncRoomTimer(matchId, auction);
} }
private emitChatHistory(socket: Socket, auction: AuctionDocument) {
socket.emit('chat-history', {
messages: (auction.chatMessages ?? []).map((message) =>
this.serializeChatMessage(message),
),
});
}
private syncRoomTimer(matchId: string, auction: AuctionDocument) { private syncRoomTimer(matchId: string, auction: AuctionDocument) {
this.clearRoomTimer(matchId); this.clearRoomTimer(matchId);
if (!auction.currentDeadline) return; if (!auction.currentDeadline) return;
@@ -382,4 +455,8 @@ export class AuctionGateway
private serializeAuction(auction: AuctionDocument) { private serializeAuction(auction: AuctionDocument) {
return JSON.parse(JSON.stringify(auction)); return JSON.parse(JSON.stringify(auction));
} }
private serializeChatMessage(message: AuctionChatMessage) {
return JSON.parse(JSON.stringify(message));
}
} }
@@ -159,6 +159,76 @@ describe('AuctionService', () => {
expect(tournamentResultService.scheduleInitialPoll).not.toHaveBeenCalled(); expect(tournamentResultService.scheduleInitialPoll).not.toHaveBeenCalled();
}); });
it('appends a chat message and keeps only the latest 200 messages', async () => {
const matchId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
const oldMessages = Array.from({ length: 200 }, (_, index) => ({
id: `old-${index}`,
displayName: 'Old',
message: `old message ${index}`,
sentAt: new Date(index),
}));
const auction = {
matchId,
chatMessages: oldMessages,
save: jest.fn().mockResolvedValue(undefined),
};
const { service } = createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
});
const appended = await service.appendChatMessage({
matchId,
userId,
displayName: ' Captain One ',
message: ' 좋은 픽입니다 ',
});
expect(appended.message).toMatchObject({
userId,
displayName: 'Captain One',
message: '좋은 픽입니다',
});
expect(appended.message.id).toHaveLength(36);
expect(appended.message.sentAt).toBeInstanceOf(Date);
expect(auction.chatMessages).toHaveLength(200);
expect(auction.chatMessages[0].id).toBe('old-1');
expect(auction.chatMessages.at(-1)).toBe(appended.message);
expect(auction.save).toHaveBeenCalledTimes(1);
});
it('rejects blank and overly long chat messages', async () => {
const matchId = new mongoose.Types.ObjectId();
const auction = {
matchId,
chatMessages: [],
save: jest.fn().mockResolvedValue(undefined),
};
const { service } = createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
});
await expect(
service.appendChatMessage({
matchId,
displayName: 'Spectator',
message: ' ',
}),
).rejects.toThrow('Chat message is required.');
await expect(
service.appendChatMessage({
matchId,
displayName: 'Spectator',
message: 'a'.repeat(301),
}),
).rejects.toThrow('Chat message must be 300 characters or less.');
expect(auction.save).not.toHaveBeenCalled();
});
it('randomizes the non-captain player order when starting an auction', async () => { it('randomizes the non-captain player order when starting an auction', async () => {
const randomSpy = jest.spyOn(Math, 'random').mockReturnValue(0); const randomSpy = jest.spyOn(Math, 'random').mockReturnValue(0);
const matchId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId();
@@ -348,7 +418,7 @@ describe('AuctionService', () => {
expect(auction.save).not.toHaveBeenCalled(); expect(auction.save).not.toHaveBeenCalled();
}); });
it('marks a zero-bid player as passed and queues them for round two', async () => { it('marks a zero-bid player as passed and queues them for another round', async () => {
const matchId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId();
const playerId = new mongoose.Types.ObjectId(); const playerId = new mongoose.Types.ObjectId();
const auction = { const auction = {
@@ -383,25 +453,63 @@ describe('AuctionService', () => {
expect(auction.save).toHaveBeenCalledTimes(1); expect(auction.save).toHaveBeenCalledTimes(1);
}); });
it('force-assigns second-pass players to the open team with most points', async () => { it('queues zero-bid passes after the first auction round', async () => {
const matchId = new mongoose.Types.ObjectId();
const playerId = new mongoose.Types.ObjectId();
const auction = {
_id: new mongoose.Types.ObjectId(),
matchId,
phase: 'bidding',
currentBid: 0,
currentIndex: 0,
auctionRound: 2,
order: [
{
userId: playerId,
preferredPositions: [{ position: 'MID', priority: 1 }],
passCount: 1,
},
],
passedQueue: [],
save: jest.fn().mockResolvedValue(undefined),
toObject: jest.fn().mockReturnValue({ _id: 'auction', matchId }),
};
const { service } = createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
});
await service.markPassed(matchId);
expect(auction.phase).toBe('passed');
expect(auction.order[0].passCount).toBe(2);
expect(auction.passedQueue).toHaveLength(1);
expect(auction.passedQueue[0]).toMatchObject({
userId: playerId.toString(),
preferredPositions: [{ position: 'MID', priority: 1 }],
passCount: 2,
});
});
it('requeues second-pass players instead of force-assigning them', async () => {
const matchId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId();
const captainOneId = new mongoose.Types.ObjectId(); const captainOneId = new mongoose.Types.ObjectId();
const captainTwoId = new mongoose.Types.ObjectId(); const captainTwoId = new mongoose.Types.ObjectId();
const passedPlayerId = new mongoose.Types.ObjectId(); const passedPlayerId = new mongoose.Types.ObjectId();
const passedPlayer = {
userId: passedPlayerId,
preferredPositions: [{ position: 'SUP', priority: 1 }],
passCount: 2,
};
const auction = { const auction = {
_id: new mongoose.Types.ObjectId(), _id: new mongoose.Types.ObjectId(),
matchId, matchId,
phase: 'passed', phase: 'passed',
currentIndex: 0, currentIndex: 0,
auctionRound: 2, auctionRound: 2,
order: [ order: [passedPlayer],
{ passedQueue: [passedPlayer],
userId: passedPlayerId,
preferredPositions: [{ position: 'SUP', priority: 1 }],
passCount: 2,
},
],
passedQueue: [],
teams: [ teams: [
{ {
teamIndex: 1, teamIndex: 1,
@@ -419,46 +527,28 @@ describe('AuctionService', () => {
save: jest.fn().mockResolvedValue(undefined), save: jest.fn().mockResolvedValue(undefined),
toObject: jest.fn().mockReturnValue({ _id: 'auction', matchId }), toObject: jest.fn().mockReturnValue({ _id: 'auction', matchId }),
}; };
const match = {
participants: [
{
userId: captainOneId,
preferredPositions: [{ position: 'TOP', priority: 1 }],
},
{
userId: captainTwoId,
preferredPositions: [{ position: 'JGL', priority: 1 }],
},
{
userId: passedPlayerId,
preferredPositions: [{ position: 'SUP', priority: 1 }],
},
],
status: 'team-built',
teams: [],
teamBuiltAt: undefined,
save: jest.fn().mockResolvedValue(undefined),
};
const { service } = createService({ const { service } = createService({
auction: { auction: {
findOne: jest.fn().mockResolvedValue(auction), findOne: jest.fn().mockResolvedValue(auction),
}, },
match: {
findById: jest.fn().mockResolvedValue(match),
},
}); });
await service.next(matchId); await service.next(matchId);
expect(auction.phase).toBe('complete'); expect(auction.phase).toBe('presenting');
expect(auction.teams[1].members).toEqual([ expect(auction.auctionRound).toBe(3);
{ expect(auction.currentIndex).toBe(1);
userId: passedPlayerId, expect(auction.order).toHaveLength(2);
assignedPosition: 'SUP', expect(auction.order[1]).toMatchObject({
cost: 1, userId: passedPlayerId.toString(),
}, preferredPositions: [{ position: 'SUP', priority: 1 }],
]); passCount: 2,
expect(auction.teams[1].points).toBe(49); });
expect(auction.passedQueue).toEqual([]);
expect(auction.teams[0].members).toEqual([]);
expect(auction.teams[1].members).toEqual([]);
expect(auction.teams[0].points).toBe(10);
expect(auction.teams[1].points).toBe(50);
}); });
it('syncs completed auction teams into the match document', async () => { it('syncs completed auction teams into the match document', async () => {
+63 -47
View File
@@ -5,10 +5,12 @@ import {
Logger, Logger,
NotFoundException, NotFoundException,
} from '@nestjs/common'; } from '@nestjs/common';
import { randomUUID } from 'crypto';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service'; import { ConnectionService } from '../global/database/connection.service';
import { import {
AuctionActionType, AuctionActionType,
AuctionChatMessage,
AuctionDocument, AuctionDocument,
AuctionPlayerSnapshot, AuctionPlayerSnapshot,
AuctionTeam, AuctionTeam,
@@ -26,6 +28,9 @@ import { TournamentResultService } from '../tournament-result/tournament-result.
const AUCTION_MAX_TEAM_SIZE = 5; const AUCTION_MAX_TEAM_SIZE = 5;
const AUCTION_BACKGROUND_ENRICHMENT_CONCURRENCY = 1; const AUCTION_BACKGROUND_ENRICHMENT_CONCURRENCY = 1;
const AUCTION_ENRICHMENT_COOLDOWN_MS = 3 * 60 * 60 * 1000; const AUCTION_ENRICHMENT_COOLDOWN_MS = 3 * 60 * 60 * 1000;
const AUCTION_CHAT_MAX_MESSAGES = 200;
const AUCTION_CHAT_MAX_MESSAGE_LENGTH = 300;
const AUCTION_CHAT_MAX_DISPLAY_NAME_LENGTH = 24;
interface StartAuctionParams { interface StartAuctionParams {
matchId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId;
@@ -54,6 +59,13 @@ interface MarkSoldParams {
assignedPosition?: Position; assignedPosition?: Position;
} }
interface AppendChatMessageParams {
matchId: mongoose.Types.ObjectId;
userId?: mongoose.Types.ObjectId;
displayName?: string;
message: string;
}
export interface AuctionHistoryView { export interface AuctionHistoryView {
sequence: number; sequence: number;
action: AuctionActionType; action: AuctionActionType;
@@ -221,6 +233,31 @@ export class AuctionService {
return auction; return auction;
} }
public async appendChatMessage(params: AppendChatMessageParams): Promise<{
auction: AuctionDocument;
message: AuctionChatMessage;
}> {
const auction = await this.getByMatchId(params.matchId);
const messageText = this.normalizeChatMessage(params.message);
const message: AuctionChatMessage = {
id: randomUUID(),
userId: params.userId,
displayName: this.normalizeChatDisplayName(params.displayName),
message: messageText,
sentAt: new Date(),
};
auction.chatMessages ??= [];
auction.chatMessages.push(message);
const overflow = auction.chatMessages.length - AUCTION_CHAT_MAX_MESSAGES;
if (overflow > 0) {
auction.chatMessages.splice(0, overflow);
}
await auction.save();
return { auction, message };
}
public async listHistory(params: { public async listHistory(params: {
matchId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId;
@@ -345,9 +382,8 @@ export class AuctionService {
await this.recordSnapshot(auction, 'passed'); await this.recordSnapshot(auction, 'passed');
current.passCount = (current.passCount ?? 0) + 1; current.passCount = (current.passCount ?? 0) + 1;
if ((auction.auctionRound ?? 1) === 1) { auction.passedQueue ??= [];
auction.passedQueue.push(this.cloneAuctionPlayerSnapshot(current)); auction.passedQueue.push(this.cloneAuctionPlayerSnapshot(current));
}
auction.phase = 'passed'; auction.phase = 'passed';
auction.currentDeadline = undefined; auction.currentDeadline = undefined;
await auction.save(); await auction.save();
@@ -368,29 +404,22 @@ export class AuctionService {
const nextIndex = auction.currentIndex + 1; const nextIndex = auction.currentIndex + 1;
const completesAuction = const completesAuction =
nextIndex >= auction.order.length && nextIndex >= auction.order.length &&
!( (auction.passedQueue?.length ?? 0) === 0;
(auction.auctionRound ?? 1) === 1 &&
(auction.passedQueue?.length ?? 0) > 0
);
await this.recordSnapshot(auction, completesAuction ? 'complete' : 'next'); await this.recordSnapshot(auction, completesAuction ? 'complete' : 'next');
if (nextIndex >= auction.order.length) { if (nextIndex >= auction.order.length) {
if ( if ((auction.passedQueue?.length ?? 0) > 0) {
(auction.auctionRound ?? 1) === 1 &&
(auction.passedQueue?.length ?? 0) > 0
) {
auction.order.push( auction.order.push(
...auction.passedQueue.map((player) => ...auction.passedQueue.map((player) =>
this.cloneAuctionPlayerSnapshot(player), this.cloneAuctionPlayerSnapshot(player),
), ),
); );
auction.passedQueue = []; auction.passedQueue = [];
auction.auctionRound = 2; auction.auctionRound = (auction.auctionRound ?? 1) + 1;
auction.currentIndex = nextIndex; auction.currentIndex = nextIndex;
auction.phase = 'presenting'; auction.phase = 'presenting';
auction.currentBid = 0; auction.currentBid = 0;
auction.currentBidderTeamIndex = undefined; auction.currentBidderTeamIndex = undefined;
} else { } else {
this.forceAssignRemainingPasses(auction);
auction.phase = 'complete'; auction.phase = 'complete';
auction.completedAt = new Date(); auction.completedAt = new Date();
} }
@@ -603,47 +632,34 @@ export class AuctionService {
return shuffled; return shuffled;
} }
private forceAssignRemainingPasses(auction: AuctionDocument): void {
const forcedPlayers = auction.order.filter(
(player) =>
(player.passCount ?? 0) >= 2 &&
!this.isAuctionPlayerAssigned(auction, player.userId),
);
for (const player of forcedPlayers) {
const targetTeam = [...auction.teams]
.filter(
(team) => this.countTeamMembersIncludingCaptain(team) < AUCTION_MAX_TEAM_SIZE,
)
.sort((left, right) => right.points - left.points)[0];
if (!targetTeam) return;
const preferredPrimary = player.preferredPositions[0]?.position;
targetTeam.members.push({
userId: player.userId,
assignedPosition: preferredPrimary ?? 'MID',
cost: 1,
});
targetTeam.points = Math.max(0, targetTeam.points - 1);
}
}
private isAuctionPlayerAssigned(
auction: AuctionDocument,
userId: mongoose.Types.ObjectId,
): boolean {
const userIdText = userId.toString();
return auction.teams.some((team) =>
team.members.some((member) => member.userId.toString() === userIdText),
);
}
private cloneAuctionPlayerSnapshot( private cloneAuctionPlayerSnapshot(
player: AuctionPlayerSnapshot, player: AuctionPlayerSnapshot,
): AuctionPlayerSnapshot { ): AuctionPlayerSnapshot {
return JSON.parse(JSON.stringify(player)) as AuctionPlayerSnapshot; return JSON.parse(JSON.stringify(player)) as AuctionPlayerSnapshot;
} }
private normalizeChatMessage(message: string): string {
const normalized = message.trim();
if (!normalized) {
throw new BadRequestException('Chat message is required.');
}
if (Array.from(normalized).length > AUCTION_CHAT_MAX_MESSAGE_LENGTH) {
throw new BadRequestException(
`Chat message must be ${AUCTION_CHAT_MAX_MESSAGE_LENGTH} characters or less.`,
);
}
return normalized;
}
private normalizeChatDisplayName(displayName: string | undefined): string {
const normalized = displayName?.trim() || '관전자';
const chars = Array.from(normalized);
if (chars.length <= AUCTION_CHAT_MAX_DISPLAY_NAME_LENGTH) {
return normalized;
}
return chars.slice(0, AUCTION_CHAT_MAX_DISPLAY_NAME_LENGTH).join('');
}
private async recordSnapshot( private async recordSnapshot(
auction: AuctionDocument, auction: AuctionDocument,
action: AuctionActionType, action: AuctionActionType,
@@ -0,0 +1,123 @@
import { Injectable } from '@nestjs/common';
import { ConnectionService } from '../global/database/connection.service';
const DEFAULT_LEASE_MS = 5 * 60 * 1000;
export type DakaoInboxClaimResult =
| { status: 'claimed' }
| { status: 'duplicate' }
| { status: 'inflight' };
@Injectable()
export class DakaoInboxService {
constructor(private readonly connectionService: ConnectionService) {}
public async claim(params: {
consumer: string;
projectId: string;
chatLogLogId: string;
leaseMs?: number;
}): Promise<DakaoInboxClaimResult> {
const Model = await this.connectionService.getModel('dakaoInboundMessage');
const now = new Date();
const processingExpiresAt = new Date(
now.getTime() + (params.leaseMs ?? DEFAULT_LEASE_MS),
);
try {
await Model.create({
consumer: params.consumer,
projectId: params.projectId,
chatLogLogId: params.chatLogLogId,
state: 'processing',
attempts: 1,
processingExpiresAt,
});
return { status: 'claimed' };
} catch (err) {
if ((err as { code?: number })?.code !== 11000) throw err;
}
const existing = await Model.findOne({
consumer: params.consumer,
projectId: params.projectId,
chatLogLogId: params.chatLogLogId,
})
.lean()
.exec();
if (!existing) return { status: 'inflight' };
if (existing.state === 'processed') return { status: 'duplicate' };
if (
existing.state === 'processing' &&
existing.processingExpiresAt &&
existing.processingExpiresAt > now
) {
return { status: 'inflight' };
}
const updated = await Model.updateOne(
{
_id: existing._id,
$or: [
{ state: 'failed' },
{ state: 'processing', processingExpiresAt: { $lte: now } },
],
},
{
$set: {
state: 'processing',
processingExpiresAt,
},
$inc: { attempts: 1 },
},
).exec();
return updated.modifiedCount > 0
? { status: 'claimed' }
: { status: 'inflight' };
}
public async markProcessed(params: {
consumer: string;
projectId: string;
chatLogLogId: string;
}): Promise<void> {
const Model = await this.connectionService.getModel('dakaoInboundMessage');
await Model.updateOne(
{
consumer: params.consumer,
projectId: params.projectId,
chatLogLogId: params.chatLogLogId,
},
{
$set: {
state: 'processed',
processedAt: new Date(),
},
$unset: { processingExpiresAt: '', lastError: '' },
},
).exec();
}
public async markFailed(params: {
consumer: string;
projectId: string;
chatLogLogId: string;
error: unknown;
}): Promise<void> {
const Model = await this.connectionService.getModel('dakaoInboundMessage');
await Model.updateOne(
{
consumer: params.consumer,
projectId: params.projectId,
chatLogLogId: params.chatLogLogId,
},
{
$set: {
state: 'failed',
lastError: (params.error as Error)?.message ?? String(params.error),
},
$unset: { processingExpiresAt: '' },
},
).exec();
}
}
@@ -0,0 +1,64 @@
import { Injectable } from '@nestjs/common';
import { NatsService } from '../global/nats/nats.service';
import { resolveDakaoNatsNames } from './dakao.nats-names';
@Injectable()
export class DakaoJetStreamResourceService {
private ensurePromise: Promise<void> | null = null;
constructor(private readonly natsService: NatsService) {}
public async ensure(): Promise<void> {
this.ensurePromise ??= this.ensureInternal();
await this.ensurePromise;
}
private async ensureInternal(): Promise<void> {
const names = resolveDakaoNatsNames();
await this.natsService.ensureJetStreamStream({
name: names.streams.botCommand,
subjects: [names.subjects.botCommandSubmitted],
retention: 'workqueue',
replicas: 1,
});
await this.natsService.ensureJetStreamConsumer({
stream: names.streams.botCommand,
durable: names.consumers.botCommand,
filterSubject: names.subjects.botCommandSubmitted,
description: 'LolyMpus Dakao bot command handler',
replicas: 1,
});
await this.natsService.ensureJetStreamStream({
name: names.streams.sendRequest,
subjects: [names.subjects.chatSendMessage],
retention: 'workqueue',
replicas: 1,
});
await this.natsService.ensureJetStreamConsumer({
stream: names.streams.sendRequest,
durable: names.consumers.sendRequest,
filterSubject: names.subjects.chatSendMessage,
description: 'Dakao send-message worker',
replicas: 1,
});
await this.natsService.ensureJetStreamStream({
name: names.streams.sendResult,
subjects: [
names.subjects.chatSendMessageSucceeded,
names.subjects.chatSendMessageFailed,
],
retention: 'limits',
maxAgeDays: 30,
replicas: 1,
});
await this.natsService.ensureJetStreamConsumer({
stream: names.streams.sendResult,
durable: names.consumers.sendResult,
filterSubject: `${names.env}.lolympus.dakao.chat.send-message.*.v1`,
description: 'LolyMpus Dakao send-message result handler',
replicas: 1,
});
}
}
@@ -0,0 +1,47 @@
import {
Injectable,
Logger,
OnModuleDestroy,
OnModuleInit,
} from '@nestjs/common';
import { DakaoOutboxService } from './dakao-outbox.service';
const SWEEP_INTERVAL_MS = 60 * 1000;
const STALE_OUTBOX_MS = 5 * 60 * 1000;
@Injectable()
export class DakaoOutboxSweeperService
implements OnModuleInit, OnModuleDestroy
{
private readonly logger = new Logger(DakaoOutboxSweeperService.name);
private timer: NodeJS.Timeout | undefined;
constructor(private readonly outboxService: DakaoOutboxService) {}
onModuleInit() {
this.timer = setInterval(() => {
void this.sweep();
}, SWEEP_INTERVAL_MS);
this.timer.unref();
}
onModuleDestroy() {
if (this.timer) clearInterval(this.timer);
}
private async sweep(): Promise<void> {
try {
const swept = await this.outboxService.sweepStale({
staleMs: STALE_OUTBOX_MS,
limit: 20,
});
if (swept > 0) {
this.logger.warn(`Re-published ${swept} stale Dakao outbox messages.`);
}
} catch (err) {
this.logger.error(
`Dakao outbox sweep failed: ${(err as Error)?.stack ?? err}`,
);
}
}
}
@@ -0,0 +1,116 @@
import { ConnectionService } from '../global/database/connection.service';
import { NatsService } from '../global/nats/nats.service';
import { DakaoOutboxService } from './dakao-outbox.service';
import { DakaoResultSubjects } from './dakao.types';
function execResult<T>(value: T) {
return { exec: jest.fn().mockResolvedValue(value) };
}
function makeService(outboxModel: Record<string, unknown>) {
const connectionService = {
getModel: jest.fn().mockResolvedValue(outboxModel),
} as unknown as ConnectionService;
const natsService = {
publishJetStream: jest.fn().mockResolvedValue(undefined),
} as unknown as NatsService;
return {
service: new DakaoOutboxService(connectionService, natsService),
connectionService,
natsService,
};
}
describe('DakaoOutboxService', () => {
it('persists result subjects when enqueuing send-message commands', async () => {
const outboxModel = {
findOneAndUpdate: jest.fn().mockReturnValue(execResult({})),
updateOne: jest.fn().mockReturnValue(execResult({})),
};
const { service, natsService } = makeService(outboxModel);
const resultSubjects: DakaoResultSubjects = {
succeeded: 'staging.lolympus.dakao.chat.send-message.succeeded.v1',
failed: 'staging.lolympus.dakao.chat.send-message.failed.v1',
};
await service.enqueueAndPublish({
subject: 'staging.dakao.chat.send-message.v1',
eventId: 'lolympus:chat.send-message:chat-log-1',
envelope: {
schema: 'dakao.command.v1',
eventId: 'lolympus:chat.send-message:chat-log-1',
type: 'chat.send-message',
eventSource: 'lolympus',
correlationId: 'chat-log-1',
resultSubjects,
payload: {
chatroomId: '18474390111480678',
segments: [{ kind: 'text', text: 'done' }],
},
},
});
expect(outboxModel.findOneAndUpdate).toHaveBeenCalledWith(
{ eventId: 'lolympus:chat.send-message:chat-log-1' },
expect.objectContaining({
$setOnInsert: expect.objectContaining({ resultSubjects }),
}),
expect.any(Object),
);
expect(natsService.publishJetStream).toHaveBeenCalledWith(
'staging.dakao.chat.send-message.v1',
expect.objectContaining({ resultSubjects }),
{ messageId: 'lolympus:chat.send-message:chat-log-1' },
);
});
it('restores send-message result subjects when sweeping legacy stale rows', async () => {
const previousNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = 'staging';
try {
const exec = jest.fn().mockResolvedValue([
{
eventId: 'lolympus:chat.send-message:chat-log-1',
type: 'chat.send-message',
eventSource: 'lolympus',
subject: 'staging.dakao.chat.send-message.v1',
correlationId: 'chat-log-1',
payload: {
chatroomId: '18474390111480678',
segments: [{ kind: 'text', text: 'done' }],
},
},
]);
const lean = jest.fn().mockReturnValue({ exec });
const limit = jest.fn().mockReturnValue({ lean });
const sort = jest.fn().mockReturnValue({ limit });
const outboxModel = {
find: jest.fn().mockReturnValue({ sort }),
};
const { service } = makeService(outboxModel);
const enqueue = jest
.spyOn(service, 'enqueueAndPublish')
.mockResolvedValue(undefined);
await expect(service.sweepStale({ staleMs: 1, limit: 1 })).resolves.toBe(
1,
);
expect(enqueue).toHaveBeenCalledWith(
expect.objectContaining({
envelope: expect.objectContaining({
resultSubjects: {
succeeded:
'staging.lolympus.dakao.chat.send-message.succeeded.v1',
failed: 'staging.lolympus.dakao.chat.send-message.failed.v1',
},
}),
}),
);
} finally {
process.env.NODE_ENV = previousNodeEnv;
}
});
});
@@ -0,0 +1,191 @@
import { Injectable, Logger } from '@nestjs/common';
import { ConnectionService } from '../global/database/connection.service';
import { NatsService } from '../global/nats/nats.service';
import { resolveDakaoNatsNames } from './dakao.nats-names';
import {
DakaoCommandEnvelope,
DakaoResultEnvelope,
DakaoResultSubjects,
} from './dakao.types';
const CHAT_SEND_MESSAGE_TYPE = 'chat.send-message';
const TERMINAL_STATES = ['sent', 'failed'] as const;
@Injectable()
export class DakaoOutboxService {
private readonly logger = new Logger(DakaoOutboxService.name);
private readonly chatSendMessageResultSubjects = {
succeeded: resolveDakaoNatsNames().subjects.chatSendMessageSucceeded,
failed: resolveDakaoNatsNames().subjects.chatSendMessageFailed,
};
constructor(
private readonly connectionService: ConnectionService,
private readonly natsService: NatsService,
) {}
public async enqueueAndPublish<TPayload>(params: {
subject: string;
eventId: string;
envelope: DakaoCommandEnvelope<TPayload>;
}): Promise<void> {
const OutboxModel =
await this.connectionService.getModel('dakaoOutboxMessage');
await OutboxModel.findOneAndUpdate(
{ eventId: params.eventId },
{
$setOnInsert: {
eventId: params.eventId,
eventSource: params.envelope.eventSource,
type: params.envelope.type,
subject: params.subject,
correlationId: params.envelope.correlationId,
resultSubjects: params.envelope.resultSubjects,
payload: params.envelope.payload as Record<string, unknown>,
state: 'pending',
publishAttempts: 0,
compensationState: 'none',
},
},
{ upsert: true, returnDocument: 'after', setDefaultsOnInsert: true },
).exec();
try {
await this.natsService.publishJetStream(params.subject, params.envelope, {
messageId: params.eventId,
});
await OutboxModel.updateOne(
{
eventId: params.eventId,
state: { $nin: TERMINAL_STATES },
},
{
$set: {
state: 'published',
publishedAt: new Date(),
},
$inc: { publishAttempts: 1 },
$unset: { lastPublishError: '' },
},
).exec();
} catch (err) {
await OutboxModel.updateOne(
{
eventId: params.eventId,
state: { $nin: TERMINAL_STATES },
},
{
$inc: { publishAttempts: 1 },
$set: {
lastPublishError: (err as Error)?.message ?? String(err),
},
},
).exec();
this.logger.error(
`Failed to publish Dakao outbox eventId=${params.eventId}: ${
(err as Error)?.stack ?? err
}`,
);
}
}
public async applySendResult(params: {
subject: string;
envelope: DakaoResultEnvelope;
}): Promise<{ duplicate: boolean; terminalState?: 'sent' | 'failed' }> {
const ResultModel = await this.connectionService.getModel(
'dakaoSendResultEvent',
);
const OutboxModel =
await this.connectionService.getModel('dakaoOutboxMessage');
try {
await ResultModel.create({
eventId: params.envelope.eventId,
requestEventId: params.envelope.requestEventId,
eventSource: params.envelope.eventSource,
requestEventSource: params.envelope.requestEventSource,
type: params.envelope.type,
subject: params.subject,
status: params.envelope.status,
correlationId: params.envelope.correlationId,
handledAt: new Date(params.envelope.handledAt),
providerMessageId: params.envelope.providerMessageId,
error: params.envelope.error,
raw: params.envelope as unknown as Record<string, unknown>,
});
} catch (err) {
if ((err as { code?: number })?.code === 11000) {
return { duplicate: true };
}
throw err;
}
const terminalState =
params.envelope.status === 'succeeded' ? 'sent' : 'failed';
await OutboxModel.updateOne(
{
eventId: params.envelope.requestEventId,
state: { $nin: TERMINAL_STATES },
},
{
$set: {
state: terminalState,
terminalAt: new Date(),
resultEventId: params.envelope.eventId,
terminalError: params.envelope.error,
compensationState:
params.envelope.status === 'failed' ? 'pending' : 'none',
compensationReason: params.envelope.error?.code,
},
},
).exec();
return { duplicate: false, terminalState };
}
public async sweepStale(params?: {
staleMs?: number;
limit?: number;
}): Promise<number> {
const OutboxModel =
await this.connectionService.getModel('dakaoOutboxMessage');
const staleBefore = new Date(
Date.now() - (params?.staleMs ?? 5 * 60 * 1000),
);
const rows = await OutboxModel.find({
state: { $in: ['pending', 'published'] },
updatedAt: { $lte: staleBefore },
})
.sort({ updatedAt: 1 })
.limit(params?.limit ?? 20)
.lean()
.exec();
for (const row of rows) {
await this.enqueueAndPublish({
subject: row.subject,
eventId: row.eventId,
envelope: {
schema: 'dakao.command.v1',
eventId: row.eventId,
type: row.type,
eventSource: row.eventSource,
correlationId: row.correlationId,
resultSubjects:
row.resultSubjects ?? this.resolveDefaultResultSubjects(row.type),
payload: row.payload,
},
});
}
return rows.length;
}
private resolveDefaultResultSubjects(
type: string,
): DakaoResultSubjects | undefined {
if (type !== CHAT_SEND_MESSAGE_TYPE) return undefined;
return this.chatSendMessageResultSubjects;
}
}
@@ -0,0 +1,81 @@
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { NatsService } from '../global/nats/nats.service';
import { DakaoJetStreamResourceService } from './dakao-jetstream-resource.service';
import { resolveDakaoNatsNames } from './dakao.nats-names';
import { DakaoOutboxService } from './dakao-outbox.service';
import { DakaoResultEnvelope } from './dakao.types';
@Injectable()
export class DakaoSendResultSubscriber implements OnModuleInit {
private readonly logger = new Logger(DakaoSendResultSubscriber.name);
constructor(
private readonly natsService: NatsService,
private readonly resources: DakaoJetStreamResourceService,
private readonly outboxService: DakaoOutboxService,
) {}
async onModuleInit() {
await this.resources.ensure();
const names = resolveDakaoNatsNames();
void this.natsService.consumeJetStream<DakaoResultEnvelope>(
{
stream: names.streams.sendResult,
durable: names.consumers.sendResult,
},
(event, msg) => this.handleResult(event, msg.subject),
);
this.logger.log(
`Dakao send-result subscriber ready on stream="${names.streams.sendResult}" durable="${names.consumers.sendResult}"`,
);
}
private async handleResult(
event: DakaoResultEnvelope,
subject: string,
): Promise<void> {
if (!this.validate(event)) {
this.logger.warn(`Ignoring invalid Dakao send-result on ${subject}`);
return;
}
const result = await this.outboxService.applySendResult({
subject,
envelope: event,
});
if (result.duplicate) {
this.logger.log(
`Duplicate Dakao result ignored eventId=${event.eventId}`,
);
return;
}
this.logger.log(
`Dakao result applied eventId=${event.eventId} requestEventId=${event.requestEventId} state=${result.terminalState ?? '-'}`,
);
}
private validate(event: unknown): event is DakaoResultEnvelope {
if (!event || typeof event !== 'object') return false;
const e = event as Partial<DakaoResultEnvelope>;
if (e.schema !== 'dakao.result.v1') return false;
if (typeof e.eventId !== 'string' || e.eventId.length === 0) return false;
if (typeof e.requestEventId !== 'string' || e.requestEventId.length === 0) {
return false;
}
if (typeof e.eventSource !== 'string' || e.eventSource.length === 0)
return false;
if (
typeof e.requestEventSource !== 'string' ||
e.requestEventSource.length === 0
) {
return false;
}
if (e.status !== 'succeeded' && e.status !== 'failed') return false;
if (
typeof e.handledAt !== 'string' ||
Number.isNaN(Date.parse(e.handledAt))
)
return false;
return true;
}
}
+11 -6
View File
@@ -1,14 +1,15 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { MatchModule } from '../match/match.module'; import { MatchModule } from '../match/match.module';
import { RiotModule } from '../riot/riot.module'; import { RiotModule } from '../riot/riot.module';
import { import { DAKAO_OPTIONS, createDefaultDakaoOptions } from './dakao.options';
DAKAO_OPTIONS,
createDefaultDakaoOptions,
} from './dakao.options';
import { DakaoPublisher } from './dakao.publisher'; import { DakaoPublisher } from './dakao.publisher';
import { DakaoSubscriber } from './dakao.subscriber'; import { DakaoSubscriber } from './dakao.subscriber';
import { DakaoInboxService } from './dakao-inbox.service';
import { DakaoJetStreamResourceService } from './dakao-jetstream-resource.service';
import { DakaoOutboxSweeperService } from './dakao-outbox-sweeper.service';
import { DakaoOutboxService } from './dakao-outbox.service';
import { DakaoUserService } from './dakao-user.service'; import { DakaoUserService } from './dakao-user.service';
import { IdempotencyCache } from './idempotency.cache'; import { DakaoSendResultSubscriber } from './dakao-send-result.subscriber';
import { AccountRegisterHandler } from './handlers/account-register.handler'; import { AccountRegisterHandler } from './handlers/account-register.handler';
import { MatchCancelHandler } from './handlers/match-cancel.handler'; import { MatchCancelHandler } from './handlers/match-cancel.handler';
import { MatchJoinHandler } from './handlers/match-join.handler'; import { MatchJoinHandler } from './handlers/match-join.handler';
@@ -22,10 +23,14 @@ import { PreferredPositionRegisterHandler } from './handlers/preferred-position-
provide: DAKAO_OPTIONS, provide: DAKAO_OPTIONS,
useFactory: createDefaultDakaoOptions, useFactory: createDefaultDakaoOptions,
}, },
DakaoOutboxService,
DakaoOutboxSweeperService,
DakaoInboxService,
DakaoJetStreamResourceService,
DakaoPublisher, DakaoPublisher,
DakaoSubscriber, DakaoSubscriber,
DakaoSendResultSubscriber,
DakaoUserService, DakaoUserService,
IdempotencyCache,
AccountRegisterHandler, AccountRegisterHandler,
MatchListHandler, MatchListHandler,
MatchJoinHandler, MatchJoinHandler,
@@ -0,0 +1,38 @@
import { resolveDakaoNatsNames } from './dakao.nats-names';
describe('resolveDakaoNatsNames', () => {
it('resolves staging subjects and JetStream resources from NODE_ENV=staging', () => {
expect(resolveDakaoNatsNames('staging')).toEqual({
env: 'staging',
shortEnv: 'STG',
subjects: {
botCommandSubmitted: 'staging.lolympus.dakao.bot-command.submitted.v1',
chatSendMessage: 'staging.dakao.chat.send-message.v1',
chatSendMessageSucceeded:
'staging.lolympus.dakao.chat.send-message.succeeded.v1',
chatSendMessageFailed:
'staging.lolympus.dakao.chat.send-message.failed.v1',
},
streams: {
botCommand: 'STG_DAKAO_TO_LOLYMPUS_BOTCMD',
sendRequest: 'STG_DAKAO_SENDREQ',
sendResult: 'STG_DAKAO_TO_LOLYMPUS_SENDRES',
},
consumers: {
botCommand: 'STG_LOLYMPUS_BOTCMD',
sendRequest: 'STG_DAKAO_SENDREQ_WORKER',
sendResult: 'STG_LOLYMPUS_SENDRES',
},
});
});
it('keeps JetStream resource names within the 32 character safety target', () => {
const names = resolveDakaoNatsNames('prod');
const resources = [
...Object.values(names.streams),
...Object.values(names.consumers),
];
expect(resources.every((name) => name.length <= 32)).toBe(true);
});
});
@@ -0,0 +1,68 @@
export type DakaoRuntimeEnv = 'dev' | 'staging' | 'prod';
export type DakaoShortEnv = 'DEV' | 'STG' | 'PROD';
export interface DakaoNatsNames {
env: DakaoRuntimeEnv;
shortEnv: DakaoShortEnv;
subjects: {
botCommandSubmitted: string;
chatSendMessage: string;
chatSendMessageSucceeded: string;
chatSendMessageFailed: string;
};
streams: {
botCommand: string;
sendRequest: string;
sendResult: string;
};
consumers: {
botCommand: string;
sendRequest: string;
sendResult: string;
};
}
export function resolveDakaoNatsNames(
nodeEnv = process.env.NODE_ENV,
): DakaoNatsNames {
const env = resolveRuntimeEnv(nodeEnv);
const shortEnv = toShortEnv(env);
return {
env,
shortEnv,
subjects: {
botCommandSubmitted: `${env}.lolympus.dakao.bot-command.submitted.v1`,
chatSendMessage: `${env}.dakao.chat.send-message.v1`,
chatSendMessageSucceeded: `${env}.lolympus.dakao.chat.send-message.succeeded.v1`,
chatSendMessageFailed: `${env}.lolympus.dakao.chat.send-message.failed.v1`,
},
streams: {
botCommand: `${shortEnv}_DAKAO_TO_LOLYMPUS_BOTCMD`,
sendRequest: `${shortEnv}_DAKAO_SENDREQ`,
sendResult: `${shortEnv}_DAKAO_TO_LOLYMPUS_SENDRES`,
},
consumers: {
botCommand: `${shortEnv}_LOLYMPUS_BOTCMD`,
sendRequest: `${shortEnv}_DAKAO_SENDREQ_WORKER`,
sendResult: `${shortEnv}_LOLYMPUS_SENDRES`,
},
};
}
function resolveRuntimeEnv(nodeEnv?: string): DakaoRuntimeEnv {
if (nodeEnv === 'prod' || nodeEnv === 'production') return 'prod';
if (nodeEnv === 'staging') return 'staging';
return 'dev';
}
function toShortEnv(env: DakaoRuntimeEnv): DakaoShortEnv {
switch (env) {
case 'prod':
return 'PROD';
case 'staging':
return 'STG';
case 'dev':
return 'DEV';
}
}
@@ -1,32 +1,38 @@
import { SecretService } from '../global/secret/secret.service'; import { SecretService } from '../global/secret/secret.service';
import { NatsService } from '../global/nats/nats.service';
import { DakaoCommandEnvelope, DakaoSendMessagePayload } from './dakao.types'; import { DakaoCommandEnvelope, DakaoSendMessagePayload } from './dakao.types';
import { DakaoPublisher } from './dakao.publisher'; import { DakaoPublisher } from './dakao.publisher';
import { DakaoOutboxService } from './dakao-outbox.service';
function makePublisher() { function makePublisher() {
const natsService = { const outboxService = {
publish: jest.fn().mockResolvedValue(undefined), enqueueAndPublish: jest.fn().mockResolvedValue(undefined),
subscribe: jest.fn(), } as unknown as DakaoOutboxService;
} as unknown as NatsService;
const secretService = {} as SecretService; const secretService = {} as SecretService;
const publisher = new DakaoPublisher(natsService, secretService, { const previousNodeEnv = process.env.NODE_ENV;
instanceId: 'test', process.env.NODE_ENV = 'staging';
try {
const publisher = new DakaoPublisher(secretService, outboxService, {
instanceId: 'staging-instance',
}); });
return { publisher, natsService }; return { publisher, outboxService };
} finally {
process.env.NODE_ENV = previousNodeEnv;
}
} }
function getPublishedPayload(natsService: NatsService): DakaoSendMessagePayload { function getPublishedEnvelope(
const publish = natsService.publish as jest.Mock; outboxService: DakaoOutboxService,
const envelope = publish.mock.calls[0][1] as DakaoCommandEnvelope< ): DakaoCommandEnvelope<DakaoSendMessagePayload> {
DakaoSendMessagePayload const enqueue = outboxService.enqueueAndPublish as jest.Mock;
>; return enqueue.mock.calls[0][0]
return envelope.payload; .envelope as DakaoCommandEnvelope<DakaoSendMessagePayload>;
} }
describe('DakaoPublisher', () => { describe('DakaoPublisher', () => {
it('keeps valid mention segments intact', async () => { it('keeps valid mention segments intact', async () => {
const { publisher, natsService } = makePublisher(); const { publisher, outboxService } = makePublisher();
await publisher.sendMessage({ await publisher.sendMessage({
chatroomId: '18474390111480678', chatroomId: '18474390111480678',
@@ -40,7 +46,7 @@ describe('DakaoPublisher', () => {
], ],
}); });
expect(getPublishedPayload(natsService).segments).toEqual([ expect(getPublishedEnvelope(outboxService).payload.segments).toEqual([
{ {
kind: 'mention', kind: 'mention',
userId: '6215844374579825921', userId: '6215844374579825921',
@@ -51,7 +57,7 @@ describe('DakaoPublisher', () => {
}); });
it('downgrades invalid mention segments to text before publishing', async () => { it('downgrades invalid mention segments to text before publishing', async () => {
const { publisher, natsService } = makePublisher(); const { publisher, outboxService } = makePublisher();
await publisher.sendMessage({ await publisher.sendMessage({
chatroomId: '18474390111480678', chatroomId: '18474390111480678',
@@ -65,9 +71,39 @@ describe('DakaoPublisher', () => {
], ],
}); });
expect(getPublishedPayload(natsService).segments).toEqual([ expect(getPublishedEnvelope(outboxService).payload.segments).toEqual([
{ kind: 'text', text: '@소쿠리' }, { kind: 'text', text: '@소쿠리' },
{ kind: 'text', text: ' 신청 완료' }, { kind: 'text', text: ' 신청 완료' },
]); ]);
}); });
it('uses deterministic event ids and the shared Dakao send subject', async () => {
const { publisher, outboxService } = makePublisher();
await publisher.sendMessage({
chatroomId: '18474390111480678',
segments: [{ kind: 'text', text: '신청 완료' }],
correlationId: 'chat-log-1',
});
const enqueue = outboxService.enqueueAndPublish as jest.Mock;
expect(enqueue.mock.calls[0][0]).toMatchObject({
subject: 'staging.dakao.chat.send-message.v1',
eventId: 'lolympus:chat.send-message:chat-log-1',
});
expect(getPublishedEnvelope(outboxService)).toMatchObject({
schema: 'dakao.command.v1',
eventId: 'lolympus:chat.send-message:chat-log-1',
eventSource: 'lolympus',
type: 'chat.send-message',
correlationId: 'chat-log-1',
resultSubjects: {
succeeded: 'staging.lolympus.dakao.chat.send-message.succeeded.v1',
failed: 'staging.lolympus.dakao.chat.send-message.failed.v1',
},
});
expect(getPublishedEnvelope(outboxService)).not.toHaveProperty(
'replySubject',
);
});
}); });
+39 -55
View File
@@ -1,86 +1,86 @@
import { import { Inject, Injectable, Logger, OnModuleInit } from '@nestjs/common';
Inject,
Injectable,
Logger,
OnModuleDestroy,
OnModuleInit,
} from '@nestjs/common';
import { randomUUID } from 'crypto'; import { randomUUID } from 'crypto';
import { SecretService } from '../global/secret/secret.service'; import { SecretService } from '../global/secret/secret.service';
import { NatsService } from '../global/nats/nats.service';
import { import {
DakaoCommandEnvelope, DakaoCommandEnvelope,
DakaoResultEnvelope, DakaoResultSubjects,
DakaoSegment, DakaoSegment,
DakaoSendMessagePayload, DakaoSendMessagePayload,
} from './dakao.types'; } from './dakao.types';
import type { DakaoOptions } from './dakao.options'; import type { DakaoOptions } from './dakao.options';
import { DAKAO_OPTIONS } from './dakao.options'; import { DAKAO_OPTIONS } from './dakao.options';
import { resolveDakaoNatsNames } from './dakao.nats-names';
import { DakaoOutboxService } from './dakao-outbox.service';
const SEND_MESSAGE_SUBJECT_DEFAULT = 'dakao.command.chat.send-message.v1'; const EVENT_SOURCE_DEFAULT = 'lolympus';
const COMMAND_SOURCE_DEFAULT = 'lolympus-tournament-support';
@Injectable() @Injectable()
export class DakaoPublisher implements OnModuleInit, OnModuleDestroy { export class DakaoPublisher implements OnModuleInit {
private readonly logger = new Logger(DakaoPublisher.name); private readonly logger = new Logger(DakaoPublisher.name);
private replySubject = ''; private readonly names = resolveDakaoNatsNames();
private sendMessageSubject = SEND_MESSAGE_SUBJECT_DEFAULT; private sendMessageSubject = this.names.subjects.chatSendMessage;
private source = COMMAND_SOURCE_DEFAULT; private resultSubjects: DakaoResultSubjects = {
succeeded: this.names.subjects.chatSendMessageSucceeded,
failed: this.names.subjects.chatSendMessageFailed,
};
private eventSource = EVENT_SOURCE_DEFAULT;
constructor( constructor(
private readonly natsService: NatsService,
private readonly secretService: SecretService, private readonly secretService: SecretService,
private readonly outboxService: DakaoOutboxService,
@Inject(DAKAO_OPTIONS) private readonly options: DakaoOptions, @Inject(DAKAO_OPTIONS) private readonly options: DakaoOptions,
) {} ) {}
async onModuleInit() { async onModuleInit() {
const replyOverride = await this.secretService
.get<string>('DAKAO_REPLY_SUBJECT_PREFIX')
.catch(() => undefined);
const sendOverride = await this.secretService const sendOverride = await this.secretService
.get<string>('DAKAO_NATS_COMMAND_CHAT_SEND_MESSAGE_SUBJECT') .get<string>('DAKAO_CHAT_SEND_MESSAGE_SUBJECT')
.catch(() => undefined); .catch(() => undefined);
const sourceOverride = await this.secretService const sourceOverride = await this.secretService
.get<string>('DAKAO_COMMAND_SOURCE') .get<string>('DAKAO_EVENT_SOURCE')
.catch(() => undefined); .catch(() => undefined);
const replyPrefix = replyOverride || `dakao.result.${COMMAND_SOURCE_DEFAULT}`; this.sendMessageSubject =
this.replySubject = `${replyPrefix}.${this.options.instanceId}`; sendOverride || resolveDakaoNatsNames().subjects.chatSendMessage;
this.sendMessageSubject = sendOverride || SEND_MESSAGE_SUBJECT_DEFAULT; this.resultSubjects = {
this.source = sourceOverride || COMMAND_SOURCE_DEFAULT; succeeded: this.names.subjects.chatSendMessageSucceeded,
failed: this.names.subjects.chatSendMessageFailed,
};
this.eventSource = sourceOverride || EVENT_SOURCE_DEFAULT;
this.natsService.subscribe<DakaoResultEnvelope>(
this.replySubject,
(data) => this.handleReply(data),
);
this.logger.log( this.logger.log(
`Dakao reply subscriber ready on subject="${this.replySubject}"`, `Dakao send-message publisher ready on subject="${this.sendMessageSubject}" source="${this.eventSource}" instanceId="${this.options.instanceId}"`,
); );
} }
async onModuleDestroy() {
// NatsService 가 subscription 정리한다.
}
public async sendMessage(params: { public async sendMessage(params: {
chatroomId: string; chatroomId: string;
segments: DakaoSegment[]; segments: DakaoSegment[];
correlationId?: string; correlationId?: string;
eventId?: string;
}): Promise<void> { }): Promise<void> {
const eventId =
params.eventId ??
(params.correlationId
? `${this.eventSource}:chat.send-message:${params.correlationId}`
: `${this.eventSource}:chat.send-message:${randomUUID()}`);
const payload: DakaoSendMessagePayload = { const payload: DakaoSendMessagePayload = {
chatroomId: params.chatroomId, chatroomId: params.chatroomId,
segments: this.normalizeSegments(params.segments), segments: this.normalizeSegments(params.segments),
}; };
const envelope: DakaoCommandEnvelope<DakaoSendMessagePayload> = { const envelope: DakaoCommandEnvelope<DakaoSendMessagePayload> = {
schema: 'dakao.command.v1', schema: 'dakao.command.v1',
id: randomUUID(), eventId,
type: 'chat.send-message', type: 'chat.send-message',
source: this.source, eventSource: this.eventSource,
correlationId: params.correlationId, correlationId: params.correlationId,
replySubject: this.replySubject, resultSubjects: this.resultSubjects,
payload, payload,
}; };
await this.natsService.publish(this.sendMessageSubject, envelope); await this.outboxService.enqueueAndPublish({
subject: this.sendMessageSubject,
eventId,
envelope,
});
} }
private normalizeSegments(segments: DakaoSegment[]): DakaoSegment[] { private normalizeSegments(segments: DakaoSegment[]): DakaoSegment[] {
@@ -111,11 +111,7 @@ export class DakaoPublisher implements OnModuleInit, OnModuleDestroy {
const id = segment.id.trim(); const id = segment.id.trim();
const altText = segment.altText.trim(); const altText = segment.altText.trim();
if ( if (id.length > 0 && altText.length > 0 && !/[()@]/.test(altText)) {
id.length > 0 &&
altText.length > 0 &&
!/[()@]/.test(altText)
) {
normalized.push({ kind: 'emoticon', id, altText }); normalized.push({ kind: 'emoticon', id, altText });
continue; continue;
} }
@@ -139,16 +135,4 @@ export class DakaoPublisher implements OnModuleInit, OnModuleDestroy {
const label = displayText || userId || '사용자'; const label = displayText || userId || '사용자';
return label.startsWith('@') ? label : `@${label}`; return label.startsWith('@') ? label : `@${label}`;
} }
private handleReply(reply: DakaoResultEnvelope): void {
if (reply.status === 'succeeded') {
this.logger.log(
`Dakao reply succeeded id=${reply.id} type=${reply.type} correlationId=${reply.correlationId ?? '-'}`,
);
return;
}
this.logger.warn(
`Dakao reply failed id=${reply.id} type=${reply.type} code=${reply.error?.code ?? '-'} retryable=${reply.error?.retryable ?? false} message=${reply.error?.message ?? '-'}`,
);
}
} }
+71 -27
View File
@@ -6,19 +6,19 @@ import { CommandParseError, parseCommand } from './parsers/command.parser';
import { DakaoInboundEvent, DakaoLong, DakaoSegment } from './dakao.types'; import { DakaoInboundEvent, DakaoLong, DakaoSegment } from './dakao.types';
import { DakaoPublisher } from './dakao.publisher'; import { DakaoPublisher } from './dakao.publisher';
import { DakaoUserError, DakaoUserService } from './dakao-user.service'; import { DakaoUserError, DakaoUserService } from './dakao-user.service';
import { IdempotencyCache } from './idempotency.cache';
import { AccountRegisterHandler } from './handlers/account-register.handler'; import { AccountRegisterHandler } from './handlers/account-register.handler';
import { MatchCancelHandler } from './handlers/match-cancel.handler'; import { MatchCancelHandler } from './handlers/match-cancel.handler';
import { MatchJoinHandler } from './handlers/match-join.handler'; import { MatchJoinHandler } from './handlers/match-join.handler';
import { MatchListHandler } from './handlers/match-list.handler'; import { MatchListHandler } from './handlers/match-list.handler';
import { PreferredPositionRegisterHandler } from './handlers/preferred-position-register.handler'; import { PreferredPositionRegisterHandler } from './handlers/preferred-position-register.handler';
import { resolveDakaoNatsNames } from './dakao.nats-names';
const INBOUND_SUBJECT_DEFAULT = 'lolympus-tournament-support.kakaotalk.command'; import { DakaoInboxService } from './dakao-inbox.service';
import { DakaoJetStreamResourceService } from './dakao-jetstream-resource.service';
@Injectable() @Injectable()
export class DakaoSubscriber implements OnModuleInit { export class DakaoSubscriber implements OnModuleInit {
private readonly logger = new Logger(DakaoSubscriber.name); private readonly logger = new Logger(DakaoSubscriber.name);
private inboundSubject = INBOUND_SUBJECT_DEFAULT; private readonly natsNames = resolveDakaoNatsNames();
private botUserId: string | undefined; private botUserId: string | undefined;
constructor( constructor(
@@ -26,7 +26,8 @@ export class DakaoSubscriber implements OnModuleInit {
private readonly secretService: SecretService, private readonly secretService: SecretService,
private readonly dakaoUserService: DakaoUserService, private readonly dakaoUserService: DakaoUserService,
private readonly publisher: DakaoPublisher, private readonly publisher: DakaoPublisher,
private readonly idempotency: IdempotencyCache, private readonly inbox: DakaoInboxService,
private readonly resources: DakaoJetStreamResourceService,
private readonly accountRegisterHandler: AccountRegisterHandler, private readonly accountRegisterHandler: AccountRegisterHandler,
private readonly matchListHandler: MatchListHandler, private readonly matchListHandler: MatchListHandler,
private readonly matchJoinHandler: MatchJoinHandler, private readonly matchJoinHandler: MatchJoinHandler,
@@ -35,21 +36,20 @@ export class DakaoSubscriber implements OnModuleInit {
) {} ) {}
async onModuleInit() { async onModuleInit() {
const subjectOverride = await this.secretService
.get<string>('DAKAO_INBOUND_SUBJECT')
.catch(() => undefined);
this.inboundSubject = subjectOverride || INBOUND_SUBJECT_DEFAULT;
this.botUserId = await this.secretService this.botUserId = await this.secretService
.get<string>('DAKAO_BOT_USER_ID') .get<string>('DAKAO_BOT_USER_ID')
.catch(() => undefined); .catch(() => undefined);
this.natsService.subscribe<DakaoInboundEvent>( await this.resources.ensure();
this.inboundSubject, void this.natsService.consumeJetStream<DakaoInboundEvent>(
{
stream: this.natsNames.streams.botCommand,
durable: this.natsNames.consumers.botCommand,
},
(event) => this.handleEvent(event), (event) => this.handleEvent(event),
); );
this.logger.log( this.logger.log(
`Dakao inbound subscriber ready on subject="${this.inboundSubject}"`, `Dakao inbound subscriber ready on stream="${this.natsNames.streams.botCommand}" durable="${this.natsNames.consumers.botCommand}"`,
); );
} }
@@ -60,35 +60,52 @@ export class DakaoSubscriber implements OnModuleInit {
return; return;
} }
const logIdKey = this.deriveLogIdKey(event); const chatLogLogId = this.serializeDakaoLong(event.origin.chatLog.logId);
if (logIdKey && this.idempotency.has(logIdKey)) { let claimed = false;
return; if (chatLogLogId) {
const claim = await this.inbox.claim({
consumer: this.natsNames.consumers.botCommand,
projectId: event.projectId,
chatLogLogId,
});
if (claim.status === 'duplicate') return;
if (claim.status === 'inflight') {
throw new Error(
`Dakao event is already being processed projectId=${event.projectId} logId=${chatLogLogId}`,
);
}
claimed = true;
} }
if (logIdKey) this.idempotency.remember(logIdKey);
let communityId: mongoose.Types.ObjectId; let communityId: mongoose.Types.ObjectId;
try { try {
communityId = await this.dakaoUserService.resolveCommunityIdByDakaoProjectId( communityId =
await this.dakaoUserService.resolveCommunityIdByDakaoProjectId(
event.projectId, event.projectId,
); );
} catch (err) { } catch (err) {
if (err instanceof DakaoUserError) { if (err instanceof DakaoUserError) {
if (err.code === 'invalid_project_id') { if (err.code === 'invalid_project_id') {
this.logger.warn(`Invalid dakao projectId format: ${event.projectId}`); this.logger.warn(
`Invalid dakao projectId format: ${event.projectId}`,
);
if (claimed) await this.markProcessed(event, chatLogLogId);
return; return;
} }
if (err.code === 'community_not_found') { if (err.code === 'community_not_found') {
// 우리 쪽이 모르는 projectId. 메시지를 보내봤자 컨텍스트가 없으므로 로그만. // 우리 쪽이 모르는 projectId. 메시지를 보내봤자 컨텍스트가 없으므로 로그만.
this.logger.warn(`Unknown dakao projectId: ${event.projectId}`); this.logger.warn(`Unknown dakao projectId: ${event.projectId}`);
if (claimed) await this.markProcessed(event, chatLogLogId);
return; return;
} }
} }
if (claimed) await this.markFailed(event, chatLogLogId, err);
throw err; throw err;
} }
let segments: DakaoSegment[]; let segments: DakaoSegment[];
const senderNickname = this.resolveSenderNickname(event); const senderNickname = this.resolveSenderNickname(event);
const correlationId = this.serializeDakaoLong(event.origin.chatLog.logId); const correlationId = chatLogLogId;
try { try {
const command = parseCommand(event.origin.chatLog.message); const command = parseCommand(event.origin.chatLog.message);
@@ -141,27 +158,35 @@ export class DakaoSubscriber implements OnModuleInit {
segments, segments,
correlationId, correlationId,
}); });
if (claimed) await this.markProcessed(event, chatLogLogId);
} catch (err) { } catch (err) {
if (err instanceof CommandParseError) { if (err instanceof CommandParseError) {
// not_a_command 는 명령이 아닌 일반 메시지 → 무시. // not_a_command 는 명령이 아닌 일반 메시지 → 무시.
if (err.code === 'not_a_command') return; if (err.code === 'not_a_command') {
if (claimed) await this.markProcessed(event, chatLogLogId);
return;
}
await this.publisher.sendMessage({ await this.publisher.sendMessage({
chatroomId: event.chatroomId, chatroomId: event.chatroomId,
segments: this.parseErrorReply(event, senderNickname, err), segments: this.parseErrorReply(event, senderNickname, err),
correlationId, correlationId,
}); });
if (claimed) await this.markProcessed(event, chatLogLogId);
return; return;
} }
this.logger.error( this.logger.error(
`Unhandled dakao event error: ${(err as Error)?.stack ?? err}`, `Unhandled dakao event error: ${(err as Error)?.stack ?? err}`,
); );
if (claimed) await this.markFailed(event, chatLogLogId, err);
throw err;
} }
} }
private validate(event: unknown): event is DakaoInboundEvent { private validate(event: unknown): event is DakaoInboundEvent {
if (!event || typeof event !== 'object') return false; if (!event || typeof event !== 'object') return false;
const e = event as Partial<DakaoInboundEvent>; const e = event as Partial<DakaoInboundEvent>;
if (typeof e.projectId !== 'string' || e.projectId.length === 0) return false; if (typeof e.projectId !== 'string' || e.projectId.length === 0)
return false;
if (typeof e.chatroomId !== 'string' || e.chatroomId.length === 0) if (typeof e.chatroomId !== 'string' || e.chatroomId.length === 0)
return false; return false;
if (typeof e.nickname !== 'string') return false; if (typeof e.nickname !== 'string') return false;
@@ -174,11 +199,6 @@ export class DakaoSubscriber implements OnModuleInit {
return true; return true;
} }
private deriveLogIdKey(event: DakaoInboundEvent): string | null {
const serialized = this.serializeDakaoLong(event.origin.chatLog.logId);
return serialized ? `${event.projectId}:${serialized}` : null;
}
private serializeDakaoLong(value: DakaoLong | string | undefined): string { private serializeDakaoLong(value: DakaoLong | string | undefined): string {
if (typeof value === 'string') return value; if (typeof value === 'string') return value;
if (!value || typeof value !== 'object') return ''; if (!value || typeof value !== 'object') return '';
@@ -197,6 +217,30 @@ export class DakaoSubscriber implements OnModuleInit {
return fallback ?? ''; return fallback ?? '';
} }
private async markProcessed(
event: DakaoInboundEvent,
chatLogLogId: string,
): Promise<void> {
await this.inbox.markProcessed({
consumer: this.natsNames.consumers.botCommand,
projectId: event.projectId,
chatLogLogId,
});
}
private async markFailed(
event: DakaoInboundEvent,
chatLogLogId: string,
error: unknown,
): Promise<void> {
await this.inbox.markFailed({
consumer: this.natsNames.consumers.botCommand,
projectId: event.projectId,
chatLogLogId,
error,
});
}
private parseErrorReply( private parseErrorReply(
event: DakaoInboundEvent, event: DakaoInboundEvent,
senderNickname: string, senderNickname: string,
+17 -8
View File
@@ -1,7 +1,7 @@
// dakao NATS contracts // dakao NATS contracts
// inbound: dakao 가 lolympus-tournament-support.kakaotalk.command 로 발행하는 이벤트 // inbound: dakao 가 {env}.lolympus.dakao.bot-command.submitted.v1 로 발행하는 이벤트
// outbound: 우리가 dakao.command.chat.send-message.v1 로 발행하는 명령 // outbound: 우리가 {env}.dakao.chat.send-message.v1 로 발행하는 명령
// reply: dakao 가 우리 envelope 의 replySubject 로 publish 하는 결과 // result: dakao 가 {env}.lolympus.dakao.chat.send-message.{succeeded|failed}.v1 로 발행하는 결과 이벤트
// ===== Inbound ===== // ===== Inbound =====
export interface DakaoLong { export interface DakaoLong {
@@ -75,24 +75,33 @@ export interface DakaoSendMessagePayload {
silence?: boolean; silence?: boolean;
} }
export interface DakaoResultSubjects {
succeeded: string;
failed: string;
}
export interface DakaoCommandEnvelope<TPayload> { export interface DakaoCommandEnvelope<TPayload> {
schema: 'dakao.command.v1'; schema: 'dakao.command.v1';
id: string; eventId: string;
type: string; type: string;
source: string; eventSource: string;
correlationId?: string; correlationId?: string;
replySubject?: string; resultSubjects?: DakaoResultSubjects;
payload: TPayload; payload: TPayload;
} }
// ===== Reply ===== // ===== Result =====
export interface DakaoResultEnvelope { export interface DakaoResultEnvelope {
schema: 'dakao.result.v1'; schema: 'dakao.result.v1';
id: string; eventId: string;
requestEventId: string;
type: string; type: string;
eventSource: string;
requestEventSource: string;
status: 'succeeded' | 'failed'; status: 'succeeded' | 'failed';
handledAt: string; handledAt: string;
correlationId?: string; correlationId?: string;
providerMessageId?: string;
result?: Record<string, unknown>; result?: Record<string, unknown>;
error?: { error?: {
code: string; code: string;
@@ -7,7 +7,7 @@ describe('resolveMongoDbName', () => {
it('uses isolated databases for non-production environments', () => { it('uses isolated databases for non-production environments', () => {
expect(resolveMongoDbName('dev')).toBe('lolympus-dev'); expect(resolveMongoDbName('dev')).toBe('lolympus-dev');
expect(resolveMongoDbName('test')).toBe('lolympus-test'); expect(resolveMongoDbName('staging')).toBe('lolympus-staging');
expect(resolveMongoDbName('')).toBe('lolympus-dev'); expect(resolveMongoDbName('')).toBe('lolympus-dev');
expect(resolveMongoDbName('local')).toBe('lolympus-dev'); expect(resolveMongoDbName('local')).toBe('lolympus-dev');
}); });
@@ -5,7 +5,7 @@ import { tournamentModelDefinitions, TournamentModelTypes } from './schema';
export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string { export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string {
if (nodeEnv === 'prod') return 'lolympus'; if (nodeEnv === 'prod') return 'lolympus';
if (nodeEnv === 'test') return 'lolympus-test'; if (nodeEnv === 'staging') return 'lolympus-staging';
return 'lolympus-dev'; return 'lolympus-dev';
} }
@@ -121,7 +121,7 @@ function parseArgs(argv: string[]): CliOptions {
} }
if (arg === '--env') { if (arg === '--env') {
const value = argv[index + 1]; const value = argv[index + 1];
if (!value) throw new Error('--env requires dev, test, or prod.'); if (!value) throw new Error('--env requires dev, staging, or prod.');
nodeEnv = value; nodeEnv = value;
index += 1; index += 1;
continue; continue;
@@ -164,8 +164,8 @@ function parseArgs(argv: string[]): CliOptions {
throw new Error(`Unknown argument: ${arg}`); throw new Error(`Unknown argument: ${arg}`);
} }
if (!['dev', 'test', 'prod'].includes(nodeEnv)) { if (!['dev', 'staging', 'prod'].includes(nodeEnv)) {
throw new Error('--env must be dev, test, or prod.'); throw new Error('--env must be dev, staging, or prod.');
} }
if (communityId && !mongoose.isValidObjectId(communityId)) { if (communityId && !mongoose.isValidObjectId(communityId)) {
throw new Error('--community-id must be a valid ObjectId.'); throw new Error('--community-id must be a valid ObjectId.');
@@ -198,7 +198,7 @@ function printHelp() {
Options: Options:
--community-id <id> Community ObjectId. Defaults to env or first community. --community-id <id> Community ObjectId. Defaults to env or first community.
--dry-run Print the payload summary without writing. --dry-run Print the payload summary without writing.
--env <env> dev | test | prod. Default: NODE_ENV or dev. --env <env> dev | staging | prod. Default: NODE_ENV or dev.
--replace Delete previous temp matches created by this script first. --replace Delete previous temp matches created by this script first.
--scheduled-at <iso> Scheduled date. Default: yesterday. --scheduled-at <iso> Scheduled date. Default: yesterday.
--title <title> Match title. Default: timestamped temp title. --title <title> Match title. Default: timestamped temp title.
@@ -71,7 +71,7 @@ function parseArgs(argv: string[]): CliOptions {
} }
if (arg === '--env') { if (arg === '--env') {
const value = argv[index + 1]; const value = argv[index + 1];
if (!value) throw new Error('--env requires dev, test, or prod.'); if (!value) throw new Error('--env requires dev, staging, or prod.');
nodeEnv = value; nodeEnv = value;
index += 1; index += 1;
continue; continue;
@@ -104,8 +104,8 @@ function parseArgs(argv: string[]): CliOptions {
throw new Error(`Unknown argument: ${arg}`); throw new Error(`Unknown argument: ${arg}`);
} }
if (!['dev', 'test', 'prod'].includes(nodeEnv)) { if (!['dev', 'staging', 'prod'].includes(nodeEnv)) {
throw new Error('--env must be dev, test, or prod.'); throw new Error('--env must be dev, staging, or prod.');
} }
return { dryRun, limit, nodeEnv }; return { dryRun, limit, nodeEnv };
@@ -119,7 +119,7 @@ function printHelp() {
Options: Options:
--dry-run Print affected counts without writing. Default. --dry-run Print affected counts without writing. Default.
--apply Apply updates to MongoDB. --apply Apply updates to MongoDB.
--env <env> dev | test | prod. Default: NODE_ENV or dev. --env <env> dev | staging | prod. Default: NODE_ENV or dev.
--limit <n> Only scan first n documents per collection. --limit <n> Only scan first n documents per collection.
`); `);
} }
@@ -130,7 +130,9 @@ async function main() {
await loadMachineEnvFile(); await loadMachineEnvFile();
const app = await NestFactory.createApplicationContext(MigrationModule, { const app = await NestFactory.createApplicationContext(MigrationModule, {
logger: options.dryRun ? ['log', 'warn', 'error'] : ['log', 'warn', 'error'], logger: options.dryRun
? ['log', 'warn', 'error']
: ['log', 'warn', 'error'],
}); });
try { try {
@@ -145,14 +147,19 @@ async function main() {
`[team-index migration] mode=${options.dryRun ? 'dry-run' : 'apply'} env=${options.nodeEnv} db=${dbName}`, `[team-index migration] mode=${options.dryRun ? 'dry-run' : 'apply'} env=${options.nodeEnv} db=${dbName}`,
); );
const stats = await migrateTeamIndex(connection.db as Parameters<typeof migrateTeamIndex>[0], { const stats = await migrateTeamIndex(
connection.db as Parameters<typeof migrateTeamIndex>[0],
{
dryRun: options.dryRun, dryRun: options.dryRun,
limit: options.limit, limit: options.limit,
}); },
);
console.table(stats); console.table(stats);
if (options.dryRun) { if (options.dryRun) {
console.log('No writes were made. Re-run with --apply to update documents.'); console.log(
'No writes were made. Re-run with --apply to update documents.',
);
} else { } else {
console.log('Migration applied.'); console.log('Migration applied.');
} }
@@ -91,6 +91,39 @@ export const LEGACY_IMPORT_JOB_STATES: LegacyImportJobState[] = [
'cancelled', 'cancelled',
]; ];
export type DakaoInboundMessageState = 'processing' | 'processed' | 'failed';
export const DAKAO_INBOUND_MESSAGE_STATES: DakaoInboundMessageState[] = [
'processing',
'processed',
'failed',
];
export type DakaoOutboxMessageState =
| 'pending'
| 'published'
| 'sent'
| 'failed';
export const DAKAO_OUTBOX_MESSAGE_STATES: DakaoOutboxMessageState[] = [
'pending',
'published',
'sent',
'failed',
];
export type DakaoOutboxCompensationState =
| 'none'
| 'pending'
| 'completed'
| 'failed';
export const DAKAO_OUTBOX_COMPENSATION_STATES: DakaoOutboxCompensationState[] =
['none', 'pending', 'completed', 'failed'];
export type DakaoSendResultStatus = 'succeeded' | 'failed';
export const DAKAO_SEND_RESULT_STATUSES: DakaoSendResultStatus[] = [
'succeeded',
'failed',
];
export interface PositionPreference { export interface PositionPreference {
position: Position; position: Position;
priority: number; // 1 = 최우선, 숫자가 작을수록 높은 우선순위 priority: number; // 1 = 최우선, 숫자가 작을수록 높은 우선순위
@@ -300,9 +333,61 @@ export interface CommunitySeason {
endedAt?: Date; endedAt?: Date;
} }
export interface DakaoInboundMessage extends MongooseTimestamps {
consumer: string;
projectId: string;
chatLogLogId: string;
state: DakaoInboundMessageState;
attempts: number;
processingExpiresAt?: Date;
processedAt?: Date;
lastError?: string;
}
export interface DakaoOutboxMessage extends MongooseTimestamps {
eventId: string;
eventSource: string;
type: string;
subject: string;
correlationId?: string;
resultSubjects?: {
succeeded: string;
failed: string;
};
payload: Record<string, unknown>;
state: DakaoOutboxMessageState;
publishAttempts: number;
publishedAt?: Date;
terminalAt?: Date;
resultEventId?: string;
lastPublishError?: string;
terminalError?: Record<string, unknown>;
compensationState: DakaoOutboxCompensationState;
compensationReason?: string;
}
export interface DakaoSendResultEvent extends MongooseTimestamps {
eventId: string;
requestEventId: string;
eventSource: string;
requestEventSource: string;
type: string;
subject: string;
status: DakaoSendResultStatus;
correlationId?: string;
handledAt: Date;
providerMessageId?: string;
error?: Record<string, unknown>;
raw: Record<string, unknown>;
}
export type CommunityDocument = HydratedDocument<Community>; export type CommunityDocument = HydratedDocument<Community>;
export type IdentityDocument = HydratedDocument<Identity>; export type IdentityDocument = HydratedDocument<Identity>;
export type UserDocument = HydratedDocument<User>; export type UserDocument = HydratedDocument<User>;
export type DakaoInboundMessageDocument = HydratedDocument<DakaoInboundMessage>;
export type DakaoOutboxMessageDocument = HydratedDocument<DakaoOutboxMessage>;
export type DakaoSendResultEventDocument =
HydratedDocument<DakaoSendResultEvent>;
// ===== RiotMatch (Riot 원본 매치 아카이브) ===== // ===== RiotMatch (Riot 원본 매치 아카이브) =====
export interface RiotMatch extends MongooseTimestamps { export interface RiotMatch extends MongooseTimestamps {
@@ -533,6 +618,14 @@ export interface AuctionBid {
timestamp: Date; timestamp: Date;
} }
export interface AuctionChatMessage {
id: string;
userId?: mongoose.Types.ObjectId;
displayName: string;
message: string;
sentAt: Date;
}
export interface Auction extends MongooseTimestamps { export interface Auction extends MongooseTimestamps {
matchId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId;
phase: AuctionPhase; phase: AuctionPhase;
@@ -550,6 +643,7 @@ export interface Auction extends MongooseTimestamps {
initialPoints: number; initialPoints: number;
topTierThreshold: AuctionTopTierThreshold; topTierThreshold: AuctionTopTierThreshold;
manualTopTierUserIds: mongoose.Types.ObjectId[]; manualTopTierUserIds: mongoose.Types.ObjectId[];
chatMessages: AuctionChatMessage[];
startedAt?: Date; startedAt?: Date;
completedAt?: Date; completedAt?: Date;
} }
@@ -844,6 +938,102 @@ CommunitySchema.index({ name: 1 }, { unique: true });
CommunitySchema.index({ ownerUserId: 1 }); CommunitySchema.index({ ownerUserId: 1 });
CommunitySchema.index({ dakaoProjectId: 1 }, { unique: true, sparse: true }); CommunitySchema.index({ dakaoProjectId: 1 }, { unique: true, sparse: true });
export const DakaoInboundMessageSchema = new Schema<DakaoInboundMessage>(
{
consumer: { type: String, required: true },
projectId: { type: String, required: true },
chatLogLogId: { type: String, required: true },
state: {
type: String,
enum: DAKAO_INBOUND_MESSAGE_STATES,
required: true,
default: 'processing',
},
attempts: { type: Number, required: true, default: 1 },
processingExpiresAt: { type: Date },
processedAt: { type: Date },
lastError: { type: String },
},
{
timestamps: true,
collection: 'dakao_inbound_message',
},
);
DakaoInboundMessageSchema.index(
{ consumer: 1, projectId: 1, chatLogLogId: 1 },
{ unique: true },
);
DakaoInboundMessageSchema.index({ state: 1, processingExpiresAt: 1 });
export const DakaoOutboxMessageSchema = new Schema<DakaoOutboxMessage>(
{
eventId: { type: String, required: true, unique: true },
eventSource: { type: String, required: true },
type: { type: String, required: true },
subject: { type: String, required: true },
correlationId: { type: String },
resultSubjects: {
succeeded: { type: String },
failed: { type: String },
},
payload: { type: Schema.Types.Mixed, required: true },
state: {
type: String,
enum: DAKAO_OUTBOX_MESSAGE_STATES,
required: true,
default: 'pending',
},
publishAttempts: { type: Number, required: true, default: 0 },
publishedAt: { type: Date },
terminalAt: { type: Date },
resultEventId: { type: String },
lastPublishError: { type: String },
terminalError: { type: Schema.Types.Mixed },
compensationState: {
type: String,
enum: DAKAO_OUTBOX_COMPENSATION_STATES,
required: true,
default: 'none',
},
compensationReason: { type: String },
},
{
timestamps: true,
collection: 'dakao_outbox_message',
},
);
DakaoOutboxMessageSchema.index({ state: 1, updatedAt: 1 });
DakaoOutboxMessageSchema.index({ correlationId: 1 }, { sparse: true });
export const DakaoSendResultEventSchema = new Schema<DakaoSendResultEvent>(
{
eventId: { type: String, required: true, unique: true },
requestEventId: { type: String, required: true },
eventSource: { type: String, required: true },
requestEventSource: { type: String, required: true },
type: { type: String, required: true },
subject: { type: String, required: true },
status: {
type: String,
enum: DAKAO_SEND_RESULT_STATUSES,
required: true,
},
correlationId: { type: String },
handledAt: { type: Date, required: true },
providerMessageId: { type: String },
error: { type: Schema.Types.Mixed },
raw: { type: Schema.Types.Mixed, required: true },
},
{
timestamps: true,
collection: 'dakao_send_result_event',
},
);
DakaoSendResultEventSchema.index({ requestEventId: 1, status: 1 });
export const UserSchema = new Schema<User>( export const UserSchema = new Schema<User>(
{ {
communityId: { communityId: {
@@ -1385,6 +1575,17 @@ const AuctionBidSubSchema = new Schema<AuctionBid>(
{ _id: false }, { _id: false },
); );
const AuctionChatMessageSubSchema = new Schema<AuctionChatMessage>(
{
id: { type: String, required: true },
userId: { type: Schema.Types.ObjectId, ref: 'user', required: false },
displayName: { type: String, required: true },
message: { type: String, required: true },
sentAt: { type: Date, required: true, default: Date.now },
},
{ _id: false },
);
export const AuctionSchema = new Schema<Auction>( export const AuctionSchema = new Schema<Auction>(
{ {
matchId: { matchId: {
@@ -1431,6 +1632,11 @@ export const AuctionSchema = new Schema<Auction>(
required: true, required: true,
default: [], default: [],
}, },
chatMessages: {
type: [AuctionChatMessageSubSchema],
required: true,
default: [],
},
startedAt: { type: Date, required: false }, startedAt: { type: Date, required: false },
completedAt: { type: Date, required: false }, completedAt: { type: Date, required: false },
}, },
@@ -1519,6 +1725,21 @@ MatchStatsSchema.index({ communityId: 1, championIds: 1 });
export const tournamentModelDefinitions: ModelDefinition[] = [ export const tournamentModelDefinitions: ModelDefinition[] = [
{ name: 'identity', schema: IdentitySchema, schemaName: 'identity' }, { name: 'identity', schema: IdentitySchema, schemaName: 'identity' },
{ name: 'community', schema: CommunitySchema, schemaName: 'community' }, { name: 'community', schema: CommunitySchema, schemaName: 'community' },
{
name: 'dakaoInboundMessage',
schema: DakaoInboundMessageSchema,
schemaName: 'dakaoInboundMessage',
},
{
name: 'dakaoOutboxMessage',
schema: DakaoOutboxMessageSchema,
schemaName: 'dakaoOutboxMessage',
},
{
name: 'dakaoSendResultEvent',
schema: DakaoSendResultEventSchema,
schemaName: 'dakaoSendResultEvent',
},
{ name: 'user', schema: UserSchema, schemaName: 'user' }, { name: 'user', schema: UserSchema, schemaName: 'user' },
{ name: 'riotMatch', schema: RiotMatchSchema, schemaName: 'riotMatch' }, { name: 'riotMatch', schema: RiotMatchSchema, schemaName: 'riotMatch' },
{ {
@@ -1548,6 +1769,9 @@ export const tournamentModelDefinitions: ModelDefinition[] = [
export interface TournamentModelTypes { export interface TournamentModelTypes {
identity: Identity; identity: Identity;
community: Community; community: Community;
dakaoInboundMessage: DakaoInboundMessage;
dakaoOutboxMessage: DakaoOutboxMessage;
dakaoSendResultEvent: DakaoSendResultEvent;
user: User; user: User;
riotMatch: RiotMatch; riotMatch: RiotMatch;
tournamentCode: TournamentCode; tournamentCode: TournamentCode;
@@ -1,11 +1,21 @@
import { Inject, Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
import { import {
Inject, AckPolicy,
Injectable, DeliverPolicy,
Logger, nanos,
OnModuleDestroy, ReplayPolicy,
} from '@nestjs/common'; RetentionPolicy,
import { StringCodec } from 'nats'; StorageType,
import type { Msg, NatsConnection, Subscription } from 'nats'; StringCodec,
} from 'nats';
import type {
ConsumerMessages,
JsMsg,
Msg,
NatsConnection,
PubAck,
Subscription,
} from 'nats';
import { NATS_CLIENT } from './nats.constants'; import { NATS_CLIENT } from './nats.constants';
export type NatsMessageHandler<T = unknown> = ( export type NatsMessageHandler<T = unknown> = (
@@ -13,17 +23,62 @@ export type NatsMessageHandler<T = unknown> = (
msg: Msg, msg: Msg,
) => Promise<void> | void; ) => Promise<void> | void;
export type JetStreamRetention = 'workqueue' | 'limits';
export type JetStreamMessageHandler<T = unknown> = (
data: T,
msg: JsMsg,
) => Promise<void> | void;
export interface JetStreamStreamOptions {
name: string;
subjects: string[];
retention: JetStreamRetention;
maxAgeDays?: number;
replicas?: number;
}
export interface JetStreamConsumerOptions {
stream: string;
durable: string;
filterSubject: string;
description?: string;
ackWaitMs?: number;
backoffMs?: number[];
maxDeliver?: number;
maxAckPending?: number;
replicas?: number;
}
export interface JetStreamConsumeOptions {
stream: string;
durable: string;
maxMessages?: number;
expiresMs?: number;
nakDelayMs?: number;
}
@Injectable() @Injectable()
export class NatsService implements OnModuleDestroy { export class NatsService implements OnModuleDestroy {
private readonly logger = new Logger(NatsService.name); private readonly logger = new Logger(NatsService.name);
private readonly stringCodec = StringCodec(); private readonly stringCodec = StringCodec();
private readonly subscriptions = new Set<Subscription>(); private readonly subscriptions = new Set<Subscription>();
private readonly jetStreamConsumers = new Set<ConsumerMessages>();
constructor( constructor(
@Inject(NATS_CLIENT) private readonly natsClient: NatsConnection, @Inject(NATS_CLIENT) private readonly natsClient: NatsConnection,
) {} ) {}
async onModuleDestroy() { async onModuleDestroy() {
for (const consumer of this.jetStreamConsumers) {
try {
await consumer.close();
} catch {
// ignore
}
}
this.jetStreamConsumers.clear();
for (const sub of this.subscriptions) { for (const sub of this.subscriptions) {
try { try {
sub.unsubscribe(); sub.unsubscribe();
@@ -68,6 +123,108 @@ export class NatsService implements OnModuleDestroy {
return sub; return sub;
} }
public async publishJetStream<T = unknown>(
subject: string,
data: T,
options?: { messageId?: string; timeoutMs?: number },
): Promise<PubAck> {
const ack = await this.natsClient
.jetstream()
.publish(subject, this.stringCodec.encode(JSON.stringify(data)), {
msgID: options?.messageId,
timeout: options?.timeoutMs ?? 5000,
});
return ack;
}
public async ensureJetStreamStream(
options: JetStreamStreamOptions,
): Promise<void> {
const manager = await this.natsClient.jetstreamManager();
const config = {
name: options.name,
subjects: options.subjects,
retention: this.toRetentionPolicy(options.retention),
storage: StorageType.File,
num_replicas: options.replicas ?? 1,
max_age: options.maxAgeDays
? nanos(options.maxAgeDays * 24 * 60 * 60 * 1000)
: 0,
};
try {
await manager.streams.info(options.name);
await manager.streams.update(options.name, {
subjects: config.subjects,
max_age: config.max_age,
num_replicas: config.num_replicas,
});
return;
} catch {
await manager.streams.add(config);
}
}
public async ensureJetStreamConsumer(
options: JetStreamConsumerOptions,
): Promise<void> {
const manager = await this.natsClient.jetstreamManager();
const config = {
durable_name: options.durable,
name: options.durable,
description: options.description,
filter_subject: options.filterSubject,
deliver_policy: DeliverPolicy.All,
ack_policy: AckPolicy.Explicit,
replay_policy: ReplayPolicy.Instant,
ack_wait: nanos(options.ackWaitMs ?? 30000),
backoff: (options.backoffMs ?? [5000, 30000, 120000, 600000]).map(
(entry) => nanos(entry),
),
max_deliver: options.maxDeliver ?? 10,
max_ack_pending: options.maxAckPending ?? 50,
num_replicas: options.replicas ?? 1,
};
try {
await manager.consumers.info(options.stream, options.durable);
await manager.consumers.update(options.stream, options.durable, config);
return;
} catch {
await manager.consumers.add(options.stream, config);
}
}
public async consumeJetStream<T = unknown>(
options: JetStreamConsumeOptions,
handler: JetStreamMessageHandler<T>,
): Promise<void> {
try {
const consumer = await this.natsClient
.jetstream()
.consumers.get(options.stream, options.durable);
const messages = await consumer.consume({
max_messages: options.maxMessages ?? 10,
expires: options.expiresMs ?? 30000,
});
this.jetStreamConsumers.add(messages);
try {
for await (const msg of messages) {
await this.dispatchJetStream(msg, handler, options);
}
} finally {
this.jetStreamConsumers.delete(messages);
}
} catch (err) {
this.logger.error(
`JetStream consumer stream="${options.stream}" durable="${options.durable}" terminated: ${
(err as Error)?.stack ?? err
}`,
);
}
}
private async consumeSubscription<T>( private async consumeSubscription<T>(
sub: Subscription, sub: Subscription,
handler: NatsMessageHandler<T>, handler: NatsMessageHandler<T>,
@@ -114,4 +271,46 @@ export class NatsService implements OnModuleDestroy {
); );
} }
} }
private async dispatchJetStream<T>(
msg: JsMsg,
handler: JetStreamMessageHandler<T>,
options: JetStreamConsumeOptions,
): Promise<void> {
let data: T;
try {
data = JSON.parse(msg.string()) as T;
} catch (err) {
this.logger.warn(
`Terminating undecodable JetStream message subject="${msg.subject}" stream="${options.stream}": ${
(err as Error)?.message ?? err
}`,
);
msg.term('invalid_json');
return;
}
try {
await handler(data, msg);
const acked = await msg.ackAck({ timeout: 5000 });
if (!acked) {
this.logger.warn(
`JetStream ack was not confirmed subject="${msg.subject}" stream="${options.stream}" seq=${msg.seq}`,
);
}
} catch (err) {
this.logger.error(
`JetStream handler error subject="${msg.subject}" stream="${options.stream}" seq=${msg.seq}: ${
(err as Error)?.stack ?? err
}`,
);
msg.nak(options.nakDelayMs ?? 5000);
}
}
private toRetentionPolicy(retention: JetStreamRetention): RetentionPolicy {
return retention === 'workqueue'
? RetentionPolicy.Workqueue
: RetentionPolicy.Limits;
}
} }
@@ -84,7 +84,7 @@ export class SecretService {
environment: environment:
process.env.NODE_ENV === 'prod' process.env.NODE_ENV === 'prod'
? 'prod' ? 'prod'
: process.env.NODE_ENV === 'test' : process.env.NODE_ENV === 'staging'
? 'staging' ? 'staging'
: 'dev', : 'dev',
projectId: bootstrapConfig.projectId, projectId: bootstrapConfig.projectId,
@@ -173,6 +173,14 @@ export class UpdateMatchDto {
schedule?: MatchScheduleItemDto[]; schedule?: MatchScheduleItemDto[];
} }
export class UpdateParticipantDto {
@IsEnum(POSITIONS)
mainPosition!: Position;
@IsEnum(POSITIONS)
subPosition!: Position;
}
export class JoinMatchDto { export class JoinMatchDto {
@IsArray() @IsArray()
@ArrayMinSize(1) @ArrayMinSize(1)
@@ -27,6 +27,7 @@ import {
CreateMatchDto, CreateMatchDto,
JoinMatchDto, JoinMatchDto,
UpdateMatchDto, UpdateMatchDto,
UpdateParticipantDto,
} from './dto/create-match.dto'; } from './dto/create-match.dto';
import { MatchService } from './match.service'; import { MatchService } from './match.service';
@@ -137,6 +138,49 @@ export class MatchController {
}); });
} }
// 관리자 전용 — 참가자 주/부 포지션 변경.
@Patch(':matchId/participants/:userId')
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
public async updateParticipant(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
@Body() body: UpdateParticipantDto,
) {
this.assertSameCommunity(currentUser, communityId);
const match = await this.matchService.updateParticipantPositions({
matchId,
communityId,
targetUserId: userId,
mainPosition: body.mainPosition,
subPosition: body.subPosition,
});
return this.matchService.serialize(match);
}
// 관리자 전용 — 참가자 강제 제외.
@Delete(':matchId/participants/:userId')
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
@HttpCode(HttpStatus.NO_CONTENT)
public async removeParticipant(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
) {
this.assertSameCommunity(currentUser, communityId);
await this.matchService.removeParticipant({
matchId,
communityId,
targetUserId: userId,
});
}
private resolveJoinerUserId( private resolveJoinerUserId(
currentUser: UserDocument | undefined, currentUser: UserDocument | undefined,
bodyUserId?: string, bodyUserId?: string,
@@ -13,6 +13,7 @@ import {
MatchDocument, MatchDocument,
MatchSeriesResult, MatchSeriesResult,
MatchStatus, MatchStatus,
Position,
PositionPreference, PositionPreference,
TierInfo, TierInfo,
} from '../global/database/schema'; } from '../global/database/schema';
@@ -54,6 +55,20 @@ interface CancelMatchJoinParams {
userId: mongoose.Types.ObjectId; userId: mongoose.Types.ObjectId;
} }
interface RemoveParticipantParams {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
targetUserId: mongoose.Types.ObjectId;
}
interface UpdateParticipantPositionsParams {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
targetUserId: mongoose.Types.ObjectId;
mainPosition: Position;
subPosition: Position;
}
@Injectable() @Injectable()
export class MatchService { export class MatchService {
constructor( constructor(
@@ -276,6 +291,86 @@ export class MatchService {
return match; return match;
} }
// 관리자 전용 — 특정 참가자를 강제로 제외한다.
public async removeParticipant(
params: RemoveParticipantParams,
): Promise<MatchDocument> {
const match = await this.loadRecruitingMatch(
params.matchId,
params.communityId,
);
const participantIndex = match.participants.findIndex((participant) =>
participant.userId.equals(params.targetUserId),
);
if (participantIndex === -1) {
throw new NotFoundException('Participant not found.');
}
match.participants.splice(participantIndex, 1);
await match.save();
return match;
}
// 관리자 전용 — 참가자의 주/부 포지션(선호 우선순위 1·2)을 교체한다.
public async updateParticipantPositions(
params: UpdateParticipantPositionsParams,
): Promise<MatchDocument> {
const match = await this.loadRecruitingMatch(
params.matchId,
params.communityId,
);
const participant = match.participants.find((entry) =>
entry.userId.equals(params.targetUserId),
);
if (!participant) {
throw new NotFoundException('Participant not found.');
}
participant.preferredPositions = this.reorderPreferredPositions(
params.mainPosition,
params.subPosition,
participant.preferredPositions,
);
match.markModified('participants');
await match.save();
return match;
}
private async loadRecruitingMatch(
matchId: mongoose.Types.ObjectId,
communityId: mongoose.Types.ObjectId,
): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findById(matchId);
if (!match) throw new NotFoundException('Match not found.');
if (!match.communityId.equals(communityId)) {
throw new BadRequestException('Different community.');
}
if (match.status !== 'recruiting') {
throw new BadRequestException('Match is not recruiting.');
}
return match;
}
// 주/부 포지션을 priority 1·2로 올리고 기존 나머지 선호는 뒤로 보존한다.
private reorderPreferredPositions(
mainPosition: Position,
subPosition: Position,
current: PositionPreference[],
): PositionPreference[] {
const ordered: Position[] = [mainPosition];
if (subPosition !== mainPosition) ordered.push(subPosition);
for (const preference of [...current].sort(
(left, right) => left.priority - right.priority,
)) {
if (!ordered.includes(preference.position)) {
ordered.push(preference.position);
}
}
return ordered.map((position, index) => ({
position,
priority: index + 1,
}));
}
private selectParticipantTier(tiers: TierInfo[]): TierInfo | undefined { private selectParticipantTier(tiers: TierInfo[]): TierInfo | undefined {
const tier = const tier =
tiers.find((entry) => entry.queueType === 'RANKED_SOLO_5x5') ?? tiers[0]; tiers.find((entry) => entry.queueType === 'RANKED_SOLO_5x5') ?? tiers[0];
@@ -0,0 +1,116 @@
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { GarnetService } from '../global/garnet/garnet.service';
import { LegacyImportService } from '../legacy-import/legacy-import.service';
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
import { RiotRecentMatchesService } from '../riot/riot-recent-matches.service';
import { TournamentResultService } from '../tournament-result/tournament-result.service';
import { RIOT_JOB_GROUP, RiotRefreshSubJob } from './riot-job-queue.types';
import { RiotJobQueueService } from './riot-job-queue.service';
import { RiotJobWorkerService } from './riot-job-worker.service';
import { RiotRefreshGateway } from './riot-refresh.gateway';
function execResult<T>(value: T) {
return { exec: jest.fn().mockResolvedValue(value) };
}
function makeWorker() {
const garnetService = {
acknowledgeStream: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<GarnetService>;
const jobQueueService = {
markProcessing: jest.fn().mockResolvedValue(undefined),
markCompleted: jest.fn().mockResolvedValue({
parentJobId: 'parent-1',
jobId: 'job-1',
queueGroup: 'summoners-rift',
puuid: 'puuid-1',
state: 'completed',
}),
markFailed: jest.fn(),
} as unknown as jest.Mocked<RiotJobQueueService>;
const recentMatchesService = {
ensureFreshForQueue: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<RiotRecentMatchesService>;
const userModel = {
updateOne: jest.fn().mockReturnValue(execResult({ modifiedCount: 1 })),
};
const connectionService = {
getModel: jest.fn().mockResolvedValue(userModel),
} as unknown as jest.Mocked<ConnectionService>;
const refreshGateway = {
broadcastRefreshEvent: jest.fn(),
} as unknown as jest.Mocked<RiotRefreshGateway>;
const tournamentResultService = {
processPollJob: jest.fn(),
} as unknown as jest.Mocked<TournamentResultService>;
const legacyImportService = {
processMemberJob: jest.fn(),
} as unknown as jest.Mocked<LegacyImportService>;
const enrichmentService = {
refreshLeagueEntries: jest.fn().mockResolvedValue('updated'),
} as unknown as jest.Mocked<RiotAccountEnrichmentService>;
const worker = new RiotJobWorkerService(
garnetService,
jobQueueService,
recentMatchesService,
connectionService,
refreshGateway,
tournamentResultService,
legacyImportService,
enrichmentService,
);
return {
worker,
garnetService,
jobQueueService,
recentMatchesService,
connectionService,
refreshGateway,
enrichmentService,
};
}
describe('RiotJobWorkerService', () => {
it('refreshes league entries while processing user history refresh jobs', async () => {
const { worker, enrichmentService, recentMatchesService, garnetService } =
makeWorker();
const userId = new mongoose.Types.ObjectId().toString();
const job: RiotRefreshSubJob = {
jobId: 'job-1',
parentJobId: 'parent-1',
userId,
puuid: 'puuid-1',
region: 'asia',
platform: 'kr',
queueGroup: 'summoners-rift',
queueIds: [420, 430],
requestedAt: Date.now(),
priority: 'high',
};
await (worker as unknown as {
processEntry: (
stream: string,
entry: { id: string; message: Record<string, string> },
) => Promise<void>;
}).processEntry('riot:queue:high', {
id: '1-0',
message: { job: JSON.stringify(job) },
});
expect(recentMatchesService.ensureFreshForQueue).toHaveBeenCalledTimes(2);
expect(enrichmentService.refreshLeagueEntries).toHaveBeenCalledWith({
userId: expect.any(mongoose.Types.ObjectId),
puuid: 'puuid-1',
platform: 'kr',
});
expect(garnetService.acknowledgeStream).toHaveBeenCalledWith(
'riot:queue:high',
RIOT_JOB_GROUP,
'1-0',
);
});
});
@@ -9,7 +9,10 @@ import { ConnectionService } from '../global/database/connection.service';
import { GarnetService, StreamEntry } from '../global/garnet/garnet.service'; import { GarnetService, StreamEntry } from '../global/garnet/garnet.service';
import { LegacyImportService } from '../legacy-import/legacy-import.service'; import { LegacyImportService } from '../legacy-import/legacy-import.service';
import type { LegacyImportMemberJob } from '../legacy-import/legacy-import.types'; import type { LegacyImportMemberJob } from '../legacy-import/legacy-import.types';
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
import { RiotRecentMatchesService } from '../riot/riot-recent-matches.service'; import { RiotRecentMatchesService } from '../riot/riot-recent-matches.service';
import { TournamentResultService } from '../tournament-result/tournament-result.service';
import type { PollTournamentResultJob } from '../tournament-result/tournament-result.types';
import { import {
RIOT_JOB_GROUP, RIOT_JOB_GROUP,
RIOT_JOB_HIGH_STREAM, RIOT_JOB_HIGH_STREAM,
@@ -19,8 +22,6 @@ import {
} from './riot-job-queue.types'; } from './riot-job-queue.types';
import { RiotJobQueueService } from './riot-job-queue.service'; import { RiotJobQueueService } from './riot-job-queue.service';
import { RiotRefreshGateway } from './riot-refresh.gateway'; import { RiotRefreshGateway } from './riot-refresh.gateway';
import { TournamentResultService } from '../tournament-result/tournament-result.service';
import type { PollTournamentResultJob } from '../tournament-result/tournament-result.types';
const LEADER_KEY = 'riot:worker:leader'; const LEADER_KEY = 'riot:worker:leader';
const LEADER_TTL_SECONDS = 60; const LEADER_TTL_SECONDS = 60;
@@ -39,6 +40,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
private readonly refreshGateway: RiotRefreshGateway, private readonly refreshGateway: RiotRefreshGateway,
private readonly tournamentResultService: TournamentResultService, private readonly tournamentResultService: TournamentResultService,
private readonly legacyImportService: LegacyImportService, private readonly legacyImportService: LegacyImportService,
private readonly enrichmentService: RiotAccountEnrichmentService,
) {} ) {}
public async onModuleInit() { public async onModuleInit() {
@@ -102,6 +104,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
queueId, queueId,
}); });
} }
await this.refreshLeagueEntries(job);
await this.markUserFetchedAt(job); await this.markUserFetchedAt(job);
const event = await this.jobQueueService.markCompleted(job); const event = await this.jobQueueService.markCompleted(job);
this.refreshGateway.broadcastRefreshEvent(event); this.refreshGateway.broadcastRefreshEvent(event);
@@ -135,6 +138,26 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
} }
} }
private async refreshLeagueEntries(job: RiotRefreshSubJob): Promise<void> {
try {
const result = await this.enrichmentService.refreshLeagueEntries({
userId: new mongoose.Types.ObjectId(job.userId),
puuid: job.puuid,
platform: job.platform,
});
if (result !== 'failed') return;
this.logger.warn(
`Riot league refresh failed ${job.jobId}: puuid=${job.puuid}`,
);
} catch (error) {
this.logger.warn(
`Riot league refresh failed ${job.jobId}: ${
error instanceof Error ? error.message : error
}`,
);
}
}
private async markUserFetchedAt(job: RiotRefreshSubJob): Promise<void> { private async markUserFetchedAt(job: RiotRefreshSubJob): Promise<void> {
const UserModel = await this.connectionService.getModel('user'); const UserModel = await this.connectionService.getModel('user');
const now = new Date(); const now = new Date();
@@ -370,6 +370,73 @@ describe('RiotAccountEnrichmentService', () => {
expect(user.save).not.toHaveBeenCalled(); expect(user.save).not.toHaveBeenCalled();
}); });
it('refreshes league entries without refreshing recent matches', async () => {
const recent = new Date(Date.now() - 60_000);
const account = makeAccount({
revisionDate: Date.now() - 60_000,
tiers: [
{
leagueId: 'L1',
queueType: 'RANKED_SOLO_5x5',
tier: 'GOLD',
rank: 'II',
puuid: 'puuid-1',
leaguePoints: 1,
wins: 1,
losses: 1,
fetchedAt: recent,
},
],
recentStatsFetchedAt: recent,
recentStatsSummary: createEmptyRiotRecentStatsSummary(),
});
const user = makeUser(account);
const { service, leagueService, recentMatchesService } = makeService({
user,
league: {
getEntriesByPuuid: jest.fn().mockResolvedValue([
{
leagueId: 'L2',
queueType: 'RANKED_SOLO_5x5',
tier: 'PLATINUM',
rank: 'IV',
puuid: 'puuid-1',
leaguePoints: 20,
wins: 10,
losses: 8,
},
]),
} as Partial<RiotLeagueService>,
});
const result = await service.refreshLeagueEntries({
userId: user._id,
puuid: 'puuid-1',
platform: 'kr',
});
expect(result).toBe('updated');
expect(leagueService.getEntriesByPuuid).toHaveBeenCalledWith('puuid-1', {
platform: 'kr',
});
expect(recentMatchesService.syncRecentMatches).not.toHaveBeenCalled();
expect(account.tiers).toHaveLength(1);
expect(account.tiers[0]).toMatchObject({
leagueId: 'L2',
queueType: 'RANKED_SOLO_5x5',
tier: 'PLATINUM',
rank: 'IV',
leaguePoints: 20,
});
expect(account.tierHistory.at(-1)).toMatchObject({
queueType: 'RANKED_SOLO_5x5',
tier: 'PLATINUM',
rank: 'IV',
leaguePoints: 20,
});
expect(user.save).toHaveBeenCalledTimes(1);
});
it('records failed for individual failing fetches but updates the rest', async () => { it('records failed for individual failing fetches but updates the rest', async () => {
const account = makeAccount(); const account = makeAccount();
const user = makeUser(account); const user = makeUser(account);
@@ -52,6 +52,8 @@ export interface EnrichResult {
account: RiotAccount | null; account: RiotAccount | null;
} }
export type RefreshLeagueEntriesResult = 'updated' | 'failed';
@Injectable() @Injectable()
export class RiotAccountEnrichmentService { export class RiotAccountEnrichmentService {
private readonly logger = new Logger(RiotAccountEnrichmentService.name); private readonly logger = new Logger(RiotAccountEnrichmentService.name);
@@ -95,6 +97,29 @@ export class RiotAccountEnrichmentService {
return promise; return promise;
} }
public async refreshLeagueEntries(params: {
userId: mongoose.Types.ObjectId;
puuid: string;
platform?: RiotPlatformRoute;
}): Promise<RefreshLeagueEntriesResult> {
const UserModel = await this.connectionService.getModel('user');
const user = await UserModel.findById(params.userId).exec();
if (!user) return 'failed';
const account = user.riotAccounts.find((a) => a.puuid === params.puuid);
if (!account) return 'failed';
const outcome = await this.fetchLeagueSafe(
params.puuid,
params.platform ?? DEFAULT_PLATFORM,
);
if (outcome.status !== 'updated' || !outcome.dto) return 'failed';
this.applyLeagueEntries(account, outcome.dto);
await user.save();
return 'updated';
}
private async doEnrichRiotAccount(params: { private async doEnrichRiotAccount(params: {
userId: mongoose.Types.ObjectId; userId: mongoose.Types.ObjectId;
puuid: string; puuid: string;
+1 -1
View File
@@ -1,4 +1,4 @@
VITE_API_BASE_URL=https://lolympus-test-api.dahyeon.us VITE_API_BASE_URL=https://lolympus-api-staging.dahyeon.us
VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1 VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1
VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3 VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3
VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863 VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863
+4 -2
View File
@@ -5,10 +5,12 @@
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"start:dev": "vite --mode development",
"start:staging": "vite --mode staging",
"build": "tsc -b && vite build", "build": "tsc -b && vite build",
"build:test": "tsc -b && vite build --mode test", "build:staging": "tsc -b && vite build --mode staging",
"build:prod": "tsc -b && vite build --mode production", "build:prod": "tsc -b && vite build --mode production",
"deploy:test": "node ../../scripts/deploy-cloudflare-pages.mjs test", "deploy:staging": "node ../../scripts/deploy-cloudflare-pages.mjs staging",
"deploy:prod": "node ../../scripts/deploy-cloudflare-pages.mjs prod", "deploy:prod": "node ../../scripts/deploy-cloudflare-pages.mjs prod",
"pages:login": "wrangler login", "pages:login": "wrangler login",
"pages:whoami": "wrangler whoami", "pages:whoami": "wrangler whoami",
+22 -22
View File
@@ -1,22 +1,22 @@
import { BrowserRouter, Link, Route, Routes } from 'react-router'; import { BrowserRouter, Link, Route, Routes } from "react-router";
import { useMsal } from '@azure/msal-react'; import { useMsal } from "@azure/msal-react";
import DevAuthSwitcher from './components/DevAuthSwitcher'; import DevAuthSwitcher from "./components/DevAuthSwitcher";
import { DEFAULT_COMMUNITY_ID } from './config'; import { DEFAULT_COMMUNITY_ID } from "./config";
import { useCommunity } from './api/hooks'; import { useCommunity } from "./api/hooks";
import { isMsalConfigured } from './lib/auth/msal.config'; import { isMsalConfigured } from "./lib/auth/msal.config";
import AuthCallbackPage from './pages/AuthCallback'; import AuthCallbackPage from "./pages/AuthCallback";
import HomePage from './pages/HomePage'; import HomePage from "./pages/HomePage";
import LoginPage from './pages/Login'; import LoginPage from "./pages/Login";
import MatchDetailPage from './pages/MatchDetailPage'; import MatchDetailPage from "./pages/MatchDetailPage";
import MatchTeamProgressPage from './pages/MatchTeamProgressPage'; import MatchTeamProgressPage from "./pages/MatchTeamProgressPage";
import AuctionPage from './pages/AuctionPage'; import AuctionPage from "./pages/AuctionPage";
import UserHistoryPage from './pages/UserHistoryPage'; import UserHistoryPage from "./pages/UserHistoryPage";
import CommunityInternalStatsPage from './pages/CommunityInternalStatsPage'; import CommunityInternalStatsPage from "./pages/CommunityInternalStatsPage";
import InternalMatchDetailPage from './pages/InternalMatchDetailPage'; import InternalMatchDetailPage from "./pages/InternalMatchDetailPage";
import LegacyImportPage from './pages/admin/LegacyImportPage'; import LegacyImportPage from "./pages/admin/LegacyImportPage";
import LegacyMatchesPage from './pages/admin/LegacyMatchesPage'; import LegacyMatchesPage from "./pages/admin/LegacyMatchesPage";
import MatchAdminPage from './pages/admin/MatchAdminPage'; import MatchAdminPage from "./pages/admin/MatchAdminPage";
import TournamentCodesPage from './pages/admin/TournamentCodesPage'; import TournamentCodesPage from "./pages/admin/TournamentCodesPage";
function MsalHeaderActions() { function MsalHeaderActions() {
const { accounts, instance } = useMsal(); const { accounts, instance } = useMsal();
@@ -43,7 +43,7 @@ function MsalHeaderActions() {
function App() { function App() {
const communityQuery = useCommunity(DEFAULT_COMMUNITY_ID); const communityQuery = useCommunity(DEFAULT_COMMUNITY_ID);
const communityLabel = communityQuery.data?.name ?? 'LOLYMPUS'; const communityLabel = communityQuery.data?.name ?? "LOLYMPUS";
return ( return (
<BrowserRouter> <BrowserRouter>
@@ -57,7 +57,7 @@ function App() {
{communityLabel} {communityLabel}
</Link> </Link>
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
{DEFAULT_COMMUNITY_ID ? ( {/* {DEFAULT_COMMUNITY_ID ? (
<span className="text-[10px] uppercase tracking-wider text-base-content/25"> <span className="text-[10px] uppercase tracking-wider text-base-content/25">
API Live API Live
</span> </span>
@@ -65,7 +65,7 @@ function App() {
<span className="text-[10px] uppercase tracking-wider text-amber-500/70"> <span className="text-[10px] uppercase tracking-wider text-amber-500/70">
Set `VITE_DEFAULT_COMMUNITY_ID` Set `VITE_DEFAULT_COMMUNITY_ID`
</span> </span>
)} )} */}
{isMsalConfigured && <MsalHeaderActions />} {isMsalConfigured && <MsalHeaderActions />}
</div> </div>
</div> </div>
+9
View File
@@ -272,6 +272,14 @@ export interface ApiAuctionBid {
timestamp: string; timestamp: string;
} }
export interface ApiAuctionChatMessage {
id: string;
userId?: string;
displayName: string;
message: string;
sentAt: string;
}
export interface ApiAuction { export interface ApiAuction {
_id: string; _id: string;
matchId: string; matchId: string;
@@ -290,6 +298,7 @@ export interface ApiAuction {
initialPoints: number; initialPoints: number;
topTierThreshold: AuctionTopTierThreshold; topTierThreshold: AuctionTopTierThreshold;
manualTopTierUserIds: string[]; manualTopTierUserIds: string[];
chatMessages?: ApiAuctionChatMessage[];
startedAt?: string; startedAt?: string;
completedAt?: string; completedAt?: string;
createdAt: string; createdAt: string;
+49 -5
View File
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react';
import { io, type Socket } from 'socket.io-client'; import { io, type Socket } from 'socket.io-client';
import { API_BASE_URL, useAuthUserId } from '../config'; import { API_BASE_URL, useAuthUserId } from '../config';
import { acquireAccessToken } from '../lib/auth/token-provider'; import { acquireAccessToken } from '../lib/auth/token-provider';
import type { ApiAuction, Position } from './types'; import type { ApiAuction, ApiAuctionChatMessage, Position } from './types';
type ConnectionStatus = type ConnectionStatus =
| 'idle' | 'idle'
@@ -17,18 +17,42 @@ interface BidPayload {
bidderUserId?: string; bidderUserId?: string;
} }
interface ChatMessagePayload {
displayName?: string;
message: string;
}
interface ChatHistoryPayload {
messages?: ApiAuctionChatMessage[];
}
const MAX_CHAT_MESSAGES = 200;
function mergeChatMessages(
current: ApiAuctionChatMessage[],
incoming: ApiAuctionChatMessage[],
) {
const byId = new Map(current.map((message) => [message.id, message]));
for (const message of incoming) {
byId.set(message.id, message);
}
return [...byId.values()]
.sort((left, right) => Date.parse(left.sentAt) - Date.parse(right.sentAt))
.slice(-MAX_CHAT_MESSAGES);
}
export function useAuctionSocket(matchId: string | undefined) { export function useAuctionSocket(matchId: string | undefined) {
const authUserId = useAuthUserId(); const authUserId = useAuthUserId();
const socketRef = useRef<Socket | null>(null); const socketRef = useRef<Socket | null>(null);
const [auction, setAuction] = useState<ApiAuction | null>(null); const [auction, setAuction] = useState<ApiAuction | null>(null);
const [chatMessages, setChatMessages] = useState<ApiAuctionChatMessage[]>([]);
const [connectionStatus, setConnectionStatus] = const [connectionStatus, setConnectionStatus] =
useState<ConnectionStatus>('idle'); useState<ConnectionStatus>('idle');
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
useEffect(() => { useEffect(() => {
if (!matchId) { if (!matchId) {
setAuction(null);
setConnectionStatus('idle');
return; return;
} }
@@ -65,9 +89,20 @@ export function useAuctionSocket(matchId: string | undefined) {
socket.on('state', (nextAuction: ApiAuction) => { socket.on('state', (nextAuction: ApiAuction) => {
setAuction(nextAuction); setAuction(nextAuction);
if (nextAuction.chatMessages) {
setChatMessages(mergeChatMessages([], nextAuction.chatMessages));
}
setError(null); setError(null);
}); });
socket.on('chat-history', (payload: ChatHistoryPayload) => {
setChatMessages(mergeChatMessages([], payload.messages ?? []));
});
socket.on('chat-message', (message: ApiAuctionChatMessage) => {
setChatMessages((current) => mergeChatMessages(current, [message]));
});
socket.on('error', (payload: { message?: string }) => { socket.on('error', (payload: { message?: string }) => {
setConnectionStatus('error'); setConnectionStatus('error');
setError(payload.message ?? '실시간 경매 연결 중 오류가 발생했습니다.'); setError(payload.message ?? '실시간 경매 연결 중 오류가 발생했습니다.');
@@ -101,9 +136,15 @@ export function useAuctionSocket(matchId: string | undefined) {
socket.emit(eventName, payload); socket.emit(eventName, payload);
} }
const visibleAuction = auction?.matchId === matchId ? auction : null;
const visibleConnectionStatus: ConnectionStatus = matchId
? connectionStatus
: 'idle';
return { return {
auction, auction: visibleAuction,
connectionStatus, chatMessages: visibleAuction ? chatMessages : [],
connectionStatus: visibleConnectionStatus,
error, error,
placeBid(payload: BidPayload) { placeBid(payload: BidPayload) {
emit('bid', payload); emit('bid', payload);
@@ -117,5 +158,8 @@ export function useAuctionSocket(matchId: string | undefined) {
next() { next() {
emit('next', {}); emit('next', {});
}, },
sendChatMessage(payload: ChatMessagePayload) {
emit('chat-message', payload);
},
}; };
} }
+159 -14
View File
@@ -1,5 +1,13 @@
import { useEffect, useMemo, useRef, useState } from 'react'; import {
useEffect,
useMemo,
useRef,
useState,
type FormEvent,
type KeyboardEvent,
} from 'react';
import { useQueryClient } from '@tanstack/react-query'; import { useQueryClient } from '@tanstack/react-query';
import { SendHorizontal } from 'lucide-react';
import { Link, useLocation, useParams } from 'react-router'; import { Link, useLocation, useParams } from 'react-router';
import { import {
useAuction, useAuction,
@@ -34,8 +42,10 @@ import {
} from '../lib/league'; } from '../lib/league';
import type { import type {
ApiAuction, ApiAuction,
ApiAuctionChatMessage,
ApiRiotLaneStats, ApiRiotLaneStats,
ApiTierInfo, ApiTierInfo,
ApiUser,
Position, Position,
} from '../api/types'; } from '../api/types';
@@ -73,6 +83,31 @@ function relativeTime(dateLike: string) {
return `${Math.floor(hours / 24)}일 전`; return `${Math.floor(hours / 24)}일 전`;
} }
function formatChatTime(dateLike: string) {
return new Intl.DateTimeFormat('ko-KR', {
hour: '2-digit',
minute: '2-digit',
}).format(new Date(dateLike));
}
function resolveChatSenderLabel(
currentUser: ApiUser | null,
captainRole: CaptainRole | null,
) {
const primaryRiotAccount =
currentUser?.riotAccounts.find((entry) => entry.isPrimary) ??
currentUser?.riotAccounts[0];
if (primaryRiotAccount?.gameName) {
return primaryRiotAccount.tagLine
? `${primaryRiotAccount.gameName}#${primaryRiotAccount.tagLine}`
: primaryRiotAccount.gameName;
}
if (currentUser?.kakaoTalkNickname) return currentUser.kakaoTalkNickname;
if (currentUser?.discordNickname) return currentUser.discordNickname;
if (captainRole) return `${teamIndexLabel(captainRole.teamIndex)} 팀장`;
return '관전자';
}
function normalizeRank(rank: string | undefined) { function normalizeRank(rank: string | undefined) {
switch (rank) { switch (rank) {
case 'I': case 'I':
@@ -738,6 +773,7 @@ export default function AuctionPage() {
: { : {
teamIndex: captainTeamIndex, teamIndex: captainTeamIndex,
}; };
const chatSenderLabel = resolveChatSenderLabel(currentUser, captainRole);
useEffect(() => { useEffect(() => {
if (auctionState?.currentPlayer) { if (auctionState?.currentPlayer) {
@@ -1073,9 +1109,35 @@ export default function AuctionPage() {
</div> </div>
<aside className="hidden xl:block"> <aside className="hidden xl:block">
<ChatPanel /> <ChatPanel
messages={socket.chatMessages}
connectionStatus={socket.connectionStatus}
senderLabel={chatSenderLabel}
onSend={(message) =>
socket.sendChatMessage({
displayName: chatSenderLabel,
message,
})
}
className="sticky top-4 h-[520px] max-h-[calc(100vh-2rem)]"
/>
</aside> </aside>
</div> </div>
<div className="mt-4 xl:hidden">
<ChatPanel
messages={socket.chatMessages}
connectionStatus={socket.connectionStatus}
senderLabel={chatSenderLabel}
onSend={(message) =>
socket.sendChatMessage({
displayName: chatSenderLabel,
message,
})
}
className="h-[420px]"
/>
</div>
</main> </main>
); );
} }
@@ -1231,37 +1293,120 @@ function PoolListItem({
); );
} }
function ChatPanel() { function ChatPanel({
messages,
connectionStatus,
senderLabel,
onSend,
className = '',
}: {
messages: ApiAuctionChatMessage[];
connectionStatus: ReturnType<typeof useAuctionSocket>['connectionStatus'];
senderLabel: string;
onSend: (message: string) => void;
className?: string;
}) {
const [draft, setDraft] = useState('');
const messagesEndRef = useRef<HTMLDivElement | null>(null);
const trimmedDraft = draft.trim();
const isConnected = connectionStatus === 'connected';
const canSend = isConnected && trimmedDraft.length > 0;
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ block: 'end' });
}, [messages.length]);
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!canSend) return;
onSend(trimmedDraft);
setDraft('');
}
function handleKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
if (event.key !== 'Enter' || event.shiftKey) return;
event.preventDefault();
if (!canSend) return;
onSend(trimmedDraft);
setDraft('');
}
const statusLabel =
connectionStatus === 'connected'
? '실시간'
: connectionStatus === 'connecting'
? '연결 중'
: '오프라인';
return ( return (
<div className="border border-base-content/10 bg-base-100 sticky top-4 h-[calc(100vh-2rem)] flex flex-col"> <div
className={`border border-base-content/10 bg-base-100 flex min-h-0 flex-col ${className}`}
>
<div className="border-b border-base-content/10 px-3 py-2.5 flex items-center justify-between"> <div className="border-b border-base-content/10 px-3 py-2.5 flex items-center justify-between">
<div className="text-[10px] font-bold uppercase tracking-wider text-base-content/35"> <div className="text-[10px] font-bold uppercase tracking-wider text-base-content/35">
채팅 채팅
</div> </div>
<span className="text-[10px] text-base-content/30"> <span
곧 활성화됩니다 className={`text-[10px] ${
isConnected ? 'text-green-500' : 'text-base-content/30'
}`}
>
{statusLabel}
</span> </span>
</div> </div>
<div className="flex-1 overflow-y-auto px-3 py-8 text-center text-[11px] text-base-content/25"> <div className="flex-1 min-h-0 overflow-y-auto px-3 py-3">
{messages.length === 0 ? (
<div className="flex h-full items-center justify-center text-center text-[11px] text-base-content/25">
아직 메시지가 없습니다 아직 메시지가 없습니다
</div> </div>
) : (
<ol className="space-y-3">
{messages.map((message) => (
<li key={message.id} className="space-y-1">
<div className="flex items-center justify-between gap-2">
<span className="min-w-0 truncate text-[11px] font-bold text-base-content/70">
{message.displayName}
</span>
<time className="shrink-0 text-[10px] tabular-nums text-base-content/25">
{formatChatTime(message.sentAt)}
</time>
</div>
<p className="whitespace-pre-wrap break-words border border-base-content/8 bg-base-content/[0.03] px-2.5 py-2 text-[12px] leading-relaxed text-base-content/75">
{message.message}
</p>
</li>
))}
</ol>
)}
<div ref={messagesEndRef} />
</div>
<div className="border-t border-base-content/10 p-2 space-y-2"> <form onSubmit={handleSubmit} className="border-t border-base-content/10 p-2 space-y-2">
<div className="flex items-center justify-between gap-2 px-0.5 text-[10px] text-base-content/30">
<span className="truncate">{senderLabel}</span>
<span className="tabular-nums">{draft.length}/300</span>
</div>
<textarea <textarea
disabled value={draft}
onChange={(event) => setDraft(event.target.value)}
onKeyDown={handleKeyDown}
disabled={!isConnected}
maxLength={300}
placeholder="메시지를 입력하세요" placeholder="메시지를 입력하세요"
className="w-full resize-none border border-base-content/10 bg-base-content/5 px-2 py-1.5 text-[12px] text-base-content/40 placeholder:text-base-content/25 focus:outline-none" className="w-full resize-none border border-base-content/10 bg-base-content/5 px-2 py-1.5 text-[12px] text-base-content/80 placeholder:text-base-content/25 focus:border-primary/40 focus:outline-none disabled:cursor-not-allowed disabled:text-base-content/30"
rows={2} rows={2}
aria-label="경매 채팅 메시지"
/> />
<button <button
type="button" type="submit"
disabled disabled={!canSend}
className="btn btn-primary btn-sm w-full text-[11px] opacity-50" className="btn btn-primary btn-sm w-full text-[11px]"
> >
<SendHorizontal className="h-3.5 w-3.5" aria-hidden="true" />
전송 전송
</button> </button>
</div> </form>
</div> </div>
); );
} }
+11 -2
View File
@@ -3,6 +3,9 @@ import { mapApiMatchToMatchDetail } from '../api/mappers';
import { useMatches, useMe } from '../api/hooks'; import { useMatches, useMe } from '../api/hooks';
import { DEFAULT_COMMUNITY_ID } from '../config'; import { DEFAULT_COMMUNITY_ID } from '../config';
const UPCOMING_GRID_MATCH_LIMIT = 3;
const UPCOMING_MATCH_LIST_LIMIT = UPCOMING_GRID_MATCH_LIMIT + 1;
function StatusBadge({ status }: { status: string }) { function StatusBadge({ status }: { status: string }) {
const styles: Record<string, string> = { const styles: Record<string, string> = {
모집중: 'bg-green-500/15 text-green-500 border-green-500/20', 모집중: 'bg-green-500/15 text-green-500 border-green-500/20',
@@ -44,7 +47,10 @@ function getStatusLabel(status: string) {
} }
export default function HomePage() { export default function HomePage() {
const upcomingMatchesQuery = useMatches({ limit: 20 }, DEFAULT_COMMUNITY_ID); const upcomingMatchesQuery = useMatches(
{ limit: UPCOMING_MATCH_LIST_LIMIT },
DEFAULT_COMMUNITY_ID,
);
const finishedMatchesQuery = useMatches( const finishedMatchesQuery = useMatches(
{ status: 'finished', limit: 10 }, { status: 'finished', limit: 10 },
DEFAULT_COMMUNITY_ID, DEFAULT_COMMUNITY_ID,
@@ -84,7 +90,10 @@ export default function HomePage() {
const finishedMatches = const finishedMatches =
finishedMatchesQuery.data?.map(mapApiMatchToMatchDetail) ?? []; finishedMatchesQuery.data?.map(mapApiMatchToMatchDetail) ?? [];
const nextMatch = upcomingMatches[0]; const nextMatch = upcomingMatches[0];
const upcomingCards = nextMatch ? upcomingMatches.slice(1) : upcomingMatches; const upcomingCards = (nextMatch
? upcomingMatches.slice(1)
: upcomingMatches
).slice(0, UPCOMING_GRID_MATCH_LIMIT);
const currentUser = const currentUser =
meQuery.data?.memberships.find( meQuery.data?.memberships.find(
(membership) => membership.community?._id === DEFAULT_COMMUNITY_ID, (membership) => membership.community?._id === DEFAULT_COMMUNITY_ID,
+479 -2
View File
@@ -24,6 +24,7 @@ import { DEFAULT_COMMUNITY_ID, useAuthUserId } from "../config";
import { apiFetch, ApiError } from "../lib/api"; import { apiFetch, ApiError } from "../lib/api";
import { profileIconUrl } from "../lib/ddragon"; import { profileIconUrl } from "../lib/ddragon";
import { import {
POSITION_ORDER,
positionIcon, positionIcon,
positionLabel, positionLabel,
sideShortLabel, sideShortLabel,
@@ -32,7 +33,9 @@ import {
} from "../lib/league"; } from "../lib/league";
import type { import type {
AuctionTopTierThreshold, AuctionTopTierThreshold,
ApiMatch,
ApiMatchParticipant, ApiMatchParticipant,
ApiPositionPreference,
ApiTierInfo, ApiTierInfo,
ManualTournamentResultCollectResponse, ManualTournamentResultCollectResponse,
Position, Position,
@@ -52,11 +55,62 @@ type CaptainSelection = {
const DEFAULT_AUCTION_MAX_TIMER_SECONDS = 30; const DEFAULT_AUCTION_MAX_TIMER_SECONDS = 30;
const DEFAULT_AUCTION_BID_EXTENSION_SECONDS = 5; const DEFAULT_AUCTION_BID_EXTENSION_SECONDS = 5;
const MAX_AUCTION_TIMER_SECONDS = 3600; const MAX_AUCTION_TIMER_SECONDS = 3600;
const ALL_PARTICIPANT_FILTER = "all";
type ParticipantPositionFilter = Position | typeof ALL_PARTICIPANT_FILTER;
type ParticipantTierFilter = string | typeof ALL_PARTICIPANT_FILTER;
const PARTICIPANT_TIER_FILTERS = [
"CHALLENGER",
"GRANDMASTER",
"MASTER",
"DIAMOND",
"EMERALD",
"PLATINUM",
"GOLD",
"SILVER",
"BRONZE",
"IRON",
"UNRANKED",
] as const;
const PARTICIPANT_TIER_LABELS: Record<string, string> = {
CHALLENGER: "챌린저",
GRANDMASTER: "그랜드마스터",
MASTER: "마스터",
DIAMOND: "다이아몬드",
EMERALD: "에메랄드",
PLATINUM: "플래티넘",
GOLD: "골드",
SILVER: "실버",
BRONZE: "브론즈",
IRON: "아이언",
UNRANKED: "언랭크",
};
function captainSlotKey(slot: CaptainSelectionSlot) { function captainSlotKey(slot: CaptainSelectionSlot) {
return String(slot.teamIndex); return String(slot.teamIndex);
} }
// 백엔드 reorderPreferredPositions와 동일 규칙. 낙관적 업데이트에서
// 캐시된 preferredPositions를 즉시 갱신하는 데 사용한다.
function reorderPreferredPositions(
mainPosition: Position,
subPosition: Position,
current: ApiPositionPreference[],
): ApiPositionPreference[] {
const ordered: Position[] = [mainPosition];
if (subPosition !== mainPosition) ordered.push(subPosition);
for (const preference of [...current].sort(
(left, right) => left.priority - right.priority,
)) {
if (!ordered.includes(preference.position)) {
ordered.push(preference.position);
}
}
return ordered.map((position, index) => ({ position, priority: index + 1 }));
}
function parseInitialPointsInput(value: string) { function parseInitialPointsInput(value: string) {
if (!value.trim()) return null; if (!value.trim()) return null;
const points = Number(value); const points = Number(value);
@@ -270,18 +324,94 @@ function statusBadge(status: MatchDetailView["status"]) {
} }
} }
function participantTierFilterValue(participant: ParticipantView) {
return participant.tier?.tier ?? "UNRANKED";
}
// PARTICIPANT_TIER_FILTERS는 높은 티어 → 낮은 티어 순서이므로
// 인덱스가 작을수록 상위 티어. (없는 값은 최하위로 취급)
function tierRank(tier: string) {
const index = PARTICIPANT_TIER_FILTERS.indexOf(
tier as (typeof PARTICIPANT_TIER_FILTERS)[number],
);
return index === -1 ? PARTICIPANT_TIER_FILTERS.length : index;
}
type ParticipantRowAdmin = {
onRemove: (userId: string) => void;
onChangePositions: (
userId: string,
mainPosition: Position,
subPosition: Position,
) => void;
isRemoving: boolean;
isUpdating: boolean;
};
function PositionSelect({
value,
sub,
disabled,
onChange,
}: {
value: Position;
sub?: boolean;
disabled?: boolean;
onChange: (next: Position) => void;
}) {
return (
<select
value={value}
disabled={disabled}
onChange={(event) => onChange(event.target.value as Position)}
className={`h-7 border bg-base-100 pl-1.5 pr-1 text-[11px] font-medium focus:border-primary/30 focus:outline-none disabled:opacity-50 ${
sub
? "border-base-content/10 text-base-content/45"
: "border-primary/20 text-primary"
}`}
>
{POSITION_ORDER.map((position) => (
<option key={position} value={position}>
{positionLabel[position]}
</option>
))}
</select>
);
}
function ParticipantRow({ function ParticipantRow({
participant, participant,
index, index,
assignedPos, assignedPos,
admin,
}: { }: {
participant: ParticipantView; participant: ParticipantView;
index: number; index: number;
assignedPos?: Position; assignedPos?: Position;
admin?: ParticipantRowAdmin;
}) { }) {
const { data: ddragon } = useDdragonManifest(); const { data: ddragon } = useDdragonManifest();
const location = useLocation(); const location = useLocation();
const historyBackTo = `${location.pathname}${location.search}${location.hash}`; const historyBackTo = `${location.pathname}${location.search}${location.hash}`;
const [confirmingRemove, setConfirmingRemove] = useState(false);
// 주/부 포지션이 겹치면 두 값을 맞바꿔 항상 서로 다르게 유지한다.
const handleMainChange = (next: Position) => {
if (!admin) return;
const sub =
next === participant.subPosition
? participant.mainPosition
: participant.subPosition;
admin.onChangePositions(participant.userId, next, sub);
};
const handleSubChange = (next: Position) => {
if (!admin) return;
const main =
next === participant.mainPosition
? participant.subPosition
: participant.mainPosition;
admin.onChangePositions(participant.userId, main, next);
};
return ( return (
<tr className="border-b border-base-content/5 last:border-b-0 hover:bg-base-content/[0.02] transition-colors"> <tr className="border-b border-base-content/5 last:border-b-0 hover:bg-base-content/[0.02] transition-colors">
@@ -324,6 +454,68 @@ function ParticipantRow({
<td className="py-2 px-3"> <td className="py-2 px-3">
<PosBadge pos={assignedPos} /> <PosBadge pos={assignedPos} />
</td> </td>
) : admin ? (
<>
<td className="py-2 px-3">
<PositionSelect
value={participant.mainPosition}
disabled={admin.isUpdating}
onChange={handleMainChange}
/>
</td>
<td className="py-2 px-3">
<PositionSelect
value={participant.subPosition}
sub
disabled={admin.isUpdating}
onChange={handleSubChange}
/>
</td>
<td className="py-2 px-3 w-20 min-w-[5rem] whitespace-nowrap text-right">
{confirmingRemove ? (
<span className="inline-flex items-center gap-1.5 whitespace-nowrap">
<button
type="button"
disabled={admin.isRemoving}
onClick={() => admin.onRemove(participant.userId)}
className="text-[10px] font-bold text-red-400 hover:text-red-300 disabled:opacity-50"
>
{admin.isRemoving ? "제외 중..." : "확인"}
</button>
<button
type="button"
onClick={() => setConfirmingRemove(false)}
className="text-[10px] text-base-content/35 hover:text-base-content/60"
>
취소
</button>
</span>
) : (
<button
type="button"
title="참가자 제외"
aria-label="참가자 제외"
onClick={() => setConfirmingRemove(true)}
className="text-base-content/25 hover:text-red-400 transition-colors"
>
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-3.5 w-3.5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M6 18L18 6M6 6l12 12"
/>
</svg>
</button>
)}
</td>
</>
) : ( ) : (
<> <>
<td className="py-2 px-3"> <td className="py-2 px-3">
@@ -345,6 +537,11 @@ function ParticipantTable({
canJoin, canJoin,
onJoin, onJoin,
isJoining, isJoining,
canManage,
onRemoveParticipant,
onUpdatePositions,
removingUserId,
updatingUserId,
}: { }: {
participants: ParticipantView[]; participants: ParticipantView[];
maxParticipants: number; maxParticipants: number;
@@ -352,7 +549,65 @@ function ParticipantTable({
canJoin: boolean; canJoin: boolean;
onJoin: () => void; onJoin: () => void;
isJoining: boolean; isJoining: boolean;
canManage: boolean;
onRemoveParticipant: (userId: string) => void;
onUpdatePositions: (
userId: string,
mainPosition: Position,
subPosition: Position,
) => void;
removingUserId: string | null;
updatingUserId: string | null;
}) { }) {
const [positionFilter, setPositionFilter] =
useState<ParticipantPositionFilter>(ALL_PARTICIPANT_FILTER);
const [tierFilter, setTierFilter] = useState<ParticipantTierFilter>(
ALL_PARTICIPANT_FILTER,
);
const filteredParticipants = participants.filter((participant) => {
const matchesPosition =
positionFilter === ALL_PARTICIPANT_FILTER ||
participant.mainPosition === positionFilter;
const matchesTier =
tierFilter === ALL_PARTICIPANT_FILTER ||
tierRank(participantTierFilterValue(participant)) <= tierRank(tierFilter);
return matchesPosition && matchesTier;
});
const isFiltered =
positionFilter !== ALL_PARTICIPANT_FILTER ||
tierFilter !== ALL_PARTICIPANT_FILTER;
const positionFilteredParticipants = participants.filter(
(participant) =>
positionFilter === ALL_PARTICIPANT_FILTER ||
participant.mainPosition === positionFilter,
);
// "이상" 임계값으로 쓸 수 있는 티어 = 참가자 중 실제 존재하는 티어.
// 언랭크는 "이상" 기준으로 전체와 동일하므로 임계값 후보에서 제외한다.
const presentTiers = new Set(
positionFilteredParticipants.map(participantTierFilterValue),
);
const availableTiers = PARTICIPANT_TIER_FILTERS.filter(
(tier) => tier !== "UNRANKED" && presentTiers.has(tier),
);
const tierAtOrAboveCounts = new Map<string, number>(
availableTiers.map((tier) => [
tier,
positionFilteredParticipants.filter(
(participant) =>
tierRank(participantTierFilterValue(participant)) <= tierRank(tier),
).length,
]),
);
const positionCounts = new Map<Position, number>(
POSITION_ORDER.map((position) => [
position,
participants.filter(
(participant) => participant.mainPosition === position,
).length,
]),
);
return ( return (
<div className="border border-base-content/10 bg-base-100 overflow-hidden"> <div className="border border-base-content/10 bg-base-100 overflow-hidden">
<div className="px-4 py-2.5 border-b border-base-content/10 bg-base-200/40 flex items-center justify-between gap-3"> <div className="px-4 py-2.5 border-b border-base-content/10 bg-base-200/40 flex items-center justify-between gap-3">
@@ -368,6 +623,86 @@ function ParticipantTable({
{joined ? "참가 완료" : isJoining ? "신청 중..." : "참가 신청"} {joined ? "참가 완료" : isJoining ? "신청 중..." : "참가 신청"}
</button> </button>
</div> </div>
<div className="border-b border-base-content/10 bg-base-100 px-4 py-2.5">
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
<div className="inline-flex items-center gap-1">
<button
type="button"
onClick={() => setPositionFilter(ALL_PARTICIPANT_FILTER)}
className={`inline-flex h-8 items-center px-2.5 text-[11px] font-semibold border transition-colors ${
positionFilter === ALL_PARTICIPANT_FILTER
? "border-primary/30 bg-primary/5 text-primary"
: "border-base-content/10 text-base-content/40 hover:text-base-content/70"
}`}
>
전체 ({participants.length})
</button>
{POSITION_ORDER.map((position) => {
const active = positionFilter === position;
const count = positionCounts.get(position) ?? 0;
return (
<button
key={position}
type="button"
title={`${positionLabel[position]} (${count}명)`}
aria-label={`${positionLabel[position]} (${count}명)`}
aria-pressed={active}
onClick={() =>
setPositionFilter(
active ? ALL_PARTICIPANT_FILTER : position,
)
}
className={`inline-flex h-8 items-center gap-1 px-2 text-[11px] font-semibold border transition-colors ${
active
? "border-primary/30 bg-primary/5 text-primary"
: "border-base-content/10 text-base-content/40 hover:text-base-content/70"
}`}
>
<img
src={positionIcon[position]}
alt=""
className="h-3.5 w-3.5 object-contain"
/>
<span className="hidden sm:inline">
{positionLabel[position]}
</span>
<span className="tabular-nums">({count})</span>
</button>
);
})}
</div>
<select
className="h-8 border border-base-content/10 bg-base-100 px-2 text-xs text-base-content focus:border-primary/30 focus:outline-none"
value={tierFilter}
onChange={(event) => setTierFilter(event.target.value)}
>
<option value={ALL_PARTICIPANT_FILTER}>티어 전체</option>
{availableTiers.map((tier) => (
<option key={tier} value={tier}>
{PARTICIPANT_TIER_LABELS[tier]} 이상 (
{tierAtOrAboveCounts.get(tier)})
</option>
))}
</select>
<div className="ml-auto flex items-center gap-2 text-[11px] text-base-content/35">
<span>
{filteredParticipants.length}/{participants.length}명
</span>
{isFiltered && (
<button
type="button"
className="btn btn-ghost btn-xs h-8 min-h-8 px-2 text-[11px] text-base-content/40"
onClick={() => {
setPositionFilter(ALL_PARTICIPANT_FILTER);
setTierFilter(ALL_PARTICIPANT_FILTER);
}}
>
초기화
</button>
)}
</div>
</div>
</div>
<div className="overflow-x-auto"> <div className="overflow-x-auto">
<table className="w-full text-left"> <table className="w-full text-left">
<thead> <thead>
@@ -377,16 +712,42 @@ function ParticipantTable({
<th className="py-2 px-3">현재 티어</th> <th className="py-2 px-3">현재 티어</th>
<th className="py-2 px-3">주 포지션</th> <th className="py-2 px-3">주 포지션</th>
<th className="py-2 px-3">부 포지션</th> <th className="py-2 px-3">부 포지션</th>
{canManage && (
<th className="py-2 px-3 w-20 min-w-[5rem] whitespace-nowrap text-right">
관리
</th>
)}
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{participants.map((participant, index) => ( {filteredParticipants.length > 0 ? (
filteredParticipants.map((participant, index) => (
<ParticipantRow <ParticipantRow
key={participant.id} key={participant.id}
participant={participant} participant={participant}
index={index} index={index}
admin={
canManage
? {
onRemove: onRemoveParticipant,
onChangePositions: onUpdatePositions,
isRemoving: removingUserId === participant.userId,
isUpdating: updatingUserId === participant.userId,
}
: undefined
}
/> />
))} ))
) : (
<tr>
<td
colSpan={canManage ? 6 : 5}
className="px-3 py-8 text-center text-sm text-base-content/35"
>
조건에 맞는 참가자가 없습니다.
</td>
</tr>
)}
</tbody> </tbody>
</table> </table>
</div> </div>
@@ -1065,6 +1426,89 @@ export default function MatchDetailPage() {
}, },
}); });
const matchQueryKey = ["match", DEFAULT_COMMUNITY_ID, id ?? null];
const removeParticipantMutation = useMutation({
mutationFn: (userId: string) =>
apiFetch(
`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants/${userId}`,
{ method: "DELETE" },
),
onMutate: async (userId: string) => {
await queryClient.cancelQueries({ queryKey: matchQueryKey });
const previous = queryClient.getQueryData<ApiMatch>(matchQueryKey);
if (previous) {
queryClient.setQueryData<ApiMatch>(matchQueryKey, {
...previous,
participants: previous.participants.filter(
(participant) => participant.userId !== userId,
),
});
}
return { previous };
},
onError: (_error, _userId, context) => {
if (context?.previous) {
queryClient.setQueryData(matchQueryKey, context.previous);
}
},
onSettled: () => {
void queryClient.invalidateQueries({ queryKey: matchQueryKey });
void queryClient.invalidateQueries({
queryKey: ["matches", DEFAULT_COMMUNITY_ID],
});
},
});
const updateParticipantMutation = useMutation({
mutationFn: ({
userId,
mainPosition,
subPosition,
}: {
userId: string;
mainPosition: Position;
subPosition: Position;
}) =>
apiFetch(
`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants/${userId}`,
{
method: "PATCH",
body: JSON.stringify({ mainPosition, subPosition }),
},
),
onMutate: async ({ userId, mainPosition, subPosition }) => {
await queryClient.cancelQueries({ queryKey: matchQueryKey });
const previous = queryClient.getQueryData<ApiMatch>(matchQueryKey);
if (previous) {
queryClient.setQueryData<ApiMatch>(matchQueryKey, {
...previous,
participants: previous.participants.map((participant) =>
participant.userId === userId
? {
...participant,
preferredPositions: reorderPreferredPositions(
mainPosition,
subPosition,
participant.preferredPositions,
),
}
: participant,
),
});
}
return { previous };
},
onError: (_error, _variables, context) => {
if (context?.previous) {
queryClient.setQueryData(matchQueryKey, context.previous);
}
},
onSettled: () => {
void queryClient.invalidateQueries({ queryKey: matchQueryKey });
},
});
const startAuctionMutation = useMutation({ const startAuctionMutation = useMutation({
mutationFn: () => mutationFn: () =>
apiFetch(`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/auction`, { apiFetch(`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/auction`, {
@@ -1335,6 +1779,18 @@ export default function MatchDetailPage() {
</div> </div>
)} )}
{removeParticipantMutation.error instanceof Error && (
<div className="mb-4 border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-500">
{removeParticipantMutation.error.message}
</div>
)}
{updateParticipantMutation.error instanceof Error && (
<div className="mb-4 border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-500">
{updateParticipantMutation.error.message}
</div>
)}
{pollTournamentResultMutation.error instanceof Error && ( {pollTournamentResultMutation.error instanceof Error && (
<div className="mb-4 border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-500"> <div className="mb-4 border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-500">
{pollTournamentResultMutation.error.message} {pollTournamentResultMutation.error.message}
@@ -1366,6 +1822,27 @@ export default function MatchDetailPage() {
canJoin={canUseMemberActions} canJoin={canUseMemberActions}
onJoin={() => joinMatchMutation.mutate()} onJoin={() => joinMatchMutation.mutate()}
isJoining={joinMatchMutation.isPending} isJoining={joinMatchMutation.isPending}
canManage={canManageAuction}
onRemoveParticipant={(userId) =>
removeParticipantMutation.mutate(userId)
}
onUpdatePositions={(userId, mainPosition, subPosition) =>
updateParticipantMutation.mutate({
userId,
mainPosition,
subPosition,
})
}
removingUserId={
removeParticipantMutation.isPending
? (removeParticipantMutation.variables ?? null)
: null
}
updatingUserId={
updateParticipantMutation.isPending
? (updateParticipantMutation.variables?.userId ?? null)
: null
}
/> />
{isCheckingPermissions ? ( {isCheckingPermissions ? (
+5 -3
View File
@@ -5,14 +5,16 @@
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"start:api:dev": "pnpm --filter api start:dev", "start:api:dev": "pnpm --filter api start:dev",
"start:api:test": "pnpm --filter api start:test", "start:api:staging": "pnpm --filter api start:staging",
"start:api:prod": "pnpm --filter api start:prod", "start:api:prod": "pnpm --filter api start:prod",
"start:api": "pnpm --filter api start:prod", "start:api": "pnpm --filter api start:prod",
"start:web:dev": "pnpm --filter web start:dev",
"start:web:staging": "pnpm --filter web start:staging",
"build:api": "pnpm --filter api build", "build:api": "pnpm --filter api build",
"dev:web": "pnpm --filter web dev", "dev:web": "pnpm --filter web dev",
"build:web:test": "pnpm --filter web build:test", "build:web:staging": "pnpm --filter web build:staging",
"build:web:prod": "pnpm --filter web build:prod", "build:web:prod": "pnpm --filter web build:prod",
"deploy:web:test": "node scripts/deploy-cloudflare-pages.mjs test", "deploy:web:staging": "node scripts/deploy-cloudflare-pages.mjs staging",
"deploy:web:prod": "node scripts/deploy-cloudflare-pages.mjs prod", "deploy:web:prod": "node scripts/deploy-cloudflare-pages.mjs prod",
"test": "echo \"Error: no test specified\" && exit 1" "test": "echo \"Error: no test specified\" && exit 1"
}, },
+14 -7
View File
@@ -28,7 +28,7 @@ const { MongoClient, ObjectId } = require("mongodb");
const CONFIG = { const CONFIG = {
MONGODB_URI: process.env.MONGODB_URI ?? "mongodb://127.0.0.1:27017", MONGODB_URI: process.env.MONGODB_URI ?? "mongodb://127.0.0.1:27017",
LOLYMPUS_DB_NAME: process.env.LOLYMPUS_DB_NAME ?? "lolympus-test", LOLYMPUS_DB_NAME: process.env.LOLYMPUS_DB_NAME ?? "lolympus-staging",
COMMUNITY_ID: new ObjectId( COMMUNITY_ID: new ObjectId(
process.env.COMMUNITY_ID ?? "69ebe0adf627c11be2f020a1", process.env.COMMUNITY_ID ?? "69ebe0adf627c11be2f020a1",
), ),
@@ -137,14 +137,18 @@ async function fetchRiotJson({ host, path, query }) {
}); });
if (response.status === 429) { if (response.status === 429) {
const retryAfterSeconds = Number(response.headers.get("retry-after") ?? 1); const retryAfterSeconds = Number(
response.headers.get("retry-after") ?? 1,
);
await sleep(Math.max(1, retryAfterSeconds) * 1000); await sleep(Math.max(1, retryAfterSeconds) * 1000);
continue; continue;
} }
if (response.status === 404) return null; if (response.status === 404) return null;
if (!response.ok) { if (!response.ok) {
const body = await response.text().catch(() => ""); const body = await response.text().catch(() => "");
throw new Error(`Riot API failed ${response.status} ${url.pathname}: ${body}`); throw new Error(
`Riot API failed ${response.status} ${url.pathname}: ${body}`,
);
} }
return response.json(); return response.json();
} }
@@ -190,13 +194,14 @@ async function fetchRecentMatchIdsByPuuid(puuid) {
async function fetchRiotData({ riotId }) { async function fetchRiotData({ riotId }) {
const fallback = splitRiotId(riotId); const fallback = splitRiotId(riotId);
const account = const account = (await fetchAccountByRiotId(fallback)) ?? {
(await fetchAccountByRiotId(fallback)) ?? {
...fallback, ...fallback,
puuid: normalizeString(INPUT.puuid), puuid: normalizeString(INPUT.puuid),
}; };
if (!account?.puuid) { if (!account?.puuid) {
throw new Error(`Riot account not found and PUUID was not provided: ${riotId}`); throw new Error(
`Riot account not found and PUUID was not provided: ${riotId}`,
);
} }
const [summoner, leagueEntries, championMasteries, matchIds] = const [summoner, leagueEntries, championMasteries, matchIds] =
@@ -280,7 +285,9 @@ function buildRiotAccount(riotData, now) {
summonerLevel: riotData.summoner?.summonerLevel ?? 0, summonerLevel: riotData.summoner?.summonerLevel ?? 0,
isPrimary: true, isPrimary: true,
tiers: riotData.leagueEntries.map((entry) => toTierInfo(entry, now)), tiers: riotData.leagueEntries.map((entry) => toTierInfo(entry, now)),
tierHistory: riotData.leagueEntries.map((entry) => toTierHistory(entry, now)), tierHistory: riotData.leagueEntries.map((entry) =>
toTierHistory(entry, now),
),
matchIds: riotData.matchIds, matchIds: riotData.matchIds,
matchIdsFetchedAt: riotData.matchIds.length > 0 ? now : undefined, matchIdsFetchedAt: riotData.matchIds.length > 0 ? now : undefined,
championMasteries: riotData.championMasteries championMasteries: riotData.championMasteries
+22 -9
View File
@@ -1,11 +1,11 @@
/** /**
* Apply already-saved Dakao user bootstrap data into lolympus-test.user. * Apply already-saved Dakao user bootstrap data into lolympus-staging.user.
* *
* This script does NOT call Riot API. * This script does NOT call Riot API.
* *
* It reads saved documents from one of: * It reads saved documents from one of:
* 1. lolympus-test.DakaoUserBootstrapRun * 1. lolympus-staging.DakaoUserBootstrapRun
* 2. lolympus-test.DakaoUserBootstrapCandidate * 2. lolympus-staging.DakaoUserBootstrapCandidate
* *
* It only applies users that already have a valid Riot identity: * It only applies users that already have a valid Riot identity:
* - dryRunUsers[].doc.riotAccounts[0].puuid, or * - dryRunUsers[].doc.riotAccounts[0].puuid, or
@@ -34,7 +34,7 @@ const { MongoClient, ObjectId } = require("mongodb");
const CONFIG = { const CONFIG = {
MONGODB_URI: process.env.MONGODB_URI ?? "mongodb://127.0.0.1:27017", MONGODB_URI: process.env.MONGODB_URI ?? "mongodb://127.0.0.1:27017",
LOLYMPUS_DB_NAME: process.env.LOLYMPUS_DB_NAME ?? "lolympus-test", LOLYMPUS_DB_NAME: process.env.LOLYMPUS_DB_NAME ?? "lolympus-staging",
COMMUNITY_ID: new ObjectId( COMMUNITY_ID: new ObjectId(
process.env.COMMUNITY_ID ?? "69ebe0adf627c11be2f020a1", process.env.COMMUNITY_ID ?? "69ebe0adf627c11be2f020a1",
), ),
@@ -151,14 +151,19 @@ function buildPlanFromDryRunUser(planned, now) {
planned.filter?.communityId ?? doc.communityId ?? CONFIG.COMMUNITY_ID, planned.filter?.communityId ?? doc.communityId ?? CONFIG.COMMUNITY_ID,
"planned.communityId", "planned.communityId",
), ),
kakaoTalkId: normalizeString(planned.filter?.kakaoTalkId ?? doc.kakaoTalkId), kakaoTalkId: normalizeString(
planned.filter?.kakaoTalkId ?? doc.kakaoTalkId,
),
}, },
doc: removeUndefined({ doc: removeUndefined({
_id: _id:
doc._id && ObjectId.isValid(String(doc._id)) doc._id && ObjectId.isValid(String(doc._id))
? toObjectId(doc._id, "planned.doc._id") ? toObjectId(doc._id, "planned.doc._id")
: new ObjectId(), : new ObjectId(),
communityId: toObjectId(doc.communityId ?? CONFIG.COMMUNITY_ID, "doc.communityId"), communityId: toObjectId(
doc.communityId ?? CONFIG.COMMUNITY_ID,
"doc.communityId",
),
role: doc.role ?? "member", role: doc.role ?? "member",
kakaoTalkId: normalizeString(doc.kakaoTalkId), kakaoTalkId: normalizeString(doc.kakaoTalkId),
kakaoTalkNickname: normalizeString(doc.kakaoTalkNickname), kakaoTalkNickname: normalizeString(doc.kakaoTalkNickname),
@@ -228,12 +233,18 @@ function buildPlanFromCandidate(candidate, now) {
return { return {
source: "candidate", source: "candidate",
filter: { filter: {
communityId: toObjectId(candidate.communityId ?? CONFIG.COMMUNITY_ID, "candidate.communityId"), communityId: toObjectId(
candidate.communityId ?? CONFIG.COMMUNITY_ID,
"candidate.communityId",
),
kakaoTalkId: normalizeString(candidate.kakaoTalkId), kakaoTalkId: normalizeString(candidate.kakaoTalkId),
}, },
doc: removeUndefined({ doc: removeUndefined({
_id: new ObjectId(), _id: new ObjectId(),
communityId: toObjectId(candidate.communityId ?? CONFIG.COMMUNITY_ID, "candidate.communityId"), communityId: toObjectId(
candidate.communityId ?? CONFIG.COMMUNITY_ID,
"candidate.communityId",
),
role: candidate.role ?? "member", role: candidate.role ?? "member",
kakaoTalkId: normalizeString(candidate.kakaoTalkId), kakaoTalkId: normalizeString(candidate.kakaoTalkId),
kakaoTalkNickname: normalizeString( kakaoTalkNickname: normalizeString(
@@ -300,7 +311,9 @@ async function loadPlansFromCandidates(lolympusDb, now) {
communityId: CONFIG.COMMUNITY_ID, communityId: CONFIG.COMMUNITY_ID,
}).toArray(); }).toArray();
const plans = dedupePlans( const plans = dedupePlans(
candidates.map((candidate) => buildPlanFromCandidate(candidate, now)).filter(Boolean), candidates
.map((candidate) => buildPlanFromCandidate(candidate, now))
.filter(Boolean),
); );
return { sourceRun: null, plans }; return { sourceRun: null, plans };
} }
+28 -11
View File
@@ -19,7 +19,7 @@
* -> join nickname base with RiotAccount.gameName * -> join nickname base with RiotAccount.gameName
* -> verify/fetch puuid from Riot Account API * -> verify/fetch puuid from Riot Account API
* -> fetch summoner / league / mastery / recent match ids from Riot API * -> fetch summoner / league / mastery / recent match ids from Riot API
* -> upsert lolympus-test.user * -> upsert lolympus-staging.user
*/ */
"use strict"; "use strict";
@@ -32,7 +32,7 @@ const CONFIG = {
RIOT_API_KEY: process.env.RIOT_API_KEY ?? "", RIOT_API_KEY: process.env.RIOT_API_KEY ?? "",
DAKAO_DB_NAME: "dakao", DAKAO_DB_NAME: "dakao",
LOLYMPUS_DB_NAME: "lolympus-test", LOLYMPUS_DB_NAME: "lolympus-staging",
RIOT_ACCOUNT_DB_NAME: process.env.RIOT_ACCOUNT_DB_NAME ?? "dakao", RIOT_ACCOUNT_DB_NAME: process.env.RIOT_ACCOUNT_DB_NAME ?? "dakao",
RIOT_ACCOUNT_COLLECTION_NAME: RIOT_ACCOUNT_COLLECTION_NAME:
process.env.RIOT_ACCOUNT_COLLECTION_NAME ?? "RiotAccount", process.env.RIOT_ACCOUNT_COLLECTION_NAME ?? "RiotAccount",
@@ -50,7 +50,7 @@ const CONFIG = {
RECENT_MATCH_COUNT: Number(process.env.RECENT_MATCH_COUNT ?? 20), RECENT_MATCH_COUNT: Number(process.env.RECENT_MATCH_COUNT ?? 20),
FETCH_RECENT_MATCH_IDS: process.env.FETCH_RECENT_MATCH_IDS !== "false", FETCH_RECENT_MATCH_IDS: process.env.FETCH_RECENT_MATCH_IDS !== "false",
// Safe default. Set DRY_RUN=false to write into lolympus-test.user. // Safe default. Set DRY_RUN=false to write into lolympus-staging.user.
DRY_RUN: process.env.DRY_RUN !== "false", DRY_RUN: process.env.DRY_RUN !== "false",
SAVE_DRY_RUN_RESULT: process.env.SAVE_DRY_RUN_RESULT !== "false", SAVE_DRY_RUN_RESULT: process.env.SAVE_DRY_RUN_RESULT !== "false",
OUTPUT_ONLY_RIOT_MATCHED: process.env.OUTPUT_ONLY_RIOT_MATCHED !== "false", OUTPUT_ONLY_RIOT_MATCHED: process.env.OUTPUT_ONLY_RIOT_MATCHED !== "false",
@@ -214,7 +214,10 @@ function remember(map, kakaoTalkId, patch) {
const nickname = const nickname =
normalizeString(patch.kakaoTalkNickname) || normalizeString(patch.kakaoTalkNickname) ||
normalizeString(current.kakaoTalkNickname); normalizeString(current.kakaoTalkNickname);
const sources = new Set([...(current.sources ?? []), ...(patch.sources ?? [])]); const sources = new Set([
...(current.sources ?? []),
...(patch.sources ?? []),
]);
const lastSeenCandidates = [current.lastSeenAt, patch.lastSeenAt] const lastSeenCandidates = [current.lastSeenAt, patch.lastSeenAt]
.filter(Boolean) .filter(Boolean)
.map((value) => new Date(value)); .map((value) => new Date(value));
@@ -229,7 +232,9 @@ function remember(map, kakaoTalkId, patch) {
sources: [...sources], sources: [...sources],
lastSeenAt: lastSeenAt:
lastSeenCandidates.length > 0 lastSeenCandidates.length > 0
? new Date(Math.max(...lastSeenCandidates.map((date) => date.getTime()))) ? new Date(
Math.max(...lastSeenCandidates.map((date) => date.getTime())),
)
: null, : null,
recentMessageCount: recentMessageCount:
(current.recentMessageCount ?? 0) + (patch.recentMessageCount ?? 0), (current.recentMessageCount ?? 0) + (patch.recentMessageCount ?? 0),
@@ -361,7 +366,12 @@ function pickRiotAccountForCandidate(candidate, index) {
const nicknameBase = candidate.nicknameBase; const nicknameBase = candidate.nicknameBase;
if (!nicknameBase) { if (!nicknameBase) {
return { source: "no-nickname-base", account: null, override, ambiguous: [] }; return {
source: "no-nickname-base",
account: null,
override,
ambiguous: [],
};
} }
const exactMatches = index.exact.get(normalizeJoinKey(nicknameBase)) ?? []; const exactMatches = index.exact.get(normalizeJoinKey(nicknameBase)) ?? [];
@@ -422,7 +432,9 @@ async function fetchRiotJson({ host, path, query }) {
}); });
if (response.status === 429) { if (response.status === 429) {
const retryAfterSeconds = Number(response.headers.get("retry-after") ?? 1); const retryAfterSeconds = Number(
response.headers.get("retry-after") ?? 1,
);
await sleep(Math.max(1, retryAfterSeconds) * 1000); await sleep(Math.max(1, retryAfterSeconds) * 1000);
continue; continue;
} }
@@ -431,7 +443,9 @@ async function fetchRiotJson({ host, path, query }) {
if (!response.ok) { if (!response.ok) {
const body = await response.text().catch(() => ""); const body = await response.text().catch(() => "");
throw new Error(`Riot API failed ${response.status} ${url.pathname}: ${body}`); throw new Error(
`Riot API failed ${response.status} ${url.pathname}: ${body}`,
);
} }
return response.json(); return response.json();
@@ -670,11 +684,14 @@ async function enrichCandidatesWithRiot({ candidates, riotAccountIndex }) {
riotApiError, riotApiError,
riotEnrichment, riotEnrichment,
riotEnrichmentError, riotEnrichmentError,
preferredPositions: normalizePositions(match.override?.preferredPositions), preferredPositions: normalizePositions(
match.override?.preferredPositions,
),
role: match.override?.role ?? "member", role: match.override?.role ?? "member",
isActivated: match.override?.isActivated ?? true, isActivated: match.override?.isActivated ?? true,
targetKakaoTalkNickname: targetKakaoTalkNickname:
normalizeString(match.override?.nickname) || candidate.kakaoTalkNickname, normalizeString(match.override?.nickname) ||
candidate.kakaoTalkNickname,
}); });
} }
@@ -798,7 +815,7 @@ async function upsertUsers({ lolympusDb, candidates }) {
preferredPositions: preferredPositions:
candidate.preferredPositions?.length > 0 candidate.preferredPositions?.length > 0
? candidate.preferredPositions ? candidate.preferredPositions
: existing?.preferredPositions ?? [], : (existing?.preferredPositions ?? []),
isActivated: candidate.isActivated ?? true, isActivated: candidate.isActivated ?? true,
updatedAt: now, updatedAt: now,
}; };
+163 -45
View File
@@ -1,59 +1,177 @@
import { spawnSync } from 'node:child_process'; import { spawnSync } from "node:child_process";
import { existsSync, readFileSync } from 'node:fs'; import { existsSync, readFileSync } from "node:fs";
import { dirname, resolve } from 'node:path'; import { dirname, resolve } from "node:path";
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url)); const scriptPath = fileURLToPath(import.meta.url);
const repoRoot = resolve(__dirname, '..'); const __dirname = dirname(scriptPath);
const webDir = resolve(repoRoot, 'apps/web'); const repoRoot = resolve(__dirname, "..");
const webDir = resolve(repoRoot, "apps/web");
const target = process.argv[2]; if (process.argv[1] === scriptPath) {
if (target !== 'test' && target !== 'prod') { main(process.argv.slice(2));
console.error('Usage: node scripts/deploy-cloudflare-pages.mjs <test|prod>'); }
export function main(args = process.argv.slice(2), env = process.env) {
const target = args[0];
if (target !== "staging" && target !== "prod") {
console.error(
"Usage: node scripts/deploy-cloudflare-pages.mjs <staging|prod>",
);
process.exit(1); process.exit(1);
} }
const viteMode = target === 'prod' ? 'production' : 'test'; const viteMode = target === "prod" ? "production" : "staging";
const projectName = const projectName =
process.env.CF_PAGES_PROJECT_NAME ?? env.CF_PAGES_PROJECT_NAME ??
process.env.CLOUDFLARE_PAGES_PROJECT_NAME ?? env.CLOUDFLARE_PAGES_PROJECT_NAME ??
'lolympus'; "lolympus";
const testBranch = process.env.CF_PAGES_TEST_BRANCH ?? 'test'; const stagingBranch =
target === "staging" ? resolveStagingBranch(env) : undefined;
validateEnv(viteMode); validateEnv(viteMode, env);
run('pnpm', ['--filter', 'web', 'run', `build:${target}`], repoRoot); run("pnpm", ["--filter", "web", "run", `build:${target}`], repoRoot);
const deployArgs = [ const deployArgs = [
'exec', "exec",
'wrangler', "wrangler",
'pages', "pages",
'deploy', "deploy",
'dist', "dist",
'--project-name', "--project-name",
projectName, projectName,
]; ];
if (target === 'test') { if (target === "staging") {
deployArgs.push('--branch', testBranch); deployArgs.push("--branch", stagingBranch);
console.error(
`Deploying staging to Cloudflare Pages branch ${stagingBranch}`,
);
} }
run('pnpm', deployArgs, webDir); run("pnpm", deployArgs, webDir);
}
export function resolveStagingBranch(env = process.env) {
const configuredBranch = env.CF_PAGES_STAGING_BRANCH?.trim();
if (configuredBranch) return configuredBranch;
refreshRemoteReleaseBranches();
const latestReleaseBranch = selectLatestReleaseBranch(
listReleaseBranchRefs(),
);
if (latestReleaseBranch) return latestReleaseBranch;
console.error(
[
"No release/* branch found for staging deploy.",
"Create a release branch, for example: git push origin main:release/66",
"Or set CF_PAGES_STAGING_BRANCH explicitly.",
].join("\n"),
);
process.exit(1);
}
export function selectLatestReleaseBranch(refRows) {
const latestByBranch = new Map();
for (const row of refRows) {
const [timestampText, refName] = row.split("\t");
const branch = normalizeReleaseBranch(refName);
const timestamp = Number(timestampText);
if (!branch || !Number.isFinite(timestamp)) continue;
const current = latestByBranch.get(branch);
if (!current || timestamp > current.timestamp) {
latestByBranch.set(branch, { branch, timestamp });
}
}
const [latest] = [...latestByBranch.values()].sort((left, right) => {
if (left.timestamp !== right.timestamp) {
return right.timestamp - left.timestamp;
}
return right.branch.localeCompare(left.branch, "en", { numeric: true });
});
return latest?.branch;
}
export function normalizeReleaseBranch(refName) {
const branch = refName?.trim();
if (!branch) return undefined;
if (branch.startsWith("origin/release/")) {
return branch.slice("origin/".length);
}
if (branch.startsWith("release/")) return branch;
return undefined;
}
function listReleaseBranchRefs() {
const result = spawnSync(
"git",
[
"for-each-ref",
"--sort=-committerdate",
"--format=%(committerdate:unix)%09%(refname:short)",
"refs/remotes/origin/release",
"refs/heads/release",
],
{
cwd: repoRoot,
encoding: "utf8",
shell: process.platform === "win32",
},
);
if (result.status !== 0) {
const stderr = result.stderr?.trim();
if (stderr) console.error(stderr);
return [];
}
return result.stdout.split(/\r?\n/).filter(Boolean);
}
function refreshRemoteReleaseBranches() {
spawnSync("git", ["remote", "prune", "origin"], {
cwd: repoRoot,
stdio: "ignore",
shell: process.platform === "win32",
});
spawnSync(
"git",
[
"fetch",
"--prune",
"origin",
"+refs/heads/release/*:refs/remotes/origin/release/*",
],
{
cwd: repoRoot,
stdio: "ignore",
shell: process.platform === "win32",
},
);
}
function run(command, args, cwd) { function run(command, args, cwd) {
const result = spawnSync(command, args, { const result = spawnSync(command, args, {
cwd, cwd,
stdio: 'inherit', stdio: "inherit",
shell: process.platform === 'win32', shell: process.platform === "win32",
}); });
if (result.status !== 0) { if (result.status !== 0) {
process.exit(result.status ?? 1); process.exit(result.status ?? 1);
} }
} }
function validateEnv(mode) { function validateEnv(mode, env) {
const fileEnv = [ const fileEnv = [
'.env', ".env",
'.env.local', ".env.local",
`.env.${mode}`, `.env.${mode}`,
`.env.${mode}.local`, `.env.${mode}.local`,
].reduce((acc, fileName) => { ].reduce((acc, fileName) => {
@@ -62,39 +180,39 @@ function validateEnv(mode) {
return { ...acc, ...parseEnvFile(envFile) }; return { ...acc, ...parseEnvFile(envFile) };
}, {}); }, {});
const requiredKeys = [ const requiredKeys = [
'VITE_API_BASE_URL', "VITE_API_BASE_URL",
'VITE_DEFAULT_COMMUNITY_ID', "VITE_DEFAULT_COMMUNITY_ID",
'VITE_MSAL_CLIENT_ID', "VITE_MSAL_CLIENT_ID",
'VITE_MSAL_AUTHORITY', "VITE_MSAL_AUTHORITY",
'VITE_MSAL_API_SCOPE', "VITE_MSAL_API_SCOPE",
'VITE_MSAL_REDIRECT_URI', "VITE_MSAL_REDIRECT_URI",
]; ];
const missing = requiredKeys.filter((key) => { const missing = requiredKeys.filter((key) => {
const value = process.env[key] ?? fileEnv[key]; const value = env[key] ?? fileEnv[key];
return !value || value.includes('<'); return !value || value.includes("<");
}); });
if (missing.length === 0) return; if (missing.length === 0) return;
console.error( console.error(
[ [
`Missing Cloudflare Pages ${mode} build env: ${missing.join(', ')}`, `Missing Cloudflare Pages ${mode} build env: ${missing.join(", ")}`,
`Create apps/web/.env.${mode}, apps/web/.env.${mode}.local, or export these variables before deploy.`, `Create apps/web/.env.${mode}, apps/web/.env.${mode}.local, or export these variables before deploy.`,
`Use apps/web/.env.${mode}.example as a template.`, `Use apps/web/.env.${mode}.example as a template.`,
].join('\n'), ].join("\n"),
); );
process.exit(1); process.exit(1);
} }
function parseEnvFile(path) { function parseEnvFile(path) {
return Object.fromEntries( return Object.fromEntries(
readFileSync(path, 'utf8') readFileSync(path, "utf8")
.split(/\r?\n/) .split(/\r?\n/)
.map((line) => line.trim()) .map((line) => line.trim())
.filter((line) => line && !line.startsWith('#')) .filter((line) => line && !line.startsWith("#"))
.map((line) => { .map((line) => {
const separatorIndex = line.indexOf('='); const separatorIndex = line.indexOf("=");
if (separatorIndex === -1) return [line, '']; if (separatorIndex === -1) return [line, ""];
const key = line.slice(0, separatorIndex).trim(); const key = line.slice(0, separatorIndex).trim();
let value = line.slice(separatorIndex + 1).trim(); let value = line.slice(separatorIndex + 1).trim();
if ( if (