Author SHA1 Message Date
Hide_D 81e101ffef 갱신 행의 ID를 보존하고 예약턴의 불필요한 시퀀스를 제거한다 2026-11-14 18:44:22 +09:00
Hide_D bc54b157c1 고빈도 저장 ID를 64비트로 확장하고 랭킹 갱신의 시퀀스 낭비를 막는다 2026-11-14 15:34:21 +09:00
Hide_D 087517821e 운영 안정화 변경을 최신 main과 통합한다 2026-11-14 15:13:53 +09:00
Hide_D f36bc2c8d7 VM 복귀 후 예약턴 잠금 복구와 Windows 부팅 식별자 확인을 추가한다 2026-11-12 09:16:04 +09:00
Hide_D fd8145d6eb 감사 유지보수 중 새 기수 예약과 identity 변경 대응을 문서화한다 2026-11-09 21:54:57 +09:00
Hide_D 79de6d484c 감사 정리 CLI가 게임 데몬 실행 역할을 상속하지 않게 한다 2026-11-09 20:49:20 +09:00
Hide_D 078b9aa205 감사 상세를 무손실 압축하고 이전 기수 정리 처리량을 개선한다 2026-11-09 20:43:05 +09:00
Hide_D c81d304073 feat: 카카오 계정의 본인 복구와 인증 후 연결 교체를 추가한다 2026-11-07 21:31:16 +09:00
Hide_D d1cdf8a85f feat: 관리자가 사유를 남겨 탈퇴 예약을 취소하도록 추가한다 2026-11-07 20:48:19 +09:00
Hide_D dcecb32ef4 feat: 관리자 행동별 모든 서버 선택과 권한 묶음 표시를 추가한다 2026-11-07 00:39:25 +09:00
Hide_D 257a2bea10 feat: 탈퇴 취소와 이관 계정 복구 예외를 추가한다 2026-11-07 00:24:57 +09:00
Hide_D f16d33e34c fix: 세력도시 기본 목록을 지역과 규모순으로 정렬한다 2026-11-02 10:39:12 +09:00
Hide_D da79013226 fix: 국호와 예약 인자의 불필요한 앰퍼샌드 escape를 제거한다 2026-10-29 23:35:17 +09:00
Hide_D 6a23e4ca08 fix: 턴 저장 트랜잭션의 연결 획득 대기를 보완한다 2026-10-26 17:57:58 +09:00
Hide_D 8c877b4a6f fix: 장수일람 특기 설명 줄바꿈을 공통 처리한다 2026-10-23 09:55:51 +09:00
Hide_D b3f7a419a9 운영 보안을 보존하여 빌드 개선 배포본 통합 2026-10-23 01:33:42 +09:00
Hide_D af51968782 빌드 선언 생성 병목과 Vue 중복 타입 검사를 개선 2026-10-23 01:33:34 +09:00
Hide_D b377250fb9 fix: 첫 빌드 전 닫힌 서버도 패치 정책으로 오픈 요청을 받는다 2026-10-23 00:42:11 +09:00
Hide_D d4a87c981f fix: 오픈 요청 화면의 복사 전용 안내를 실제 등록 흐름에 맞춘다 2026-10-23 00:35:54 +09:00
Hide_D e42eaa4e58 fix: 오픈 요청 관계의 갱신 규칙을 migration 제약과 맞춘다 2026-10-23 00:23:33 +09:00
Hide_D 2662091a6a merge: 최신 main의 NPC 정책과 운영 보완을 오픈 요청에 통합한다 2026-10-23 00:18:45 +09:00
Hide_D 236f1bc4ed feat: 정식 사용자의 오픈 요청과 동의 기반 예약을 영속화한다 2026-10-23 00:18:45 +09:00
Hide_D 8e5bd94cb8 NPC 사령턴에서 비활성 발령 절차를 건너뛰는지 검증한다 2026-10-23 00:01:51 +09:00
Hide_D e5a39cb714 최신 main의 수비 설정 수정을 NPC 정책 작업에 통합한다 2026-10-22 23:50:35 +09:00
Hide_D 039c5d2a59 NPC 정책 적용을 검증하고 자국 변경 이력 조회를 제공한다 2026-10-22 23:50:35 +09:00
Hide_D 856187b315 수비끔 전환에서 전투 훈련·사기 상한을 보존한다 2026-10-22 23:11:52 +09:00
Hide_D b67924a71d chore: Node.js 24.22.1 보안 릴리스로 개발 버전을 고정한다 2026-10-22 17:18:48 +09:00
Hide_D 4e668b9fb6 fix: 공개 API와 토너먼트의 사용자·장수 권한 경계를 강화한다 2026-10-10 01:56:31 +09:00
231 changed files with 10525 additions and 1143 deletions

No files matched your search

+8
View File
@@ -38,6 +38,11 @@ GATEWAY_INTERNAL_API_URL=http://127.0.0.1:13000
ACCOUNT_ICON_RESET_RECONCILE_INTERVAL_MS=30000
WEB_PUSH_OUTBOX_POLL_MS=1000
GATEWAY_PUBLIC_URL=http://localhost:13000
# Browser origins default to GATEWAY_PUBLIC_URL (Game API also accepts GAME_PUBLIC_URL).
# Add exact HTTP(S) origins for a separate frontend; wildcards/null/path entries are rejected.
# Requests with a different Origin fail with 403 before mutation. No-Origin clients still need auth.
# API_ALLOWED_ORIGINS=http://localhost:5173,http://localhost:5174
# GAME_PUBLIC_URL=http://localhost:14000
# Gateway authentication protection shares atomic 60s counters under this prefix.
# Defaults: 10 login attempts/account, 600 auth requests/socket peer, 1200 globally;
# expensive auth work is capped at 4/process. Forwarded headers are not trusted.
@@ -86,6 +91,9 @@ DAEMON_REQUEST_TIMEOUT_MS=5000
# realtime은 벽시계 경과를 game tick으로 투영합니다. manual은 daemon이
# 다음 월 snapshot을 대기 없이 실행하며 테스트/장기 시뮬레이션에 사용합니다.
GAME_CLOCK_MODE=realtime
# Optional Windows host boot identity. Key is a private file, never a VITE_* value.
# TURN_HOST_BOOT_URL=http://windows-private-address:17781/v1/boot-id
# TURN_HOST_BOOT_KEY_FILE=/run/secrets/host_boot_key
TRPC_PATH=/trpc
# Frontend public URLs
+3
View File
@@ -16,6 +16,9 @@ GAME_API_HOST=0.0.0.0
GAME_API_PORT=14000
PROFILE=hwe
SCENARIO=default
# Optional Windows observation; unavailable or unconfigured service never blocks gameplay.
# TURN_HOST_BOOT_URL=http://windows-private-address:17781/v1/boot-id
# TURN_HOST_BOOT_KEY_FILE=/run/sammo-host-recovery/host_boot.key
KAKAO_REST_KEY=your-kakao-rest-key
KAKAO_ADMIN_KEY=your-kakao-admin-key
KAKAO_REDIRECT_URI=https://example.com/oauth/kakao/callback
+1
View File
@@ -89,6 +89,7 @@ web_modules/
.env.local
.env.ci
.env.ops
tools/host-recovery/*.key
tools/legacy-db-migration/migration-plan.json
tools/legacy-db-migration/secrets/
+1 -1
View File
@@ -1 +1 @@
24.21.0
24.22.1
+4 -1
View File
@@ -204,10 +204,13 @@ HTTPS 검증과 구분합니다.
## 코드 스타일
- Vite, Vue/Volar와 compiler API 소비자는 workspace 전체에서 정확히
- Vite, ESLint와 일반 compiler API 소비자는 workspace 전체에서 정확히
TypeScript `6.0.3`을 사용해 주세요. CLI project build/typecheck는 root의
`@typescript/native` alias로 고정한 TypeScript 7 `tsc`를 사용하며 package-local
다른 compiler version이나 직접 `tsc` 호출을 추가하지 말아 주세요.
Vue CLI만 `tools/vue-typecheck.mjs`로 고정한
`typescript-native-bridge@6.0.3-bridge.18.tsgo.7.0.2`를 사용합니다. 이 예외는
Vue 타입 검사에 한하며 workspace `typescript` override를 교체하지 않습니다.
- TypeScript/JSON/Vue SFC는 기존 4-space 스타일을 유지해 주세요.
- public API는 명시적 타입을 사용하고 `any`, 불필요하게 넓은 `unknown`,
`as unknown as` 우회를 피해 주세요.
+11 -4
View File
@@ -58,8 +58,13 @@ Gateway 자체 릴리스는 Gateway 프로세스 밖의 `release-controller`가
Kakao 계정은 OAuth callback과 일반 비밀번호 로그인 모두에서 Kakao 고유 ID와
현재 인증 이메일을 다시 확인합니다. 로컬 고유 ID 연결이 없지만 영구 보존된
이메일 계정이 있으면 자동 로그인하지 않고 그 계정에 연결할지 묻습니다. 기존
계정 연결을 확인하면 이전 Kakao ID와 과거 talk proof를 교체하고 새
“나와의 채팅” 숫자 코드로 다시 증명한 뒤에만 Gateway session을 발급합니다.
계정 연결은 새 “나와의 채팅” 숫자 코드 인증까지 끝난 뒤에만 저장하며, 그 전에는
이전 연결과 비밀번호를 유지합니다. 일반 계정은 카카오가 인증한 동일 이메일로
관리자 승인 없이 복구하고, 기존 서비스 비밀번호로 확인하면 이메일이 달라도
새 카카오에 연결할 수 있습니다. 관리자 계정 교체에는 승인을 유지하며 다른 계정과의
연결·이메일 충돌은 자동 처리하지 않습니다. 새 교체부터 이전 Kakao ID는 원래 계정의
복구 이력으로 보존하여 같은 계정에만 다시 연결할 수 있습니다. 기존에 영구 폐기된
ID는 계속 차단합니다.
Kakao가 `already registered`를 반환했지만 보존 이메일 계정도 없으면 재가입
확인 뒤 신규 가입 form을 엽니다. 이미 로컬에 연결된 stable ID의 변경 이메일이
다른 계정에 있으면 기존처럼 충돌을 거부합니다.
@@ -87,8 +92,9 @@ input-event 결과를 transaction으로 반영합니다. Redis pub/sub과 SSE는
## 도구 체인
- Node.js `24.21.0`, pnpm `12.5.1`, Turbo
- Node.js `24.22.1`, pnpm `12.5.1`, Turbo
- TypeScript `6.0.3` compiler API와 TypeScript `7.0.2` native `tsc`
- Vue CLI 전용 `typescript-native-bridge` (`6.0.3-bridge.18.tsgo.7.0.2`)
- Fastify, tRPC, zod
- Vue 3, Pinia, Vue Router, Vite
- PostgreSQL, Prisma, Redis
@@ -99,7 +105,8 @@ Node.js는 `.nvmrc`에서 24.x로 고정합니다. 의존성 설치와 검증에
`package.json`과 `pnpm-lock.yaml`을 함께 사용해 주세요. 모든 workspace package는
내부 전용(`private`)이므로 manifest의 `0.0.0`은 배포 버전이 아닙니다. 배포 source는
full Git commit으로 고정하고, 실험 릴리스 같은 milestone은 annotated Git tag로
식별합니다. Profile frontend는 같은 commit의 정적 버전 문서를 고정 URL과 ETag로
식별합니다. 선언 파일 생성·Vue 검사 범위와 캐시 계약은 [빌드 도구](docs/build-performance.md)를
확인해 주세요. Profile frontend는 같은 commit의 정적 버전 문서를 고정 URL과 ETag로
주기적으로 재검증하고, 현재 열린 bundle과 달라졌을 때만 강제 reload 없이 공용
toast로 한 번 안내합니다.
+6 -1
View File
@@ -1,4 +1,4 @@
import { parseNumberWithFallback } from '@sammo-ts/common';
import { parseNumberWithFallback, resolveApiAllowedOrigins } from '@sammo-ts/common';
const parseReconcileInterval = (value: string | undefined): number => {
const parsed = parseNumberWithFallback(value, 30_000, 'ACCOUNT_ICON_RESET_RECONCILE_INTERVAL_MS');
@@ -10,6 +10,7 @@ const parseReconcileInterval = (value: string | undefined): number => {
export interface GameApiConfig {
host: string;
corsAllowedOrigins: string[];
port: number;
trpcPath: string;
eventsPath: string;
@@ -48,6 +49,10 @@ export const resolveGameApiConfigFromEnv = (env: NodeJS.ProcessEnv = process.env
return {
host: env.GAME_API_HOST ?? '0.0.0.0',
corsAllowedOrigins: resolveApiAllowedOrigins(env.API_ALLOWED_ORIGINS, [
env.GATEWAY_PUBLIC_URL,
env.GAME_PUBLIC_URL,
]),
port: parseNumberWithFallback(env.GAME_API_PORT, 14000, 'GAME_API_PORT'),
trpcPath: env.GAME_TRPC_PATH ?? env.TRPC_PATH ?? '/trpc',
eventsPath: env.GAME_API_EVENTS_PATH ?? '/events',
+12 -6
View File
@@ -76,7 +76,7 @@ export class ReadModelOutboxWorker implements ReadModelOutboxWakeup {
this.leaseMs = normalizePositiveInteger(options.leaseMs, 30_000);
this.retentionMs = normalizePositiveInteger(options.retentionMs, 24 * 60 * 60 * 1_000);
this.pruneIntervalMs = normalizePositiveInteger(options.pruneIntervalMs, 60_000);
this.pruneLimit = normalizePositiveInteger(options.pruneLimit, 100);
this.pruneLimit = Math.min(500, normalizePositiveInteger(options.pruneLimit, 500));
this.owner = options.owner ?? `game-api:${profileName}:${process.pid}:${randomUUID()}`;
this.now = options.now ?? (() => new Date());
this.onError = options.onError ?? (() => undefined);
@@ -109,11 +109,17 @@ export class ReadModelOutboxWorker implements ReadModelOutboxWakeup {
const now = this.now();
if (now.getTime() >= this.nextPruneAt) {
this.nextPruneAt = now.getTime() + this.pruneIntervalMs;
await pruneDeliveredReadModelOutbox(this.db, {
deliveredBefore: new Date(now.getTime() - this.retentionMs),
limit: this.pruneLimit,
});
// backlog가 있으면 다음 dispatch에서도 이어서 정리한다. 평상시에는 낮은 빈도로 확인한다.
// 한 호출은 최대 10 batch/50ms이며 각 SQL도 최대 500행이다.
const started = performance.now();
for (let batch = 0; batch < 10; batch += 1) {
const deleted = await pruneDeliveredReadModelOutbox(this.db, {
deliveredBefore: new Date(now.getTime() - this.retentionMs),
limit: this.pruneLimit,
});
this.nextPruneAt = deleted < this.pruneLimit ? now.getTime() + this.pruneIntervalMs : 0;
if (deleted < this.pruneLimit || performance.now() - started >= 50) break;
}
}
return result;
}
+14 -4
View File
@@ -1,3 +1,4 @@
import { toSafeInteger } from '@sammo-ts/common';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
@@ -281,7 +282,7 @@ export const auctionRouter = router({
callerAlias,
remainPoint: point?.value ?? 0,
recentLogs: recentLogs.map((log) => ({
id: log.id,
id: toSafeInteger(log.id),
text: log.text,
createdAt: log.createdAt.toISOString(),
})),
@@ -444,7 +445,10 @@ export const auctionRouter = router({
const timerKeys = buildAuctionTimerKeys(ctx.profile.name);
const nextCloseAt = new Date(result.closeAt);
await ctx.redis.zAdd(timerKeys.timerKey, [
{ score: resolveAuctionTimerScore(gameTime, nextCloseAt, BigInt(result.closeTick)), value: String(auction.id) },
{
score: resolveAuctionTimerScore(gameTime, nextCloseAt, BigInt(result.closeTick)),
value: String(auction.id),
},
]);
return { ok: true };
@@ -521,7 +525,10 @@ export const auctionRouter = router({
const timerKeys = buildAuctionTimerKeys(ctx.profile.name);
const nextCloseAt = new Date(result.closeAt);
await ctx.redis.zAdd(timerKeys.timerKey, [
{ score: resolveAuctionTimerScore(gameTime, nextCloseAt, BigInt(result.closeTick)), value: String(auction.id) },
{
score: resolveAuctionTimerScore(gameTime, nextCloseAt, BigInt(result.closeTick)),
value: String(auction.id),
},
]);
return { ok: true };
@@ -659,7 +666,10 @@ export const auctionRouter = router({
const timerKeys = buildAuctionTimerKeys(ctx.profile.name);
const nextCloseAt = new Date(result.closeAt);
await ctx.redis.zAdd(timerKeys.timerKey, [
{ score: resolveAuctionTimerScore(gameTime, nextCloseAt, BigInt(result.closeTick)), value: String(auction.id) },
{
score: resolveAuctionTimerScore(gameTime, nextCloseAt, BigInt(result.closeTick)),
value: String(auction.id),
},
]);
return { ok: true };
+3 -2
View File
@@ -1,3 +1,4 @@
import { upsertWithoutSequence } from '@sammo-ts/infra';
import { TRPCError } from '@trpc/server';
import { CLOCK_OPERATION_PERSISTENCE_LOCK, GamePrisma, acquireGameSchemaAdvisoryXactLock } from '@sammo-ts/infra';
import { z } from 'zod';
@@ -223,7 +224,7 @@ export const bettingRouter = router({
world.currentMonth,
`${input.amount} 포인트를 베팅에 사용`
);
await ctx.db.rankData.upsert({
await upsertWithoutSequence(ctx.db.rankData, {
where: {
generalId_type: {
generalId: general.id,
@@ -245,7 +246,7 @@ export const bettingRouter = router({
});
}
await ctx.db.nationBet.upsert({
await upsertWithoutSequence(ctx.db.nationBet, {
where: {
bettingId_userId_selectionKey: {
bettingId: input.bettingId,
+6 -9
View File
@@ -2,7 +2,7 @@ import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { getBillByLevel, LogCategory, LogScope } from '@sammo-ts/logic';
import { asRecord, readOfficeRequest, type RankDataType } from '@sammo-ts/common';
import { asRecord, readOfficeRequest, toSafeInteger, withSafeIntegerId, type RankDataType } from '@sammo-ts/common';
import type { GameApiContext } from '../../context.js';
import {
@@ -588,10 +588,7 @@ export const getGeneralContext = async (ctx: GameApiContext) => {
recentWar: general.recentWarTime?.toISOString() ?? null,
defenceTrain: settings.defence_train,
killTurn: readNumber(metaRecord.killturn ?? metaRecord.killTurn, 0),
remainingMinutes: resolveRemainingMinutes(
general.turnTime,
gameTime.now
),
remainingMinutes: resolveRemainingMinutes(general.turnTime, gameTime.now),
crewTypeId: general.crewTypeId,
crewTypeName: crewTypeDetails.get(general.crewTypeId)?.name ?? '-',
crewTypeInfo: crewTypeDetails.get(general.crewTypeId) ?? null,
@@ -916,7 +913,7 @@ export const generalRouter = router({
return {
type: input.type,
logs: logs.map((entry) => ({
id: entry.id,
id: toSafeInteger(entry.id),
text: entry.text,
})),
};
@@ -966,9 +963,9 @@ export const generalRouter = router({
]);
return {
global: trimRecentRecords(global, input.lastGeneralRecordId),
general: trimRecentRecords(general, input.lastGeneralRecordId),
history: trimRecentRecords(history, input.lastWorldHistoryId),
global: trimRecentRecords(global.map(withSafeIntegerId), input.lastGeneralRecordId),
general: trimRecentRecords(general.map(withSafeIntegerId), input.lastGeneralRecordId),
history: trimRecentRecords(history.map(withSafeIntegerId), input.lastWorldHistoryId),
};
}),
// 메인 화면은 SSE invalidation, 탭 복귀와 직접 갱신이 같은 read model을
+3 -3
View File
@@ -1,3 +1,4 @@
import { withSafeIntegerId } from '@sammo-ts/common';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
@@ -38,7 +39,6 @@ const BUFF_KEYS: InheritBuffType[] = [
const UNIQUE_ITEM_SLOT_ORDER: readonly ItemSlot[] = ['horse', 'weapon', 'book', 'item'];
const POSTGRES_INTEGER_MAX = 2_147_483_647;
const MIN_INHERIT_BUFF_LEVEL = 1;
const MAX_INHERIT_BUFF_LEVEL = 5;
@@ -283,7 +283,7 @@ export const inheritRouter = router({
getLogs: authedProcedure
.input(
z.object({
lastId: z.number().int().min(1).max(POSTGRES_INTEGER_MAX).optional(),
lastId: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER).optional(),
})
)
.query(async ({ ctx, input }) => {
@@ -300,7 +300,7 @@ export const inheritRouter = router({
take: 30,
select: { id: true, year: true, month: true, text: true, createdAt: true },
});
return logs;
return logs.map(withSafeIntegerId);
}),
buyHiddenBuff: engineAuthedProcedure
.input(
@@ -1,3 +1,4 @@
import { toSafeInteger } from '@sammo-ts/common';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
@@ -77,7 +78,7 @@ export const getGeneralLog = accessLimitAuthedInputProcedure(
type: input.type,
generalId: target.id,
logs: logs.map((entry) => ({
id: entry.id,
id: toSafeInteger(entry.id),
text: entry.text,
year: entry.year,
month: entry.month,
@@ -1,3 +1,4 @@
import { withSafeIntegerId } from '@sammo-ts/common';
import { TRPCError } from '@trpc/server';
import { asRecord } from '@sammo-ts/common';
@@ -129,6 +130,6 @@ export const getNationInfo = authedProcedure.query(async ({ ctx }) => {
name: city.name,
capital: city.id === nation.capitalCityId,
})),
history,
history: history.map(withSafeIntegerId),
};
});
+91
View File
@@ -0,0 +1,91 @@
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import type { GamePrisma } from '@sammo-ts/infra';
import type { GameApiContext } from '../../context.js';
import { authedProcedure } from '../../trpc.js';
import { getAuthenticatedUserId } from '../shared/general.js';
import { resolveSecretPermission } from '../shared/secretPermission.js';
import { projectPolicyConfiguration, projectPolicySummary } from '../playAudit/policies.js';
import { readAudit, readAuditWorld } from '../playAudit/shared.js';
const area = z.enum(['NPC_VALUES', 'NPC_NATION_PRIORITY', 'NPC_GENERAL_PRIORITY']);
const summarySelect = {
id: true,
schemaVersion: true,
nationId: true,
area: true,
revision: true,
previousId: true,
source: true,
year: true,
month: true,
actor: true,
createdAt: true,
} satisfies GamePrisma.PlayAuditPolicySelect;
// 소속·기밀 권한과 이력을 같은 snapshot에서 읽어 이적/권한 변경 경합을 막는다.
const readNationId = async (ctx: GameApiContext, tx: GamePrisma.TransactionClient): Promise<number> => {
const general = await tx.general.findFirst({ where: { userId: getAuthenticatedUserId(ctx) } });
if (!general) throw new TRPCError({ code: 'NOT_FOUND', message: '장수 정보를 찾을 수 없습니다.' });
if (general.nationId <= 0)
throw new TRPCError({ code: 'PRECONDITION_FAILED', message: '국가에 소속되어있지 않습니다.' });
const nation = await tx.nation.findUnique({ where: { id: general.nationId }, select: { meta: true } });
if (!nation) throw new TRPCError({ code: 'NOT_FOUND', message: '국가 정보를 찾을 수 없습니다.' });
if (resolveSecretPermission(general, nation.meta) < 1)
throw new TRPCError({ code: 'FORBIDDEN', message: '권한이 부족합니다.' });
return general.nationId;
};
export const policyHistory = authedProcedure
.input(
z
.object({
area,
cursor: z.number().int().positive().optional(),
limit: z.number().int().min(1).max(50).default(20),
})
.strict()
)
.query(({ ctx, input }) =>
readAudit(ctx, async (tx) => {
const nationId = await readNationId(ctx, tx);
const world = await readAuditWorld(tx);
const rows = world.serverId
? await tx.playAuditPolicy.findMany({
where: {
serverId: world.serverId,
nationId,
area: input.area,
revision: input.cursor === undefined ? undefined : { lt: input.cursor },
},
orderBy: { revision: 'desc' },
take: input.limit + 1,
select: summarySelect,
})
: [];
return {
coverage: world.serverId ? ('RECORDED_VERSIONS_ONLY' as const) : ('IDENTITY_MISSING' as const),
historyGap: world.historyGap,
items: rows.slice(0, input.limit).map(projectPolicySummary),
nextCursor: rows.length > input.limit ? rows[input.limit - 1]!.revision : null,
};
})
);
export const policyVersion = authedProcedure
.input(z.object({ id: z.string().regex(/^[a-f0-9]{64}$/) }).strict())
.query(({ ctx, input }) =>
readAudit(ctx, async (tx) => {
const nationId = await readNationId(ctx, tx);
const world = await readAuditWorld(tx);
const row = world.serverId
? await tx.playAuditPolicy.findFirst({
where: { id: input.id, serverId: world.serverId, nationId, area: { in: area.options } },
select: { ...summarySelect, before: true, after: true },
})
: null;
if (!row)
throw new TRPCError({ code: 'NOT_FOUND', message: '자국의 현재 기수 정책 기록을 찾을 수 없습니다.' });
return projectPolicyConfiguration(row);
})
);
+3
View File
@@ -15,6 +15,7 @@ import { loadUnitSetDefinitionByName } from '@sammo-ts/game-engine/scenario/unit
import type { GameApiContext } from '../../context.js';
import { getMyGeneral } from '../shared/general.js';
import { resolveSecretPermission } from '../shared/secretPermission.js';
import { policyHistory, policyVersion } from './history.js';
type SetterInfo = {
setter: string | null;
@@ -356,6 +357,8 @@ const requestNpcPolicyMutation = async (
};
export const npcRouter = router({
policyHistory,
policyVersion,
getPolicy: authedProcedure.query(async ({ ctx }) => {
const general = await getMyGeneral(ctx);
if (general.nationId <= 0) {
@@ -1,6 +1,6 @@
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import type { GamePrisma } from '@sammo-ts/infra';
import { decodeAuditDecisionSteps, type GamePrisma } from '@sammo-ts/infra';
import { auditProcedure, monthOrdinal, readAudit, readAuditWorld, zAuditMonth } from './shared.js';
const zEffectivePolicy = z.object({
@@ -275,7 +275,7 @@ export const decisionDetail = auditProcedure
decision: project(row),
chunks: chunks.slice(0, input.limit).map((chunk) => ({
ordinal: chunk.ordinal,
steps: z.array(zStep).max(128).parse(chunk.steps),
steps: z.array(zStep).max(128).parse(decodeAuditDecisionSteps(chunk.steps)),
})),
nextCursor:
chunks.length && chunks.at(-1)!.ordinal + 1 < Math.ceil(row.stepCount / 128)
+3 -2
View File
@@ -1,3 +1,4 @@
import { toSafeInteger, withSafeIntegerId } from '@sammo-ts/common';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { auditProcedure, monthOrdinal, readAudit, readAuditWorld } from './shared.js';
@@ -53,8 +54,8 @@ export const generalLogs = auditProcedure
...world,
type: input.type,
coverage: world.serverId ? ('IDENTIFIED_LOGS_ONLY' as const) : ('IDENTITY_MISSING' as const),
items: rows.slice(0, input.limit),
nextCursor: rows.length > input.limit ? rows[input.limit - 1]!.id : null,
items: rows.slice(0, input.limit).map(withSafeIntegerId),
nextCursor: rows.length > input.limit ? toSafeInteger(rows[input.limit - 1]!.id) : null,
};
})
);
+2 -2
View File
@@ -1,5 +1,5 @@
import { TRPCError } from '@trpc/server';
import { asNumber, asRecord } from '@sammo-ts/common';
import { asNumber, asRecord, withSafeIntegerId } from '@sammo-ts/common';
import { LEGACY_DEFAULT_MAX_LEVEL, LogCategory, LogScope } from '@sammo-ts/logic';
import { z } from 'zod';
@@ -306,7 +306,7 @@ export const publicRouter = router({
}
const snapshot = {
...map,
history,
history: history.map(withSafeIntegerId),
};
await ctx.redis.set(cacheKey, JSON.stringify(snapshot), { EX: PUBLIC_CACHE_TTL_SECONDS });
return snapshot;
+55 -70
View File
@@ -1,7 +1,7 @@
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { asRecord } from '@sammo-ts/common';
import { asRecord, type TurnDaemonCommandResult } from '@sammo-ts/common';
import type { TournamentType } from '@sammo-ts/logic';
import type { TournamentState } from '../../tournament/types.js';
@@ -18,6 +18,16 @@ import {
} from '../../services/redisClockFence.js';
import { loadClockAdminStatus } from '../../services/clockReadiness.js';
const assertTournamentAdjustment = (result: TurnDaemonCommandResult | null): void => {
if (result?.type === 'commandRejected') {
throw new TRPCError({ code: 'FORBIDDEN', message: result.reason });
}
if (!result || result.type !== 'tournamentAdjustGeneral') {
throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', message: 'Unexpected tournament response' });
}
if (!result.ok) throw new TRPCError({ code: result.code, message: result.reason });
};
const hasAdminRole = (roles: string[], profileName: string): boolean => {
if (roles.includes('superuser') || roles.includes('admin') || roles.includes('admin.superuser')) {
return true;
@@ -197,6 +207,7 @@ const zMatch = z.object({
const zBetEntry = z.object({
generalId: z.number().int().positive(),
userId: z.string().min(1).nullable().optional(),
targetId: z.number().int().positive(),
amount: z.number().int().positive(),
});
@@ -458,7 +469,7 @@ export const tournamentRouter = router({
});
}),
getBettingSummary: authedProcedure.query(async ({ ctx }) => {
const general = await getMyGeneral(ctx);
await getMyGeneral(ctx);
const store = new TournamentStore(ctx.redis, buildTournamentKeys(ctx.profile.name));
const [state, entries, matches] = await Promise.all([
store.getState(),
@@ -488,7 +499,7 @@ export const tournamentRouter = router({
}
totals[entry.targetId] = (totals[entry.targetId] ?? 0) + entry.amount;
totalAmount += entry.amount;
if (entry.generalId === general.id) {
if (entry.userId === ctx.auth!.user.id) {
myTotals[entry.targetId] = (myTotals[entry.targetId] ?? 0) + entry.amount;
myAmount += entry.amount;
}
@@ -523,20 +534,15 @@ export const tournamentRouter = router({
const develCost = resolveCurrentDevelCost(worldState);
const feeResult = await ctx.turnDaemon.requestCommand({
type: 'adjustGeneralResources',
type: 'tournamentAdjustGeneral',
requestId: tournamentJoinCommandRequestId(ctx.requestId, 'resources'),
reason: 'tournamentJoin',
adjustments: [{ generalId: general.id, goldDelta: -develCost, minGoldAfter: 0 }],
userId: ctx.auth!.user.id,
generalId: general.id,
goldDelta: -develCost,
minGoldAfter: 0,
});
if (!feeResult || feeResult.type !== 'adjustGeneralResources') {
throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', message: 'Unexpected response' });
}
if (!feeResult.ok || feeResult.processed !== 1) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: feeResult.ok ? '금이 부족합니다.' : feeResult.reason,
});
}
assertTournamentAdjustment(feeResult);
const meta = asRecord(general.meta);
const level = typeof meta.explevel === 'number' ? meta.explevel : 0;
@@ -558,12 +564,17 @@ export const tournamentRouter = router({
try {
await store.setParticipants(next);
} catch (error) {
await ctx.turnDaemon.requestCommand({
type: 'adjustGeneralResources',
requestId: tournamentJoinCommandRequestId(ctx.requestId, 'projection-rollback-resources'),
reason: 'tournamentJoinRollback',
adjustments: [{ generalId: general.id, goldDelta: develCost }],
});
assertTournamentAdjustment(
await ctx.turnDaemon.requestCommand({
type: 'tournamentAdjustGeneral',
requestId: tournamentJoinCommandRequestId(ctx.requestId, 'projection-rollback-resources'),
reason: 'tournamentJoinRollback',
userId: ctx.auth!.user.id,
generalId: general.id,
goldDelta: develCost,
minGoldAfter: 0,
})
);
throw error;
}
return { ok: true, count: next.length };
@@ -663,8 +674,13 @@ export const tournamentRouter = router({
throw new TRPCError({ code: 'BAD_REQUEST', message: '올바르지 않은 베팅 대상입니다.' });
}
// 구형 row의 당시 actor는 현재 장수 소유자로 추정할 수 없다.
// 운영 전환은 베팅 종료 뒤 하거나 검증한 actor 정보를 관리자가 복원해야 한다.
if (entries.some((entry) => entry.userId === undefined)) {
throw new TRPCError({ code: 'BAD_REQUEST', message: '이전 베팅의 사용자 확인이 필요합니다.' });
}
const previousBetAmount = entries
.filter((entry) => entry.generalId === general.id)
.filter((entry) => entry.userId === ctx.auth!.user.id)
.reduce((sum, entry) => sum + entry.amount, 0);
if (previousBetAmount + input.amount > 1_000) {
throw new TRPCError({
@@ -674,68 +690,37 @@ export const tournamentRouter = router({
}
const adjustResult = await ctx.turnDaemon.requestCommand({
type: 'adjustGeneralResources',
type: 'tournamentAdjustGeneral',
requestId: tournamentBetCommandRequestId(ctx.requestId, 'resources'),
reason: 'tournamentBet',
adjustments: [{ generalId: general.id, goldDelta: -input.amount, minGoldAfter: 500 }],
userId: ctx.auth!.user.id,
generalId: general.id,
goldDelta: -input.amount,
betGoldDelta: input.amount,
minGoldAfter: 500,
});
if (!adjustResult || adjustResult.type !== 'adjustGeneralResources') {
throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', message: 'Unexpected response' });
}
if (!adjustResult.ok || adjustResult.processed !== 1) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: adjustResult.ok ? '금이 부족합니다.' : adjustResult.reason,
});
}
const rankResult = await ctx.turnDaemon.requestCommand({
type: 'adjustGeneralMeta',
requestId: tournamentBetCommandRequestId(ctx.requestId, 'rank'),
reason: 'tournamentBet',
adjustments: [
{
generalId: general.id,
metaDelta: { betgold: input.amount },
},
],
});
if (!rankResult || rankResult.type !== 'adjustGeneralMeta' || !rankResult.ok) {
await ctx.turnDaemon.requestCommand({
type: 'adjustGeneralResources',
requestId: tournamentBetCommandRequestId(ctx.requestId, 'rank-rollback-resources'),
reason: 'tournamentBetRollback',
adjustments: [{ generalId: general.id, goldDelta: input.amount }],
});
throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', message: '베팅 기록을 저장하지 못했습니다.' });
}
assertTournamentAdjustment(adjustResult);
try {
await store.appendBettingEntry({
generalId: general.id,
userId: ctx.auth!.user.id,
targetId: input.targetId,
amount: input.amount,
});
} catch (error) {
await Promise.all([
ctx.turnDaemon.requestCommand({
type: 'adjustGeneralResources',
assertTournamentAdjustment(
await ctx.turnDaemon.requestCommand({
type: 'tournamentAdjustGeneral',
requestId: tournamentBetCommandRequestId(ctx.requestId, 'projection-rollback-resources'),
reason: 'tournamentBetRollback',
adjustments: [{ generalId: general.id, goldDelta: input.amount }],
}),
ctx.turnDaemon.requestCommand({
type: 'adjustGeneralMeta',
requestId: tournamentBetCommandRequestId(ctx.requestId, 'projection-rollback-rank'),
reason: 'tournamentBetRollback',
adjustments: [
{
generalId: general.id,
metaDelta: { betgold: -input.amount },
},
],
}),
]);
userId: ctx.auth!.user.id,
generalId: general.id,
goldDelta: input.amount,
betGoldDelta: -input.amount,
minGoldAfter: 0,
})
);
throw error;
}
return { ok: true };
+8 -6
View File
@@ -1,4 +1,4 @@
import { safeHttpLoggerOptions, safeHttpErrorHandler } from '@sammo-ts/common';
import { safeHttpLoggerOptions, safeHttpErrorHandler, createApiOriginGuard } from '@sammo-ts/common';
import fastify, { type FastifyRequest } from 'fastify';
import cors from '@fastify/cors';
import fastifyStatic from '@fastify/static';
@@ -76,13 +76,14 @@ const extractBearerToken = (value: string | string[] | undefined): string | null
const resolveAuthFromToken = async (
token: string | null,
accessTokenStore: RedisAccessTokenStore,
flushStore: FlushStore
flushStore: FlushStore,
profileName: string
): Promise<GameSessionTokenPayload | null> => {
if (!token) {
return null;
}
const stored = await accessTokenStore.get(token);
if (!stored) {
if (!stored || stored.profile !== profileName) {
return null;
}
let flushedAt: Date | null;
@@ -273,8 +274,9 @@ export const createGameApiServer = async () => {
app.addHook('onClose', closeResources);
app.addHook('onRequest', createApiOriginGuard(config.corsAllowedOrigins));
await app.register(cors, {
origin: true,
origin: config.corsAllowedOrigins,
credentials: true,
});
@@ -290,7 +292,7 @@ export const createGameApiServer = async () => {
...trpcJsonBodyHttpServerOptions,
createContext: async ({ req }: { req: FastifyRequest }) => {
const token = extractBearerToken(req.headers.authorization);
const auth = await resolveAuthFromToken(token, accessTokenStore, flushStore);
const auth = await resolveAuthFromToken(token, accessTokenStore, flushStore, config.profileName);
const rawIdempotencyKey = Array.isArray(req.headers['idempotency-key'])
? req.headers['idempotency-key'][0]
: req.headers['idempotency-key'];
@@ -334,7 +336,7 @@ export const createGameApiServer = async () => {
});
const resolveRealtimeAuth = async (token: string | null): Promise<GameSessionTokenPayload | null> => {
const auth = await resolveAuthFromToken(token, accessTokenStore, flushStore);
const auth = await resolveAuthFromToken(token, accessTokenStore, flushStore, config.profileName);
if (
!auth ||
auth.profile !== config.profileName ||
@@ -1,3 +1,4 @@
import { existingRowIdOrNext } from '@sammo-ts/infra';
import { createHash, randomUUID } from 'node:crypto';
import { asRecord, resolveAccessLimitLevel, resolveAccessRefreshLimit } from '@sammo-ts/common';
@@ -94,7 +95,13 @@ export const enqueueDeferredGeneralAccess = async (
}
await redis.eval(ENQUEUE_SCRIPT, {
keys: [activeKey(profileName)],
arguments: [String(generalId), auth.user.id, String(weight), String(now.getTime()), String(ACTIVE_BATCH_TTL_MS)],
arguments: [
String(generalId),
auth.user.id,
String(weight),
String(now.getTime()),
String(ACTIVE_BATCH_TTL_MS),
],
});
return true;
};
@@ -258,9 +265,10 @@ export const flushDeferredGeneralAccessBatch = async (
),
missing_periods AS (
INSERT INTO "traffic_period" (
"world_state_id", "year", "month", "started_at", "last_refresh", "refresh", "online"
"id", "world_state_id", "year", "month", "started_at", "last_refresh", "refresh", "online"
)
SELECT
${existingRowIdOrNext('traffic_period', GamePrisma.sql`stable_id.world_state_id = ${worldState.id} AND stable_id.year = (missing_key / 12)::INTEGER AND stable_id.month = (missing_key % 12 + 1)::INTEGER`)},
${worldState.id},
(missing_key / 12)::INTEGER,
(missing_key % 12 + 1)::INTEGER,
@@ -281,9 +289,10 @@ export const flushDeferredGeneralAccessBatch = async (
),
period_upsert AS (
INSERT INTO "traffic_period" (
"world_state_id", "year", "month", "started_at", "last_refresh", "refresh", "online"
"id", "world_state_id", "year", "month", "started_at", "last_refresh", "refresh", "online"
)
SELECT
${existingRowIdOrNext('traffic_period', GamePrisma.sql`stable_id.world_state_id = ${worldState.id} AND stable_id.year = ${worldState.currentYear} AND stable_id.month = ${worldState.currentMonth}`)},
${worldState.id},
${worldState.currentYear},
${worldState.currentMonth},
@@ -343,10 +352,11 @@ export const flushDeferredGeneralAccessBatch = async (
),
access_updates AS (
INSERT INTO "general_access_log" (
"general_id", "user_id", "last_refresh", "refresh", "refresh_total",
"id", "general_id", "user_id", "last_refresh", "refresh", "refresh_total",
"refresh_score", "refresh_score_total"
)
SELECT
${existingRowIdOrNext('general_access_log', GamePrisma.sql`stable_id.general_id = resolved."general_id"`)},
resolved."general_id",
resolved."user_id",
resolved."last_refresh",
@@ -471,11 +481,9 @@ export class DeferredGeneralAccessWorker {
await this.redis.del(key);
return;
}
await this.redis.set(
key,
JSON.stringify({ nextAccessAt: state.nextAccessAt.toISOString() }),
{ PX: Math.max(1, state.nextAccessAt.getTime() - now.getTime()) }
);
await this.redis.set(key, JSON.stringify({ nextAccessAt: state.nextAccessAt.toISOString() }), {
PX: Math.max(1, state.nextAccessAt.getTime() - now.getTime()),
});
})
);
}
+6 -1
View File
@@ -1,3 +1,4 @@
import { existingRowIdOrNext } from '@sammo-ts/infra';
import { asRecord, resolveAccessLimitLevel, resolveAccessRefreshLimit, type AccessLimitLevel } from '@sammo-ts/common';
import { acquireGameSchemaAdvisoryXactLock, GENERAL_ACCESS_PERSISTENCE_LOCK, GamePrisma } from '@sammo-ts/infra';
@@ -230,7 +231,7 @@ export const upsertGeneralAccess = async (
await db.$transaction(async (transaction) => {
await acquireGameSchemaAdvisoryXactLock(transaction, GENERAL_ACCESS_PERSISTENCE_LOCK);
const periodKey = input.year * 12 + input.month - 1;
const periodRows = await transaction.$queryRaw<Array<{ id: number }>>(
const periodRows = await transaction.$queryRaw<Array<{ id: bigint }>>(
GamePrisma.sql`
WITH latest_period AS (
SELECT MAX(year * 12 + month - 1)::INTEGER AS period_key
@@ -269,6 +270,7 @@ export const upsertGeneralAccess = async (
RETURNING id
)
INSERT INTO traffic_period (
id,
world_state_id,
year,
month,
@@ -277,6 +279,7 @@ export const upsertGeneralAccess = async (
refresh
)
VALUES (
${existingRowIdOrNext('traffic_period', GamePrisma.sql`stable_id.world_state_id = ${input.worldStateId} AND stable_id.year = ${input.year} AND stable_id.month = ${input.month}`)},
${input.worldStateId},
${input.year},
${input.month},
@@ -341,6 +344,7 @@ export const upsertGeneralAccess = async (
await transaction.$executeRaw(
GamePrisma.sql`
INSERT INTO general_access_log (
id,
general_id,
user_id,
last_refresh,
@@ -350,6 +354,7 @@ export const upsertGeneralAccess = async (
refresh_score_total
)
VALUES (
${existingRowIdOrNext('general_access_log', GamePrisma.sql`stable_id.general_id = ${input.generalId}`)},
${input.generalId},
${input.userId},
${input.now},
@@ -1,3 +1,4 @@
import { existingRowIdOrNext } from '@sammo-ts/infra';
import { GamePrisma } from '@sammo-ts/infra';
import type { GameApiContext } from '../context.js';
@@ -20,11 +21,13 @@ export const recordGeneralActivity = async (
const written = await ctx.db.$executeRaw(
GamePrisma.sql`
INSERT INTO general_access_log (
id,
general_id,
user_id,
last_action_at
)
SELECT
${existingRowIdOrNext('general_access_log', GamePrisma.sql`stable_id.general_id = "general".id`)},
id,
${user.id},
${now}
+2 -1
View File
@@ -1,3 +1,4 @@
import { upsertWithoutSequence } from '@sammo-ts/infra';
import { asNumber, asRecord } from '@sammo-ts/common';
import { GamePrisma } from '@sammo-ts/infra';
import {
@@ -132,7 +133,7 @@ export const setInheritancePoint = async (
key: InheritPointKey,
value: number
): Promise<void> => {
await db.inheritancePoint.upsert({
await upsertWithoutSequence(db.inheritancePoint, {
where: {
userId_key: {
userId,
+5 -1
View File
@@ -31,6 +31,7 @@ export class CorruptTournamentProjectionError extends Error {
const zTournamentBet = z
.object({
generalId: z.number().int(),
userId: z.string().min(1).nullable().optional(),
targetId: z.number().int(),
amount: z.number(),
})
@@ -286,7 +287,10 @@ export class TournamentStore {
async appendBettingEntry(entry: TournamentBetEntry): Promise<TournamentBetEntry[]> {
const entries = await this.getBettingEntries();
const existing = entries.find(
(candidate) => candidate.generalId === entry.generalId && candidate.targetId === entry.targetId
(candidate) =>
candidate.generalId === entry.generalId &&
candidate.targetId === entry.targetId &&
candidate.userId === entry.userId
);
if (existing) {
existing.amount += entry.amount;
+2
View File
@@ -74,6 +74,8 @@ export interface TournamentMatchEntry {
export interface TournamentBetEntry {
generalId: number;
// 로그인 actor는 장수 빙의와 독립적이다. null은 서버가 만든 NPC, 생략은 구형 row다.
userId?: string | null;
targetId: number;
amount: number;
}
+18 -13
View File
@@ -760,7 +760,7 @@ const buildNpcBettingPlan = async (options: {
for (const npc of npcBetList) {
const targetId = rng.choice(candidateIds);
if (!existingBettors.has(npc.id as number)) {
entries.push({ generalId: npc.id as number, targetId, amount: betGold });
entries.push({ generalId: npc.id as number, userId: null, targetId, amount: betGold });
}
}
return entries;
@@ -789,19 +789,24 @@ export const seedNpcBets = async (options: {
}
const requestPrefix = `tournament:${state.bettingId ?? `${state.openYear}:${state.openMonth}:${state.type}`}:npc-bet`;
await daemonTransport.sendCommand({
type: 'adjustGeneralResources',
requestId: `${requestPrefix}:resources`,
reason: 'tournamentNpcBet',
adjustments: plan.map((entry) => ({ generalId: entry.generalId, goldDelta: -entry.amount })),
});
await daemonTransport.sendCommand({
type: 'adjustGeneralMeta',
requestId: `${requestPrefix}:meta`,
reason: 'tournamentNpcBet',
adjustments: plan.map((entry) => ({ generalId: entry.generalId, metaDelta: { betgold: entry.amount } })),
// Wait for one durable ENGINE result before publishing entries or opening stage 6.
// The engine skips NPCs whose owner changed after this deterministic plan was stored.
const result = await daemonTransport.requestCommand({
type: 'tournamentSeedNpcBets',
requestId: `${requestPrefix}:atomic`,
bets: plan.map((entry) => ({ generalId: entry.generalId, amount: entry.amount })),
});
if (!result || result.type !== 'tournamentSeedNpcBets' || !result.ok) {
throw new Error('NPC tournament betting did not commit.');
}
const processed = new Set(result.processedGeneralIds);
const existing = await store.getBettingEntries();
const existingBettors = new Set(existing.map((entry) => entry.generalId));
await store.setBettingEntries(existing.concat(plan.filter((entry) => !existingBettors.has(entry.generalId))));
await store.setBettingEntries(
existing.concat(
plan
.filter((entry) => processed.has(entry.generalId) && !existingBettors.has(entry.generalId))
.map((entry) => ({ ...entry, userId: null }))
)
);
};
+1 -1
View File
@@ -24,7 +24,7 @@ import { recordGeneralActivity } from './services/generalActivity.js';
const t = initTRPC.context<GameApiContext>().create({ errorFormatter: safeTrpcErrorFormatter });
const requireAuthMiddleware = t.middleware(({ ctx, next }) => {
if (!ctx.auth) {
if (!ctx.auth || ctx.auth.profile !== ctx.profile.name) {
throw new TRPCError({
code: 'UNAUTHORIZED',
message: 'Unauthorized',
+3 -1
View File
@@ -472,8 +472,10 @@ const sanitizeLegacyTurnArgString = (value: string): string => {
if (stripped === '' || stripped === '0') {
return '';
}
// Core의 Vue text와 formatLegacyLogHtml이 출력 시 &를 escape한다.
// Ref의 입력 단계 & 변환까지 적용하면 국호/예약 인자에 entity가 저장된다.
// <, > 중화는 로그의 legacy markup과 사용자 입력을 구분하기 위해 유지한다.
return stripped
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replace(/^[\p{Z}\p{C}]+|[\p{Z}\p{C}]+$/gu, '');
+23 -1
View File
@@ -152,7 +152,29 @@ describe('turn command argument input', () => {
);
});
it('recursively sanitizes reserved command strings like Ref before command parsing', async () => {
it('preserves ampersands through reservation parsing and repeated sanitization', async () => {
const args = { nationName: '풍년F&B', nested: ['A&B', '&amp;', '&lt;img&gt;'] };
expect(sanitizeReservedTurnArgs(args)).toEqual(args);
expect(sanitizeReservedTurnArgs(sanitizeReservedTurnArgs(args))).toEqual(args);
await expect(parseReservedTurnArgs('nation', 'che_국호변경', args)).resolves.toEqual({
nationName: '풍년F&B',
});
await expect(
parseReservedTurnArgs('general', 'che_건국', {
nationName: '풍년F&B',
nationType: 'che_도적',
colorType: 0,
})
).resolves.toMatchObject({ nationName: '풍년F&B' });
// 반각 18자 판정에 &amp;의 저장 길이가 끼어들지 않는다.
const maxWidthName = '가나다라마바사아&B';
expect(() => assertReservedTurnArgsPassLegacyBasicValidation({ nationName: maxWidthName })).not.toThrow();
await expect(parseReservedTurnArgs('nation', 'che_국호변경', { nationName: maxWidthName })).resolves.toEqual({
nationName: maxWidthName,
});
});
it('retains Ref character removal and angle-bracket neutralization before command parsing', async () => {
expect(
sanitizeReservedTurnArgs({
nationName: ' <신-국># ',
@@ -12,6 +12,7 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import {
DeferredGeneralAccessWorker,
flushDeferredGeneralAccessBatch,
enqueueDeferredGeneralAccess,
getDeferredGeneralAccessLimit,
} from '../src/services/deferredGeneralAccess.js';
@@ -91,7 +92,7 @@ liveIntegration('deferred general access with PostgreSQL and Redis', () => {
await redis.disconnect();
}
if (db) {
await db.generalAccessBatch.deleteMany({ where: { id: batchId } });
await db.generalAccessBatch.deleteMany({ where: { id: { startsWith: batchId } } });
await db.generalAccessLog.deleteMany({ where: { generalId } });
await db.general.deleteMany({ where: { id: generalId } });
await db.worldState.deleteMany({ where: { id: worldStateId } });
@@ -153,9 +154,19 @@ liveIntegration('deferred general access with PostgreSQL and Redis', () => {
nextAccessAt,
});
const counters =
await db.$queryRaw`SELECT 'access' AS kind,last_value FROM general_access_log_id_seq UNION ALL SELECT 'period',last_value FROM traffic_period_id_seq`;
const accessId = (await db.generalAccessLog.findUniqueOrThrow({ where: { generalId } })).id;
await flushDeferredGeneralAccessBatch(workerDb as never, `${batchId}-second`, [
{ generalId, userId, weight: 1, lastRefresh: now },
]);
expect(
await db.$queryRaw`SELECT 'access' AS kind,last_value FROM general_access_log_id_seq UNION ALL SELECT 'period',last_value FROM traffic_period_id_seq`
).toEqual(counters);
expect((await db.generalAccessLog.findUniqueOrThrow({ where: { generalId } })).id).toBe(accessId);
await worker.flushOnce();
await expect(db.generalAccessLog.findUniqueOrThrow({ where: { generalId } })).resolves.toMatchObject({
refreshTotal: 2,
refreshTotal: 3,
});
});
});
@@ -25,7 +25,7 @@ const deferredBatchId = `deferred-access-${endpointGeneralId}`;
const endpointAuth = (roles = ['user']): GameSessionTokenPayload => ({
version: 1,
profile: `${yearbookProfile}:default`,
profile: yearbookProfile,
issuedAt: '2026-07-26T00:00:00.000Z',
expiresAt: '2026-07-27T00:00:00.000Z',
sessionId: `access-session-${endpointGeneralId}`,
@@ -167,6 +167,9 @@ integration('general access tracking persistence', () => {
scoreStartedAt: new Date('2026-07-26T03:00:00.000Z'),
};
await upsertGeneralAccess(db, { ...firstWindow, weight: 2 });
const counters =
await db.$queryRaw`SELECT 'access' AS kind,last_value FROM general_access_log_id_seq UNION ALL SELECT 'period',last_value FROM traffic_period_id_seq`;
const accessId = (await db.generalAccessLog.findUniqueOrThrow({ where: { generalId } })).id;
await Promise.all(
Array.from({ length: 20 }, (_, index) =>
upsertGeneralAccess(db, {
@@ -177,6 +180,10 @@ integration('general access tracking persistence', () => {
)
);
expect(
await db.$queryRaw`SELECT 'access' AS kind,last_value FROM general_access_log_id_seq UNION ALL SELECT 'period',last_value FROM traffic_period_id_seq`
).toEqual(counters);
expect((await db.generalAccessLog.findUniqueOrThrow({ where: { generalId } })).id).toBe(accessId);
expect(await db.generalAccessLog.findUniqueOrThrow({ where: { generalId } })).toMatchObject({
userId: 'access-user-a',
refresh: 22,
@@ -387,7 +387,7 @@ describe('general access tracking', () => {
db,
generalAccessTracking: true,
requestId: 'access-boundary-test',
profile: { id: 'che:default', name: 'che' },
profile: { id: 'che', name: 'che:default', scenario: 'default' },
profileStatusSource,
} as unknown as GameApiContext;
@@ -26,7 +26,7 @@ const buildContext = (executeRaw = vi.fn(async (_query: unknown) => 1), token =
auth: token,
db: { $executeRaw: executeRaw },
generalAccessTracking: true,
profile: { id: 'che:default', name: 'che', scenario: 'default' },
profile: { id: 'che', name: 'che:default', scenario: 'default' },
}) as unknown as GameApiContext;
const activityRouter = router({
+15 -12
View File
@@ -108,7 +108,7 @@ const buildContext = (options: {
inheritancePoint?: number;
inheritanceRows?: Array<{ key: string; value: number }>;
rankRows?: Array<{ type: string; value: number }>;
inheritanceLogs?: Array<{ id: number; year: number; month: number; text: string; createdAt: Date }>;
inheritanceLogs?: Array<{ id: number | bigint; year: number; month: number; text: string; createdAt: Date }>;
configConst?: Record<string, unknown>;
scenarioCode?: string;
configMap?: Record<string, unknown>;
@@ -460,11 +460,11 @@ describe('inherit router actor and permission boundaries', () => {
it('loads the first inheritance-log page without an out-of-range integer cursor', async () => {
const createdAt = new Date('2026-07-26T00:00:00Z');
const fixture = buildContext({
inheritanceLogs: [{ id: 2_147_483_647, year: 200, month: 4, text: '경계 로그', createdAt }],
inheritanceLogs: [{ id: 2_147_483_648n, year: 200, month: 4, text: '경계 로그', createdAt }],
});
await expect(appRouter.createCaller(fixture.context).inherit.getLogs({})).resolves.toEqual([
{ id: 2_147_483_647, year: 200, month: 4, text: '경계 로그', createdAt },
{ id: 2_147_483_648, year: 200, month: 4, text: '경계 로그', createdAt },
]);
expect(fixture.inheritanceLogFindMany).toHaveBeenCalledWith({
where: { userId: 'user-1' },
@@ -478,23 +478,26 @@ describe('inherit router actor and permission boundaries', () => {
const fixture = buildContext({ inheritanceLogs: [] });
const caller = appRouter.createCaller(fixture.context);
await expect(caller.inherit.getLogs({ lastId: 2_147_483_647 })).resolves.toEqual([]);
await expect(caller.inherit.getLogs({ lastId: 2_147_483_648 })).resolves.toEqual([]);
expect(fixture.inheritanceLogFindMany).toHaveBeenCalledWith({
where: { userId: 'user-1', id: { lt: 2_147_483_647 } },
where: { userId: 'user-1', id: { lt: 2_147_483_648 } },
orderBy: { id: 'desc' },
take: 30,
select: { id: true, year: true, month: true, text: true, createdAt: true },
});
});
it.each([0, -1, 1.5, 2_147_483_648])('rejects an invalid inheritance-log cursor: %s', async (lastId) => {
const fixture = buildContext({});
it.each([0, -1, 1.5, Number.MAX_SAFE_INTEGER + 1])(
'rejects an invalid inheritance-log cursor: %s',
async (lastId) => {
const fixture = buildContext({});
await expect(appRouter.createCaller(fixture.context).inherit.getLogs({ lastId })).rejects.toMatchObject({
code: 'BAD_REQUEST',
});
expect(fixture.inheritanceLogFindMany).not.toHaveBeenCalled();
});
await expect(appRouter.createCaller(fixture.context).inherit.getLogs({ lastId })).rejects.toMatchObject({
code: 'BAD_REQUEST',
});
expect(fixture.inheritanceLogFindMany).not.toHaveBeenCalled();
}
);
it('delegates the authenticated actor and maps a missing-general daemon rejection', async () => {
const fixture = buildContext({
@@ -31,6 +31,7 @@ const buildContext = (
) =>
({
auth: options.auth === undefined ? auth : options.auth,
profile: { id: 'che', name: 'che:default', scenario: 'default' },
db: {
general: {
findFirst: vi.fn(async () => ({
+18 -1
View File
@@ -33,9 +33,10 @@ type LogQuery = {
select: { id: true; text: true; createdAt: true };
};
const buildContext = (findMany: (query: LogQuery) => Promise<Array<{ id: number; text: string }>>) =>
const buildContext = (findMany: (query: LogQuery) => Promise<Array<{ id: number | bigint; text: string }>>) =>
({
auth,
profile: { id: 'che', name: 'che:default', scenario: 'default' },
db: {
general: {
findFirst: vi.fn(async ({ where }: { where: { userId: string } }) => ({
@@ -93,6 +94,22 @@ describe('general.getRecentRecords', () => {
});
});
it('returns exact numeric JSON cursors above int4 and trims a bigint cursor row', async () => {
const findMany = vi.fn(async () => [
{ id: 2_147_483_650n, text: '최신' },
{ id: 2_147_483_648n, text: '이전 cursor' },
]);
const caller = appRouter.createCaller(buildContext(findMany));
const result = await caller.general.getRecentRecords({
lastGeneralRecordId: 2_147_483_648,
lastWorldHistoryId: 2_147_483_648,
});
expect(result.global).toEqual([{ id: 2_147_483_650, text: '최신' }]);
expect(result.general).toEqual(result.global);
expect(result.history).toEqual(result.global);
expect(() => JSON.stringify(result)).not.toThrow();
});
it('caps an initial bucket at the legacy 15-row limit', async () => {
const rows = Array.from({ length: 16 }, (_, index) => ({
id: 100 - index,
@@ -0,0 +1,375 @@
import { afterAll, beforeAll, expect, it } from 'vitest';
import fastify from 'fastify';
import { fastifyTRPCPlugin } from '@trpc/server/adapters/fastify';
import { asRecord } from '@sammo-ts/common';
import {
decodeAuditDecisionSteps,
createGamePostgresConnector,
createRedisConnector,
GamePrisma,
} from '@sammo-ts/infra';
import { createTurnDaemonRuntime, seedScenarioToDatabase, type TurnDaemonRuntime } from '@sammo-ts/game-engine';
import { appRouter } from '../src/router.js';
import { DatabaseTurnDaemonTransport } from '../src/daemon/databaseTransport.js';
import { RedisAccessTokenStore } from '../src/auth/accessTokenStore.js';
import { InMemoryFlushStore } from '../src/auth/flushStore.js';
import type { GameApiContext } from '../src/context.js';
const databaseUrl = process.env.NPC_POLICY_DATABASE_URL;
const integration = it.skipIf(!databaseUrl || !process.env.REDIS_URL);
const connector = databaseUrl ? createGamePostgresConnector({ url: databaseUrl }) : null;
const redis = process.env.REDIS_URL ? createRedisConnector({ url: process.env.REDIS_URL }) : null;
let runtime: TurnDaemonRuntime | undefined;
let loop: Promise<void> | undefined;
const profile = `npc-policy:${databaseUrl ? new URL(databaseUrl).searchParams.get('schema') : 'fixture'}`;
const baseTime = new Date('0185-01-01T00:00:00Z');
beforeAll(async () => {
if (!databaseUrl) return;
if (!new URL(databaseUrl).searchParams.get('schema')?.endsWith('_npc_policy_fixture'))
throw new Error('Dedicated NPC policy fixture schema required');
await connector!.connect();
await redis!.connect();
});
afterAll(async () => {
if (loop) {
await runtime?.lifecycle.stop();
await loop;
}
await runtime?.close();
await connector?.disconnect();
await redis?.disconnect();
});
integration(
'HTTP user edits survive daemon restart and real NPC turns, with readable actor and before/after history',
async () => {
const db = connector!.prisma;
await db.playAuditPolicy.deleteMany({
where: {
OR: [
{ serverId: 'npc-policy-lifecycle' },
{ id: { in: ['c'.repeat(64), 'd'.repeat(64), 'e'.repeat(64)] } },
],
},
});
await db.playAuditMonth.deleteMany({ where: { serverId: 'npc-policy-lifecycle' } });
await db.playAuditDecisionChunk.deleteMany({ where: { decision: { serverId: 'npc-policy-lifecycle' } } });
await db.playAuditDecision.deleteMany({ where: { serverId: 'npc-policy-lifecycle' } });
await db.playAuditDiplomacyEvent.deleteMany({ where: { serverId: 'npc-policy-lifecycle' } });
await db.inputEvent.deleteMany({ where: { requestId: { startsWith: 'npc-policy-http-' } } });
await seedScenarioToDatabase({
scenarioId: 903,
databaseUrl: databaseUrl!,
now: new Date(),
installOptions: {
openAt: new Date(Date.now() + 86_400_000),
turnTermMinutes: 5,
npcMode: 2,
showImgLevel: 3,
serverId: 'npc-policy-lifecycle',
season: 1,
},
});
await db.generalTurn.deleteMany();
await db.nationTurn.deleteMany();
await db.general.deleteMany();
await db.nation.deleteMany();
await db.diplomacy.deleteMany();
// 185년 고정 fixture에 180년 시나리오의 지연 등장 이벤트를 이월하지 않는다.
// 일반턴·월간 재정/도시 갱신은 실제 runtime handler를 그대로 실행한다.
await db.event.deleteMany();
const city = await db.city.findFirstOrThrow({ orderBy: { id: 'asc' } });
const world = await db.worldState.findFirstOrThrow();
await db.worldState.update({
where: { id: world.id },
data: {
currentYear: 185,
currentMonth: 1,
clockBaseTime: baseTime,
clockTick: 0n,
lastTurnTick: 0n,
clockPhase: 'RUNNING',
clockMode: 'realtime',
clockWallAnchor: new Date(),
config: { ...asRecord(world.config), tournamentTrig: false },
},
});
await db.nation.create({
data: {
id: 1,
name: '정책국',
color: '#ffffff',
level: 3,
chiefGeneralId: 1,
capitalCityId: city.id,
gold: 100_000,
rice: 100_000,
tech: 3000,
meta: {},
},
});
await db.city.updateMany({ data: { nationId: 0 } });
await db.city.update({
where: { id: city.id },
data: {
nationId: 1,
population: 100_000,
populationMax: 200_000,
supplyState: 1,
frontState: 1,
meta: { trust: 80, trade: 100 },
},
});
await db.general.createMany({
data: [
{
id: 1,
userId: 'npc-policy-owner',
name: '정책군주',
nationId: 1,
cityId: city.id,
officerLevel: 12,
npcState: 0,
turnTime: new Date('0185-02-01Z'),
turnTick: 100_000_000n,
meta: { belong: 5, killturn: 24 },
},
{
id: 2,
name: '징병검증장',
nationId: 1,
cityId: city.id,
officerLevel: 5,
npcState: 2,
leadership: 80,
strength: 80,
intel: 30,
gold: 100_000,
rice: 100_000,
crew: 0,
turnTime: baseTime,
turnTick: 0n,
meta: { killturn: 24, armType: 1, dex1: 1000 },
},
],
});
const transport = new DatabaseTurnDaemonTransport(db, 10_000);
const auth: NonNullable<GameApiContext['auth']> = {
version: 1,
profile,
sessionId: 'fixture-session',
issuedAt: new Date().toISOString(),
expiresAt: '2999-01-01T00:00:00Z',
user: { id: 'npc-policy-owner', username: 'fixture', displayName: 'fixture', roles: [] },
sanctions: {},
};
const app = fastify();
let request = 0;
await app.register(fastifyTRPCPlugin, {
prefix: '/che/api/trpc',
trpcOptions: {
router: appRouter,
createContext: ({
req,
}: {
req: { headers: Record<string, string | string[] | undefined> };
}): GameApiContext => ({
db,
redis: redis!.client,
profile: { id: 'hwe', scenario: '903', name: profile },
auth: req.headers['x-session-token'] === 'fixture-session' ? auth : null,
requestId: `npc-policy-http-${++request}`,
turnDaemon: transport,
accessTokenStore: new RedisAccessTokenStore(redis!.client, profile),
flushStore: new InMemoryFlushStore(),
battleSim: {} as GameApiContext['battleSim'],
uploadDir: '/tmp',
uploadPath: '/uploads',
uploadPublicUrl: null,
gameTokenSecret: 'fixture-only',
}),
},
});
const actions: Array<{ kind: string; actionKey: string; generalId: number; completed?: boolean }> = [];
const start = async () => {
const instance = await createTurnDaemonRuntime({
profile,
databaseUrl: databaseUrl!,
enableLeaseHeartbeat: false,
onActionResolved: (action) => actions.push(action),
});
// 자연 진행은 정지하고, 사용자 command와 명시한 due 턴만 처리한다.
instance.lifecycle.pause('NPC policy fixture');
return instance;
};
const call = async (endpoint: string, input: unknown, mutation = false) => {
const response = await app.inject({
method: mutation ? 'POST' : 'GET',
url: `/che/api/trpc/npc.${endpoint}${mutation ? '' : `?input=${encodeURIComponent(JSON.stringify(input))}`}`,
headers: {
'x-session-token': 'fixture-session',
...(mutation ? { 'content-type': 'application/json' } : {}),
},
...(mutation ? { payload: JSON.stringify(input) } : {}),
});
expect(response.statusCode, response.body).toBe(200);
return response.json<{ result: { data: unknown } }>().result.data;
};
const configuration = (value: unknown) => {
const data = asRecord(value);
return {
values: data.currentNationPolicy,
nation: data.currentNationPriority,
general: data.currentGeneralActionPriority,
setters: data.lastSetters,
};
};
try {
runtime = await start();
loop = runtime.lifecycle.start();
// 발령과 징병을 목록에서 빼면 실제 턴에서도 수행하지 않아야 한다.
await call('setNationPriority', ['NPC포상'], true);
await call('setGeneralPriority', ['출병', '일반내정'], true);
await call(
'setNationPolicy',
{ minWarCrew: 2000, minNPCRecruitCityPopulation: 30000, safeRecruitCityPopulationRatio: 0 },
true
);
const withoutRecruitment = await call('getPolicy', {});
expect(withoutRecruitment).toMatchObject({
currentNationPriority: ['NPC포상'],
currentGeneralActionPriority: ['출병', '일반내정'],
});
await runtime.lifecycle.stop();
await loop;
loop = undefined;
await runtime.close();
runtime = await start();
expect(configuration(await call('getPolicy', {}))).toEqual(configuration(withoutRecruitment));
let result = await runtime.processor.run(baseTime, { budgetMs: 10_000, maxGenerals: 1, catchUpCap: 1 });
expect(result.processedGenerals).toBe(1);
expect(runtime.world.getGeneralById(2)!.crew).toBe(0);
expect(actions).toContainEqual(expect.objectContaining({ generalId: 2, kind: 'nation' }));
expect(
actions.filter((action) => action.generalId === 2).some((action) => action.actionKey === 'che_징병')
).toBe(false);
await runtime.hooks!.flushChanges!(result);
const nationDecision = await db.playAuditDecision.findFirstOrThrow({
where: { generalId: 2, phase: 'nation' },
include: { chunks: { orderBy: { ordinal: 'asc' } } },
});
const procedures = nationDecision.chunks.flatMap((chunk) =>
decodeAuditDecisionSteps(chunk.steps)
.map(asRecord)
.filter((step) => step.kind === 'PROCEDURE_START')
.map((step) => step.procedure)
);
expect(procedures).toEqual(['NPC포상']);
expect(configuration(await call('getPolicy', {}))).toEqual(configuration(withoutRecruitment));
// 같은 장수·자원으로 징병 우선순위를 맨 앞에 저장한 뒤 다시 시작한다.
loop = runtime.lifecycle.start();
await call('setGeneralPriority', ['징병', '출병', '일반내정'], true);
const saved = await call('getPolicy', {});
await runtime.lifecycle.stop();
await loop;
loop = undefined;
await runtime.close();
runtime = await start();
expect(configuration(await call('getPolicy', {}))).toEqual(configuration(saved));
const beforeMeta = asRecord(runtime.world.getNationById(1)!.meta);
// 실제 due 턴과 command를 실행한다. 전방의 중립 도시가 전쟁 상태를 만든다.
actions.length = 0;
result = await runtime.processor.run(runtime.world.getGeneralById(2)!.turnTime, {
budgetMs: 10_000,
maxGenerals: 1,
catchUpCap: 1,
});
expect(result.processedGenerals).toBe(1);
expect(runtime.world.getGeneralById(2)!.crew).toBeGreaterThan(0);
expect(actions).toContainEqual(
expect.objectContaining({ generalId: 2, actionKey: 'che_징병', completed: true })
);
await runtime.hooks!.flushChanges!(result);
expect((await db.general.findUniqueOrThrow({ where: { id: 2 } })).crew).toBeGreaterThan(0);
expect(asRecord(runtime.world.getNationById(1)!.meta).npc_nation_policy).toEqual(
beforeMeta.npc_nation_policy
);
expect(configuration(await call('getPolicy', {}))).toEqual(configuration(saved));
// 병력이 소진되고 도시 인구가 정책 하한 미만이면 징병을 거른다.
runtime.world.updateGeneral(2, { crew: 0 });
runtime.world.updateCity(city.id, { population: 30_100 });
actions.length = 0;
result = await runtime.processor.run(runtime.world.getGeneralById(2)!.turnTime, {
budgetMs: 10_000,
maxGenerals: 1,
catchUpCap: 1,
});
expect(result.processedGenerals).toBe(1);
expect(runtime.world.getGeneralById(2)!.crew).toBe(0);
expect(actions.some((action) => action.actionKey === 'che_징병')).toBe(false);
await runtime.hooks!.flushChanges!(result);
expect(configuration(await call('getPolicy', {}))).toEqual(configuration(saved));
// 이후의 개인턴/월간 갱신도 정책을 덮어쓰면 안 된다.
const target = new Date(runtime.world.getGeneralById(2)!.turnTime.getTime() + 30 * 60_000);
result = await runtime.processor.run(target, { budgetMs: 10_000, maxGenerals: 100, catchUpCap: 12 });
expect(result.processedGenerals).toBeGreaterThan(1);
await runtime.hooks!.flushChanges!(result);
expect(await call('getPolicy', {})).toMatchObject({
currentNationPriority: ['NPC포상'],
currentGeneralActionPriority: ['징병', '출병', '일반내정'],
currentNationPolicy: { minWarCrew: 2000, minNPCRecruitCityPopulation: 30000 },
});
expect(runtime.world.getState().meta.playAuditGap).toBeUndefined();
const history = await call('policyHistory', { area: 'NPC_NATION_PRIORITY' });
expect(history).toMatchObject({
items: [
expect.objectContaining({ source: 'CHANGE', actor: expect.objectContaining({ name: '정책군주' }) }),
expect.anything(),
],
});
const row = await db.playAuditPolicy.findFirstOrThrow({
where: { nationId: 1, area: 'NPC_NATION_PRIORITY', source: 'CHANGE' },
});
expect(await call('policyVersion', { id: row.id })).toMatchObject({
actor: { name: '정책군주' },
fields: [{ key: 'priority', beforeJson: 'null', afterJson: '["NPC포상"]', changed: true }],
});
expect(row.inputSequence).not.toBeNull();
expect((await db.inputEvent.findUniqueOrThrow({ where: { sequence: row.inputSequence! } })).status).toBe(
'SUCCEEDED'
);
// 외국/이전 기수/국방 정책 ID를 알아도 자국 NPC 정책으로 조회할 수 없다.
for (const [id, patch] of [
['c'.repeat(64), { nationId: 2 }],
['d'.repeat(64), { serverId: 'previous-season' }],
['e'.repeat(64), { area: 'DEFENCE' }],
] as const) {
await db.playAuditPolicy.create({
data: {
...row,
id,
...patch,
actor: row.actor ?? GamePrisma.DbNull,
before: row.before ?? GamePrisma.DbNull,
after: row.after ?? GamePrisma.JsonNull,
},
});
const response = await app.inject({
url: `/che/api/trpc/npc.policyVersion?input=${encodeURIComponent(JSON.stringify({ id }))}`,
headers: { 'x-session-token': 'fixture-session' },
});
expect(response.statusCode).toBe(404);
}
await db.general.update({ where: { id: 1 }, data: { penalty: { noChief: true } } });
const denied = await app.inject({
url: `/che/api/trpc/npc.policyHistory?input=${encodeURIComponent(JSON.stringify({ area: 'NPC_VALUES' }))}`,
headers: { 'x-session-token': 'fixture-session' },
});
expect(denied.statusCode).toBe(403);
} finally {
await app.close();
}
},
90_000
);
+154 -1
View File
@@ -1,4 +1,6 @@
import { describe, expect, it, vi } from 'vitest';
import fastify from 'fastify';
import { fastifyTRPCPlugin } from '@trpc/server/adapters/fastify';
import type { GameSessionTokenPayload } from '@sammo-ts/common/auth/gameToken';
import type { RedisConnector } from '@sammo-ts/infra';
@@ -96,10 +98,16 @@ const createContext = (
options: {
me?: GeneralRow;
nation?: typeof baseNation;
world?: typeof baseWorld;
world?: {
config: typeof baseWorld.config;
meta: Record<string, unknown>;
currentYear?: number;
currentMonth?: number;
};
requestCommand?: ReturnType<typeof vi.fn>;
troopRows?: Array<{ troopLeaderId: number }>;
cityRows?: Array<{ id: number }>;
historyRows?: Array<Record<string, unknown>>;
} = {}
): { context: GameApiContext; findFirst: ReturnType<typeof vi.fn>; requestCommand: ReturnType<typeof vi.fn> } => {
const requestCommand =
@@ -117,6 +125,11 @@ const createContext = (
worldState: { findFirst: vi.fn(async () => options.world ?? baseWorld) },
troop: { findMany: vi.fn(async () => options.troopRows ?? [{ troopLeaderId: 101 }]) },
city: { findMany: vi.fn(async () => options.cityRows ?? [{ id: 1 }, { id: 2 }]) },
playAuditPolicy: {
findMany: vi.fn(async () => options.historyRows ?? []),
findFirst: vi.fn(async () => options.historyRows?.[0] ?? null),
},
$transaction: async <T>(read: (tx: object) => Promise<T>): Promise<T> => read(db),
};
const redisClient = { get: async () => null, set: async () => null };
return {
@@ -140,6 +153,146 @@ const createContext = (
};
describe('NPC policy router', () => {
const historyRow = {
id: 'a'.repeat(64),
schemaVersion: 1,
nationId: 1,
area: 'NPC_NATION_PRIORITY',
revision: 2,
previousId: 'b'.repeat(64),
source: 'CHANGE',
year: 185,
month: 1,
createdAt: new Date('2026-01-01Z'),
actor: {
userId: 'private-user',
generalId: 22,
name: '정책담당',
nationId: 1,
officerLevel: 12,
npcState: 0,
permission: 4,
},
before: { priority: ['NPC전방발령', 'NPC포상'] },
after: { priority: ['NPC포상'] },
};
const historyContext = (options: Parameters<typeof createContext>[0] = {}) =>
createContext({
...options,
world: {
...baseWorld,
currentYear: 185,
currentMonth: 1,
meta: { ...baseWorld.meta, serverId: 'current-season' },
},
historyRows: options.historyRows ?? [historyRow],
});
it('lets an ordinary nation reader inspect the actor and changes without admin request/account fields', async () => {
const fixture = historyContext({ me: { ...baseGeneral, officerLevel: 2 } });
const caller = appRouter.createCaller(fixture.context);
const page = await caller.npc.policyHistory({ area: 'NPC_NATION_PRIORITY', limit: 1 });
expect(page.items[0]).toMatchObject({ actor: { name: '정책담당' }, revision: 2 });
const detail = await caller.npc.policyVersion({ id: historyRow.id });
expect(detail.fields).toEqual([
{ key: 'priority', beforeJson: '["NPC전방발령","NPC포상"]', afterJson: '["NPC포상"]', changed: true },
]);
expect(JSON.stringify(detail)).not.toMatch(/private-user|permission|requestId|inputSequence/);
});
it.each([
{ nationId: 0 },
{ officerLevel: 0 },
{ officerLevel: 1, meta: { belong: 0 } },
{ penalty: { noChief: true } },
])('denies history when current nation read permission is missing: %j', async (patch) => {
const fixture = historyContext({ me: { ...baseGeneral, ...patch } });
await expect(
appRouter.createCaller(fixture.context).npc.policyHistory({ area: 'NPC_VALUES' })
).rejects.toBeDefined();
});
it('scopes cursor and version lookups to the authenticated nation and current season', async () => {
const fixture = historyContext();
const caller = appRouter.createCaller(fixture.context);
await caller.npc.policyHistory({ area: 'NPC_VALUES', cursor: 7, limit: 1 });
const tx = await fixture.context.db.$transaction!(async (db) => db);
expect(tx.playAuditPolicy.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: { serverId: 'current-season', nationId: 1, area: 'NPC_VALUES', revision: { lt: 7 } },
take: 2,
})
);
await caller.npc.policyVersion({ id: historyRow.id });
expect(tx.playAuditPolicy.findFirst).toHaveBeenCalledWith(
expect.objectContaining({
where: {
id: historyRow.id,
serverId: 'current-season',
nationId: 1,
area: { in: ['NPC_VALUES', 'NPC_NATION_PRIORITY', 'NPC_GENERAL_PRIORITY'] },
},
})
);
await expect(caller.npc.policyHistory({ area: 'NPC_VALUES', limit: 51 })).rejects.toMatchObject({
code: 'BAD_REQUEST',
});
await expect(caller.npc.policyVersion({ id: 'bad' })).rejects.toMatchObject({ code: 'BAD_REQUEST' });
});
it('requires authentication and rejects caller-supplied nation or defence history over HTTP', async () => {
const fixture = historyContext();
const app = fastify();
await app.register(fastifyTRPCPlugin, {
prefix: '/che/api/trpc',
trpcOptions: {
router: appRouter,
createContext: ({ req }: { req: { headers: Record<string, string | string[] | undefined> } }) => ({
...fixture.context,
auth: req.headers['x-session-token'] === 'fixture-session' ? auth : null,
}),
},
});
try {
const query = (input: object, authenticated = true) =>
app.inject({
url: `/che/api/trpc/npc.policyHistory?input=${encodeURIComponent(JSON.stringify(input))}`,
headers: authenticated ? { 'x-session-token': 'fixture-session' } : {},
});
expect((await query({ area: 'NPC_VALUES' }, false)).statusCode).toBe(401);
expect((await query({ area: 'NPC_VALUES' })).statusCode).toBe(200);
expect((await query({ area: 'DEFENCE' })).statusCode).toBe(400);
expect((await query({ area: 'NPC_VALUES', nationId: 2 })).statusCode).toBe(400);
} finally {
await app.close();
}
});
it('denies sanctioned sessions before reading history', async () => {
const fixture = historyContext();
fixture.context.auth = { ...auth, sanctions: { suspendedUntil: '2999-01-01T00:00:00Z' } };
await expect(
appRouter.createCaller(fixture.context).npc.policyHistory({ area: 'NPC_VALUES' })
).rejects.toMatchObject({ code: 'FORBIDDEN' });
expect(fixture.findFirst).not.toHaveBeenCalled();
});
it('paginates revisions without exposing a missing or unavailable version', async () => {
const fixture = historyContext({ historyRows: [historyRow, { ...historyRow, revision: 1 }] });
const page = await appRouter
.createCaller(fixture.context)
.npc.policyHistory({ area: 'NPC_NATION_PRIORITY', limit: 1 });
expect(page.items).toHaveLength(1);
expect(page.nextCursor).toBe(2);
const missing = historyContext({ historyRows: [] });
await expect(
appRouter.createCaller(missing.context).npc.policyVersion({ id: historyRow.id })
).rejects.toMatchObject({ code: 'NOT_FOUND' });
const noIdentity = createContext();
await expect(
appRouter.createCaller(noIdentity.context).npc.policyHistory({ area: 'NPC_VALUES' })
).resolves.toMatchObject({ coverage: 'IDENTITY_MISSING', items: [], nextCursor: null });
});
it('loads server and nation overrides while calculating legacy zero-value hints from nation tech', async () => {
const fixture = createContext();
const result = await appRouter.createCaller(fixture.context).npc.getPolicy();
@@ -38,8 +38,8 @@ const buildContext = () => {
},
logEntry: {
findMany: vi.fn(async () => [
{ id: 9, text: '<Y>최근 정세</>' },
{ id: 8, text: '이전 정세' },
{ id: 9n, text: '<Y>최근 정세</>' },
{ id: 8n, text: '이전 정세' },
]),
},
$queryRaw: vi
+2 -2
View File
@@ -20,7 +20,7 @@ const profile: GameProfile = {
const auth: GameSessionTokenPayload = {
version: 1,
profile: 'che',
profile: 'che:default',
issuedAt: '2026-07-26T00:00:00.000Z',
expiresAt: '2026-07-27T00:00:00.000Z',
sessionId: 'ranking-session',
@@ -239,7 +239,7 @@ const buildContext = (options?: {
turnDaemon: new InMemoryTurnDaemonTransport(),
battleSim: new InMemoryBattleSimTransport(),
profile: selectedProfile,
auth: options?.authenticated === false ? null : auth,
auth: options?.authenticated === false ? null : { ...auth, profile: selectedProfile.name },
uploadDir: 'uploads',
uploadPath: '/uploads',
uploadPublicUrl: null,
@@ -45,6 +45,28 @@ const createFixture = (rows: readonly object[]) => {
};
describe('ReadModelOutboxWorker', () => {
it('drains more than one full retention batch rather than leaving a permanent 100-per-minute backlog', async () => {
let now = new Date('2026-11-09T00:00:00Z');
const fixture = createFixture([]);
fixture.queryRaw
.mockReset()
.mockResolvedValueOnce([])
.mockResolvedValueOnce([{ id: 1n }, { id: 2n }])
.mockResolvedValueOnce([{ id: 3n }, { id: 4n }])
.mockResolvedValueOnce([]);
const worker = new ReadModelOutboxWorker(fixture.db, fixture.redis, 'che:default', {
intervalMs: 60000,
pruneLimit: 2,
now: () => now,
});
now = new Date('2026-11-09T00:01:00Z');
worker.start();
await vi.waitFor(() => expect(fixture.queryRaw).toHaveBeenCalledTimes(4));
await worker.stop();
const query = fixture.queryRaw.mock.calls[1]?.[0] as { sql: string };
expect(query.sql).toContain('FOR UPDATE SKIP LOCKED');
expect(query.sql).toContain('ORDER BY "delivered_at", "available_at", "id"');
});
it('publishes a survey-style global front-status invalidation without a turn daemon', async () => {
const fixture = createFixture([{ id: 10n, payload: payload('front.global'), attempts: 1 }]);
const worker = new ReadModelOutboxWorker(fixture.db, fixture.redis, 'che:default', {
+23 -26
View File
@@ -69,8 +69,7 @@ const buildDb = (autorunLimit: number | null = null) => {
},
createMany: async ({ data }: GeneralTurnCreateManyArgs) => {
const dataList = (Array.isArray(data) ? data : [data]) as Record<string, unknown>[];
const rows: GeneralTurnRow[] = dataList.map((row, index: number) => ({
id: index + 1,
const rows: GeneralTurnRow[] = dataList.map((row) => ({
generalId: row.generalId as number,
turnIdx: row.turnIdx as number,
actionCode: row.actionCode as string,
@@ -136,8 +135,7 @@ const buildDb = (autorunLimit: number | null = null) => {
},
createMany: async ({ data }: NationTurnCreateManyArgs) => {
const dataList = (Array.isArray(data) ? data : [data]) as Record<string, unknown>[];
const rows: NationTurnRow[] = dataList.map((row, index: number) => ({
id: index + 1,
const rows: NationTurnRow[] = dataList.map((row) => ({
nationId: row.nationId as number,
officerLevel: row.officerLevel as number,
turnIdx: row.turnIdx as number,
@@ -203,26 +201,27 @@ const buildDb = (autorunLimit: number | null = null) => {
describe('reservedTurns', () => {
it('loads multiple nation officer queues with two batched queries and preserves defaults', async () => {
const findTurns = vi.fn(async () => [
{
id: 1,
nationId: 4,
officerLevel: 12,
turnIdx: 1,
actionCode: 'che_징병',
arg: { amount: 100 },
createdAt: new Date(),
},
{
id: 2,
nationId: 4,
officerLevel: 10,
turnIdx: 0,
actionCode: 'che_훈련',
arg: {},
createdAt: new Date(),
},
] satisfies NationTurnRow[]);
const findTurns = vi.fn(
async () =>
[
{
nationId: 4,
officerLevel: 12,
turnIdx: 1,
actionCode: 'che_징병',
arg: { amount: 100 },
createdAt: new Date(),
},
{
nationId: 4,
officerLevel: 10,
turnIdx: 0,
actionCode: 'che_훈련',
arg: {},
createdAt: new Date(),
},
] satisfies NationTurnRow[]
);
const findRevisions = vi.fn(async () => [
{ nationId: 4, officerLevel: 12, revision: 7, updatedAt: new Date() },
]);
@@ -411,7 +410,6 @@ describe('reservedTurns', () => {
nationRevisions.set('6:12', 2);
nationTurns.set('6:12', [
{
id: 1,
nationId: 6,
officerLevel: 12,
turnIdx: 0,
@@ -420,7 +418,6 @@ describe('reservedTurns', () => {
createdAt: new Date(),
},
{
id: 2,
nationId: 6,
officerLevel: 12,
turnIdx: 1,
+7 -10
View File
@@ -901,7 +901,6 @@ describe('appRouter', () => {
const general = buildGeneralRow({ id: 11, meta: { autorun_limit: 2408 } });
const generalTurns: GeneralTurnRow[] = [
{
id: 1,
generalId: 11,
turnIdx: 0,
actionCode: 'che_화계',
@@ -922,7 +921,6 @@ describe('appRouter', () => {
const general = buildGeneralRow({ id: 12, nationId: 3, officerLevel: 5 });
const nationTurns: NationTurnRow[] = [
{
id: 1,
nationId: 3,
officerLevel: 5,
turnIdx: 0,
@@ -1008,7 +1006,6 @@ describe('appRouter', () => {
general,
generalTurns: [
{
id: 1,
generalId: general.id,
turnIdx: 0,
actionCode: 'che_훈련',
@@ -1016,7 +1013,6 @@ describe('appRouter', () => {
createdAt: new Date(),
},
{
id: 2,
generalId: general.id,
turnIdx: 1,
actionCode: 'che_사기진작',
@@ -1110,7 +1106,10 @@ describe('appRouter', () => {
expect(nationWrites).toHaveLength(2);
});
it('stores Ref-sanitized nation command strings in the reserved queue', async () => {
it.each([
[' <신-국># ', '&lt;신국&gt;'],
['풍년F&B', '풍년F&B'],
])('stores the sanitized nation name %s in the reserved queue as %s', async (input, stored) => {
const general = buildGeneralRow({ id: 19, nationId: 3, officerLevel: 12 });
const nationWrites: unknown[] = [];
const caller = appRouter.createCaller(
@@ -1121,16 +1120,14 @@ describe('appRouter', () => {
generalId: general.id,
turnIndex: 0,
action: 'che_국호변경',
args: { nationName: ' <신-국># ' },
args: { nationName: input },
expectedRevision: 0,
});
expect(response.turns[0]?.args).toEqual({ nationName: '&lt;신국&gt;' });
expect(response.turns[0]?.args).toEqual({ nationName: stored });
expect(nationWrites).toHaveLength(1);
expect(nationWrites[0]).toMatchObject({
data: expect.arrayContaining([
expect.objectContaining({ turnIdx: 0, arg: { nationName: '&lt;신국&gt;' } }),
]),
data: expect.arrayContaining([expect.objectContaining({ turnIdx: 0, arg: { nationName: stored } })]),
});
});
@@ -13,6 +13,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
import { encryptGameSessionToken, type GameSessionTokenPayload } from '@sammo-ts/common/auth/gameToken';
import {
createGamePostgresConnector,
encodeAuditDecisionSteps,
GamePrisma,
hashAuditDiplomacyDocument,
createRedisConnector,
@@ -70,6 +71,7 @@ const envKeys = [
'GATEWAY_REDIS_PREFIX',
'GATEWAY_INTERNAL_API_URL',
'GAME_UPLOAD_DIR',
'API_ALLOWED_ORIGINS',
] as const;
const originalEnv = new Map(envKeys.map((key) => [key, process.env[key]]));
@@ -642,6 +644,7 @@ integration('game API security over HTTP transport', () => {
process.env.GATEWAY_REDIS_PREFIX = redisPrefix;
process.env.GATEWAY_INTERNAL_API_URL = await listenGatewayStatusStub();
process.env.GAME_UPLOAD_DIR = uploadDir;
process.env.API_ALLOWED_ORIGINS = 'https://sam.hided.net';
const connector = createGamePostgresConnector({ url: dedicatedTarget.databaseUrl });
await connector.connect();
@@ -966,7 +969,7 @@ integration('game API security over HTTP transport', () => {
const telemetryAfter = await readAccessTelemetryState();
expect(telemetryAfter.periods).toEqual([
{
id: expect.any(Number),
id: expect.any(BigInt),
worldStateId: fixtureWorldId,
year: 190,
month: 1,
@@ -989,7 +992,7 @@ integration('game API security over HTTP transport', () => {
]);
expect(telemetryAfter.accessLogs).toEqual([
{
id: expect.any(Number),
id: expect.any(BigInt),
generalId,
userId,
lastRefresh: trafficPeriod.lastRefresh,
@@ -1545,8 +1548,8 @@ integration('game API security over HTTP transport', () => {
arg,
}))
).toEqual(databaseAfter.generalTurns);
expect(new Set(committedGeneralTurns.map(({ id }) => id)).size).toBe(30);
expect(committedGeneralTurns.every(({ id, createdAt }) => id > 0 && createdAt instanceof Date)).toBe(true);
expect(new Set(committedGeneralTurns.map(({ generalId, turnIdx }) => `${generalId}:${turnIdx}`)).size).toBe(30);
expect(committedGeneralTurns.every(({ createdAt }) => createdAt instanceof Date)).toBe(true);
expect(allowedTablesAfter.generalTurnRevisions.filter((row) => row.generalId !== generalId)).toEqual(
allowedTablesBefore.generalTurnRevisions.filter((row) => row.generalId !== generalId)
);
@@ -1564,7 +1567,7 @@ integration('game API security over HTTP transport', () => {
);
expect(allowedTablesAfter.generalAccessLogs.filter((row) => row.generalId === generalId)).toEqual([
{
id: expect.any(Number),
id: expect.any(BigInt),
generalId,
userId,
lastRefresh: null,
@@ -1730,8 +1733,14 @@ integration('game API security over HTTP transport', () => {
arg,
}))
).toEqual(expectedTurns);
expect(new Set(committedNationTurns.map(({ id }) => id)).size).toBe(12);
expect(committedNationTurns.every(({ id, createdAt }) => id > 0 && createdAt instanceof Date)).toBe(true);
expect(
new Set(
committedNationTurns.map(
({ nationId, officerLevel, turnIdx }) => `${nationId}:${officerLevel}:${turnIdx}`
)
).size
).toBe(12);
expect(committedNationTurns.every(({ createdAt }) => createdAt instanceof Date)).toBe(true);
expect(
allowedTablesAfter.nationTurnRevisions.filter(
(row) => row.nationId !== ownerNationId || row.officerLevel !== 5
@@ -1760,7 +1769,7 @@ integration('game API security over HTTP transport', () => {
);
expect(allowedTablesAfter.generalAccessLogs.filter((row) => row.generalId === sameNationGeneralId)).toEqual([
{
id: expect.any(Number),
id: expect.any(BigInt),
generalId: sameNationGeneralId,
userId: sameNationUserId,
lastRefresh: null,
@@ -1877,8 +1886,14 @@ integration('game API security over HTTP transport', () => {
arg,
}))
).toEqual(committed.nationTurns);
expect(new Set(committedNationTurns.map(({ id }) => id)).size).toBe(12);
expect(committedNationTurns.every(({ id, createdAt }) => id > 0 && createdAt instanceof Date)).toBe(true);
expect(
new Set(
committedNationTurns.map(
({ nationId, officerLevel, turnIdx }) => `${nationId}:${officerLevel}:${turnIdx}`
)
).size
).toBe(12);
expect(committedNationTurns.every(({ createdAt }) => createdAt instanceof Date)).toBe(true);
expect(
allowedTablesAfter.nationTurnRevisions.filter(
(row) => row.nationId !== ownerNationId || row.officerLevel !== 12
@@ -1907,7 +1922,7 @@ integration('game API security over HTTP transport', () => {
);
expect(allowedTablesAfter.generalAccessLogs.filter((row) => row.generalId === generalId)).toEqual([
{
id: expect.any(Number),
id: expect.any(BigInt),
generalId,
userId,
lastRefresh: null,
@@ -2343,50 +2358,52 @@ integration('game API security over HTTP transport', () => {
{
decisionId: decisionIds[0]!,
ordinal: 0,
steps: Array.from({ length: 128 }, (_, sequence) =>
sequence === 127
? {
...step,
sequence,
kind: 'DECISION_START',
reservedAction: '휴식',
effectivePolicy: {
schemaVersion: 1,
general: { priority: ['징병'], flags: { 징병: true, 출병: false } },
nation: {
priority: ['천도'],
flags: { 천도: true },
values: {
reqNationGold: 4321,
reqNationRice: 100,
reqHumanWarUrgentGold: 100,
reqHumanWarUrgentRice: 100,
reqHumanWarRecommandGold: 100,
reqHumanWarRecommandRice: 100,
reqHumanDevelGold: 100,
reqHumanDevelRice: 100,
reqNpcWarGold: 100,
reqNpcWarRice: 100,
reqNpcDevelGold: 100,
reqNpcDevelRice: 100,
minimumResourceActionAmount: 100,
maximumResourceActionAmount: 100,
minNpcWarLeadership: 100,
minWarCrew: 100,
minNpcRecruitCityPopulation: 100,
safeRecruitCityPopulationRatio: 100,
properWarTrainAtmos: 100,
cureThreshold: 100,
steps: encodeAuditDecisionSteps(
Array.from({ length: 128 }, (_, sequence) =>
sequence === 127
? {
...step,
sequence,
kind: 'DECISION_START',
reservedAction: '휴식',
effectivePolicy: {
schemaVersion: 1,
general: { priority: ['징병'], flags: { 징병: true, 출병: false } },
nation: {
priority: ['천도'],
flags: { 천도: true },
values: {
reqNationGold: 4321,
reqNationRice: 100,
reqHumanWarUrgentGold: 100,
reqHumanWarUrgentRice: 100,
reqHumanWarRecommandGold: 100,
reqHumanWarRecommandRice: 100,
reqHumanDevelGold: 100,
reqHumanDevelRice: 100,
reqNpcWarGold: 100,
reqNpcWarRice: 100,
reqNpcDevelGold: 100,
reqNpcDevelRice: 100,
minimumResourceActionAmount: 100,
maximumResourceActionAmount: 100,
minNpcWarLeadership: 100,
minWarCrew: 100,
minNpcRecruitCityPopulation: 100,
safeRecruitCityPopulationRatio: 100,
properWarTrainAtmos: 100,
cureThreshold: 100,
},
combatForce: { '1': [2, 3] },
supportForce: [4],
developForce: [5],
secret: 'decision-secret',
},
combatForce: { '1': [2, 3] },
supportForce: [4],
developForce: [5],
secret: 'decision-secret',
},
secret: 'decision-secret',
},
}
: { ...step, sequence }
}
: { ...step, sequence }
)
),
},
{
@@ -2863,7 +2880,7 @@ integration('game API security over HTTP transport', () => {
result: {
data: {
coverage: 'IDENTIFIED_LOGS_ONLY',
items: [{ id: ownLogs[index]!.id }],
items: [{ id: Number(ownLogs[index]!.id) }],
nextCursor: null,
},
},
@@ -2872,17 +2889,19 @@ integration('game API security over HTTP transport', () => {
}
expect(
(await get('generalLogs', admin, { generalId: logGeneralId, type: 'generalHistory', limit: 1 })).body
).toMatchObject({ result: { data: { items: [{ id: latest.id }], nextCursor: latest.id } } });
).toMatchObject({
result: { data: { items: [{ id: Number(latest.id) }], nextCursor: Number(latest.id) } },
});
expect(
(
await get('generalLogs', admin, {
generalId: logGeneralId,
type: 'generalHistory',
limit: 1,
cursor: latest.id,
cursor: Number(latest.id),
})
).body
).toMatchObject({ result: { data: { items: [{ id: ownLogs[0]!.id }], nextCursor: null } } });
).toMatchObject({ result: { data: { items: [{ id: Number(ownLogs[0]!.id) }], nextCursor: null } } });
for (const invalid of [
{ limit: 201 },
{ cursor: 0 },
@@ -3774,6 +3793,58 @@ integration('game API security over HTTP transport', () => {
}
}, 15_000);
it('rejects an untrusted browser Origin before an authenticated logout mutation', async () => {
const token = await createAccessToken('origin-mutation', {});
const response = await fetch(`${baseUrl}/trpc/auth.logout`, {
method: 'POST',
headers: {
authorization: `Bearer ${token}`,
origin: 'https://untrusted.example',
'content-type': 'application/json',
},
body: JSON.stringify({}),
});
expect(response.status).toBe(403);
expect(response.headers.get('access-control-allow-origin')).toBeNull();
expect(await accessTokenStore.get(token)).not.toBeNull();
for (const origin of ['https://sam.hided.net', 'https://untrusted.example', 'null']) {
const preflight = await fetch(`${baseUrl}/trpc/auth.logout`, {
method: 'OPTIONS',
headers: {
origin,
'access-control-request-method': 'POST',
'access-control-request-headers': 'authorization,content-type',
},
});
expect(preflight.status).toBe(origin === 'https://sam.hided.net' ? 204 : 403);
expect(preflight.headers.get('access-control-allow-origin')).toBe(
origin === 'https://sam.hided.net' ? origin : null
);
}
await accessTokenStore.revoke(token);
});
it('rejects a same-namespace foreign-profile token over tRPC before any DB mutation', async () => {
const foreign = await accessTokenStore.create({
...buildPayload('trpc-foreign', {}),
profile: 'other:default',
});
if (!foreign) throw new Error('Foreign token fixture failed');
const before = await readReservedMutationState();
try {
const response = await fetch(
`${baseUrl}/trpc/turns.reserved.getGeneral?input=${encodeURIComponent(JSON.stringify({ generalId }))}`,
{
headers: { authorization: `Bearer ${foreign.accessToken}` },
}
);
expect(response.status).toBe(401);
expect(await readReservedMutationState()).toEqual(before);
} finally {
await accessTokenStore.revoke(foreign.accessToken);
}
});
it('SSE accepts header auth and rejects query or cross-profile credentials', async () => {
const token = await createAccessToken('sse-query', {});
const queryOnly = await fetch(`${baseUrl}${server!.config.eventsPath}?token=${encodeURIComponent(token)}`);
+99 -35
View File
@@ -76,35 +76,21 @@ class TournamentTransport implements TurnDaemonTransport {
async requestCommand(command: TurnDaemonCommand): Promise<TurnDaemonCommandResult | null> {
this.commands.push(command);
if (command.type === 'adjustGeneralResources') {
const adjustment = command.adjustments[0];
if (!adjustment) {
return { type: 'adjustGeneralResources', ok: false, reason: '조정 대상이 없습니다.' };
if (command.type === 'tournamentAdjustGeneral') {
if (command.betGoldDelta !== undefined && this.failNextRankUpdate) {
this.failNextRankUpdate = false;
return { type: command.type, ok: false, code: 'BAD_REQUEST', reason: 'rank update failed' };
}
const nextGold = (this.gold.get(adjustment.generalId) ?? 0) + (adjustment.goldDelta ?? 0);
if (nextGold < (adjustment.minGoldAfter ?? 0)) {
return { type: 'adjustGeneralResources', ok: false, reason: '자원이 부족합니다.' };
const nextGold = (this.gold.get(command.generalId) ?? 0) + command.goldDelta;
if (nextGold < command.minGoldAfter) {
return { type: command.type, ok: false, code: 'BAD_REQUEST', reason: '자원이 부족합니다.' };
}
this.gold.set(adjustment.generalId, nextGold);
return {
type: 'adjustGeneralResources',
ok: true,
processed: 1,
missing: 0,
totalGoldDelta: adjustment.goldDelta ?? 0,
totalRiceDelta: 0,
};
this.gold.set(command.generalId, nextGold);
return { type: command.type, ok: true, generalId: command.generalId };
}
if (command.type === 'setMySetting') {
return { type: 'setMySetting', ok: true, generalId: command.generalId };
}
if (command.type === 'adjustGeneralMeta') {
if (this.failNextRankUpdate) {
this.failNextRankUpdate = false;
return { type: 'adjustGeneralMeta', ok: false, reason: 'rank update failed' };
}
return { type: 'adjustGeneralMeta', ok: true, processed: 1, missing: 0 };
}
return null;
}
@@ -404,12 +390,12 @@ describe('tournament router permissions and mutations', () => {
await expect(caller.tournament.join()).resolves.toEqual({ ok: true, count: 1 });
expect(transport.gold.get(general.id)).toBe(1_800);
expect(transport.commands.filter((command) => command.type === 'adjustGeneralResources')).toHaveLength(1);
expect(transport.commands.filter((command) => command.type === 'tournamentAdjustGeneral')).toHaveLength(1);
expect(transport.commands).toContainEqual(
expect.objectContaining({
type: 'adjustGeneralResources',
type: 'tournamentAdjustGeneral',
requestId: 'http:tournament-join:tournamentJoin:resources',
reason: 'tournamentJoin',
userId: 'user-1',
})
);
expect(outerApiTransaction).not.toHaveBeenCalled();
@@ -459,9 +445,12 @@ describe('tournament router permissions and mutations', () => {
await expect(caller.tournament.join()).resolves.toEqual({ ok: true, count: 1 });
expect(transport.gold.get(general.id)).toBe(1_936);
expect(transport.commands).toContainEqual({
type: 'adjustGeneralResources',
type: 'tournamentAdjustGeneral',
userId: 'user-1',
reason: 'tournamentJoin',
adjustments: [{ generalId: general.id, goldDelta: -64, minGoldAfter: 0 }],
generalId: general.id,
goldDelta: -64,
minGoldAfter: 0,
});
});
@@ -534,21 +523,96 @@ describe('tournament router permissions and mutations', () => {
expect((await caller.tournament.getBettingSummary()).myAmount).toBe(600);
expect(transport.commands).toContainEqual(
expect.objectContaining({
type: 'adjustGeneralResources',
type: 'tournamentAdjustGeneral',
requestId: 'http:suspended-tournament-bet:tournamentBet:resources',
reason: 'tournamentBet',
userId: 'user-1',
})
);
expect(outerApiTransaction).not.toHaveBeenCalled();
expect(transport.commands).toContainEqual(
expect.objectContaining({
type: 'adjustGeneralMeta',
requestId: 'http:suspended-tournament-bet:tournamentBet:rank',
reason: 'tournamentBet',
type: 'tournamentAdjustGeneral',
userId: 'user-1',
betGoldDelta: 600,
})
);
});
it("keeps the per-user cap across possession and separates a previous owner's bets", async () => {
const redis = new MemoryRedis();
const transport = new TournamentTransport();
const general = buildGeneral(1, 'user-2', 3_000);
transport.gold.set(general.id, general.gold);
await setTournamentFixture(redis, {
stage: 6,
phase: 0,
type: 0,
auto: true,
openYear: 193,
openMonth: 1,
termSeconds: 60,
nextAt: '2026-07-26T01:00:00.000Z',
bettingCloseAt: '2099-01-01T00:00:00.000Z',
});
await redis.set(
'sammo:che:default:tournament:betting',
JSON.stringify([
{ generalId: 1, userId: 'user-1', targetId: 11, amount: 900 },
{ generalId: 99, userId: 'user-2', targetId: 12, amount: 800 },
{ generalId: 98, userId: null, targetId: 11, amount: 100 },
])
);
const caller = appRouter.createCaller(
buildContext({ redis, transport, generals: [general], userId: 'user-2' })
);
expect(await caller.tournament.getBettingSummary()).toMatchObject({
myAmount: 800,
myTotals: { 12: 800 },
totalAmount: 1_800,
});
await expect(caller.tournament.placeBet({ targetId: 11, amount: 300 })).rejects.toMatchObject({
code: 'BAD_REQUEST',
});
expect(transport.commands).toHaveLength(0);
await expect(caller.tournament.placeBet({ targetId: 11, amount: 200 })).resolves.toEqual({ ok: true });
expect(await caller.tournament.getBettingSummary()).toMatchObject({
myAmount: 1_000,
myTotals: { 11: 200, 12: 800 },
});
expect(transport.gold.get(1)).toBe(2_800);
});
it('does not infer a legacy bet actor from the current general owner', async () => {
const redis = new MemoryRedis();
const transport = new TournamentTransport();
const general = buildGeneral(1, 'user-2', 3_000);
transport.gold.set(1, 3_000);
await setTournamentFixture(redis, {
stage: 6,
phase: 0,
type: 0,
auto: true,
openYear: 193,
openMonth: 1,
termSeconds: 60,
nextAt: '2026-07-26T01:00:00.000Z',
bettingCloseAt: '2099-01-01T00:00:00.000Z',
});
await redis.set(
'sammo:che:default:tournament:betting',
JSON.stringify([{ generalId: 1, targetId: 11, amount: 900 }])
);
const caller = appRouter.createCaller(
buildContext({ redis, transport, generals: [general], userId: 'user-2' })
);
expect(await caller.tournament.getBettingSummary()).toMatchObject({ myAmount: 0, totalAmount: 900 });
await expect(caller.tournament.placeBet({ targetId: 11, amount: 10 })).rejects.toMatchObject({
code: 'BAD_REQUEST',
});
expect(transport.commands).toHaveLength(0);
expect(transport.gold.get(1)).toBe(3_000);
});
it('rejects a tournament bet during reconciliation without debiting gold', async () => {
const redis = new MemoryRedis();
const transport = new TournamentTransport();
@@ -796,7 +860,7 @@ describe('tournament router permissions and mutations', () => {
expect(snapshot.sourceRevision).toBe('41');
});
it('refunds gold when the tournament bet rank update fails', async () => {
it('does not debit gold when the atomic tournament adjustment is rejected', async () => {
const redis = new MemoryRedis();
const transport = new TournamentTransport();
const general = buildGeneral(1, 'user-1', 2_000);
@@ -818,7 +882,7 @@ describe('tournament router permissions and mutations', () => {
);
await expect(caller.tournament.placeBet({ targetId: 11, amount: 100 })).rejects.toMatchObject({
code: 'INTERNAL_SERVER_ERROR',
code: 'BAD_REQUEST',
});
expect(transport.gold.get(general.id)).toBe(2_000);
await expect(caller.tournament.getBettingSummary()).resolves.toMatchObject({
+55 -30
View File
@@ -53,7 +53,15 @@ const isRecord = (value: unknown): value is Record<string, unknown> => typeof va
const createNoopDaemonTransport = (): TurnDaemonTransport => ({
sendCommand: async () => 'ok',
requestCommand: async () => null,
requestCommand: async (command) =>
command.type === 'tournamentSeedNpcBets'
? {
type: command.type,
ok: true,
processedGeneralIds: command.bets.map((bet) => bet.generalId),
skippedGeneralIds: [],
}
: null,
requestStatus: async () => null,
});
@@ -440,10 +448,10 @@ describe('tournament worker (in-memory)', () => {
const commands: TurnDaemonCommand[] = [];
const daemonTransport: TurnDaemonTransport = {
...createNoopDaemonTransport(),
sendCommand: async (command) => {
requestCommand: async (command) => {
expect((await store.getState())?.stage).toBe(5);
commands.push(command);
return 'ok';
return createNoopDaemonTransport().requestCommand(command);
},
};
const opened = await applyPreBattleStage(store, prisma, state, 'opening-seed', daemonTransport);
@@ -455,21 +463,14 @@ describe('tournament worker (in-memory)', () => {
expect(new Set(bets.slice(1).map((bet) => bet.targetId)).size).toBeGreaterThan(1);
expect(commands).toEqual([
{
type: 'adjustGeneralResources',
requestId: 'tournament:123:npc-bet:resources',
reason: 'tournamentNpcBet',
adjustments: [3, 4, 5, 6, 7].map((generalId) => ({ generalId, goldDelta: -amount })),
},
{
type: 'adjustGeneralMeta',
requestId: 'tournament:123:npc-bet:meta',
reason: 'tournamentNpcBet',
adjustments: [3, 4, 5, 6, 7].map((generalId) => ({ generalId, metaDelta: { betgold: amount } })),
type: 'tournamentSeedNpcBets',
requestId: 'tournament:123:npc-bet:atomic',
bets: [3, 4, 5, 6, 7].map((generalId) => ({ generalId, amount })),
},
]);
await seedNpcBets({ prisma, store, state: opened, baseSeed: 'opening-seed', daemonTransport });
expect(await store.getBettingEntries()).toEqual(bets);
expect(commands).toHaveLength(2);
expect(commands).toHaveLength(1);
// A fresh projection with the same seed and DB inputs has the same choices.
await store.setBettingEntries([bets[0]!]);
await seedNpcBets({
@@ -482,6 +483,32 @@ describe('tournament worker (in-memory)', () => {
expect(await store.getBettingEntries()).toEqual(bets);
});
it('publishes only NPC bets acknowledged after the current-owner check', async () => {
const store = new TournamentStore(new MemoryRedis(), buildTournamentKeys('npc-owned-after-plan'));
const state = createTournamentState({
stage: 5,
bettingId: 789,
npcBettingPlan: [
{ generalId: 3, userId: null, targetId: 11, amount: 10 },
{ generalId: 4, userId: null, targetId: 12, amount: 10 },
],
});
await store.setState(state);
await store.setMatches([{ id: 1, stage: 7, roundIndex: 0, attackerId: 11, defenderId: 12 }]);
const transport: TurnDaemonTransport = {
...createNoopDaemonTransport(),
requestCommand: async (command) => {
expect(command.type).toBe('tournamentSeedNpcBets');
expect((await store.getState())?.stage).toBe(5);
expect(await store.getBettingEntries()).toEqual([]);
return { type: 'tournamentSeedNpcBets', ok: true, processedGeneralIds: [4], skippedGeneralIds: [3] };
},
};
const opened = await applyPreBattleStage(store, createPrismaMock({}), state, 'seed', transport);
expect(opened.stage).toBe(6);
expect(await store.getBettingEntries()).toEqual([{ generalId: 4, userId: null, targetId: 12, amount: 10 }]);
});
it('retries an opening query failure without advancing stage or changing the betting identity', async () => {
const store = new TournamentStore(new MemoryRedis(), buildTournamentKeys('npc-opening-retry'));
const state = createTournamentState({ stage: 5 });
@@ -509,7 +536,7 @@ describe('tournament worker (in-memory)', () => {
expect(await store.getBettingEntries()).toHaveLength(1);
});
it('reuses durable command identities after a partial enqueue failure', async () => {
it('reuses durable command identities after an uncertain atomic command response', async () => {
const store = new TournamentStore(new MemoryRedis(), buildTournamentKeys('npc-enqueue-retry'));
const state = createTournamentState({ stage: 5, bettingId: 456 });
await store.setState(state);
@@ -523,15 +550,15 @@ describe('tournament worker (in-memory)', () => {
let fail = true;
const transport: TurnDaemonTransport = {
...createNoopDaemonTransport(),
sendCommand: async (command) => {
requestCommand: async (command) => {
commands.push(command);
if (command.type === 'adjustGeneralMeta' && fail) {
if (command.type === 'tournamentSeedNpcBets' && fail) {
fail = false;
// The accepted debit may already have committed before retry.
prisma.general.findMany = async () => [];
throw new Error('enqueue unavailable');
}
return 'ok';
return createNoopDaemonTransport().requestCommand(command);
},
};
await expect(applyPreBattleStage(store, prisma, state, 'seed', transport)).rejects.toThrow(
@@ -539,16 +566,14 @@ describe('tournament worker (in-memory)', () => {
);
expect(await store.getState()).toMatchObject({
stage: 5,
npcBettingPlan: [{ generalId: 3, targetId: expect.any(Number), amount: 10 }],
npcBettingPlan: [{ generalId: 3, userId: null, targetId: expect.any(Number), amount: 10 }],
});
expect(await store.getBettingEntries()).toEqual([]);
await applyPreBattleStage(store, prisma, (await store.getState())!, 'seed', transport);
expect(commands.slice(2)).toEqual(commands.slice(0, 2));
expect(commands.slice(1)).toEqual(commands.slice(0, 1));
expect(commands.map((command) => command.requestId)).toEqual([
'tournament:456:npc-bet:resources',
'tournament:456:npc-bet:meta',
'tournament:456:npc-bet:resources',
'tournament:456:npc-bet:meta',
'tournament:456:npc-bet:atomic',
'tournament:456:npc-bet:atomic',
]);
expect(await store.getBettingEntries()).toHaveLength(1);
});
@@ -577,7 +602,10 @@ describe('tournament worker (in-memory)', () => {
commands.push(command);
return 'ok';
},
requestCommand: async () => null,
requestCommand: async (command) => {
commands.push(command);
return createNoopDaemonTransport().requestCommand(command);
},
requestStatus: async () => null,
};
@@ -598,11 +626,8 @@ describe('tournament worker (in-memory)', () => {
expect(rankedGeneralIds.size).toBeGreaterThanOrEqual(10);
expect(commands).toContainEqual(
expect.objectContaining({
type: 'adjustGeneralMeta',
reason: 'tournamentNpcBet',
adjustments: expect.arrayContaining([
expect.objectContaining({ metaDelta: { betgold: expect.any(Number) } }),
]),
type: 'tournamentSeedNpcBets',
bets: expect.arrayContaining([expect.objectContaining({ amount: expect.any(Number) })]),
})
);
}
+5 -1
View File
@@ -3,7 +3,11 @@
"compilerOptions": {
"rootDir": "src",
"outDir": "dist",
"composite": false
"composite": false,
"paths": {
"@sammo-ts/game-api": ["./src/index.ts"],
"@sammo-ts/game-api/*": ["./src/*"]
}
},
"include": ["src"]
}
+5 -3
View File
@@ -1,3 +1,4 @@
import { existingRowIdOrNext } from '@sammo-ts/infra';
import { resolveMessageTargetIcon } from '@sammo-ts/logic';
import { randomUUID } from 'node:crypto';
@@ -580,8 +581,8 @@ export const createAuctionBidder = async (options: {
}
await tx.$executeRaw(
GamePrisma.sql`
INSERT INTO rank_data (nation_id, general_id, type, value)
SELECT nation_id, id, 'inherit_spent_dyn', ${morePoint}
INSERT INTO rank_data (id, nation_id, general_id, type, value)
SELECT ${existingRowIdOrNext('rank_data', GamePrisma.sql`stable_id.general_id = "general".id AND stable_id.type = 'inherit_spent_dyn'`)}, nation_id, id, 'inherit_spent_dyn', ${morePoint}
FROM general
WHERE id = ${command.generalId}
ON CONFLICT (general_id, type)
@@ -598,8 +599,9 @@ export const createAuctionBidder = async (options: {
}
await tx.$executeRaw(
GamePrisma.sql`
INSERT INTO inheritance_point (user_id, key, value, updated_at)
INSERT INTO inheritance_point (id, user_id, key, value, updated_at)
VALUES (
${existingRowIdOrNext('inheritance_point', GamePrisma.sql`stable_id.user_id = ${prevUserId} AND stable_id.key = 'previous'`)},
${prevUserId},
'previous',
${highestBid.amount},
+3 -2
View File
@@ -1,3 +1,4 @@
import { existingRowIdOrNext } from '@sammo-ts/infra';
import { resolveMessageTargetIcon } from '@sammo-ts/logic';
import { createGamePostgresConnector, GamePrisma } from '@sammo-ts/infra';
import { ActionLogger, ItemLoader, LogFormat, isItemKey, type MessageDraft } from '@sammo-ts/logic';
@@ -212,8 +213,8 @@ const refundInheritancePoint = async (options: {
}
await prisma.$executeRaw(
GamePrisma.sql`
INSERT INTO inheritance_point (user_id, key, value, updated_at)
VALUES (${userId}, 'previous', ${amount}, ${new Date()})
INSERT INTO inheritance_point (id, user_id, key, value, updated_at)
VALUES (${existingRowIdOrNext('inheritance_point', GamePrisma.sql`stable_id.user_id = ${userId} AND stable_id.key = 'previous'`)}, ${userId}, 'previous', ${amount}, ${new Date()})
ON CONFLICT (user_id, key)
DO UPDATE SET
value = inheritance_point.value + EXCLUDED.value,
+3 -2
View File
@@ -1,3 +1,4 @@
import { existingRowIdOrNext } from '@sammo-ts/infra';
import { randomUUID } from 'node:crypto';
import { asRecord, JosaUtil } from '@sammo-ts/common';
@@ -289,8 +290,8 @@ const openUniqueAuction = async (
});
await db.$executeRaw(
GamePrisma.sql`
INSERT INTO rank_data (nation_id, general_id, type, value)
VALUES (${general.nationId}, ${general.id}, 'inherit_spent_dyn', ${command.amount})
INSERT INTO rank_data (id, nation_id, general_id, type, value)
VALUES (${existingRowIdOrNext('rank_data', GamePrisma.sql`stable_id.general_id = ${general.id} AND stable_id.type = 'inherit_spent_dyn'`)}, ${general.nationId}, ${general.id}, 'inherit_spent_dyn', ${command.amount})
ON CONFLICT (general_id, type)
DO UPDATE SET
nation_id = EXCLUDED.nation_id,
+1
View File
@@ -13,6 +13,7 @@ export * from './scenario/databaseUrl.js';
export * from './scenario/mapLoader.js';
export * from './scenario/scenarioSeeder.js';
export * from './scenario/gameCancellation.js';
export * from './playAudit/retention.js';
export * from './turn/types.js';
export * from './turn/worldLoader.js';
export * from './turn/inMemoryWorld.js';
@@ -120,7 +120,13 @@ export class DatabaseTurnDaemonCommandQueue implements TurnDaemonControlQueue, T
const claimCoordinate = await readInputEventClockCoordinate(transaction);
const world = await transaction.worldState.findFirst({
orderBy: { id: 'asc' },
select: { clockPhase: true, clockRevision: true, deadlineGeneration: true, clockTick: true, meta: true },
select: {
clockPhase: true,
clockRevision: true,
deadlineGeneration: true,
clockTick: true,
meta: true,
},
});
// 가오픈도 장수 생성·삭제·거병·예약 등 사용자 명령은 처리한다.
// 자동 턴의 RUNNING/MANUAL gate는 TurnDaemonLifecycle이 별도로 지킨다.
@@ -184,7 +190,7 @@ export class DatabaseTurnDaemonCommandQueue implements TurnDaemonControlQueue, T
OR (${postUnificationSurvey} AND "event_type" = 'voteReward')
OR (
${suspendedTournamentBetCommand}
AND "event_type" IN ('adjustGeneralResources', 'adjustGeneralMeta')
AND "event_type" IN ('adjustGeneralResources', 'adjustGeneralMeta', 'tournamentAdjustGeneral')
AND "payload" ->> 'reason' IN ('tournamentBet', 'tournamentBetRollback')
)
OR (
@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';
import { performance } from 'node:perf_hooks';
import { createGamePostgresConnector, GamePrisma, type GamePrismaClient } from '@sammo-ts/infra';
import type { HostBootMonitor } from '../turn/hostBootMonitor.js';
export interface TurnDaemonLeaseToken {
profile: string;
@@ -14,6 +15,7 @@ export interface DatabaseTurnDaemonLeaseOptions {
ownerId?: string;
leaseDurationMs?: number;
heartbeat?: boolean;
hostBootMonitor?: HostBootMonitor;
}
export class TurnDaemonLeaseUnavailableError extends Error {
@@ -45,6 +47,7 @@ export class DatabaseTurnDaemonLease {
private readonly ownerId: string;
private readonly leaseDurationMs: number;
private readonly heartbeatEnabled: boolean;
private readonly hostBootMonitor?: HostBootMonitor;
private token: TurnDaemonLeaseToken | null = null;
private heartbeatTimer: NodeJS.Timeout | null = null;
private expiryTimer: NodeJS.Timeout | null = null;
@@ -63,6 +66,7 @@ export class DatabaseTurnDaemonLease {
this.ownerId = options.ownerId ?? randomUUID();
this.leaseDurationMs = normalizeLeaseDuration(options.leaseDurationMs);
this.heartbeatEnabled = options.heartbeat ?? true;
this.hostBootMonitor = options.hostBootMonitor;
}
static async connect(
@@ -75,6 +79,8 @@ export class DatabaseTurnDaemonLease {
}
async acquire(): Promise<TurnDaemonLeaseToken | null> {
await this.checkHostBoot();
if (this.lost) throw this.getLossError();
const requestStartedAt = performance.now();
const rows = await this.db.$queryRaw<LeaseRow[]>(GamePrisma.sql`
INSERT INTO "turn_daemon_lease" (
@@ -145,6 +151,12 @@ export class DatabaseTurnDaemonLease {
return new TurnDaemonLeaseLostError(this.profile, this.lossReason);
}
async checkHostBoot(): Promise<void> {
if (!this.lost && (await this.hostBootMonitor?.hasChanged())) {
this.markLost('Host boot identity changed; restart with a fresh database snapshot.');
}
}
async renew(): Promise<boolean> {
const token = this.token;
if (!token || this.lost || this.renewalInFlight) {
@@ -153,6 +165,8 @@ export class DatabaseTurnDaemonLease {
const requestStartedAt = performance.now();
this.renewalInFlight = true;
try {
await this.checkHostBoot();
if (this.lost) return false;
const rows = await this.db.$queryRaw<LeaseRow[]>(GamePrisma.sql`
UPDATE "turn_daemon_lease"
SET
@@ -180,6 +194,7 @@ export class DatabaseTurnDaemonLease {
}
async assertActive(transaction?: GamePrisma.TransactionClient): Promise<void> {
await this.checkHostBoot();
const token = this.token;
if (!token || this.lost) {
throw this.getLossError();
@@ -207,12 +222,13 @@ export class DatabaseTurnDaemonLease {
this.stopExpiryWatchdog();
const token = this.token;
this.token = null;
if (!token || this.lost) {
if (!token) {
return;
}
await this.db.$executeRaw(GamePrisma.sql`
UPDATE "turn_daemon_lease"
SET "lease_until" = CURRENT_TIMESTAMP AT TIME ZONE 'UTC',
SET "clock_ready" = FALSE,
"lease_until" = CURRENT_TIMESTAMP AT TIME ZONE 'UTC',
"heartbeat_at" = CURRENT_TIMESTAMP AT TIME ZONE 'UTC'
WHERE
"profile" = ${token.profile}
@@ -45,6 +45,7 @@ export interface TurnDaemonLifecycleDeps {
commandResponder?: TurnDaemonCommandResponder;
pauseGate?: () => Promise<boolean>;
stateManager?: Pick<EngineStateManager, 'transaction'>;
runErrorRetry?: { wait(error: unknown): Promise<boolean>; reset(): void };
}
export class TurnDaemonLifecycle {
@@ -59,6 +60,7 @@ export class TurnDaemonLifecycle {
private readonly commandResponder?: TurnDaemonCommandResponder;
private readonly pauseGate?: () => Promise<boolean>;
private readonly stateManager?: Pick<EngineStateManager, 'transaction'>;
private readonly runErrorRetry?: TurnDaemonLifecycleDeps['runErrorRetry'];
private readonly options: TurnDaemonLifecycleOptions;
private status: TurnDaemonStatus;
@@ -79,6 +81,7 @@ export class TurnDaemonLifecycle {
this.commandResponder = deps.commandResponder;
this.pauseGate = deps.pauseGate;
this.stateManager = deps.stateManager;
this.runErrorRetry = deps.runErrorRetry;
this.options = options;
this.status = {
state: 'idle',
@@ -192,8 +195,9 @@ export class TurnDaemonLifecycle {
// 수동 실행 요청도 가오픈·정지·재조정의 턴 실행 gate를 통과해야 한다.
// 사용자 명령 처리는 루프 시작에서 계속하되 시간 진행은 여기서 분리한다.
if (this.pendingRun) {
await this.runOnce(this.pendingRun);
const pending = this.pendingRun;
this.pendingRun = null;
await this.runOnce(pending);
continue;
}
@@ -447,6 +451,15 @@ export class TurnDaemonLifecycle {
};
result = this.stateManager ? await this.stateManager.transaction(runAndFlush) : await runAndFlush();
} catch (error) {
// savepoint 복원이 성공한 획득 충돌만 대기한다. 복원 실패/AggregateError나
// 저장 중 소유권 상실을 자동 재실행하면 중복 효과를 숨길 수 있다.
if (this.stateManager && (await this.runErrorRetry?.wait(error))) {
this.status.running = false;
this.status.state = 'idle';
this.pendingRun = pending;
return;
}
this.runErrorRetry?.reset();
this.status.running = false;
this.status.state = 'paused';
this.status.paused = true;
@@ -459,6 +472,7 @@ export class TurnDaemonLifecycle {
}
await this.applyRunResult(result, startMs);
this.runErrorRetry?.reset();
this.status.state = 'idle';
try {
await this.hooks?.publishEvents?.(result);
@@ -1,4 +1,4 @@
import type { GamePrisma, InputJsonValue } from '@sammo-ts/infra';
import { encodeAuditDecisionSteps, type GamePrisma, type InputJsonValue } from '@sammo-ts/infra';
import { auditPolicyHash } from './policy.js';
import type { PendingAuditDecision } from './decision.js';
@@ -50,7 +50,9 @@ export const persistAuditDecisions = async (
chunks.push({
decisionId: decision.id,
ordinal: start / AUDIT_DECISION_CHUNK_STEPS,
steps: decision.steps.slice(start, start + AUDIT_DECISION_CHUNK_STEPS) as InputJsonValue,
steps: encodeAuditDecisionSteps(
decision.steps.slice(start, start + AUDIT_DECISION_CHUNK_STEPS) as InputJsonValue[]
),
});
if (chunks.length === BATCH) {
await tx.playAuditDecisionChunk.createMany({ data: chunks, skipDuplicates: true });
+37 -22
View File
@@ -1,5 +1,5 @@
import { asRecord } from '@sammo-ts/common';
import type { GamePrismaClient } from '@sammo-ts/infra';
import { GamePrisma, type GamePrismaClient } from '@sammo-ts/infra';
export const AUDIT_RETENTION_BATCH_SIZE = 200;
export type AuditRetentionResult = { status: 'progress' | 'complete' | 'busy' | 'identityChanged'; deleted: number };
@@ -13,6 +13,7 @@ export const prunePreviousAuditBatch = async (
return db.$transaction(
async (tx) => {
await tx.$executeRaw`SET LOCAL statement_timeout = '2000ms'`;
await tx.$executeRaw`SET LOCAL lock_timeout = '250ms'`;
// seeder와 동일한 잠금이다. RESET을 기다리게 하지 않고 다음 batch에서 재시도한다.
const [lock] = await tx.$queryRaw<{ locked: boolean }[]>`
SELECT pg_try_advisory_xact_lock(hashtextextended(current_schema(), 0)) AS locked
@@ -32,29 +33,43 @@ export const prunePreviousAuditBatch = async (
});
return { status: 'progress', deleted: deleted.count };
}
const [decision] = await tx.$queryRaw<{ id: string }[]>`
SELECT id FROM play_audit_decision WHERE id = COALESCE(
(SELECT id FROM play_audit_decision WHERE server_id < ${expectedServerId}
ORDER BY server_id, general_id, tick, id LIMIT 1),
(SELECT id FROM play_audit_decision WHERE server_id > ${expectedServerId}
ORDER BY server_id, general_id, tick, id LIMIT 1)
) FOR UPDATE
// 이미 있는 (server_id,nation_id,tick,id) 인덱스 순서로 여러 부모를 잠근다.
// chunk 총량과 빈 header 삭제량의 합도 BATCH 이하로 제한한다.
let decisions = await tx.$queryRaw<{ id: string }[]>`
SELECT id FROM play_audit_decision WHERE server_id < ${expectedServerId}
ORDER BY server_id, nation_id, tick, id LIMIT ${AUDIT_RETENTION_BATCH_SIZE} FOR UPDATE
`;
if (decision) {
const chunks = await tx.playAuditDecisionChunk.findMany({
where: { decisionId: decision.id },
orderBy: { ordinal: 'asc' },
take: AUDIT_RETENTION_BATCH_SIZE,
select: { ordinal: true },
if (!decisions.length) {
decisions = await tx.$queryRaw<{ id: string }[]>`
SELECT id FROM play_audit_decision WHERE server_id > ${expectedServerId}
ORDER BY server_id, nation_id, tick, id LIMIT ${AUDIT_RETENTION_BATCH_SIZE} FOR UPDATE
`;
}
if (decisions.length) {
const ids = decisions.map(({ id }) => id);
const [chunks] = await tx.$queryRaw<{ deleted: number }[]>(GamePrisma.sql`
WITH batch AS (
SELECT decision_id, ordinal FROM play_audit_decision_chunk
WHERE decision_id IN (${GamePrisma.join(ids)})
ORDER BY decision_id, ordinal LIMIT ${AUDIT_RETENTION_BATCH_SIZE}
), removed AS (
DELETE FROM play_audit_decision_chunk c USING batch b
WHERE c.decision_id=b.decision_id AND c.ordinal=b.ordinal RETURNING 1
) SELECT count(*)::integer AS deleted FROM removed
`);
const count = chunks?.deleted ?? 0;
const remaining = AUDIT_RETENTION_BATCH_SIZE - count;
if (!remaining) return { status: 'progress', deleted: count };
const empty = await tx.playAuditDecision.findMany({
where: { id: { in: ids }, chunks: { none: {} } },
select: { id: true },
orderBy: { id: 'asc' },
take: remaining,
});
if (chunks.length) {
const deleted = await tx.playAuditDecisionChunk.deleteMany({
where: { decisionId: decision.id, ordinal: { in: chunks.map((row) => row.ordinal) } },
});
return { status: 'progress', deleted: deleted.count };
}
await tx.playAuditDecision.delete({ where: { id: decision.id } });
return { status: 'progress', deleted: 1 };
const headers = await tx.playAuditDecision.deleteMany({
where: { id: { in: empty.map(({ id }) => id) } },
});
return { status: 'progress', deleted: count + headers.count };
}
const policies = await tx.playAuditPolicy.findMany({
where: { serverId: { not: expectedServerId } },
@@ -17,7 +17,7 @@ export const startAuditRetentionWorker = (options: {
timer.unref();
};
const run = async () => {
let delay = 1000;
let delay = 100;
try {
const result = await options.prune();
if (result.status === 'complete' || result.status === 'identityChanged') stopped = true;
@@ -1,3 +1,4 @@
import { upsertWithoutSequence } from '@sammo-ts/infra';
import { asRecord } from '@sammo-ts/common';
import { createGamePostgresConnector, type GamePrisma, type InputJsonValue } from '@sammo-ts/infra';
import { LogCategory, LogScope } from '@sammo-ts/logic';
@@ -424,7 +425,7 @@ const cancelGameInTransaction = async (
earnedPointRetentionPercent: request.earnedPointRetentionPercent,
});
const currentPoint = pointsByUser.get(userId)?.get('previous') ?? 0;
await prisma.inheritancePoint.upsert({
await upsertWithoutSequence(prisma.inheritancePoint, {
where: { userId_key: { userId, key: 'previous' } },
update: { value: calculated.finalPoint },
create: { userId, key: 'previous', value: calculated.finalPoint },
@@ -470,7 +471,7 @@ const cancelGameInTransaction = async (
}
for (const general of activeGenerals) {
if (!general.userId || general.npcState >= 2) continue;
await prisma.oldGeneral.upsert({
await upsertWithoutSequence(prisma.oldGeneral, {
where: { by_no: { serverId, generalNo: general.id } },
update: {
owner: general.userId,
@@ -1,3 +1,4 @@
import { upsertWithoutSequence } from '@sammo-ts/infra';
import { prunePreviousAuditBatch } from '../playAudit/retention.js';
import { randomBytes } from 'node:crypto';
@@ -497,7 +498,7 @@ export const seedScenarioToDatabase = async (options: ScenarioSeedOptions): Prom
);
}
}
await prisma.gameHistory.upsert({
await upsertWithoutSequence(prisma.gameHistory, {
where: { serverId: worldMeta.serverId },
create: {
serverId: worldMeta.serverId,
+2 -1
View File
@@ -1,3 +1,4 @@
import { upsertWithoutSequence } from '@sammo-ts/infra';
import { areSeasonRecordsFinalized } from '../turn/seasonRecords.js';
import { JosaUtil, asRecord } from '@sammo-ts/common';
import { createGamePostgresConnector, type GamePrisma } from '@sammo-ts/infra';
@@ -256,7 +257,7 @@ export const createTournamentRewardFinalizer = async (options: {
const recordsFinalized = await areSeasonRecordsFinalized(db, world.getState().meta.serverId);
for (const entry of recordsFinalized ? [] : pointUpdates) {
await db.inheritancePoint.upsert({
await upsertWithoutSequence(db.inheritancePoint, {
where: {
userId_key: { userId: entry.userId!, key: 'tournament' },
},
+3
View File
@@ -8,6 +8,7 @@ import { createTurnDaemonMemoryReporter } from './turnDaemonMemoryReporter.js';
import { createGatewayProfileGate } from './gatewayProfileGate.js';
import { retryTurnDaemonLeaseStartup } from './leaseStartupRetry.js';
import { TurnDaemonLeaseUnavailableError } from '../lifecycle/databaseTurnDaemonLease.js';
import { loadHostBootMonitor } from './hostBootMonitor.js';
export interface TurnDaemonCliOptions {
profile?: string;
@@ -80,6 +81,7 @@ export const runTurnDaemonCli = async (options: TurnDaemonCliOptions = {}): Prom
throw new Error(`GAME_CLOCK_MODE must be realtime or manual: ${rawGameClockMode}`);
}
const gameClockMode = rawGameClockMode as GameClockMode | undefined;
const hostBootMonitor = await loadHostBootMonitor(env);
const runtime = await retryTurnDaemonLeaseStartup(() =>
createTurnDaemonRuntime({
@@ -95,6 +97,7 @@ export const runTurnDaemonCli = async (options: TurnDaemonCliOptions = {}): Prom
pauseGateIntervalMs,
adminActionIntervalMs,
gameClockMode,
hostBootMonitor,
})
).catch(async (error: unknown) => {
// 중복 starter가 정상 owner를 멈추면 안 된다. 그 밖의 초기화 실패는
@@ -269,6 +269,21 @@ const zSetNpcPolicy = z.object({
]),
});
const zTournamentAdjustGeneral = z.object({
type: z.literal('tournamentAdjustGeneral'),
reason: z.enum(['tournamentJoin', 'tournamentJoinRollback', 'tournamentBet', 'tournamentBetRollback']),
userId: z.string().min(1),
generalId: zSafeInteger.positive(),
goldDelta: zFiniteNumber,
betGoldDelta: zFiniteNumber.optional(),
minGoldAfter: zFiniteNumber.nonnegative(),
});
const zTournamentSeedNpcBets = z.object({
type: z.literal('tournamentSeedNpcBets'),
bets: z.array(z.object({ generalId: zSafeInteger.positive(), amount: zSafeInteger.positive() })).min(1),
});
const zAdjustGeneralResources = z.object({
type: z.literal('adjustGeneralResources'),
reason: z.string().optional(),
@@ -737,6 +752,16 @@ const normalizeSetNpcPolicy: CommandNormalizer<'setNpcPolicy'> = (envelope) => {
return { ...command, requestId: envelope.requestId };
};
const normalizeTournamentAdjustGeneral: CommandNormalizer<'tournamentAdjustGeneral'> = (envelope) => {
const command = parseWith(zTournamentAdjustGeneral, envelope.command);
return command ? { ...command, requestId: envelope.requestId } : null;
};
const normalizeTournamentSeedNpcBets: CommandNormalizer<'tournamentSeedNpcBets'> = (envelope) => {
const command = parseWith(zTournamentSeedNpcBets, envelope.command);
return command ? { ...command, requestId: envelope.requestId } : null;
};
const normalizeAdjustGeneralResources: CommandNormalizer<'adjustGeneralResources'> = (envelope) => {
const command = parseWith(zAdjustGeneralResources, envelope.command);
if (!command) {
@@ -905,6 +930,8 @@ const normalizers: CommandNormalizerMap = {
voteReward: normalizeVoteReward,
setNationSetting: normalizeSetNationSetting,
setNpcPolicy: normalizeSetNpcPolicy,
tournamentAdjustGeneral: normalizeTournamentAdjustGeneral,
tournamentSeedNpcBets: normalizeTournamentSeedNpcBets,
adjustGeneralResources: normalizeAdjustGeneralResources,
adjustGeneralMeta: normalizeAdjustGeneralMeta,
tournamentMatchResult: normalizeTournamentMatchResult,
+31 -12
View File
@@ -1,3 +1,4 @@
import { upsertWithoutSequence } from '@sammo-ts/infra';
import { persistAuditDecisions } from '../playAudit/decisionPersistence.js';
import { collectPlayAudit, markAuditGap } from '../playAudit/bestEffort.js';
import { persistAuditDiplomacyEvents, withPlayAuditSavepoint } from '@sammo-ts/infra';
@@ -119,7 +120,7 @@ export interface RealtimeReadModelBaseline {
}
export type PersistedVisibleLogRow = {
id: number;
id: number | bigint;
scope: LogScope;
category: LogCategory;
generalId: number | null;
@@ -697,12 +698,12 @@ const persistNationBettingFinish = async (
});
const previousPoint = existing?.value ?? 0;
const nextPoint = previousPoint + reward.amount;
await prisma.inheritancePoint.upsert({
await upsertWithoutSequence(prisma.inheritancePoint, {
where: { userId_key: { userId: reward.userId, key: 'previous' } },
update: { value: nextPoint },
create: { userId: reward.userId, key: 'previous', value: nextPoint },
});
await prisma.rankData.upsert({
await upsertWithoutSequence(prisma.rankData, {
where: {
generalId_type: {
generalId: reward.generalId,
@@ -831,17 +832,28 @@ const buildPersistedGeneralMeta = (
const RANK_DATA_UPSERT_BATCH_SIZE = 1_000;
const upsertRankRows = async (
export const upsertRankRows = async (
prisma: GamePrisma.TransactionClient,
rows: Array<{ generalId: number; nationId: number; type: string; value: number }>
): Promise<void> => {
for (let offset = 0; offset < rows.length; offset += RANK_DATA_UPSERT_BATCH_SIZE) {
const batch = rows.slice(offset, offset + RANK_DATA_UPSERT_BATCH_SIZE);
// Ref와 같은 (장수, 항목) 값을 저장한다. 이미 있는 행의 ID를 재사용해
// 매 턴 44종 갱신마다 nextval을 소비하지 않고, 신규 행만 시퀀스를 사용한다.
// 동시 신규 insert 경합은 기존 ON CONFLICT 계약으로 처리한다.
await prisma.$executeRaw(GamePrisma.sql`
INSERT INTO "rank_data" ("general_id", "nation_id", "type", "value")
VALUES ${GamePrisma.join(
batch.map((row) => GamePrisma.sql`(${row.generalId}, ${row.nationId}, ${row.type}, ${row.value})`)
)}
INSERT INTO "rank_data" ("id", "general_id", "nation_id", "type", "value")
SELECT
COALESCE(existing."id", nextval(pg_get_serial_sequence('rank_data', 'id'))),
incoming."general_id", incoming."nation_id", incoming."type", incoming."value"
FROM (VALUES ${GamePrisma.join(
batch.map(
(row) =>
GamePrisma.sql`(${row.generalId}::integer, ${row.nationId}::integer, ${row.type}::text, ${row.value}::integer)`
)
)}) AS incoming("general_id", "nation_id", "type", "value")
LEFT JOIN "rank_data" AS existing
ON existing."general_id" = incoming."general_id" AND existing."type" = incoming."type"
ON CONFLICT ("general_id", "type") DO UPDATE
SET
"nation_id" = EXCLUDED."nation_id",
@@ -1079,6 +1091,7 @@ export const createDatabaseTurnHooks = async (
profileName?: string;
reservedTurns?: InMemoryReservedTurnStore;
turnDaemonLease?: DatabaseTurnDaemonLease;
transactionMaxWaitMs?: number;
transactionTimeoutMs?: number;
}
): Promise<DatabaseTurnHooks> => {
@@ -1089,7 +1102,13 @@ export const createDatabaseTurnHooks = async (
// Prisma's 5-second default matches the normal turn execution budget too
// closely. A populated season can finish the turn but expire while flushing
// it, which rolls the transaction back and marks the profile PAUSED.
const transactionOptions = { timeout: options?.transactionTimeoutMs ?? 30_000 };
// 실행 timeout과 연결 획득 대기는 별도 제한이다. 기본 maxWait 2초는
// 일시적인 DB 지연에도 callback 시작 전에 턴을 영구 PAUSED로 만들었다.
// 대기를 유한하게 늘리되 callback 재실행이나 lease/fencing 우회는 하지 않는다.
const transactionOptions = {
maxWait: options?.transactionMaxWaitMs ?? 10_000,
timeout: options?.transactionTimeoutMs ?? 30_000,
};
const readModelBaseline = createRealtimeReadModelBaseline(world);
let worldReadModelBaseline = createWorldReadModelSignature(world);
let persistedTickSeconds = world.getState().tickSeconds;
@@ -1122,7 +1141,7 @@ export const createDatabaseTurnHooks = async (
const persistChanges = async (
transaction?: GamePrisma.TransactionClient,
commandCompletion?: { requestId: string; result: TurnDaemonCommandResult },
directLogFloor?: number
directLogFloor?: number | bigint
): Promise<{
acknowledge: () => void;
readModelChanges: RealtimeReadModelChanges;
@@ -1556,7 +1575,7 @@ export const createDatabaseTurnHooks = async (
}
}
for (const entry of grouped.values()) {
await prisma.inheritancePoint.upsert({
await upsertWithoutSequence(prisma.inheritancePoint, {
where: { userId_key: { userId: entry.userId, key: entry.key } },
update: { value: { increment: entry.amount } },
create: { userId: entry.userId, key: entry.key, value: entry.amount },
@@ -1624,7 +1643,7 @@ export const createDatabaseTurnHooks = async (
}
await Promise.all(
deletedNationSnapshots.map((snapshot) =>
prisma.oldNation.upsert({
upsertWithoutSequence(prisma.oldNation, {
where: {
serverId_nation_sourceId: {
serverId,
@@ -1,3 +1,4 @@
import { existingRowIdOrNext } from '@sammo-ts/infra';
import { GamePrisma, type TurnEngineGeneralUpdateInput } from '@sammo-ts/infra';
// Fixed schema identifiers only; all row values remain bound parameters.
@@ -91,8 +92,8 @@ export const persistGeneralAccessScores = async (
for (let offset = 0; offset < updates.length; offset += GENERAL_UPDATE_BATCH_SIZE) {
const batch = updates.slice(offset, offset + GENERAL_UPDATE_BATCH_SIZE);
await database.$executeRaw(GamePrisma.sql`
INSERT INTO "general_access_log" ("general_id", "user_id", "refresh_score_total")
VALUES ${GamePrisma.join(batch.map((row) => GamePrisma.sql`(${row.generalId}, ${row.userId}, ${row.refreshScoreTotal})`))}
INSERT INTO "general_access_log" ("id", "general_id", "user_id", "refresh_score_total")
VALUES ${GamePrisma.join(batch.map((row) => GamePrisma.sql`(${existingRowIdOrNext('general_access_log', GamePrisma.sql`stable_id.general_id = ${row.generalId}`)}, ${row.generalId}, ${row.userId}, ${row.refreshScoreTotal})`))}
ON CONFLICT ("general_id") DO UPDATE
SET "refresh_score_total" = EXCLUDED."refresh_score_total"
`);
@@ -1,3 +1,4 @@
import { upsertWithoutSequence } from '@sammo-ts/infra';
import { areSeasonRecordsFinalized } from './seasonRecords.js';
import {
asRecord,
@@ -77,7 +78,7 @@ const persistPostRetirementRankValues = async (
return;
}
for (const row of buildPersistedRankRows(event.after)) {
await prisma.rankData.upsert({
await upsertWithoutSequence(prisma.rankData, {
where: { generalId_type: { generalId: row.generalId, type: row.type } },
update: { nationId: row.nationId, value: row.value },
create: row,
@@ -142,7 +143,7 @@ const settleInheritance = async (
);
const total = Math.trunc(previous + refund + settlement.totalEarned);
await prisma.inheritancePoint.upsert({
await upsertWithoutSequence(prisma.inheritancePoint, {
where: { userId_key: { userId, key: 'previous' } },
update: { value: total },
create: { userId, key: 'previous', value: total },
@@ -152,7 +153,7 @@ const settleInheritance = async (
([key, value]) => key === 'max_belong' || points.has(key) || value !== 0
);
for (const [key, value] of retainedEntries) {
await prisma.inheritancePoint.upsert({
await upsertWithoutSequence(prisma.inheritancePoint, {
where: { userId_key: { userId, key } },
update: { value },
create: { userId, key, value },
@@ -367,7 +368,7 @@ const archiveGeneral = async (
records: { battleResult: battleResults },
availability: { battleResultLogs: true },
};
await prisma.oldGeneral.upsert({
await upsertWithoutSequence(prisma.oldGeneral, {
where: { by_no: { serverId, generalNo: event.generalId } },
update: {
owner: event.before.userId ?? null,
+142
View File
@@ -0,0 +1,142 @@
import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { performance } from 'node:perf_hooks';
import { isRecord } from '@sammo-ts/common';
export interface HostBootMonitor {
hasChanged(): Promise<boolean>;
}
const mac = (key: Buffer, value: string): string => createHmac('sha256', key).update(value).digest('hex');
/** 부팅 세대는 첫 인증 응답에 고정한다. 통신 실패는 기존 lease 복구를 막지 않는다. */
export const createHostBootMonitor = (options: {
url: string;
key: Buffer;
pollMs?: number;
timeoutMs?: number;
now?: () => number;
wallNow?: () => number;
onUnavailable?: () => void;
onVerified?: () => void;
}): HostBootMonitor => {
const url = new URL(options.url);
if (
!['http:', 'https:'].includes(url.protocol) ||
url.username ||
url.password ||
url.search ||
url.hash ||
url.pathname !== '/v1/boot-id'
) {
throw new Error('Host boot URL must use HTTP(S) and /v1/boot-id without credentials or query.');
}
if (options.key.length !== 32) throw new Error('Host boot key must contain exactly 32 bytes.');
const now = options.now ?? (() => performance.now());
const wallNow = options.wallNow ?? (() => Date.now());
let baseline: string | null = null;
let changed = false;
let lastAttempt = -Infinity;
let lastWall = 0;
let lastWarning = -Infinity;
let inFlight: Promise<boolean> | null = null;
const sample = async (): Promise<boolean> => {
const nonce = randomBytes(32).toString('hex');
const response = await fetch(url, {
method: 'GET',
redirect: 'error',
signal: AbortSignal.timeout(options.timeoutMs ?? 1_000),
headers: {
'x-sammo-challenge': nonce,
'x-sammo-signature': mac(options.key, `sammo-host-boot-request-v1\n${nonce}`),
},
});
if (!response.ok || !response.body) {
await response.body?.cancel();
throw new Error('Host boot response unavailable.');
}
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let size = 0;
try {
for (;;) {
const { done, value } = await reader.read();
if (done) break;
size += value.length;
if (size > 2_048) throw new Error('Host boot response exceeds its limit.');
chunks.push(value);
}
} finally {
await reader.cancel();
}
const body: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8'));
if (
!isRecord(body) ||
body.version !== 1 ||
body.challenge !== nonce ||
typeof body.bootId !== 'string' ||
!/^[a-f0-9]{64}$/.test(body.bootId) ||
typeof body.signature !== 'string' ||
!/^[a-f0-9]{64}$/.test(body.signature)
) {
throw new Error('Host boot response is invalid.');
}
const expected = mac(options.key, `sammo-host-boot-response-v1\n${nonce}\n${body.bootId}`);
if (!timingSafeEqual(Buffer.from(expected, 'hex'), Buffer.from(body.signature, 'hex'))) {
throw new Error('Host boot response signature is invalid.');
}
if (baseline === null) {
baseline = body.bootId;
options.onVerified?.();
}
changed ||= body.bootId !== baseline;
return changed;
};
return {
hasChanged(): Promise<boolean> {
if (changed) return Promise.resolve(true);
if (inFlight) return inFlight;
const current = now();
const wall = wallNow();
const discontinuity = Math.abs(wall - lastWall - (current - lastAttempt)) > 1_000;
if (current - lastAttempt < (options.pollMs ?? 2_000) && !discontinuity) return Promise.resolve(false);
lastAttempt = current;
lastWall = wall;
inFlight = sample()
.catch(() => {
if (current - lastWarning >= 60_000) {
options.onUnavailable?.();
lastWarning = current;
}
return false;
})
.finally(() => {
inFlight = null;
});
return inFlight;
},
};
};
export const loadHostBootMonitor = async (env: NodeJS.ProcessEnv): Promise<HostBootMonitor | undefined> => {
const url = env.TURN_HOST_BOOT_URL?.trim();
const keyFile = env.TURN_HOST_BOOT_KEY_FILE?.trim();
if (!url && !keyFile) return undefined;
try {
if (!url || !keyFile) throw new Error('Incomplete optional configuration.');
const encoded = (await readFile(keyFile, 'utf8')).trim();
if (!/^[a-f0-9]{64}$/.test(encoded)) throw new Error('Invalid optional key file.');
return createHostBootMonitor({
url,
key: Buffer.from(encoded, 'hex'),
onVerified: () => console.info('[turn-daemon] host boot identity verified.'),
onUnavailable: () => {
console.warn('[turn-daemon] host boot identity unavailable; ordinary lease recovery remains active.');
},
});
} catch {
// 보조 관측기의 설정/파일 부재도 게임 기동의 필수 의존성이 되지 않는다.
console.warn('[turn-daemon] host boot observation disabled; check optional configuration and key file.');
return undefined;
}
};
@@ -1,3 +1,4 @@
import { upsertWithoutSequence } from '@sammo-ts/infra';
import { areSeasonRecordsFinalized } from './seasonRecords.js';
import { asNumber, asRecord, JosaUtil, LiteHashDRBG, RandUtil } from '@sammo-ts/common';
import { acquireGameSchemaAdvisoryXactLock, GamePrisma } from '@sammo-ts/infra';
@@ -246,7 +247,7 @@ const applyInheritanceUser = async (
};
const setInheritancePoint = async (db: DatabaseClient, userId: string, value: number): Promise<void> => {
await db.inheritancePoint.upsert({
await upsertWithoutSequence(db.inheritancePoint, {
where: { userId_key: { userId, key: 'previous' } },
update: { value },
create: { userId, key: 'previous', value },
@@ -860,7 +861,7 @@ export const createGeneralFromJoin = async (options: {
await db.generalTurnRevision.create({
data: { generalId, revision: 0 },
});
await db.generalAccessLog.upsert({
await upsertWithoutSequence(db.generalAccessLog, {
where: { generalId },
update: { userId: input.userId, lastRefresh: operationalAcceptedAt },
create: {
@@ -1,3 +1,4 @@
import { upsertWithoutSequence } from '@sammo-ts/infra';
import { randomInt } from 'node:crypto';
import { asNumber, asRecord, GAME_TICKS_PER_TURN, JosaUtil, LiteHashDRBG, RandUtil, type RNG } from '@sammo-ts/common';
@@ -337,18 +338,12 @@ export const reserveNpcPossessionCandidates = async (options: {
}
return toReservation(inFlightToken, options.createdGameTick, ticksPerSecond);
}
if (
existing &&
(existing.validUntilTick === null || Number(existing.validUntilTick) < options.createdGameTick)
) {
if (existing && (existing.validUntilTick === null || Number(existing.validUntilTick) < options.createdGameTick)) {
await db.npcSelectionToken.deleteMany({
where: {
ownerUserId: userId,
nonce: existing.nonce,
OR: [
{ validUntilTick: null },
{ validUntilTick: { lt: BigInt(options.createdGameTick) } },
],
OR: [{ validUntilTick: null }, { validUntilTick: { lt: BigInt(options.createdGameTick) } }],
},
});
existing = null;
@@ -425,9 +420,7 @@ export const reserveNpcPossessionCandidates = async (options: {
const validUntilTick = options.createdGameTick + Math.round(validSeconds * ticksPerSecond);
const pickMoreFromTick = options.createdGameTick + Math.round(pickMoreSeconds * ticksPerSecond);
const validUntil = new Date(now.getTime() + validSeconds * 1000);
const refreshedPickMoreFrom = new Date(
now.getTime() + pickMoreSeconds * 1000
);
const refreshedPickMoreFrom = new Date(now.getTime() + pickMoreSeconds * 1000);
const nonce = randomInt(0, 0x10000000);
if (existing) {
@@ -566,7 +559,7 @@ export const possessNpcGeneral = async (options: {
},
});
await db.generalAccessLog.upsert({
await upsertWithoutSequence(db.generalAccessLog, {
where: { generalId },
update: {
userId,
@@ -0,0 +1,38 @@
import { performance } from 'node:perf_hooks';
import { setTimeout } from 'node:timers/promises';
import { ReservedTurnLeaseBusyError } from './reservedTurnStore.js';
/** rollback 완료 뒤에만 대기한다. 다음 loop에서 pause/lease gate와 최신 큐를 다시 읽는다. */
export const createReservedTurnLeaseRetry = (
options: {
now?: () => number;
sleep?: (ms: number) => Promise<void>;
maxWaitMs?: number;
onWait?: (queueKey: string) => void;
} = {}
) => {
const now = options.now ?? (() => performance.now());
const sleep = options.sleep ?? ((ms: number) => setTimeout(ms));
const maxWaitMs = options.maxWaitMs ?? 5 * 60_000 + 1_000;
let startedAt: number | null = null;
let lastReportedAt = -Infinity;
return {
reset(): void {
startedAt = null;
lastReportedAt = -Infinity;
},
async wait(error: unknown): Promise<boolean> {
if (!(error instanceof ReservedTurnLeaseBusyError)) return false;
const current = now();
startedAt ??= current;
const remaining = maxWaitMs - (current - startedAt);
if (remaining <= 0) return false;
if (current - lastReportedAt >= 30_000) {
options.onWait?.(error.queueKey);
lastReportedAt = current;
}
await sleep(Math.min(1_000, remaining));
return true;
},
};
};
+36 -8
View File
@@ -129,6 +129,14 @@ export class ReservedTurnLeaseConflictError extends Error {
}
}
/** 실행 전 획득 충돌만 재시도한다. flush/finalize의 소유권 상실과 구분한다. */
export class ReservedTurnLeaseBusyError extends ReservedTurnLeaseConflictError {
constructor(queueKey: string) {
super(queueKey);
this.name = 'ReservedTurnLeaseBusyError';
}
}
export class InMemoryReservedTurnStore {
private readonly generalTurns = new Map<number, ReservedTurnEntry[]>();
private readonly nationTurns = new Map<string, ReservedTurnEntry[]>();
@@ -249,11 +257,7 @@ export class InMemoryReservedTurnStore {
}
};
pruneNationKeys(Array.from(this.nationTurns.keys()), (key) => this.nationTurns.delete(key));
for (const keys of [
this.dirtyNationKeys,
this.pendingNationInitializationKeys,
this.leasedNationKeys,
]) {
for (const keys of [this.dirtyNationKeys, this.pendingNationInitializationKeys, this.leasedNationKeys]) {
for (const key of Array.from(keys)) {
const nationId = Number(key.split(':', 1)[0]);
if (deletedNations.has(nationId)) {
@@ -376,7 +380,7 @@ export class InMemoryReservedTurnStore {
}
}
if (claimed.count !== 1) {
throw new ReservedTurnLeaseConflictError(`general:${generalId}`);
throw new ReservedTurnLeaseBusyError(`general:${generalId}`);
}
this.leasedGeneralIds.add(generalId);
return !retainedExistingLease;
@@ -427,7 +431,7 @@ export class InMemoryReservedTurnStore {
}
}
if (claimed.count !== 1) {
throw new ReservedTurnLeaseConflictError(`nation:${nationId}:${officerLevel}`);
throw new ReservedTurnLeaseBusyError(`nation:${nationId}:${officerLevel}`);
}
this.leasedNationKeys.add(buildNationKey(nationId, officerLevel));
return !retainedExistingLease;
@@ -904,6 +908,24 @@ export class InMemoryReservedTurnStore {
await this.persistChanges(this.prisma, changes);
this.acknowledgeDirtyState(changes);
}
/** 실행 루프 종료 뒤 호출한다. rollback으로 journal에서 빠진 DB 임대도 해제한다. */
async releaseOwnedLeases(): Promise<void> {
const results = await Promise.allSettled([
this.prisma.generalTurnRevision?.updateMany({
where: { leaseOwner: this.leaseOwner },
data: { leaseOwner: null, leaseExpiresAt: null },
}),
this.prisma.nationTurnRevision?.updateMany({
where: { leaseOwner: this.leaseOwner },
data: { leaseOwner: null, leaseExpiresAt: null },
}),
]);
const errors = results.flatMap((result) => (result.status === 'rejected' ? [result.reason] : []));
if (errors.length) throw new AggregateError(errors, 'Reserved turn lease cleanup failed.');
this.leasedGeneralIds.clear();
this.leasedNationKeys.clear();
}
}
export const createReservedTurnStore = async (options: ReservedTurnStoreOptions): Promise<ReservedTurnStoreHandle> => {
@@ -918,6 +940,12 @@ export const createReservedTurnStore = async (options: ReservedTurnStoreOptions)
await store.loadAll();
return {
store,
close: () => connector.disconnect(),
close: async () => {
try {
await store.releaseOwnedLeases();
} finally {
await connector.disconnect();
}
},
};
};
+2 -2
View File
@@ -2,7 +2,7 @@ import type { GameClockPhase } from '@sammo-ts/common';
/** Gateway의 실행 gate와 durable 시계를 명령 claim 전에 맞춘다. */
export const createRuntimePauseGate = (options: {
assertLease(): void;
assertLease(): void | Promise<void>;
shouldPause(): Promise<boolean>;
getPhase(): GameClockPhase;
isExplicitlyPaused(): boolean;
@@ -11,7 +11,7 @@ export const createRuntimePauseGate = (options: {
}): (() => Promise<boolean>) => {
let lastPaused: boolean | null = null;
return async () => {
options.assertLease();
await options.assertLease();
const paused = await options.shouldPause();
const phase = options.getPhase();
// 오류 정지는 Gateway 상태만 PAUSED로 바꿀 수 있다. 그대로 두면 가입은
@@ -1,3 +1,4 @@
import { upsertWithoutSequence } from '@sammo-ts/infra';
import { z } from 'zod';
import { asNumber, asRecord, GAME_TICKS_PER_TURN, JosaUtil, LiteHashDRBG, RandUtil } from '@sammo-ts/common';
@@ -567,11 +568,7 @@ const assertGeneralIdSnapshotMatches = async (db: DatabaseClient, world: InMemor
}
};
const clearUnusedReservations = async (
db: DatabaseClient,
userId: string,
nowTick: number
): Promise<void> => {
const clearUnusedReservations = async (db: DatabaseClient, userId: string, nowTick: number): Promise<void> => {
await db.selectPoolEntry.updateMany({
where: {
generalId: null,
@@ -914,7 +911,7 @@ export const createGeneralFromSelectionPool = async (options: {
if (occupied.count === 0) {
throw new Error('장수 등록 중 선택 후보 점유에 실패했습니다.');
}
await db.generalAccessLog.upsert({
await upsertWithoutSequence(db.generalAccessLog, {
where: { generalId },
update: { userId, lastRefresh: options.operationalAcceptedAt },
create: { generalId, userId, lastRefresh: options.operationalAcceptedAt },
+36 -14
View File
@@ -108,6 +108,8 @@ import { DatabaseTurnDaemonLease, TurnDaemonLeaseUnavailableError } from '../lif
import { EngineStateManager } from './engineStateManager.js';
import { applyRuntimeClockShift } from './runtimeClockShift.js';
import { applyRuntimeGameSettings } from './runtimeGameSettings.js';
import { createReservedTurnLeaseRetry } from './reservedTurnLeaseRetry.js';
import type { HostBootMonitor } from './hostBootMonitor.js';
export interface TurnDaemonRuntimeOptions {
profile: string;
@@ -134,11 +136,13 @@ export interface TurnDaemonRuntimeOptions {
leaseDurationMs?: number;
leaseOwnerId?: string;
enableLeaseHeartbeat?: boolean;
hostBootMonitor?: HostBootMonitor;
/**
* Isolated, single-process fixture acceleration only. Reserved turns are
* loaded once and no concurrent API writer may touch this database.
*/
exclusiveFastForward?: boolean;
databaseTransactionMaxWaitMs?: number;
databaseTransactionTimeoutMs?: number;
onActionResolved?: NonNullable<Parameters<typeof createReservedTurnHandler>[0]['onActionResolved']>;
}
@@ -933,6 +937,7 @@ const createTurnDaemonRuntimeWithLease = async (
profileName: options.profileName ?? options.profile,
reservedTurns: reservedTurnStoreHandle?.store,
turnDaemonLease: turnDaemonLease ?? undefined,
transactionMaxWaitMs: options.databaseTransactionMaxWaitMs,
transactionTimeoutMs: options.databaseTransactionTimeoutMs,
});
try {
@@ -983,6 +988,7 @@ const createTurnDaemonRuntimeWithLease = async (
prepareClockRecovery = dbHooks.prepareRealtimeRecovery;
prunePreviousAudit = dbHooks.prunePreviousAudit;
close = async () => {
await adminActionConsumer?.stop();
if (auctionBidder) {
await auctionBidder.close();
}
@@ -993,12 +999,15 @@ const createTurnDaemonRuntimeWithLease = async (
await tournamentRewardFinalizer.close();
}
await dbHooks.close();
if (reservedTurnStoreHandle) {
await reservedTurnStoreHandle.close();
try {
await reservedTurnStoreHandle?.close();
} finally {
try {
await gatewayGate?.close();
} finally {
await turnDaemonLease?.close();
}
}
await gatewayGate?.close();
await adminActionConsumer?.stop();
await turnDaemonLease?.close();
};
} else if (reservedTurnStoreHandle) {
hooks = {
@@ -1007,9 +1016,12 @@ const createTurnDaemonRuntimeWithLease = async (
},
};
close = async () => {
await reservedTurnStoreHandle.close();
await gatewayGate?.close();
await adminActionConsumer?.stop();
try {
await reservedTurnStoreHandle.close();
} finally {
await gatewayGate?.close();
}
};
} else if (gatewayGate) {
hooks = {
@@ -1068,12 +1080,17 @@ const createTurnDaemonRuntimeWithLease = async (
const baseClose = close;
close = async () => {
stopClockProjectionWorker();
await baseClose();
await neutralAuctionRegistrar.close();
if (redisConnector) {
await redisConnector.disconnect();
}
await commandConnector?.disconnect();
const baseResults = await Promise.allSettled([baseClose()]);
// queue 임대 정리 실패도 다른 연결/worker의 종료를 막지 않게 한다.
const results = await Promise.allSettled([
neutralAuctionRegistrar.close(),
redisConnector?.disconnect(),
commandConnector?.disconnect(),
]);
const failures = [...baseResults, ...results].flatMap((result) =>
result.status === 'rejected' ? [result.reason] : []
);
if (failures.length) throw new AggregateError(failures, 'Turn daemon connection cleanup failed.');
};
const resolvedControlQueue = options.controlQueue ?? databaseCommandQueue ?? controlQueue;
@@ -1107,7 +1124,8 @@ const createTurnDaemonRuntimeWithLease = async (
processor,
hooks,
pauseGate: createRuntimePauseGate({
assertLease: () => {
assertLease: async () => {
await turnDaemonLease?.checkHostBoot();
if (turnDaemonLease?.isLost()) throw turnDaemonLease.getLossError();
},
shouldPause: async () => (await pauseGate?.()) ?? false,
@@ -1125,6 +1143,9 @@ const createTurnDaemonRuntimeWithLease = async (
// accumulated world before every due tick in that isolated mode;
// production and gateway-managed runtimes keep rollback savepoints.
stateManager: options.exclusiveFastForward ? undefined : stateManager,
runErrorRetry: createReservedTurnLeaseRetry({
onWait: (queueKey) => console.info(`[turn-daemon] waiting for reserved turn lease: ${queueKey}`),
}),
},
{ profile: options.profile, defaultBudget }
);
@@ -1177,6 +1198,7 @@ export const createTurnDaemonRuntime = async (options: TurnDaemonRuntimeOptions)
ownerId: options.leaseOwnerId,
leaseDurationMs: options.leaseDurationMs,
heartbeat: options.enableLeaseHeartbeat,
hostBootMonitor: options.hostBootMonitor,
})
: null;
if (turnDaemonLease && !(await turnDaemonLease.acquire())) {
@@ -1,3 +1,4 @@
import { upsertWithoutSequence } from '@sammo-ts/infra';
import { resolveMessageTargetIcon } from '@sammo-ts/logic';
import { areSeasonRecordsFinalized } from './seasonRecords.js';
import { asRecord, HALL_OF_FAME_TYPES, resolveLegacyTextColor, type HallOfFameType } from '@sammo-ts/common';
@@ -209,12 +210,12 @@ const cancelPendingUniqueAuctions = async (
if (!bidder?.userId || bidder.userId !== dbBidder?.userId) {
throw new Error(`Unification auction refund owner is unavailable: ${planned.auctionId}.`);
}
await transaction.inheritancePoint.upsert({
await upsertWithoutSequence(transaction.inheritancePoint, {
where: { userId_key: { userId: bidder.userId, key: 'previous' } },
update: { value: { increment: highest.amount } },
create: { userId: bidder.userId, key: 'previous', value: highest.amount },
});
await transaction.rankData.upsert({
await upsertWithoutSequence(transaction.rankData, {
where: {
generalId_type: { generalId: bidder.id, type: 'inherit_spent_dyn' },
},
@@ -345,7 +346,7 @@ export const persistUnificationFinalization = async (
) as Record<(typeof ALL_MERGED_INHERITANCE_KEYS)[number], number>;
const total = Math.floor(previous + Object.values(mergedPoints).reduce((sum, value) => sum + value, 0));
await transaction.inheritancePoint.upsert({
await upsertWithoutSequence(transaction.inheritancePoint, {
where: { userId_key: { userId, key: 'previous' } },
update: { value: total },
create: { userId, key: 'previous', value: total },
@@ -508,7 +509,7 @@ export const persistUnificationFinalization = async (
}),
generationKey: input.generationKey,
};
await transaction.oldNation.upsert({
await upsertWithoutSequence(transaction.oldNation, {
where: { serverId_nation_sourceId: { serverId, nation: input.winnerNationId, sourceId: 0 } },
update: { data: asJson(winnerData), date: input.completedAt },
create: {
@@ -525,7 +526,7 @@ export const persistUnificationFinalization = async (
generals: neutralGenerals.map((general) => general.id),
generationKey: input.generationKey,
};
await transaction.oldNation.upsert({
await upsertWithoutSequence(transaction.oldNation, {
where: { serverId_nation_sourceId: { serverId, nation: 0, sourceId: 0 } },
update: { data: neutralData, date: input.completedAt },
create: { serverId, nation: 0, sourceId: 0, data: neutralData, date: input.completedAt },
@@ -572,7 +573,7 @@ export const persistUnificationFinalization = async (
availability: { battleResultLogs: true },
generationKey: input.generationKey,
};
await transaction.oldGeneral.upsert({
await upsertWithoutSequence(transaction.oldGeneral, {
where: { by_no: { serverId, generalNo: general.id } },
update: {
owner: general.userId ?? null,
@@ -1,3 +1,4 @@
import { existingRowIdOrNext } from '@sammo-ts/infra';
import { handleCityOfficeRequest, settleCityOfficeRequests } from './cityOfficeRequests.js';
import type {
TurnDaemonCommandHandler,
@@ -175,6 +176,7 @@ const requireCommandDatabase = (ctx: CommandHandlerContext): DatabaseClient => {
};
const ACTOR_BOUND_GENERAL_COMMAND_TYPE_LIST = [
'tournamentAdjustGeneral',
'troopCreate',
'troopJoin',
'troopExit',
@@ -627,11 +629,84 @@ async function handleSetNpcPolicy(
return applyNpcPolicyMutation({ world: ctx.world, command, acceptedAt });
}
async function handleTournamentAdjustGeneral(
ctx: CommandHandlerContext,
command: Extract<TurnDaemonCommand, { type: 'tournamentAdjustGeneral' }>
): Promise<TurnDaemonCommandResult> {
const general = ctx.world.getGeneralById(command.generalId);
// Ref의 참가/베팅 actor는 로그인 장수다. 큐 대기 중 빙의 소유자가 바뀐 경우도 막는다.
if (!general || general.userId !== command.userId) {
return { type: command.type, ok: false, code: 'FORBIDDEN', reason: '장수의 현재 소유자가 일치하지 않습니다.' };
}
const gold = general.gold + command.goldDelta;
if (!Number.isFinite(gold) || gold < command.minGoldAfter) {
return { type: command.type, ok: false, code: 'BAD_REQUEST', reason: '금이 부족합니다.' };
}
const meta = { ...general.meta };
if (command.betGoldDelta !== undefined) {
const current = typeof meta.betgold === 'number' ? meta.betgold : 0;
const betgold = current + command.betGoldDelta;
if (!Number.isFinite(betgold) || betgold < 0) {
return { type: command.type, ok: false, code: 'BAD_REQUEST', reason: '베팅 기록이 일치하지 않습니다.' };
}
meta.betgold = betgold;
}
// 금과 통계는 하나의 ENGINE event에서 함께 commit하거나 함께 거부한다.
ctx.world.updateGeneral(command.generalId, { gold, meta });
return { type: command.type, ok: true, generalId: command.generalId };
}
async function handleTournamentSeedNpcBets(
ctx: CommandHandlerContext,
command: Extract<TurnDaemonCommand, { type: 'tournamentSeedNpcBets' }>
): Promise<TurnDaemonCommandResult> {
if (ctx.commandDb) {
const event = command.requestId
? await ctx.commandDb.inputEvent.findUnique({
where: { requestId: command.requestId },
select: { actorUserId: true, target: true, eventType: true },
})
: null;
if (!event || event.actorUserId !== null || event.target !== 'ENGINE' || event.eventType !== command.type) {
return { type: command.type, ok: false, reason: 'NPC 베팅 입력 이벤트가 일치하지 않습니다.' };
}
}
if (new Set(command.bets.map((bet) => bet.generalId)).size !== command.bets.length) {
return { type: command.type, ok: false, reason: 'NPC 베팅 대상이 중복됩니다.' };
}
const processedGeneralIds: number[] = [];
const skippedGeneralIds: number[] = [];
for (const bet of command.bets) {
const general = ctx.world.getGeneralById(bet.generalId);
// 계획 이후 유저가 빙의한 장수는 NPC 비용·통계를 변경하지 않는다.
if (!general || general.userId != null || general.npcState < 2 || general.gold - bet.amount < 500) {
skippedGeneralIds.push(bet.generalId);
continue;
}
const current = typeof general.meta.betgold === 'number' ? general.meta.betgold : 0;
ctx.world.updateGeneral(bet.generalId, {
gold: general.gold - bet.amount,
meta: { ...general.meta, betgold: current + bet.amount },
});
processedGeneralIds.push(bet.generalId);
}
return { type: command.type, ok: true, processedGeneralIds, skippedGeneralIds };
}
const isLegacyTournamentAdjustment = (reason: string | undefined): boolean =>
reason !== undefined &&
['tournamentJoin', 'tournamentJoinRollback', 'tournamentBet', 'tournamentBetRollback', 'tournamentNpcBet'].includes(
reason
);
async function handleAdjustGeneralResources(
ctx: CommandHandlerContext,
command: Extract<TurnDaemonCommand, { type: 'adjustGeneralResources' }>
): Promise<TurnDaemonCommandResult> {
const { world } = ctx;
if (isLegacyTournamentAdjustment(command.reason)) {
return { type: command.type, ok: false, reason: '소유권 없는 이전 토너먼트 조정 명령은 허용하지 않습니다.' };
}
if (!command.adjustments || command.adjustments.length === 0) {
return { type: 'adjustGeneralResources', ok: false, reason: '조정 대상이 없습니다.' };
}
@@ -688,6 +763,9 @@ async function handleAdjustGeneralMeta(
command: Extract<TurnDaemonCommand, { type: 'adjustGeneralMeta' }>
): Promise<TurnDaemonCommandResult> {
const { world } = ctx;
if (isLegacyTournamentAdjustment(command.reason)) {
return { type: command.type, ok: false, reason: '소유권 없는 이전 토너먼트 조정 명령은 허용하지 않습니다.' };
}
if (!command.adjustments || command.adjustments.length === 0) {
return {
type: 'adjustGeneralMeta',
@@ -2004,8 +2082,10 @@ async function handleSetMySetting(
const scenarioEffect = world.getScenarioConfig().environment.scenarioEffect;
const ignoresPenalty = isDefenceTrainPenaltyWaivedByScenarioEffect(scenarioEffect);
const constValues = asRecord(world.getScenarioConfig().const);
const maxTrain = readMetaNumber(constValues, 'maxTrainByWar', 100);
const maxAtmos = readMetaNumber(constValues, 'maxAtmosByWar', 100);
// Ref GameConstBase의 전투 상한을 사용한다. 명령 상한(100)으로 제한하면
// 전투에서 오른 훈련·사기가 수비끔 전환 한 번에 소실된다.
const maxTrain = readMetaNumber(constValues, 'maxTrainByWar', 110);
const maxAtmos = readMetaNumber(constValues, 'maxAtmosByWar', 150);
const trainDelta = ignoresPenalty ? 0 : -3;
const atmosDelta = ignoresPenalty ? 0 : -6;
nextTrain = Math.max(20, Math.min(maxTrain, general.train + trainDelta));
@@ -2785,8 +2865,8 @@ const insertVoteSelection = async (
}
const createdAt = new Date();
const rows = await ctx.commandDb.$queryRaw<Array<{ id: number }>>(GamePrisma.sql`
INSERT INTO vote (vote_id, general_id, nation_id, selection, created_at)
SELECT poll.id,
INSERT INTO vote (id, vote_id, general_id, nation_id, selection, created_at)
SELECT ${existingRowIdOrNext('vote', GamePrisma.sql`stable_id.vote_id = poll.id AND stable_id.general_id = ${general.id}`)}, poll.id,
${general.id},
${general.nationId},
CAST(${JSON.stringify(selection)} AS jsonb),
@@ -3267,6 +3347,13 @@ export const createTurnDaemonCommandHandler = (options: {
handleSetNationSetting(ctx, command as Extract<TurnDaemonCommand, { type: 'setNationSetting' }>),
setNpcPolicy: (command) =>
handleSetNpcPolicy(ctx, command as Extract<TurnDaemonCommand, { type: 'setNpcPolicy' }>),
tournamentAdjustGeneral: (command) =>
handleTournamentAdjustGeneral(
ctx,
command as Extract<TurnDaemonCommand, { type: 'tournamentAdjustGeneral' }>
),
tournamentSeedNpcBets: (command) =>
handleTournamentSeedNpcBets(ctx, command as Extract<TurnDaemonCommand, { type: 'tournamentSeedNpcBets' }>),
adjustGeneralResources: (command) =>
handleAdjustGeneralResources(
ctx,
@@ -1,3 +1,4 @@
import { upsertWithoutSequence } from '@sammo-ts/infra';
import { createHash } from 'node:crypto';
import type { GamePrisma, InputJsonValue } from '@sammo-ts/infra';
@@ -44,7 +45,7 @@ export const persistYearbookSnapshot = async (
globalAction,
});
await transaction.yearbookHistory.upsert({
await upsertWithoutSequence(transaction.yearbookHistory, {
where: {
profileName_year_month_sourceId: {
profileName: snapshot.serverId,
@@ -7,6 +7,16 @@ import { normalizeTurnDaemonCommand } from '../src/turn/commandRegistry.js';
import { createTurnDaemonCommandHandler } from '../src/turn/worldCommandHandler.js';
const buildActorBoundCommands = (userId = 'old-owner'): TurnDaemonCommand[] => [
{
type: 'tournamentAdjustGeneral',
reason: 'tournamentBet',
requestId: 'tournamentAdjustGeneral',
userId,
generalId: 7,
goldDelta: -100,
betGoldDelta: 100,
minGoldAfter: 500,
},
{ type: 'troopCreate', requestId: 'troopCreate', userId, generalId: 7, troopName: '백마대' },
{ type: 'troopJoin', requestId: 'troopJoin', userId, generalId: 7, troopId: 8 },
{ type: 'troopExit', requestId: 'troopExit', userId, generalId: 7 },
@@ -274,69 +274,79 @@ integration('database command queue', () => {
});
});
it('stores a stale-owner rejection once and never redispatches the exact durable request', async () => {
const requestId = 'integration:engine:stale-owner-replay';
const command: TurnDaemonCommand = {
type: 'vacation',
requestId,
userId: 'old-owner',
generalId: 7,
};
await db.inputEvent.create({
data: {
requestId,
target: 'ENGINE',
eventType: command.type,
it.each(['vacation', 'tournamentAdjustGeneral'] as const)(
'stores a stale-owner %s rejection once and never redispatches it',
async (type) => {
const requestId = `integration:engine:stale-owner-replay:${type}`;
const command: TurnDaemonCommand =
type === 'vacation'
? { type, requestId, userId: 'old-owner', generalId: 7 }
: {
type,
reason: 'tournamentBet',
requestId,
userId: 'old-owner',
generalId: 7,
goldDelta: -100,
betGoldDelta: 100,
minGoldAfter: 500,
};
await db.inputEvent.create({
data: {
requestId,
target: 'ENGINE',
eventType: command.type,
actorUserId: command.userId,
payload: command as GamePrisma.InputJsonValue,
},
});
const mutation = vi.fn();
const world = {
getGeneralById: vi.fn(() => ({ id: command.generalId, userId: 'new-owner' })),
updateGeneral: mutation,
updateNation: mutation,
createTroop: mutation,
updateTroop: mutation,
removeTroop: mutation,
pushLog: mutation,
queueMessage: mutation,
} as unknown as InMemoryTurnWorld;
const handler = createTurnDaemonCommandHandler({ world });
const handle = vi.spyOn(handler, 'handle');
const owner = new DatabaseTurnDaemonCommandQueue(db);
const claimed = await owner.drain();
expect(claimed).toEqual([
{
...command,
processingGameTick: 123,
requestedAtWall: expect.any(Date),
},
]);
const result = await db.$transaction((transaction) => handler.handle(claimed[0]!, { db: transaction }));
expect(result).toMatchObject({
type: 'commandRejected',
ok: false,
commandType: command.type,
});
await owner.publishCommandResult(requestId, result!);
await expect(db.inputEvent.findUniqueOrThrow({ where: { requestId } })).resolves.toMatchObject({
status: 'SUCCEEDED',
attempts: 1,
actorUserId: command.userId,
payload: command as GamePrisma.InputJsonValue,
},
});
const mutation = vi.fn();
const world = {
getGeneralById: vi.fn(() => ({ id: command.generalId, userId: 'new-owner' })),
updateGeneral: mutation,
updateNation: mutation,
createTroop: mutation,
updateTroop: mutation,
removeTroop: mutation,
pushLog: mutation,
queueMessage: mutation,
} as unknown as InMemoryTurnWorld;
const handler = createTurnDaemonCommandHandler({ world });
const handle = vi.spyOn(handler, 'handle');
const owner = new DatabaseTurnDaemonCommandQueue(db);
const claimed = await owner.drain();
expect(claimed).toEqual([
{
...command,
processingGameTick: 123,
requestedAtWall: expect.any(Date),
},
]);
const result = await db.$transaction((transaction) => handler.handle(claimed[0]!, { db: transaction }));
expect(result).toMatchObject({
type: 'commandRejected',
ok: false,
commandType: command.type,
});
await owner.publishCommandResult(requestId, result!);
await expect(db.inputEvent.findUniqueOrThrow({ where: { requestId } })).resolves.toMatchObject({
status: 'SUCCEEDED',
attempts: 1,
actorUserId: command.userId,
eventType: command.type,
payload: command,
result,
lockedBy: null,
leaseUntil: null,
});
await expect(new DatabaseTurnDaemonCommandQueue(db).drain()).resolves.toEqual([]);
expect(handle).toHaveBeenCalledOnce();
expect(mutation).not.toHaveBeenCalled();
});
eventType: command.type,
payload: command,
result,
lockedBy: null,
leaseUntil: null,
});
await expect(new DatabaseTurnDaemonCommandQueue(db).drain()).resolves.toEqual([]);
expect(handle).toHaveBeenCalledOnce();
expect(mutation).not.toHaveBeenCalled();
}
);
it.each(['PREOPEN', 'RUNNING', 'MANUAL', 'SUSPENDED', 'RECONCILING', 'COMPLETED'])(
'handles pre-opening user commands in %s without treating them as scheduled turns',
@@ -630,6 +640,8 @@ integration('database command queue', () => {
const metaId = 'integration:engine:suspended-tournament-bet-meta';
const rollbackId = 'integration:engine:suspended-tournament-bet-rollback';
const unrelatedId = 'integration:engine:suspended-resource-adjustment';
const atomicBetId = 'integration:engine:suspended-atomic-bet';
const atomicJoinId = 'integration:engine:suspended-atomic-join';
await db.inputEvent.createMany({
data: [
{
@@ -679,6 +691,41 @@ integration('database command queue', () => {
],
});
await db.inputEvent.createMany({
data: [
{
requestId: atomicBetId,
target: 'ENGINE',
eventType: 'tournamentAdjustGeneral',
actorUserId: 'user-7',
payload: {
type: 'tournamentAdjustGeneral',
requestId: atomicBetId,
userId: 'user-7',
generalId: 7,
reason: 'tournamentBet',
goldDelta: -100,
betGoldDelta: 100,
minGoldAfter: 500,
},
},
{
requestId: atomicJoinId,
target: 'ENGINE',
eventType: 'tournamentAdjustGeneral',
actorUserId: 'user-7',
payload: {
type: 'tournamentAdjustGeneral',
requestId: atomicJoinId,
userId: 'user-7',
generalId: 7,
reason: 'tournamentJoin',
goldDelta: -200,
minGoldAfter: 0,
},
},
],
});
const queue = new DatabaseTurnDaemonCommandQueue(db);
await expect(queue.drain()).resolves.toEqual([
expect.objectContaining({ type: 'adjustGeneralResources', requestId: resourceId, reason: 'tournamentBet' }),
@@ -688,7 +735,15 @@ integration('database command queue', () => {
requestId: rollbackId,
reason: 'tournamentBetRollback',
}),
expect.objectContaining({
type: 'tournamentAdjustGeneral',
requestId: atomicBetId,
reason: 'tournamentBet',
}),
]);
await expect(db.inputEvent.findUniqueOrThrow({ where: { requestId: atomicJoinId } })).resolves.toMatchObject({
status: 'PENDING',
});
await expect(db.inputEvent.findUniqueOrThrow({ where: { requestId: resourceId } })).resolves.toMatchObject({
status: 'PROCESSING',
processingGameTick: 321n,
@@ -198,6 +198,23 @@ integration('general batch persistence', () => {
);
});
expect(writes).toBe(2);
const originalIds = (
await db.generalAccessLog.findMany({
where: { generalId: { gte: firstId, lte: firstId + GENERAL_UPDATE_BATCH_SIZE } },
orderBy: { generalId: 'asc' },
})
).map((row) => row.id);
const sequence = await db.$queryRaw`SELECT last_value FROM general_access_log_id_seq`;
await db.$transaction((tx) => persistGeneralAccessScores(tx, updates));
expect(
(
await db.generalAccessLog.findMany({
where: { generalId: { gte: firstId, lte: firstId + GENERAL_UPDATE_BATCH_SIZE } },
orderBy: { generalId: 'asc' },
})
).map((row) => row.id)
).toEqual(originalIds);
expect(await db.$queryRaw`SELECT last_value FROM general_access_log_id_seq`).toEqual(sequence);
expect(await db.generalAccessLog.findUniqueOrThrow({ where: { generalId: firstId } })).toMatchObject({
userId: 'original-owner',
lastRefresh: at,
@@ -1,12 +1,20 @@
import { describe, expect, it, vi } from 'vitest';
import type { GamePrisma } from '@sammo-ts/infra';
import { GamePrisma } from '@sammo-ts/infra';
import { LogCategory, LogScope } from '@sammo-ts/logic';
import { persistGeneralLifecycleEvents } from '../src/turn/generalTurnLifecyclePersistence.js';
import type { GeneralLifecycleEvent } from '../src/turn/inMemoryWorld.js';
import type { TurnGeneral } from '../src/turn/types.js';
// This harness begins without the durable archive/point row.
const missingRecordUpdate = async (): Promise<never> => {
throw new GamePrisma.PrismaClientKnownRequestError('fixture record missing', {
code: 'P2025',
clientVersion: 'fixture',
});
};
const archivedGeneral = (): TurnGeneral => ({
id: 91,
userId: null,
@@ -65,12 +73,13 @@ describe('general lifecycle archive history', () => {
]),
},
rankData: {
update: missingRecordUpdate,
findMany: vi.fn(async () => [
{ type: 'warnum', value: 2 },
{ type: 'killnum', value: 1 },
]),
},
oldGeneral: { upsert },
oldGeneral: { update: missingRecordUpdate, upsert },
} as unknown as GamePrisma.TransactionClient;
const event: GeneralLifecycleEvent = {
generalId: general.id,
@@ -137,6 +146,7 @@ describe('general lifecycle archive history', () => {
updateMany: vi.fn(async () => ({ count: 1 })),
},
rankData: {
update: missingRecordUpdate,
findMany: vi.fn(async () => [
{ type: 'warnum', value: 10 },
{ type: 'inherit_earned', value: 123 },
@@ -156,6 +166,7 @@ describe('general lifecycle archive history', () => {
update: vi.fn(async () => undefined),
},
inheritancePoint: {
update: missingRecordUpdate,
findMany: vi.fn(async () => [{ key: 'previous', value: 0 }]),
upsert: vi.fn(async () => undefined),
deleteMany: vi.fn(async () => ({ count: 0 })),
@@ -0,0 +1,134 @@
import { createHmac, randomBytes } from 'node:crypto';
import { once } from 'node:events';
import { createServer } from 'node:http';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createHostBootMonitor, loadHostBootMonitor } from '../src/turn/hostBootMonitor.js';
const cleanups: Array<() => Promise<void>> = [];
afterEach(async () => {
await Promise.all(cleanups.splice(0).map((cleanup) => cleanup()));
});
const fixture = async () => {
const key = randomBytes(32);
let bootId = 'a'.repeat(64);
let replay: string | null = null;
let mode: 'valid' | 'replay' | 'forged' | 'oversized' | 'offline' | 'hang' = 'valid';
const requests: string[] = [];
const server = createServer((request, response) => {
const nonce = String(request.headers['x-sammo-challenge']);
requests.push(nonce);
expect(request.headers['x-sammo-signature']).toBe(
createHmac('sha256', key).update(`sammo-host-boot-request-v1\n${nonce}`).digest('hex')
);
if (mode === 'hang') return;
if (mode === 'offline') {
response.writeHead(503).end();
return;
}
if (mode === 'oversized') {
response.end('x'.repeat(4096));
return;
}
if (mode === 'replay') {
response.end(replay);
return;
}
const body = JSON.stringify({
version: 1,
challenge: nonce,
bootId,
signature:
mode === 'forged'
? '0'.repeat(64)
: createHmac('sha256', key)
.update(`sammo-host-boot-response-v1\n${nonce}\n${bootId}`)
.digest('hex'),
});
replay ??= body;
response.end(body);
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
cleanups.push(
() =>
new Promise<void>((resolve) => {
server.close(() => resolve());
server.closeAllConnections();
})
);
const address = server.address();
if (!address || typeof address === 'string') throw new Error('Missing fixture listener');
return {
key,
requests,
url: `http://127.0.0.1:${address.port}/v1/boot-id`,
setBoot: (value: string) => {
bootId = value;
},
setMode: (value: typeof mode) => {
mode = value;
},
};
};
describe('Windows boot observation', () => {
it('uses a stable baseline, survives outages, and latches a signed boot change', async () => {
const f = await fixture();
const monitor = createHostBootMonitor({ ...f, pollMs: 0 });
expect(await monitor.hasChanged()).toBe(false);
f.setMode('offline');
expect(await monitor.hasChanged()).toBe(false);
f.setBoot('b'.repeat(64));
f.setMode('valid');
expect(await monitor.hasChanged()).toBe(true);
f.setMode('offline');
expect(await monitor.hasChanged()).toBe(true);
});
it.each(['replay', 'forged', 'oversized', 'hang'] as const)(
'rejects %s without changing the baseline',
async (mode) => {
const f = await fixture();
const onUnavailable = vi.fn();
const monitor = createHostBootMonitor({ ...f, pollMs: 0, timeoutMs: 100, onUnavailable });
expect(await monitor.hasChanged()).toBe(false);
f.setBoot('b'.repeat(64));
f.setMode(mode);
expect(await monitor.hasChanged()).toBe(false);
expect(onUnavailable).toHaveBeenCalledOnce();
f.setMode('valid');
expect(await monitor.hasChanged()).toBe(true);
}
);
it('samples immediately after a wall-clock jump despite a frozen monotonic cache and coalesces requests', async () => {
const f = await fixture();
let wall = 10_000;
const monitor = createHostBootMonitor({ ...f, now: () => 0, wallNow: () => wall });
expect(await monitor.hasChanged()).toBe(false);
expect(await monitor.hasChanged()).toBe(false);
expect(f.requests).toHaveLength(1);
wall += 300_000;
f.setBoot('b'.repeat(64));
expect(await Promise.all([monitor.hasChanged(), monitor.hasChanged()])).toEqual([true, true]);
expect(f.requests).toHaveLength(2);
expect(new Set(f.requests).size).toBe(2);
});
it('does not block game startup when optional configuration or its key file is absent', async () => {
const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
expect(await loadHostBootMonitor({})).toBeUndefined();
expect(await loadHostBootMonitor({ TURN_HOST_BOOT_URL: 'http://host/v1/boot-id' })).toBeUndefined();
expect(
await loadHostBootMonitor({
TURN_HOST_BOOT_URL: 'http://host/v1/boot-id',
TURN_HOST_BOOT_KEY_FILE: '/nonexistent-host-boot-key',
})
).toBeUndefined();
expect(() =>
createHostBootMonitor({ url: 'http://user:password@host/v1/boot-id', key: randomBytes(32) })
).toThrow('without credentials');
warning.mockRestore();
});
});
@@ -87,7 +87,11 @@ const buildGeneral = (overrides: Partial<TurnGeneral> = {}): TurnGeneral => ({
const buildWorld = (
general = buildGeneral(),
options: { autorunLimit?: boolean; scenarioEffect?: ScenarioEffectKey | null } = {}
options: {
autorunLimit?: boolean;
scenarioEffect?: ScenarioEffectKey | null;
scenarioConst?: Record<string, unknown>;
} = {}
) => {
const state: TurnWorldState = {
id: 1,
@@ -126,7 +130,7 @@ const buildWorld = (
stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 50, npcMin: 10, chiefMin: 65 },
iconPath: '',
map: {},
const: { maxTrainByWar: 100, maxAtmosByWar: 100 },
const: options.scenarioConst ?? {},
environment: {
mapName: 'test',
unitSet: 'test',
@@ -277,6 +281,53 @@ describe('my information world commands', () => {
});
});
it.each([
{ train: 110, atmos: 150, expectedTrain: 107, expectedAtmos: 144 },
{ train: 104, atmos: 107, expectedTrain: 101, expectedAtmos: 101 },
{ train: 90, atmos: 90, expectedTrain: 87, expectedAtmos: 84 },
{ train: 21, atmos: 25, expectedTrain: 20, expectedAtmos: 20 },
{
train: 140,
atmos: 180,
scenarioConst: { maxTrainByWar: 120, maxAtmosByWar: 160 },
expectedTrain: 120,
expectedAtmos: 160,
},
{
train: 110,
atmos: 150,
scenarioConst: { maxTrainByWar: 100, maxAtmosByWar: 100 },
expectedTrain: 100,
expectedAtmos: 100,
},
])('applies war caps to no-defence penalties: $train/$atmos', async (testCase) => {
const fixture = buildWorld(buildGeneral({ train: testCase.train, atmos: testCase.atmos }), {
scenarioConst: testCase.scenarioConst,
});
const command = {
type: 'setMySetting' as const,
userId: 'user-7',
generalId: 7,
settings: { defence_train: 999 },
};
await expect(fixture.handler.handle(command)).resolves.toMatchObject({ ok: true });
const expected = {
train: testCase.expectedTrain,
atmos: testCase.expectedAtmos,
meta: { defence_train: 999, myset: 2 },
};
expect(fixture.world.getGeneralById(7)).toMatchObject(expected);
// 같은 설정의 재저장과 수비 재개는 훈련·사기를 다시 차감하지 않는다.
await fixture.handler.handle(command);
expect(fixture.world.getGeneralById(7)).toMatchObject(expected);
await fixture.handler.handle({ ...command, settings: { defence_train: 90 } });
expect(fixture.world.getGeneralById(7)).toMatchObject({
...expected,
meta: { defence_train: 90, myset: 1 },
});
});
it.each([
'event_UnlimitedDefenceThresholdChange',
'event_StrongAttacker',
@@ -284,14 +335,18 @@ describe('my information world commands', () => {
] satisfies ScenarioEffectKey[])(
'preserves the %s scenario that waives the no-defence penalty',
async (scenarioEffect) => {
const fixture = buildWorld(buildGeneral(), { scenarioEffect });
const fixture = buildWorld(buildGeneral({ train: 110, atmos: 150 }), { scenarioEffect });
await fixture.handler.handle({
type: 'setMySetting',
userId: 'user-7',
generalId: 7,
settings: { defence_train: 999 },
});
expect(fixture.world.getGeneralById(7)).toMatchObject({ train: 90, atmos: 90 });
expect(fixture.world.getGeneralById(7)).toMatchObject({
train: 110,
atmos: 150,
meta: { defence_train: 999, myset: 2 },
});
}
);
@@ -1,7 +1,12 @@
import { writeFile } from 'node:fs/promises';
import { performance } from 'node:perf_hooks';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { createGamePostgresConnector, type GamePrisma, type GamePrismaClient } from '@sammo-ts/infra';
import {
decodeAuditDecisionSteps,
createGamePostgresConnector,
type GamePrisma,
type GamePrismaClient,
} from '@sammo-ts/infra';
import { persistAuditDecisions } from '../src/playAudit/decisionPersistence.js';
import { buildAuditDecisionFixture } from './fixtures/playAuditDecision.js';
@@ -61,11 +66,15 @@ describe.skipIf(!databaseUrl)('decision storage cost probe', () => {
>`
SELECT
(SELECT count(*) FROM play_audit_decision) AS headers,
(SELECT sum(jsonb_array_length(steps)) FROM play_audit_decision_chunk) AS steps,
(SELECT sum(step_count) FROM play_audit_decision) AS steps,
(SELECT sum(pg_column_size(d)) FROM play_audit_decision d) AS "headerBytes",
(SELECT sum(pg_column_size(c)) FROM play_audit_decision_chunk c) AS "chunkBytes"
`;
expect(Number(storage!.steps)).toBe(201 * 302);
const chunks = await db.playAuditDecisionChunk.findMany({ select: { steps: true } });
expect(chunks.reduce((total, chunk) => total + decodeAuditDecisionSteps(chunk.steps).length, 0)).toBe(
201 * 302
);
const relations = await db.$queryRaw<
{ name: string; tableBytes: bigint; indexBytes: bigint; totalBytes: bigint }[]
>`
@@ -99,7 +108,8 @@ describe.skipIf(!databaseUrl)('decision storage cost probe', () => {
`;
const metrics = {
scope: 'synthetic 201 decisions, 302 steps each; isolated schema, warm local reads',
limitations: 'Not production p95; no gameplay baseline, WAL or retained heap measurement. SQL counts cover only the persistence transaction. Repetitive synthetic steps compress well. Relation allocation can retain space from previous runs.',
limitations:
'Not production p95; no gameplay baseline, WAL or retained heap measurement. SQL counts cover only the persistence transaction. Repetitive synthetic steps compress well. Relation allocation can retain space from previous runs.',
decisions: 201,
steps: Number(storage!.steps),
chunks: 603,
@@ -1,5 +1,5 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { createGamePostgresConnector, type GamePrismaClient } from '@sammo-ts/infra';
import { decodeAuditDecisionSteps, createGamePostgresConnector, type GamePrismaClient } from '@sammo-ts/infra';
import { persistAuditDecisions } from '../src/playAudit/decisionPersistence.js';
import { buildAuditExecutionFixture, buildAuditDecisionFixture as draft } from './fixtures/playAuditDecision.js';
import { prunePreviousAuditBatch } from '../src/playAudit/retention.js';
@@ -36,7 +36,40 @@ integration('decision persistence and bounded retention', () => {
});
it('rolls back gameplay/header/chunks on insert failure, retries and rejects divergent replay', async () => {
const decision = draft('decision-one');
if (decision.steps[0]?.kind === 'DECISION_START') decision.steps[0].effectivePolicy = {"schemaVersion":1,"general":{"priority":["징병"],"flags":{"징병":true,"출병":false}},"nation":{"priority":["천도"],"flags":{"천도":true},"values":{"reqNationGold":4321,"reqNationRice":100,"reqHumanWarUrgentGold":100,"reqHumanWarUrgentRice":100,"reqHumanWarRecommandGold":100,"reqHumanWarRecommandRice":100,"reqHumanDevelGold":100,"reqHumanDevelRice":100,"reqNpcWarGold":100,"reqNpcWarRice":100,"reqNpcDevelGold":100,"reqNpcDevelRice":100,"minimumResourceActionAmount":100,"maximumResourceActionAmount":100,"minNpcWarLeadership":100,"minWarCrew":100,"minNpcRecruitCityPopulation":100,"safeRecruitCityPopulationRatio":100,"properWarTrainAtmos":100,"cureThreshold":100},"combatForce":{"1":[2,3]},"supportForce":[4],"developForce":[5]}};
if (decision.steps[0]?.kind === 'DECISION_START')
decision.steps[0].effectivePolicy = {
schemaVersion: 1,
general: { priority: ['징병'], flags: { 징병: true, 출병: false } },
nation: {
priority: ['천도'],
flags: { 천도: true },
values: {
reqNationGold: 4321,
reqNationRice: 100,
reqHumanWarUrgentGold: 100,
reqHumanWarUrgentRice: 100,
reqHumanWarRecommandGold: 100,
reqHumanWarRecommandRice: 100,
reqHumanDevelGold: 100,
reqHumanDevelRice: 100,
reqNpcWarGold: 100,
reqNpcWarRice: 100,
reqNpcDevelGold: 100,
reqNpcDevelRice: 100,
minimumResourceActionAmount: 100,
maximumResourceActionAmount: 100,
minNpcWarLeadership: 100,
minWarCrew: 100,
minNpcRecruitCityPopulation: 100,
safeRecruitCityPopulationRatio: 100,
properWarTrainAtmos: 100,
cureThreshold: 100,
},
combatForce: { '1': [2, 3] },
supportForce: [4],
developForce: [5],
},
};
decision.summary.codeVersion = 'a'.repeat(40);
decision.summary.executionCoverage = 'ATTEMPTS';
decision.steps.push({ ...decision.steps[0]!, ...buildAuditExecutionFixture(), sequence: 302 });
@@ -85,7 +118,7 @@ integration('decision persistence and bounded retention', () => {
orderBy: { ordinal: 'asc' },
});
expect(chunks).toHaveLength(3);
expect(chunks.flatMap((chunk) => chunk.steps)).toEqual(decision.steps);
expect(chunks.flatMap((chunk) => decodeAuditDecisionSteps(chunk.steps))).toEqual(decision.steps);
await expect(
db.$transaction((tx) =>
persistAuditDecisions(tx, [{ ...decision, summary: { ...decision.summary, completed: true } }])
@@ -109,10 +142,34 @@ integration('decision persistence and bounded retention', () => {
expect(await db.playAuditDecisionChunk.count({ where: { decisionId: 'decision-one' } })).toBe(204);
expect(await db.playAuditDecision.count({ where: { id: 'decision-one' } })).toBe(1);
expect(await prunePreviousAuditBatch(db, 'decision-current')).toEqual({ status: 'progress', deleted: 200 });
expect(await prunePreviousAuditBatch(db, 'decision-current')).toEqual({ status: 'progress', deleted: 4 });
expect(await prunePreviousAuditBatch(db, 'decision-current')).toEqual({ status: 'progress', deleted: 1 });
expect(await prunePreviousAuditBatch(db, 'decision-current')).toEqual({ status: 'progress', deleted: 5 });
expect(await prunePreviousAuditBatch(db, 'decision-current')).toEqual({ status: 'complete', deleted: 0 });
expect(await db.playAuditDecision.count()).toBe(1);
expect(await db.playAuditDecisionChunk.count()).toBe(3);
});
it('removes many small decisions in one bounded batch and rolls chunks back on header failure', async () => {
const decisions = Array.from({ length: 100 }, (_, index) => {
const row = draft(`batch-old-${index}`, 'batch-old');
return { ...row, steps: [row.steps[0]!, row.steps.at(-1)!] };
});
await db.$transaction((tx) => persistAuditDecisions(tx, decisions));
await db.$executeRawUnsafe(
`CREATE OR REPLACE FUNCTION decision_header_failure() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'header fixture rollback'; END $$`
);
await db.$executeRawUnsafe(
`CREATE TRIGGER decision_header_failure BEFORE DELETE ON play_audit_decision FOR EACH ROW EXECUTE FUNCTION decision_header_failure()`
);
try {
await expect(prunePreviousAuditBatch(db, 'decision-current')).rejects.toThrow();
expect(
await db.playAuditDecisionChunk.count({ where: { decisionId: { in: decisions.map(({ id }) => id) } } })
).toBe(100);
} finally {
await db.$executeRawUnsafe('DROP TRIGGER decision_header_failure ON play_audit_decision');
await db.$executeRawUnsafe('DROP FUNCTION decision_header_failure()');
}
expect(await prunePreviousAuditBatch(db, 'decision-current')).toEqual({ status: 'progress', deleted: 200 });
expect(await db.playAuditDecision.count()).toBe(1);
expect(await prunePreviousAuditBatch(db, 'decision-current')).toEqual({ status: 'complete', deleted: 0 });
});
});
@@ -20,7 +20,7 @@ describe('audit retention scheduling', () => {
expect(prune).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(30_001);
expect(prune).toHaveBeenCalledTimes(3);
await vi.advanceTimersByTimeAsync(1000);
await vi.advanceTimersByTimeAsync(100);
expect(prune).toHaveBeenCalledTimes(4);
await vi.advanceTimersByTimeAsync(600_000);
expect(prune).toHaveBeenCalledTimes(4);
@@ -0,0 +1,147 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { createGamePostgresConnector, type GamePrismaClient } from '@sammo-ts/infra';
import { upsertRankRows } from '../src/turn/databaseHooks.js';
const databaseUrl = process.env.IMMEDIATE_ACTION_DATABASE_URL;
// The conditional runner owns this schema and runs integration files serially.
describe.skipIf(!databaseUrl)('rank data bigint PostgreSQL persistence', () => {
let db: GamePrismaClient;
let disconnect: () => Promise<void>;
const generalId = 7_319;
beforeAll(async () => {
const schema = new URL(databaseUrl!).searchParams.get('schema');
if (!schema?.endsWith('immediate_action_integration')) {
throw new Error('Refusing to mutate a non-dedicated rank persistence schema');
}
const connector = createGamePostgresConnector({ url: databaseUrl! });
await connector.connect();
db = connector.prisma;
disconnect = () => connector.disconnect();
await db.rankData.deleteMany({ where: { generalId } });
// Even conflict-update on an existing row used to exhaust int4 IDs.
await db.$executeRaw`SELECT setval(pg_get_serial_sequence('rank_data', 'id'), 2147483647)`;
});
afterAll(async () => {
if (db) await db.rankData.deleteMany({ where: { generalId } });
await disconnect?.();
});
it('reuses IDs across batches, updates ownership and values, and allocates bigint IDs only for new rows', async () => {
const rows = Array.from({ length: 1_001 }, (_, index) => ({
generalId,
nationId: 10,
type: `rank_fixture_${index}`,
value: index,
}));
await db.$transaction((tx) => upsertRankRows(tx, rows));
const original = await db.rankData.findMany({ where: { generalId }, orderBy: { type: 'asc' } });
expect(original).toHaveLength(rows.length);
expect(original.every((row) => row.id > 2_147_483_647n)).toBe(true);
const sequenceBefore = await db.$queryRaw<
Array<{ last_value: bigint }>
>`SELECT last_value FROM rank_data_id_seq`;
for (let count = 0; count < 3; count++) {
await db.$transaction((tx) =>
upsertRankRows(
tx,
rows.map((row) => ({ ...row, nationId: 20, value: row.value + 3 }))
)
);
}
const updated = await db.rankData.findMany({ where: { generalId }, orderBy: { type: 'asc' } });
expect(updated.map((row) => row.id)).toEqual(original.map((row) => row.id));
expect(updated.map((row) => [row.nationId, row.value])).toEqual(original.map((row) => [20, row.value + 3]));
expect(await db.$queryRaw`SELECT last_value FROM rank_data_id_seq`).toEqual(sequenceBefore);
await db.$transaction((tx) =>
upsertRankRows(tx, [rows[0]!, { generalId, nationId: 30, type: 'new_rank', value: 17 }])
);
expect(await db.rankData.count({ where: { generalId } })).toBe(1_002);
expect(await db.$queryRaw`SELECT last_value FROM rank_data_id_seq`).toEqual([
{ last_value: sequenceBefore[0]!.last_value + 1n },
]);
});
it('reloads bigint IDs for high churn queues, logs, upserts and the traffic foreign key', async () => {
const tables = [
'general_access_log',
'diplomacy',
'inheritance_point',
'log_entry',
'error_log',
'inheritance_log',
'traffic_period',
];
for (const table of tables) {
await db.$executeRaw`SELECT setval(pg_get_serial_sequence(${table}, 'id'), 2147483647)`;
}
await expect(
db.$transaction(async (tx) => {
const now = new Date();
const world = await tx.worldState.create({
data: {
scenarioCode: 'bigint-fixture',
currentYear: 200,
currentMonth: 1,
tickSeconds: 600,
},
});
const rows = await Promise.all([
tx.generalAccessLog.create({ data: { generalId } }),
tx.diplomacy.create({ data: { srcNationId: 3, destNationId: 4, stateCode: 0 } }),
tx.inheritancePoint.create({ data: { userId: 'bigint-fixture', key: 'previous', value: 123 } }),
tx.logEntry.create({
data: { scope: 'SYSTEM', category: 'HISTORY', year: 200, month: 1, text: 'fixture' },
}),
tx.errorLog.create({ data: { category: 'fixture', message: 'fixture' } }),
tx.inheritanceLog.create({
data: { userId: 'bigint-fixture', year: 200, month: 1, text: 'fixture' },
}),
]);
expect(rows.every((row) => row.id > 2_147_483_647n)).toBe(true);
const generalQueue = await tx.generalTurn.create({
data: { generalId, turnIdx: 0, actionCode: 'fixture' },
});
const nationQueue = await tx.nationTurn.create({
data: { nationId: 3, officerLevel: 12, turnIdx: 0, actionCode: 'fixture' },
});
expect(generalQueue).not.toHaveProperty('id');
expect(nationQueue).not.toHaveProperty('id');
const period = await tx.trafficPeriod.create({
data: {
worldStateId: world.id,
year: 200,
month: 1,
startedAt: now,
lastRefresh: now,
generals: { create: { generalId, lastRefresh: now } },
},
include: { generals: true },
});
expect(period.id).toBeGreaterThan(2_147_483_647n);
expect(period.generals[0]?.periodId).toBe(period.id);
expect((await tx.logEntry.findUniqueOrThrow({ where: { id: rows[3]!.id } })).text).toBe('fixture');
throw new Error('high churn fixture rollback');
})
).rejects.toThrow('high churn fixture rollback');
});
it('rolls value updates back atomically and retains the logical unique constraint', async () => {
const where = { generalId_type: { generalId, type: 'new_rank' } };
const before = await db.rankData.findUniqueOrThrow({ where });
await expect(
db.$transaction(async (tx) => {
await upsertRankRows(tx, [{ generalId, nationId: 99, type: 'new_rank', value: 999 }]);
throw new Error('fixture rollback');
})
).rejects.toThrow('fixture rollback');
expect(await db.rankData.findUniqueOrThrow({ where })).toEqual(before);
await expect(
db.rankData.create({ data: { generalId, nationId: 99, type: 'new_rank', value: 999 } })
).rejects.toThrow();
});
});
@@ -4,7 +4,9 @@ import { createGamePostgresConnector } from '@sammo-ts/infra';
import {
InMemoryReservedTurnStore,
ReservedTurnLeaseConflictError,
createReservedTurnStore,
} from '../src/turn/reservedTurnStore.js';
import { createReservedTurnLeaseRetry } from '../src/turn/reservedTurnLeaseRetry.js';
const databaseUrl = process.env.RESERVED_TURN_DATABASE_URL;
const describeIntegration = databaseUrl ? describe : describe.skip;
@@ -132,4 +134,98 @@ describeIntegration('reserved turn daemon/API lease integration', () => {
});
expect(after.map((turn) => turn.actionCode)).toEqual(before.map((turn) => turn.actionCode));
});
it('cleans persisted ownership after rollback loses the journal, preserves other writers, and reloads once', async () => {
if (!connector || !databaseUrl) throw new Error('integration connector is unavailable');
await connector.prisma.generalTurnRevision.update({
where: { generalId: GENERAL_ID },
data: { leaseOwner: null, leaseExpiresAt: null },
});
const before = await connector.prisma.generalTurn.findMany({
where: { generalId: GENERAL_ID },
orderBy: { turnIdx: 'asc' },
});
const revision = await connector.prisma.generalTurnRevision.findUniqueOrThrow({
where: { generalId: GENERAL_ID },
});
const old = await createReservedTurnStore({ databaseUrl, leaseOwner: 'interrupted-daemon' });
const savepoint = old.store.captureTransactionState();
await old.store.prepareTurnsForExecution(GENERAL_ID);
old.store.shiftGeneralTurns(GENERAL_ID, -1);
old.store.restoreState(savepoint);
expect(old.store.getQueueCounts().leasedGeneralQueues).toBe(0);
const next = await createReservedTurnStore({ databaseUrl, leaseOwner: 'new-daemon' });
try {
await expect(next.store.prepareTurnsForExecution(GENERAL_ID)).rejects.toBeInstanceOf(
ReservedTurnLeaseConflictError
);
await old.close();
const released = await connector.prisma.generalTurnRevision.findUniqueOrThrow({
where: { generalId: GENERAL_ID },
});
expect(released).toMatchObject({ leaseOwner: null, leaseExpiresAt: null, revision: revision.revision });
await next.store.prepareTurnsForExecution(GENERAL_ID);
// A delayed close of an old owner cannot clear the new owner's lease.
const delayedCleaner = new InMemoryReservedTurnStore(connector.prisma, {
maxGeneralTurns: 2,
maxNationTurns: 1,
leaseOwner: 'interrupted-daemon',
});
await delayedCleaner.releaseOwnedLeases();
expect(
await connector.prisma.generalTurnRevision.findUniqueOrThrow({ where: { generalId: GENERAL_ID } })
).toMatchObject({ leaseOwner: 'new-daemon', revision: revision.revision });
await next.store.releaseOwnedLeases();
const actual = await connector.prisma.generalTurn.findMany({
where: { generalId: GENERAL_ID },
orderBy: { turnIdx: 'asc' },
});
expect(actual.map((row) => row.actionCode)).toEqual(before.map((row) => row.actionCode));
} finally {
await next.close();
}
});
it('waits out an orphaned lease without deleting it and reloads an intervening API edit', async () => {
if (!connector) throw new Error('integration connector is unavailable');
await connector.prisma.generalTurnRevision.update({
where: { generalId: GENERAL_ID },
data: { leaseOwner: 'killed-daemon', leaseExpiresAt: new Date(Date.now() + 300_000) },
});
const store = new InMemoryReservedTurnStore(connector.prisma, {
maxGeneralTurns: 2,
maxNationTurns: 1,
leaseOwner: 'recovery-daemon',
});
await store.loadAll();
const retry = createReservedTurnLeaseRetry({
sleep: async () => {
// Simulate the recorded expiry, then an authorized API edit before the next claim.
expect(
await connector.prisma.generalTurnRevision.findUniqueOrThrow({ where: { generalId: GENERAL_ID } })
).toMatchObject({ leaseOwner: 'killed-daemon' });
await connector.prisma.generalTurnRevision.update({
where: { generalId: GENERAL_ID },
data: { leaseExpiresAt: new Date(0) },
});
await connector.prisma.generalTurn.updateMany({
where: { generalId: GENERAL_ID, turnIdx: 0 },
data: { actionCode: 'che_수련' },
});
},
});
try {
let failure: unknown;
try {
await store.prepareTurnsForExecution(GENERAL_ID);
} catch (error) {
failure = error;
}
expect(await retry.wait(failure)).toBe(true);
await store.prepareTurnsForExecution(GENERAL_ID);
expect(store.getGeneralTurns(GENERAL_ID)[0]?.action).toBe('che_수련');
} finally {
await store.releaseOwnedLeases();
}
});
});
@@ -169,6 +169,18 @@ const buildHarness = (initialRevision: RevisionRow | null = null) => {
};
describe('reserved turn daemon lease', () => {
it('cleans both persisted lease kinds even after their journal is rolled back', async () => {
const harness = buildHarness();
const snapshot = harness.store.captureTransactionState();
await harness.store.prepareTurnsForExecution(7, { nationId: 3, officerLevel: 12 });
harness.store.restoreState(snapshot);
expect(harness.store.getQueueCounts()).toMatchObject({ leasedGeneralQueues: 0, leasedNationQueues: 0 });
await harness.store.releaseOwnedLeases();
expect(harness.getRevision()).toMatchObject({ leaseOwner: null, leaseExpiresAt: null, revision: 0 });
expect(harness.getNationRevision()).toMatchObject({ leaseOwner: null, leaseExpiresAt: null, revision: 0 });
expect(harness.generalDeleteMany).not.toHaveBeenCalled();
});
it('prunes deleted general and nation queues together with their journal state', () => {
const harness = buildHarness();
harness.store.ensureGeneralTurns(7);
@@ -0,0 +1,38 @@
import { describe, expect, it, vi } from 'vitest';
import { createReservedTurnLeaseRetry } from '../src/turn/reservedTurnLeaseRetry.js';
import { ReservedTurnLeaseBusyError, ReservedTurnLeaseConflictError } from '../src/turn/reservedTurnStore.js';
describe('reserved turn acquisition retry', () => {
it('bounds the entire contention episode across different queues and resets after progress', async () => {
let now = 0;
const onWait = vi.fn();
const retry = createReservedTurnLeaseRetry({
now: () => now,
sleep: async (ms) => {
now += ms;
},
maxWaitMs: 2_500,
onWait,
});
expect(await retry.wait(new ReservedTurnLeaseBusyError('general:1'))).toBe(true);
expect(await retry.wait(new ReservedTurnLeaseBusyError('nation:2:12'))).toBe(true);
expect(await retry.wait(new ReservedTurnLeaseBusyError('general:3'))).toBe(true);
expect(now).toBe(2_500);
expect(await retry.wait(new ReservedTurnLeaseBusyError('general:1'))).toBe(false);
expect(onWait).toHaveBeenCalledTimes(1);
retry.reset();
expect(await retry.wait(new ReservedTurnLeaseBusyError('general:1'))).toBe(true);
});
it('never retries flush ownership loss, calculation errors, or failed savepoint restoration', async () => {
const sleep = vi.fn();
const retry = createReservedTurnLeaseRetry({ sleep });
for (const error of [
new ReservedTurnLeaseConflictError('general:1'),
new Error('calculation failed'),
new AggregateError([new ReservedTurnLeaseBusyError('general:1')], 'restore failed'),
])
expect(await retry.wait(error)).toBe(false);
expect(sleep).not.toHaveBeenCalled();
});
});
+25 -1
View File
@@ -3,12 +3,36 @@ import type { GameClockPhase } from '@sammo-ts/common';
import { createRuntimePauseGate } from '../src/turn/runtimePauseGate.js';
describe('runtime pause clock boundary', () => {
it('awaits a host authority check before reading profile state or changing the clock', async () => {
const calls: string[] = [];
const gate = createRuntimePauseGate({
assertLease: async () => {
await Promise.resolve();
calls.push('host');
throw new Error('host changed');
},
shouldPause: async () => {
calls.push('profile');
return false;
},
isExplicitlyPaused: () => false,
getPhase: () => 'RUNNING',
prepareRecovery: async () => {
calls.push('recovery');
},
synchronize: async () => {},
});
await expect(gate()).rejects.toThrow('host changed');
expect(calls).toEqual(['host']);
});
it('freezes a live error pause before commands, resumes without restart, and does not freeze twice', async () => {
let phase: GameClockPhase = 'RUNNING';
let paused = true;
const calls: string[] = [];
const gate = createRuntimePauseGate({
assertLease: () => calls.push('lease'),
assertLease: () => {
calls.push('lease');
},
shouldPause: async () => paused,
isExplicitlyPaused: () => paused,
getPhase: () => phase,
@@ -79,6 +79,83 @@ const buildWorld = (
return new InMemoryTurnWorld(state, snapshot, { schedule });
};
describe('tournament mutation ownership', () => {
it('checks the current owner and commits gold plus bet statistics together', async () => {
const general = { ...buildGeneral(1), userId: 'owner' };
const world = buildWorld([general]);
const handler = createTurnDaemonCommandHandler({ world });
const command = {
type: 'tournamentAdjustGeneral' as const,
reason: 'tournamentBet' as const,
userId: 'owner',
generalId: 1,
goldDelta: -100,
betGoldDelta: 100,
minGoldAfter: 500,
};
await expect(handler.handle(command)).resolves.toEqual({ type: command.type, ok: true, generalId: 1 });
expect(world.getGeneralById(1)).toMatchObject({ gold: 900, meta: { betgold: 100 } });
const before = structuredClone(world.getGeneralById(1));
await expect(handler.handle({ ...command, goldDelta: -500 })).resolves.toMatchObject({
ok: false,
code: 'BAD_REQUEST',
});
expect(world.getGeneralById(1)).toEqual(before);
world.updateGeneral(1, { userId: 'new-owner' });
const transferred = structuredClone(world.getGeneralById(1));
for (const goldDelta of [-100, 100]) {
await expect(handler.handle({ ...command, goldDelta })).resolves.toMatchObject({
ok: false,
code: 'FORBIDDEN',
});
expect(world.getGeneralById(1)).toEqual(transferred);
}
});
it('skips possessed NPCs and commits only eligible NPC fees and statistics', async () => {
const world = buildWorld([
{ ...buildGeneral(1, {}, 1), userId: 'new-owner' },
buildGeneral(2, {}, 2),
{ ...buildGeneral(3, {}, 2), gold: 509 },
]);
const handler = createTurnDaemonCommandHandler({ world });
const possessed = structuredClone(world.getGeneralById(1));
await expect(
handler.handle({
type: 'tournamentSeedNpcBets',
bets: [1, 2, 3].map((generalId) => ({ generalId, amount: 10 })),
})
).resolves.toEqual({
type: 'tournamentSeedNpcBets',
ok: true,
processedGeneralIds: [2],
skippedGeneralIds: [1, 3],
});
expect(world.getGeneralById(1)).toEqual(possessed);
expect(world.getGeneralById(2)).toMatchObject({ gold: 990, meta: { betgold: 10 } });
expect(world.getGeneralById(3)).toMatchObject({ gold: 509, meta: { killturn: 24 } });
});
it.each(['tournamentJoin', 'tournamentJoinRollback', 'tournamentBet', 'tournamentBetRollback', 'tournamentNpcBet'])(
'rejects actorless legacy %s commands before mutation',
async (reason) => {
const world = buildWorld([{ ...buildGeneral(1), userId: 'new-owner' }]);
const before = structuredClone(world.getGeneralById(1));
const handler = createTurnDaemonCommandHandler({ world });
for (const command of [
{ type: 'adjustGeneralResources' as const, reason, adjustments: [{ generalId: 1, goldDelta: -100 }] },
{
type: 'adjustGeneralMeta' as const,
reason,
adjustments: [{ generalId: 1, metaDelta: { betgold: 100 } }],
},
])
await expect(handler.handle(command)).resolves.toMatchObject({ ok: false });
expect(world.getGeneralById(1)).toEqual(before);
}
);
});
describe('tournament world commands', () => {
it('uses the current world develcost for Ref-compatible tournament prizes', () => {
const currentWorld = buildWorld([], {
@@ -187,7 +264,7 @@ describe('tournament world commands', () => {
});
it('records all four tournament types and NPC betting for at least ten generals', async () => {
const generals = Array.from({ length: 12 }, (_, index) => buildGeneral(index + 1));
const generals = Array.from({ length: 12 }, (_, index) => ({ ...buildGeneral(index + 1, {}, 2), gold: 2_000 }));
const world = buildWorld(generals);
const handler = createTurnDaemonCommandHandler({ world });
@@ -204,13 +281,11 @@ describe('tournament world commands', () => {
}
}
await handler.handle({
type: 'adjustGeneralMeta',
reason: 'tournamentNpcBet',
adjustments: generals.map((general) => ({
generalId: general.id,
metaDelta: { betgold: 1_000 },
})),
type: 'tournamentSeedNpcBets',
bets: generals.map((general) => ({ generalId: general.id, amount: 1_000 })),
});
// Ref의 betwin 통계 대상은 npcState <= 1이다. 개방 시 NPC 비용 검증과 분리한다.
for (const general of generals) world.updateGeneral(general.id, { npcState: 0 });
await handler.handle({
type: 'tournamentBettingPayout',
bettingId: 1,
@@ -207,6 +207,39 @@ integration('database turn daemon lease and fencing', () => {
expect(row.ownerId).toBe(firstToken ? 'owner-a' : 'owner-b');
});
it('fences a host boot change inside a transaction before mutation, without expiring the DB lease', async () => {
const profile = `${profilePrefix}host-boot`;
let changed = false;
const lease = await DatabaseTurnDaemonLease.connect(databaseUrl!, {
profile,
ownerId: 'saved-vm-owner',
heartbeat: false,
leaseDurationMs: 60_000,
hostBootMonitor: { hasChanged: async () => changed },
});
leases.push(lease);
await lease.acquire();
await lease.markClockReady();
changed = true;
let committed = false;
await expect(
db.$transaction(async (transaction) => {
await lease.assertActive(transaction);
committed = true;
})
).rejects.toBeInstanceOf(TurnDaemonLeaseLostError);
expect(committed).toBe(false);
expect(lease.isLost()).toBe(true);
expect(await lease.renew()).toBe(false);
// The monitor does not force-clear ownership or bypass the successor's fencing.
expect((await db.turnDaemonLease.findUniqueOrThrow({ where: { profile } })).ownerId).toBe('saved-vm-owner');
const next = await createLease(profile, 'fresh-vm-owner');
expect(await next.acquire()).toBeNull();
await lease.release();
expect((await db.turnDaemonLease.findUniqueOrThrow({ where: { profile } })).clockReady).toBe(false);
expect((await next.acquire())?.fencingEpoch).toBe(2n);
});
it('persists and evaluates lease wall time as UTC under a non-UTC database session', async () => {
const profile = `${profilePrefix}utc-wall`;
const zonedUrl = new URL(databaseUrl!);
@@ -1,6 +1,8 @@
import { describe, expect, it, vi } from 'vitest';
import { ManualClock } from '@sammo-ts/common';
import { TurnDaemonLeaseLostError } from '../src/lifecycle/databaseTurnDaemonLease.js';
import { ReservedTurnLeaseBusyError } from '../src/turn/reservedTurnStore.js';
import { createReservedTurnLeaseRetry } from '../src/turn/reservedTurnLeaseRetry.js';
import {
InMemoryControlQueue,
@@ -15,6 +17,68 @@ import {
const addMinutes = (time: Date, minutes: number): Date => new Date(time.getTime() + minutes * 60_000);
describe('TurnDaemonLifecycle', () => {
it('rolls back a busy queue, checks the operator gate, and retries an explicit run exactly once', async () => {
const now = new Date('2026-11-12T00:00:00Z');
const queue = new InMemoryControlQueue();
queue.enqueue({ type: 'run', reason: 'manual', targetTime: now.toISOString() });
let resource = 10;
let runs = 0;
const stateManager = new EngineStateManager();
stateManager.register('resource', {
capture: () => resource,
restore: (value) => {
resource = value;
},
});
const onRunError = vi.fn();
const flushChanges = vi.fn();
const gate = vi.fn(async () => false);
const retry = createReservedTurnLeaseRetry({
sleep: async () => {
expect(resource).toBe(10);
},
});
const lifecycle = new TurnDaemonLifecycle(
{
clock: new ManualClock(now.getTime()),
controlQueue: queue,
stateManager,
runErrorRetry: retry,
getNextTickTime: (value) => addMinutes(value, 5),
pauseGate: gate,
stateStore: {
loadLastTurnTime: async () => now,
loadNextGeneralTurnTime: async () => null,
saveLastTurnTime: async () => {},
loadCheckpoint: async () => undefined,
saveCheckpoint: async () => {},
},
processor: {
run: async () => {
resource -= 2;
if (++runs === 1) throw new ReservedTurnLeaseBusyError('general:7');
queue.enqueue({ type: 'shutdown' });
return {
lastTurnTime: now.toISOString(),
processedGenerals: 1,
processedTurns: 0,
durationMs: 0,
partial: false,
};
},
},
hooks: { onRunError, flushChanges },
},
{ profile: 'che', defaultBudget: { budgetMs: 100, maxGenerals: 1, catchUpCap: 1 } }
);
await lifecycle.start();
expect(runs).toBe(2);
expect(resource).toBe(8);
expect(gate.mock.calls.length).toBeGreaterThanOrEqual(2);
expect(flushChanges).toHaveBeenCalledOnce();
expect(onRunError).not.toHaveBeenCalled();
});
it.each([false, true])('reports a fatal lease gate and exits even if reporting fails (%s)', async (reportFails) => {
const now = new Date('2026-09-09T17:30:00Z');
const error = new TurnDaemonLeaseLostError('che:default');
@@ -135,3 +135,106 @@ integration('turn failure personal-record persistence', () => {
]);
});
});
integration('turn persistence connection acquisition', () => {
let connector: ReturnType<typeof createGamePostgresConnector>;
let hooks: DatabaseTurnHooks;
const fixtureWorldId = worldId + 10;
beforeAll(async () => {
connector = createGamePostgresConnector({ url: databaseUrl! });
await connector.connect();
await connector.prisma.worldState.create({
data: {
id: fixtureWorldId,
scenarioCode: 'transaction-acquisition',
currentYear: state.currentYear,
currentMonth: state.currentMonth,
tickSeconds: state.tickSeconds,
clockBaseTime: turnTime,
clockWallAnchor: turnTime,
clockMode: 'manual',
clockPhase: 'MANUAL',
clockTick: 0n,
lastTurnTick: 0n,
},
});
hooks = await createDatabaseTurnHooks(
databaseUrl!,
new InMemoryTurnWorld({ ...state, id: fixtureWorldId }, snapshot, { schedule }),
{ transactionTimeoutMs: 1_000 }
);
});
afterAll(async () => {
await hooks?.close();
await connector?.prisma.worldState.deleteMany({ where: { id: fixtureWorldId } });
await connector?.disconnect();
});
const occupyPool = async () => {
let release!: () => void;
const held = new Promise<void>((resolve) => {
release = resolve;
});
const started: Promise<void>[] = [];
const blockers = Array.from({ length: connector.getPoolStats().max }, () => {
let markStarted!: () => void;
started.push(new Promise<void>((resolve) => (markStarted = resolve)));
return connector.prisma.$transaction(
async (tx) => {
await tx.$queryRaw`SELECT 1`;
markStarted();
await held;
},
{ maxWait: 10_000, timeout: 20_000 }
);
});
// Attach handlers immediately so a setup failure cannot leak transactions.
const settled = Promise.allSettled(blockers);
try {
await Promise.all(started);
} catch (error) {
release();
await settled;
throw error;
}
return { release, settled };
};
it('waits beyond Prisma default without spending the callback execution budget', async () => {
const held = await occupyPool();
const sync = hooks.synchronizeClockAuthority();
// Observe the result immediately; the old 2-second default rejects here.
const outcome = sync.then(
(value) => ({ ok: true, value }),
(error: unknown) => ({ ok: false, error })
);
try {
const deadline = Date.now() + 1_000;
while (!connector.getPoolStats().waiting && Date.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, 10));
}
expect(connector.getPoolStats().waiting).toBeGreaterThan(0);
await new Promise((resolve) => setTimeout(resolve, 2_500));
held.release();
expect(await outcome).toMatchObject({ ok: true });
} finally {
held.release();
await held.settled;
await outcome;
}
}, 15_000);
it('still rejects sustained connection exhaustion at the finite acquisition limit', async () => {
const held = await occupyPool();
try {
await expect(hooks.synchronizeClockAuthority()).rejects.toMatchObject({ code: 'P2028' });
} finally {
held.release();
await held.settled;
}
// Timed-out acquisition must not prevent the next normal operation.
await expect(hooks.synchronizeClockAuthority()).resolves.toBeTypeOf('boolean');
}, 15_000);
});
@@ -1,13 +1,21 @@
import { describe, expect, it, vi } from 'vitest';
import { normalizeArchivedGeneral, type ArchivedJsonValue } from '@sammo-ts/common';
import type { GamePrisma } from '@sammo-ts/infra';
import { GamePrisma } from '@sammo-ts/infra';
import { LogCategory, LogScope, type City, type Nation } from '@sammo-ts/logic';
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
import { persistUnificationFinalization, resolveStoredInheritancePoint } from '../src/turn/unificationPersistence.js';
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
// This harness begins without the durable archive/point row.
const missingRecordUpdate = async (): Promise<never> => {
throw new GamePrisma.PrismaClientKnownRequestError('fixture record missing', {
code: 'P2025',
clientVersion: 'fixture',
});
};
const buildWorld = (): InMemoryTurnWorld => {
const turnTime = new Date('0190-07-01T00:00:00.000Z');
const general: TurnGeneral = {
@@ -206,6 +214,7 @@ describe('persistUnificationFinalization', () => {
create: vi.fn().mockResolvedValue({}),
},
inheritancePoint: {
update: missingRecordUpdate,
findMany: vi.fn().mockResolvedValue([
{ userId: 'user-1', key: 'previous', value: 100 },
{ userId: 'user-1', key: 'unifier', value: 7 },
@@ -216,6 +225,7 @@ describe('persistUnificationFinalization', () => {
inheritanceResult: { create: inheritanceResultCreate },
inheritanceLog: { create: inheritanceLogCreate },
rankData: {
update: missingRecordUpdate,
findMany: vi.fn().mockResolvedValue([
{ generalId: 1, type: 'warnum', value: 15 },
{ generalId: 1, type: 'killnum', value: 9 },
@@ -251,10 +261,11 @@ describe('persistUnificationFinalization', () => {
),
},
oldNation: {
update: missingRecordUpdate,
upsert: oldNationUpsert,
findMany: vi.fn().mockResolvedValue([]),
},
oldGeneral: { upsert: oldGeneralUpsert },
oldGeneral: { update: missingRecordUpdate, upsert: oldGeneralUpsert },
emperor: { create: emperorCreate },
});
await expect(persistUnificationFinalization(transaction, input, buildWorld())).resolves.toEqual({
@@ -1,10 +1,18 @@
import { describe, expect, it, vi } from 'vitest';
import type { GamePrisma } from '@sammo-ts/infra';
import { GamePrisma } from '@sammo-ts/infra';
import { LogCategory, LogScope } from '@sammo-ts/logic';
import { persistYearbookSnapshot } from '../src/turn/yearbookPersistence.js';
// This harness begins without the durable archive/point row.
const missingRecordUpdate = async (): Promise<never> => {
throw new GamePrisma.PrismaClientKnownRequestError('fixture record missing', {
code: 'P2025',
clientVersion: 'fixture',
});
};
describe('persistYearbookSnapshot', () => {
it('archives canonical summary logs and compatible action logs together in descending ID order', async () => {
const findMany = vi
@@ -14,7 +22,7 @@ describe('persistYearbookSnapshot', () => {
const upsert = vi.fn().mockResolvedValue(undefined);
const transaction = {
logEntry: { findMany },
yearbookHistory: { upsert },
yearbookHistory: { update: missingRecordUpdate, upsert },
} as unknown as GamePrisma.TransactionClient;
await persistYearbookSnapshot(transaction, {
+6 -3
View File
@@ -3,8 +3,11 @@
"compilerOptions": {
"rootDir": "src",
"outDir": "dist",
"composite": false
"composite": false,
"paths": {
"@sammo-ts/game-engine": ["./src/index.ts"],
"@sammo-ts/game-engine/*": ["./src/*"]
}
},
"include": ["src"],
"references": [{ "path": "../../packages/common" }, { "path": "../../packages/logic" }]
"include": ["src"]
}
+3 -3
View File
@@ -1,4 +1,5 @@
import { defineConfig } from 'tsdown';
import { emitDeclarations } from '../../tools/build-scripts/emit-declarations.mjs';
export default defineConfig({
entry: {
@@ -30,9 +31,8 @@ export default defineConfig({
},
format: 'es',
outDir: 'dist',
dts: {
build: true,
},
dts: false,
hooks: { 'build:done': emitDeclarations },
sourcemap: true,
target: 'node22',
platform: 'node',
Loaded 100 of 231 files, more files were not shown because too many files have changed in this diff. Show more