Merge branch 'main' into fix/tournament-bracket-20260802

This commit is contained in:
2026-08-02 05:07:23 +00:00
9 changed files with 332 additions and 50 deletions
+16 -9
View File
@@ -82,15 +82,22 @@ export const worldRouter = router({
throw new TRPCError({ code: 'PRECONDITION_FAILED', message: 'World state is not initialized.' });
}
const nationRows = nations
.map((nation) => ({
id: nation.id,
name: nation.name,
color: nation.color,
capitalCityId: nation.capitalCityId ?? 0,
level: nation.level,
power: typeof asRecord(nation.meta).power === 'number' ? Number(asRecord(nation.meta).power) : 0,
cities: cities.filter((city) => city.nationId === nation.id).map((city) => city.name),
}))
.map((nation) => {
const meta = asRecord(nation.meta);
return {
id: nation.id,
name: nation.name,
color: nation.color,
capitalCityId: nation.capitalCityId ?? 0,
level: nation.level,
power: typeof meta.power === 'number' && Number.isFinite(meta.power) ? meta.power : 0,
generalCount:
typeof meta.gennum === 'number' && Number.isFinite(meta.gennum)
? Math.max(0, Math.trunc(meta.gennum))
: 0,
cities: cities.filter((city) => city.nationId === nation.id).map((city) => city.name),
};
})
.sort((left, right) => right.power - left.power || left.id - right.id);
const matrix: Record<number, Record<number, number>> = {};
for (const nation of nationRows) {
+51 -3
View File
@@ -106,6 +106,7 @@ const context = (
findFirst: vi.fn(async ({ where }: { where: { userId: string } }) =>
where.userId === me.userId ? me : null
),
findUnique: vi.fn(async ({ where }: { where: { id: number } }) => (where.id === me.id ? me : null)),
findMany: vi.fn(async (args: { where?: Record<string, unknown>; select?: Record<string, boolean> }) => {
if (args.where?.nationId === 1 && args.select?.cityId)
return [
@@ -128,14 +129,52 @@ const context = (
meta: options.nationMeta ?? {},
})),
findMany: vi.fn(async () => [
{ id: 1, name: '아국', color: '#008000', level: 1, capitalCityId: 1, meta: { power: 100 } },
{ id: 2, name: '적국', color: '#800000', level: 1, capitalCityId: 2, meta: { power: 90 } },
{
id: 1,
name: '아국',
color: '#008000',
level: 1,
capitalCityId: 1,
meta: { power: 100, gennum: 4 },
},
{
id: 2,
name: '적국',
color: '#800000',
level: 1,
capitalCityId: 2,
meta: { power: 90, gennum: 3 },
},
]),
},
city: { findMany: vi.fn(async () => cities) },
worldState: { findFirst: vi.fn(async () => ({ meta: { turntime: '2026-01-01' } })) },
worldState: {
findFirst: vi.fn(async () => ({
currentYear: 200,
currentMonth: 1,
config: { startYear: 180 },
meta: { turntime: '2026-01-01' },
})),
},
generalTurn: { findMany: vi.fn(async () => []) },
diplomacy: { findMany: vi.fn(async () => []) },
$queryRaw: vi
.fn()
.mockResolvedValueOnce(
cities.map((item) => ({
id: item.id,
level: item.level,
nationId: item.nationId,
region: item.region,
supplyState: item.supplyState,
meta: item.meta,
}))
)
.mockResolvedValueOnce([
{ id: 1, name: '아국', color: '#008000', capitalCityId: 1, meta: {} },
{ id: 2, name: '적국', color: '#800000', capitalCityId: 2, meta: {} },
])
.mockResolvedValueOnce([{ cityId: me.cityId }]),
};
const redis = { get: vi.fn(async () => null), set: vi.fn(async () => null) } as unknown as RedisConnector['client'];
const accessTokenStore = new RedisAccessTokenStore(redis, 'che:default');
@@ -156,6 +195,15 @@ const context = (
};
describe('in-game information permissions', () => {
it('returns the ref nation summary fields in descending power order', async () => {
const result = await appRouter.createCaller(context()).world.getGlobalInfo();
expect(result.nations).toEqual([
expect.objectContaining({ id: 1, name: '아국', power: 100, generalCount: 4, cities: ['도시1', '도시80'] }),
expect.objectContaining({ id: 2, name: '적국', power: 90, generalCount: 3, cities: ['도시2', '도시3'] }),
]);
});
it('does not expose nation-only pages to a wandering general', async () => {
const caller = appRouter.createCaller(context({ me: general({ nationId: 0, officerLevel: 0 }) }));
await expect(caller.nation.getNationInfo()).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
@@ -244,7 +244,7 @@ export const seedScenarioToDatabase = async (options: ScenarioSeedOptions): Prom
blockGeneralCreate: install?.blockGeneralCreate,
npcMode: install?.npcMode,
showImgLevel: install?.showImgLevel,
tournamentTrig: install?.tournamentTrig,
tournamentTrig: install?.tournamentTrig ?? true,
extendedGeneral: includeExtendedGeneral,
turnTermMinutes: install?.turnTermMinutes,
syncTurnTime: install?.sync,
+4 -1
View File
@@ -103,6 +103,7 @@ describeDb('scenario database seed', () => {
await connector.connect();
try {
const prisma = connector.prisma as unknown as ScenarioSeederPrismaClient;
const worldState = await prisma.worldState.findFirst();
const [nationCount, cityCount, generalCount, diplomacyCount, eventCount] = await Promise.all([
prisma.nation.count(),
prisma.city.count(),
@@ -116,6 +117,7 @@ describeDb('scenario database seed', () => {
expect(generalCount).toBe(seed.generals.length);
expect(diplomacyCount).toBe(seed.nations.length * Math.max(0, seed.nations.length - 1));
expect(eventCount).toBe(seed.events.length);
expect(worldState?.config).toMatchObject({ tournamentTrig: true });
expect(generalCount).toBeGreaterThan(0);
const seededGeneral = await prisma.general.findFirst();
expect(seededGeneral?.startAge).toBe(seededGeneral?.age);
@@ -201,7 +203,7 @@ describeDb('scenario database seed', () => {
blockGeneralCreate: 2,
npcMode: 0,
showImgLevel: 3,
tournamentTrig: true,
tournamentTrig: false,
joinMode: 'full',
autorunUser: {
limitMinutes: 60,
@@ -234,6 +236,7 @@ describeDb('scenario database seed', () => {
const config = (worldState.config ?? {}) as Record<string, unknown>;
expect(config.extendedGeneral).toBe(false);
expect(config.joinMode).toBe('full');
expect(config.tournamentTrig).toBe(false);
const meta = (worldState.meta ?? {}) as Record<string, unknown>;
const autorun = (meta.autorun_user ?? {}) as Record<string, unknown>;
+65
View File
@@ -219,6 +219,7 @@ const install = async (page: Page, mode: 'member' | 'wanderer' | 'admin' = 'memb
capitalCityId: 1,
level: 1,
power: 1234,
generalCount: 2,
cities: ['업'],
},
{
@@ -228,6 +229,7 @@ const install = async (page: Page, mode: 'member' | 'wanderer' | 'admin' = 'memb
capitalCityId: 2,
level: 1,
power: 1000,
generalCount: 1,
cities: ['허창'],
},
],
@@ -350,6 +352,69 @@ test('four legacy menu pages keep the 1000px desktop table contract', async ({ p
}
});
test('global-info renders the ref nation summary columns beside the map', async ({ page }) => {
await install(page);
await page.setViewportSize({ width: 1200, height: 900 });
await go(page, 'global-info');
const summary = page.locator('.simple-nation-list');
await expect(summary).toBeVisible();
await expect(summary.locator('thead')).toContainText('국명');
await expect(summary.locator('thead')).toContainText('국력');
await expect(summary.locator('thead')).toContainText('장수');
await expect(summary.locator('thead')).toContainText('속령');
await expect(summary.locator('tbody tr').first()).toHaveText(/\s*1,234\s*2\s*1/u);
await expect(summary.locator('tbody tr').first().locator('td').last()).toHaveAttribute('title', '업');
const geometry = await summary.evaluate((element) => {
const rect = element.getBoundingClientRect();
const headings = Array.from(element.querySelectorAll('th')).map((heading) => heading.getBoundingClientRect().width);
return { x: rect.x, width: rect.width, headings };
});
expect(geometry).toMatchObject({ x: 800, width: 300 });
expect(geometry.headings[0]).toBeCloseTo((300 * 44) / 97, 0);
expect(geometry.headings[1]).toBeCloseTo((300 * 23) / 97, 0);
expect(geometry.headings[2]).toBeCloseTo((300 * 15) / 97, 0);
expect(geometry.headings[3]).toBeCloseTo((300 * 15) / 97, 0);
if (artifactRoot) {
await mkdir(artifactRoot, { recursive: true });
await writeFile(
resolve(artifactRoot, 'core-global-info-computed-dom.json'),
`${JSON.stringify(
{
geometry,
headings: await summary.locator('th').allTextContents(),
rows: await summary.locator('tbody tr').allTextContents(),
cityTitles: await summary.locator('tbody td:last-child').evaluateAll((cells) =>
cells.map((cell) => cell.getAttribute('title'))
),
},
null,
2
)}\n`,
'utf8'
);
await page.screenshot({ path: resolve(artifactRoot, 'core-global-info-desktop.png'), fullPage: true });
}
await page.setViewportSize({ width: 390, height: 844 });
const mobileGeometry = await page.locator('.map-grid').evaluate((element) => {
const map = element.querySelector('.map-viewer')?.getBoundingClientRect();
const summary = element.querySelector('.simple-nation-list')?.getBoundingClientRect();
return {
map: map ? { y: map.y, width: map.width, bottom: map.bottom } : null,
summary: summary ? { y: summary.y, width: summary.width } : null,
};
});
expect(mobileGeometry.map?.width).toBe(500);
expect(mobileGeometry.summary?.width).toBe(500);
expect(mobileGeometry.summary?.y).toBe(mobileGeometry.map?.bottom);
if (artifactRoot) {
await page.screenshot({ path: resolve(artifactRoot, 'core-global-info-mobile.png'), fullPage: true });
}
});
test('current-city hides values and general rows for a wandering user', async ({ page }) => {
await install(page, 'wanderer');
await go(page, 'current-city');
+67 -7
View File
@@ -11,6 +11,18 @@ const error = ref('');
const state = (value: number) => ({ 0: '★', 1: '▲', 2: '', 7: '@' })[value] ?? 'ㆍ';
const stateClass = (value: number) => `state-${value}`;
const nationMap = computed(() => new Map(data.value?.nations.map((nation) => [nation.id, nation]) ?? []));
const isBrightColor = (color: string): boolean => {
const normalized = color.trim().replace(/^#/u, '');
if (!/^[0-9a-f]{6}$/iu.test(normalized)) return false;
const red = Number.parseInt(normalized.slice(0, 2), 16);
const green = Number.parseInt(normalized.slice(2, 4), 16);
const blue = Number.parseInt(normalized.slice(4, 6), 16);
return red * 0.299 + green * 0.587 + blue * 0.114 > 170;
};
const nationNameStyle = (color: string) => ({
backgroundColor: color,
color: isBrightColor(color) ? '#000' : '#fff',
});
onMounted(async () => {
try {
[data.value, layout.value] = await Promise.all([
@@ -96,10 +108,29 @@ onMounted(async () => {
<div class="map-grid">
<MapViewer :map-data="data.map" :map-layout="layout" :loading="false" />
<div class="nation-list">
<div v-for="nation in data.nations" :key="nation.id">
<b :style="{ color: nation.color }">{{ nation.name }}</b> {{ nation.power.toLocaleString()
}}<br /><small>{{ nation.cities.join(', ') }}</small>
</div>
<table class="simple-nation-list">
<thead>
<tr>
<th class="nation-name-column">국명</th>
<th class="nation-power-column">국력</th>
<th class="nation-count-column">장수</th>
<th class="nation-count-column">속령</th>
</tr>
</thead>
<tbody>
<tr v-for="nation in data.nations" :key="nation.id">
<td><span :style="nationNameStyle(nation.color)">{{ nation.name }}</span></td>
<td>{{ nation.power.toLocaleString() }}</td>
<td>{{ nation.generalCount.toLocaleString() }}</td>
<td
:title="nation.cities.join(', ')"
:aria-label="`속령 ${nation.cities.length}: ${nation.cities.join(', ')}`"
>
{{ nation.cities.length.toLocaleString() }}
</td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
@@ -218,9 +249,38 @@ onMounted(async () => {
display: grid;
grid-template-columns: 700px 300px;
}
.nation-list > div {
padding: 6px;
border-bottom: 1px solid #666;
.simple-nation-list {
width: 100%;
border-collapse: collapse;
}
.simple-nation-list thead {
background-color: #ccc;
color: #000;
text-align: center;
}
.simple-nation-list th {
border: 0;
border-left: 1px solid gray;
padding: 2px 6px;
font-weight: 700;
}
.simple-nation-list td {
border: 0;
border-left: 1px solid gray;
padding: 1px 6px;
text-align: right;
}
.simple-nation-list td:first-child {
text-align: left;
}
.nation-name-column {
width: 44%;
}
.nation-power-column {
width: 23%;
}
.nation-count-column {
width: 15%;
}
.footer {
margin-top: 20px;
@@ -4,7 +4,12 @@ import path from 'node:path';
import { createHash, randomBytes, randomUUID } from 'node:crypto';
import { type ScenarioInstallOptions } from '@sammo-ts/game-engine';
import { createGamePostgresConnector, resolvePostgresConfigFromEnv } from '@sammo-ts/infra';
import {
createGamePostgresConnector,
createRedisConnector,
resolvePostgresConfigFromEnv,
resolveRedisConfigFromEnv,
} from '@sammo-ts/infra';
import { isRecord } from '@sammo-ts/common';
import type { BuildCommand, BuildRunner } from './buildRunner.js';
@@ -41,6 +46,7 @@ export interface GatewayOrchestratorOptions {
profileReadinessTimeoutMs?: number;
now?: () => Date;
fetchImpl?: typeof fetch;
clearTournamentRuntimeState?: (profileName: string) => Promise<void>;
}
export interface ProfileRuntimeState {
@@ -150,6 +156,18 @@ class OperationLeaseLostError extends Error {}
const normalizeMeta = (value: unknown): Record<string, unknown> => (isRecord(value) ? value : {});
export const buildTournamentRuntimeKeys = (profileName: string): string[] => [
`sammo:${profileName}:tournament:state`,
`sammo:${profileName}:tournament:participants`,
`sammo:${profileName}:tournament:matches`,
`sammo:${profileName}:tournament:betting`,
];
export const clearTournamentRuntimeKeys = async (
redis: { del(keys: string[]): Promise<number> },
profileName: string
): Promise<number> => redis.del(buildTournamentRuntimeKeys(profileName));
const buildServerId = (profileName: string, now: Date, installOperationId?: string): string => {
const year = String(now.getFullYear()).slice(-2);
const month = String(now.getMonth() + 1).padStart(2, '0');
@@ -545,6 +563,7 @@ export class GatewayOrchestrator implements GatewayOrchestratorHandle {
private readonly profileReadinessTimeoutMs: number;
private readonly now: () => Date;
private readonly fetchImpl: typeof fetch;
private readonly clearTournamentRuntimeState: (profileName: string) => Promise<void>;
private reconcileTimer?: NodeJS.Timeout;
private scheduleTimer?: NodeJS.Timeout;
private buildTimer?: NodeJS.Timeout;
@@ -573,6 +592,9 @@ export class GatewayOrchestrator implements GatewayOrchestratorHandle {
this.profileReadinessTimeoutMs = options.profileReadinessTimeoutMs ?? 30_000;
this.now = options.now ?? (() => new Date());
this.fetchImpl = options.fetchImpl ?? fetch;
this.clearTournamentRuntimeState =
options.clearTournamentRuntimeState ??
((profileName) => this.clearTournamentRuntimeStateFromRedis(profileName));
}
start(): void {
@@ -1383,6 +1405,8 @@ export class GatewayOrchestrator implements GatewayOrchestratorHandle {
if (!seedResult.ok) {
throw new Error(`Selected profile seed failed: ${seedResult.output.slice(-4000)}`);
}
await this.clearTournamentRuntimeState(profile.profileName);
await assertLease?.();
const completedAt = this.now().toISOString();
const now = this.now();
const shouldPreopen = openAt ? openAt.getTime() > now.getTime() : false;
@@ -1590,6 +1614,18 @@ export class GatewayOrchestrator implements GatewayOrchestratorHandle {
}).url;
}
private async clearTournamentRuntimeStateFromRedis(profileName: string): Promise<void> {
const connector = createRedisConnector(
resolveRedisConfigFromEnv(this.processConfig.baseEnv ?? process.env)
);
await connector.connect();
try {
await clearTournamentRuntimeKeys(connector.client, profileName);
} finally {
await connector.disconnect();
}
}
async cleanupStaleWorkspaces(): Promise<{ removed: string[]; skipped: string[] }> {
const profiles = await this.repository.listProfiles();
const cutoff = this.computeCutoffDate(6);
@@ -0,0 +1,34 @@
import { describe, expect, it } from 'vitest';
import {
buildTournamentRuntimeKeys,
clearTournamentRuntimeKeys,
} from '../src/orchestrator/gatewayOrchestrator.js';
describe('tournament reset state', () => {
it('targets every season-owned tournament key for the selected profile only', () => {
expect(buildTournamentRuntimeKeys('che:1010')).toEqual([
'sammo:che:1010:tournament:state',
'sammo:che:1010:tournament:participants',
'sammo:che:1010:tournament:matches',
'sammo:che:1010:tournament:betting',
]);
expect(buildTournamentRuntimeKeys('hwe:915')).not.toContain('sammo:che:1010:tournament:state');
});
it('deletes the tournament state as one profile-scoped reset operation', async () => {
const calls: string[][] = [];
const deleted = await clearTournamentRuntimeKeys(
{
del: async (keys) => {
calls.push(keys);
return keys.length;
},
},
'che:1010'
);
expect(deleted).toBe(4);
expect(calls).toEqual([buildTournamentRuntimeKeys('che:1010')]);
});
});
@@ -8,7 +8,7 @@ import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import { sealGatewayPassword } from '../src/passwordEnvelope.js';
import type { AppRouter as GatewayAppRouter } from '@sammo-ts/gateway-api';
import { createGatewayApiServer } from '@sammo-ts/gateway-api';
import { clearTournamentRuntimeKeys, createGatewayApiServer } from '@sammo-ts/gateway-api';
import type { AppRouter as GameAppRouter } from '@sammo-ts/game-api';
import {
buildTournamentKeys,
@@ -17,7 +17,7 @@ import {
processTournamentTick,
TournamentStore,
} from '@sammo-ts/game-api';
import { createTurnDaemonRuntime } from '@sammo-ts/game-engine';
import { createTurnDaemonRuntime, seedScenarioToDatabase } from '@sammo-ts/game-engine';
import {
createGamePostgresConnector,
createGatewayPostgresConnector,
@@ -92,7 +92,8 @@ const truncateSchema = async (schema: string): Promise<void> => {
await connector.connect();
try {
const rows = (await connector.prisma.$queryRawUnsafe(
`SELECT tablename FROM pg_tables WHERE schemaname = '${schema}'`
`SELECT tablename FROM pg_tables
WHERE schemaname = '${schema}' AND tablename <> '_prisma_migrations'`
)) as Array<{ tablename: string }>;
if (rows.length === 0) {
return;
@@ -168,6 +169,7 @@ describe('actual tournament lifecycle', () => {
gatewayServer = await createGatewayApiServer();
await gatewayServer.app.listen({ host: gatewayServer.config.host, port: gatewayServer.config.port });
process.env.GATEWAY_INTERNAL_API_URL = `http://127.0.0.1:${gatewayServer.config.port}`;
gameServer = await createGameApiServer();
await gameServer.app.listen({ host: gameServer.config.host, port: gameServer.config.port });
@@ -210,10 +212,23 @@ describe('actual tournament lifecycle', () => {
localAccountGeneralCreationGraceDays: 7,
},
});
await gatewayClient.admin.profiles.installNow.mutate({
profileName: 'che:908',
install: {
scenarioId: 908,
const staleTournamentRedis = createRedisConnector(resolveRedisConfigFromEnv());
await staleTournamentRedis.connect();
const staleTournamentKeys = buildTournamentKeys('che:908');
try {
await staleTournamentRedis.client.mSet({
[staleTournamentKeys.stateKey]: JSON.stringify({ stage: 6, auto: true }),
[staleTournamentKeys.participantsKey]: '[{"id":99999}]',
[staleTournamentKeys.matchesKey]: '[{"id":99999}]',
[staleTournamentKeys.bettingKey]: '[{"generalId":99999}]',
});
} finally {
await staleTournamentRedis.disconnect();
}
await seedScenarioToDatabase({
scenarioId: 908,
databaseUrl: resolvePostgresConfigFromEnv({ schema: 'che' }).url,
installOptions: {
turnTermMinutes: 1,
sync: false,
fiction: 0,
@@ -227,6 +242,41 @@ describe('actual tournament lifecycle', () => {
},
});
const resetTournamentRedis = createRedisConnector(resolveRedisConfigFromEnv());
await resetTournamentRedis.connect();
try {
await clearTournamentRuntimeKeys(resetTournamentRedis.client, 'che:908');
expect(
await resetTournamentRedis.client.mGet([
staleTournamentKeys.stateKey,
staleTournamentKeys.participantsKey,
staleTournamentKeys.matchesKey,
staleTournamentKeys.bettingKey,
])
).toEqual([null, null, null, null]);
} finally {
await resetTournamentRedis.disconnect();
}
const gameDatabaseUrl = resolvePostgresConfigFromEnv({ schema: 'che' }).url;
const gatewayDatabaseUrl = resolvePostgresConfigFromEnv({ schema: 'public' }).url;
gameConnector = createGamePostgresConnector({ url: gameDatabaseUrl });
await gameConnector.connect();
redisConnector = createRedisConnector(resolveRedisConfigFromEnv());
await redisConnector.connect();
store = new TournamentStore(redisConnector.client, buildTournamentKeys('che:908'));
transport = new DatabaseTurnDaemonTransport(gameConnector.prisma, 30_000);
turnDaemon = await createTurnDaemonRuntime({
profile: 'che',
profileName: 'che:908',
databaseUrl: gameDatabaseUrl,
gatewayDatabaseUrl,
redisUrl: resolveRedisConfigFromEnv().url,
});
turnDaemonLoop = turnDaemon.lifecycle.start();
const status = await transport.requestStatus(10_000);
expect(status).not.toBeNull();
for (const [username, displayName] of users) {
const login = await gatewayClient.auth.login.mutate({
username,
@@ -255,10 +305,6 @@ describe('actual tournament lifecycle', () => {
}
}
const gameDatabaseUrl = resolvePostgresConfigFromEnv({ schema: 'che' }).url;
const gatewayDatabaseUrl = resolvePostgresConfigFromEnv({ schema: 'public' }).url;
gameConnector = createGamePostgresConnector({ url: gameDatabaseUrl });
await gameConnector.connect();
await gameConnector.prisma.general.updateMany({
where: { id: { in: [...generalIds.values()] } },
data: { gold: 10_000 },
@@ -296,19 +342,6 @@ describe('actual tournament lifecycle', () => {
})),
});
redisConnector = createRedisConnector(resolveRedisConfigFromEnv());
await redisConnector.connect();
store = new TournamentStore(redisConnector.client, buildTournamentKeys('che:908'));
transport = new DatabaseTurnDaemonTransport(gameConnector.prisma, 30_000);
turnDaemon = await createTurnDaemonRuntime({
profile: 'che',
profileName: 'che:908',
databaseUrl: gameDatabaseUrl,
gatewayDatabaseUrl,
redisUrl: resolveRedisConfigFromEnv().url,
});
for (let attempt = 0; attempt < 36; attempt += 1) {
const current = turnDaemon.world.getState().lastTurnTime;
const next = new Date(current.getTime());
@@ -319,10 +352,6 @@ describe('actual tournament lifecycle', () => {
}
}
expect(await store.getState()).toMatchObject({ stage: 1, auto: true });
turnDaemonLoop = turnDaemon.lifecycle.start();
const status = await transport.requestStatus(10_000);
expect(status).not.toBeNull();
}, 120_000);
afterAll(async () => {