Author SHA1 Message Date
Hide_D 3f51bec90a 입찰 장수가 사라진 유니크 경매를 복구하고 시스템 공지를 지원한다 2026-12-04 09:57:02 +09:00
Hide_D 0ae14d5ee0 랜덤 임관에서 이전 소속국을 제외하고 후보 소진 시 다시 순환한다 2026-11-19 10:57:32 +09:00
Hide_D 6a4f170fd9 인사부에서 사람을 검색할 때 공석 선택을 숨긴다 2026-11-19 00:39:42 +09:00
Hide_D 0ed2f4a80b 장수 명령 선택기에 능력치 경험 종류를 복원한다 2026-11-19 00:39:42 +09:00
Hide_D bebd4848b4 감찰부 장수 카드에 특기와 장비 설명을 표시한다 2026-11-19 00:29:16 +09:00
Hide_D 8125d68c95 세력 장수 이름에서 해당 장수의 감찰부를 연다 2026-11-19 00:26:01 +09:00
Hide_D cc1cfea33b 부대 즉시 명령을 전용 모듈로 분리하고 저장과 갱신을 검증한다 2026-11-18 23:53:28 +09:00
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
177 changed files with 7190 additions and 930 deletions

No files matched your search

+3
View File
@@ -91,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/
+7 -2
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의 변경 이메일이
다른 계정에 있으면 기존처럼 충돌을 거부합니다.
+19 -5
View File
@@ -8,6 +8,7 @@ import {
resolvePostgresConfigFromEnv,
resolveRedisConfigFromEnv,
} from '@sammo-ts/infra';
import { asRecord } from '@sammo-ts/common';
import { resolveGameApiConfigFromEnv } from '../config.js';
import { createBestEffortResourceCloser } from '../services/bestEffortResourceCloser.js';
@@ -258,7 +259,7 @@ export const processDueAuctionId = async (options: {
}
const current = await transaction.auction.findUnique({
where: { id: auctionId },
select: { status: true, closeAt: true, closeTick: true },
select: { type: true, status: true, closeAt: true, closeTick: true },
});
if (!current) {
return { status: 'IGNORED' as const };
@@ -278,7 +279,8 @@ export const processDueAuctionId = async (options: {
if (current.closeTick === null) throw new Error(`Auction ${auctionId} has no GAME_TIME close authority.`);
const deadline = { closeAt: current.closeAt, closeTick: current.closeTick };
for (let retry = 0; retry <= AUCTION_FINALIZE_RECOVERY_LIMIT; retry += 1) {
let retryLimit = AUCTION_FINALIZE_RECOVERY_LIMIT;
for (let retry = 0; retry <= retryLimit; retry += 1) {
const requestId = buildAuctionFinalizeRequestId(auctionId, deadline, retry);
const existing = await transaction.inputEvent.findUnique({
where: { requestId },
@@ -304,9 +306,21 @@ export const processDueAuctionId = async (options: {
return { status: 'PENDING' as const };
}
if (existing.status === 'SUCCEEDED' && isSuccessfulAuctionFinalizeResult(existing.result, auctionId)) {
throw new Error(
`Auction remained ${current.status} after successful durable event: ${requestId}`
);
throw new Error(`Auction remained ${current.status} after successful durable event: ${requestId}`);
}
const result = asRecord(existing.result);
if (
retry === AUCTION_FINALIZE_RECOVERY_LIMIT &&
current.type === 'UNIQUE_ITEM' &&
current.status === 'FINALIZING' &&
existing.status === 'SUCCEEDED' &&
result.type === 'auctionFinalize' &&
result.auctionId === auctionId &&
result.ok === false &&
result.reason === '입찰자를 찾을 수 없습니다.'
) {
// Re-enqueue once for rows left behind by the previous finalizer.
retryLimit += 1;
}
}
throw new Error(`Auction finalization recovery exhausted: ${auctionId}`);
+9 -3
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, {
// 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(
+13 -1
View File
@@ -1,7 +1,7 @@
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { asRecord, ChangeJournal } from '@sammo-ts/common';
import { writeReadModelChangeJournal } from '@sammo-ts/infra';
import { publishPublicSystemMessage, writeReadModelChangeJournal } from '@sammo-ts/infra';
import type { UserSanctions } from '@sammo-ts/common/auth/gameToken';
import { isMessageAccessBlocked } from '@sammo-ts/common/auth/sanctions';
@@ -492,6 +492,18 @@ export const messagesRouter = router({
...messageBuckets,
};
}),
sendSystem: wallAuthedProcedure
.input(
z.object({ noticeId: z.string().regex(/^[a-zA-Z0-9._-]{1,100}$/), text: z.string().trim().min(1).max(500) })
)
.mutation(async ({ ctx, input }) => {
const roles = ctx.auth?.user.roles ?? [];
if (!roles.includes('superuser') && !roles.includes('admin.superuser')) {
throw new TRPCError({ code: 'FORBIDDEN', message: '시스템 메시지를 보낼 권한이 없습니다.' });
}
const msgId = await publishPublicSystemMessage(ctx.db, input);
return { msgId };
}),
send: accessWallAuthedInputProcedure(
z.object({
generalId: z.number().int().positive(),
@@ -6,7 +6,7 @@ import { getBillByLevel, LogCategory } from '@sammo-ts/logic';
import { accessAuthedProcedure } from '../../../trpc.js';
import {
loadCrewTypeDisplayNames,
loadItemDisplayNames,
loadItemDisplayDetails,
resolveDedicationLevelName,
resolveOfficerLevelName,
sanitizeInternalDisplayCode,
@@ -133,7 +133,7 @@ export const getBattleCenter = accessAuthedProcedure.query(async ({ ctx }) => {
typeof constValues.maxDedLevel === 'number' && Number.isFinite(constValues.maxDedLevel)
? Math.max(0, Math.trunc(constValues.maxDedLevel))
: 30;
const [personalityNames, domesticNames, warNames, crewTypeNames, itemNames] = await Promise.all([
const [personalityNames, domesticNames, warNames, crewTypeNames, itemDetails] = await Promise.all([
loadTraitNames(
generalRows.map((general) => general.personalCode),
'personality'
@@ -147,7 +147,7 @@ export const getBattleCenter = accessAuthedProcedure.query(async ({ ctx }) => {
'war'
),
loadCrewTypeDisplayNames(worldState, ctx.profile.id),
loadItemDisplayNames(
loadItemDisplayDetails(
generalRows.flatMap((general) => [
general.weaponCode,
general.bookCode,
@@ -158,7 +158,8 @@ export const getBattleCenter = accessAuthedProcedure.query(async ({ ctx }) => {
]);
const traitName = (code: string, names: Awaited<ReturnType<typeof loadTraitNames>>): string =>
names.get(code)?.name ?? sanitizeInternalDisplayCode(code);
const itemName = (code: string): string => itemNames.get(code) ?? sanitizeInternalDisplayCode(code);
const itemName = (code: string): string => itemDetails.get(code)?.name ?? sanitizeInternalDisplayCode(code);
const itemInfo = (code: string): string => itemDetails.get(code)?.info ?? '';
const generals = generalRows.map((general) => {
const meta =
@@ -225,11 +226,22 @@ export const getBattleCenter = accessAuthedProcedure.query(async ({ ctx }) => {
horse: itemName(general.horseCode),
item: itemName(general.itemCode),
},
itemInfo: {
weapon: itemInfo(general.weaponCode),
book: itemInfo(general.bookCode),
horse: itemInfo(general.horseCode),
item: itemInfo(general.itemCode),
},
traits: {
personal: traitName(general.personalCode, personalityNames),
specialDomestic: traitName(general.specialCode, domesticNames),
specialWar: traitName(general.special2Code, warNames),
},
traitInfo: {
personal: personalityNames.get(general.personalCode)?.info ?? '',
specialDomestic: domesticNames.get(general.specialCode)?.info ?? '',
specialWar: warNames.get(general.special2Code)?.info ?? '',
},
progression: {
experienceLevel: metaNumber('explevel'),
dedicationLevel,
@@ -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),
};
});
@@ -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;
@@ -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,
+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, '');
+36
View File
@@ -48,6 +48,7 @@ export interface TurnCommandAvailability {
name: string;
turnDurationText?: string;
costText?: string;
statExperienceText?: string;
reqArg: boolean;
possible: boolean;
status: AvailabilityStatus;
@@ -151,6 +152,39 @@ const REF_GENERAL_COMMAND_GROUPS = [
commands: ReadonlyArray<GeneralTurnCommandKey>;
}>;
// Ref 명령 선택기의 경험 종류를 복원하며, 결과나 병종에 따라 달라지는 경우는 따로 표시한다.
const GENERAL_COMMAND_STAT_EXPERIENCE = {
'통솔 경험': [
'che_강행',
'che_귀환',
'che_등용',
'che_모병',
'che_사기진작',
'che_선동',
'che_숙련전환',
'che_이동',
'che_전투태세',
'che_정착장려',
'che_주민선정',
'che_증여',
'che_집합',
'che_징병',
'che_첩보',
'che_헌납',
'che_훈련',
'cr_맹훈련',
],
'무력 경험': ['che_성벽보수', 'che_수비강화', 'che_치안강화', 'che_탈취', 'che_파괴'],
'지력 경험': ['che_기술연구', 'che_농지개간', 'che_상업투자', 'che_화계'],
'무작위 능력치 경험': ['che_군량매매', 'che_단련', 'che_물자조달', 'che_인재탐색'],
'무작위 능력치 경험 가능': ['che_견문'],
'병종별 능력치 경험': ['che_출병'],
} as const satisfies Record<string, readonly GeneralTurnCommandKey[]>;
const statExperienceByCommand = new Map<string, string>(
Object.entries(GENERAL_COMMAND_STAT_EXPERIENCE).flatMap(([text, keys]) => keys.map((key) => [key, text] as const))
);
const REF_NATION_COMMAND_GROUPS = [
{
category: '휴식',
@@ -858,11 +892,13 @@ const buildGroups = (
// 개인·국가 모두 실행 정의의 준비 턴과 마지막 실행 턴을 표시한다.
const turnDurationText = getTurnDurationText(entry.definition);
const costText = getCommandCostText(entry, ctx, view, env);
const statExperienceText = scope === 'general' ? statExperienceByCommand.get(entry.definition.key) : undefined;
const value: TurnCommandAvailability = {
key: entry.definition.key,
name: entry.definition.name,
...(turnDurationText ? { turnDurationText } : {}),
...(costText ? { costText } : {}),
...(statExperienceText ? { statExperienceText } : {}),
reqArg: entry.reqArg,
inputFields: entry.inputFields,
...availability,
+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: ' <신-국># ',
+31
View File
@@ -504,6 +504,37 @@ describe('buildTurnCommandTable', () => {
}
});
it('projects stat experience hints for general commands without promising a fixed stat increase', async () => {
const table = await buildTurnCommandTable({
worldState: buildWorldState(),
general: buildGeneral(),
city: buildCity(),
nation: buildNation(),
nationGenerals: null,
});
const find = (key: string) => table.general.flatMap(({ values }) => values).find((entry) => entry.key === key);
const expected = {
che_선동: '통솔 경험',
che_탈취: '무력 경험',
che_파괴: '무력 경험',
che_화계: '지력 경험',
che_이동: '통솔 경험',
che_수비강화: '무력 경험',
che_상업투자: '지력 경험',
che_물자조달: '무작위 능력치 경험',
che_인재탐색: '무작위 능력치 경험',
che_견문: '무작위 능력치 경험 가능',
che_출병: '병종별 능력치 경험',
};
for (const [key, statExperienceText] of Object.entries(expected)) {
expect(find(key)).toMatchObject({ statExperienceText });
}
expect(find('휴식')?.statExperienceText).toBeUndefined();
expect(
table.nation.flatMap(({ values }) => values).every(({ statExperienceText }) => !statExperienceText)
).toBe(true);
});
it('projects the Ref twenty-year non-aggression end-year window', async () => {
const table = await buildTurnCommandTable({
worldState: buildWorldState(),
@@ -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,
@@ -1072,6 +1072,34 @@ describe('battle-center general and user permissions', () => {
});
});
it('projects registered trait and equipment descriptions for battle center viewers', async () => {
const me = buildGeneral({ meta: { belong: 3 } });
const other = buildGeneral({
id: 8,
personalCode: 'che_안전',
specialCode: 'che_상재',
special2Code: 'che_신산',
horseCode: 'che_명마_15_적토마',
weaponCode: 'unregistered',
itemCode: 'che_내정_납금박산로',
});
const fixture = createContext({ me, targets: [me, other], nationMeta: { secretLimit: 3 } });
const result = await appRouter.createCaller(fixture.context).nation.getBattleCenter();
expect(result.generals.find(({ id }) => id === other.id)).toMatchObject({
traitInfo: {
personal: expect.stringContaining('징·모병 비용'),
specialDomestic: expect.stringContaining('상업 투자'),
specialWar: expect.stringContaining('[계략] 화계·탈취·파괴·선동'),
},
itemInfo: { horse: '통솔 +15', weapon: '', book: '', item: '[내정] 내정 성공률 +15%p' },
});
expect(result.generals.find(({ id }) => id === me.id)).toMatchObject({
traitInfo: { personal: '', specialDomestic: '', specialWar: '' },
itemInfo: { horse: '', weapon: '', book: '', item: '' },
});
});
it('redacts another user action log while allowing own, NPC, chief, and non-private logs', async () => {
const me = buildGeneral({ meta: { belong: 3, permission: 'normal' } });
const otherUser = buildGeneral({ id: 8, userId: 'user-8', name: '타유저', npcState: 0 });
+10 -7
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) => {
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();
});
}
);
it('delegates the authenticated actor and maps a missing-general daemon rejection', async () => {
const fixture = buildContext({
+17 -1
View File
@@ -33,7 +33,7 @@ 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' },
@@ -94,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,
@@ -2,7 +2,12 @@ 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 { createGamePostgresConnector, createRedisConnector, GamePrisma } from '@sammo-ts/infra';
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';
@@ -255,12 +260,10 @@ integration(
include: { chunks: { orderBy: { ordinal: 'asc' } } },
});
const procedures = nationDecision.chunks.flatMap((chunk) =>
Array.isArray(chunk.steps)
? chunk.steps
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));
@@ -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
@@ -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', {
+7 -10
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,9 +201,10 @@ 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 () => [
const findTurns = vi.fn(
async () =>
[
{
id: 1,
nationId: 4,
officerLevel: 12,
turnIdx: 1,
@@ -214,7 +213,6 @@ describe('reservedTurns', () => {
createdAt: new Date(),
},
{
id: 2,
nationId: 4,
officerLevel: 10,
turnIdx: 0,
@@ -222,7 +220,8 @@ describe('reservedTurns', () => {
arg: {},
createdAt: new Date(),
},
] satisfies NationTurnRow[]);
] 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,
@@ -968,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,
@@ -991,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,
@@ -1547,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)
);
@@ -1566,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,
@@ -1732,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
@@ -1762,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,
@@ -1879,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
@@ -1909,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,
@@ -2345,7 +2358,8 @@ integration('game API security over HTTP transport', () => {
{
decisionId: decisionIds[0]!,
ordinal: 0,
steps: Array.from({ length: 128 }, (_, sequence) =>
steps: encodeAuditDecisionSteps(
Array.from({ length: 128 }, (_, sequence) =>
sequence === 127
? {
...step,
@@ -2389,6 +2403,7 @@ integration('game API security over HTTP transport', () => {
},
}
: { ...step, sequence }
)
),
},
{
@@ -2865,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,
},
},
@@ -2874,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 },
+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},
+84 -3
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,
@@ -232,6 +233,40 @@ const refundInheritancePoint = async (options: {
}
};
const findUniqueAuctionEscrowOwner = async (
db: AuctionDb,
auctionId: number,
bid: AuctionBidRow
): Promise<string | null> => {
const owners = await db.$queryRaw<{ userId: string }[]>(
GamePrisma.sql`
SELECT e.actor_user_id AS "userId"
FROM auction_bid b
JOIN input_event e
ON e.created_at = b.requested_at_wall
AND e.processing_game_tick = b.occurred_game_tick
WHERE b.id = ${bid.id}
AND b.auction_id = ${auctionId}
AND e.target = 'ENGINE'
AND e.status = 'SUCCEEDED'
AND e.event_type IN ('auctionOpen', 'auctionBid')
AND e.result->>'type' = e.event_type
AND e.result->'ok' = 'true'::jsonb
AND e.result->'auctionId' = to_jsonb(b.auction_id)
AND e.payload->'generalId' = to_jsonb(b.general_id)
AND e.payload->'amount' = to_jsonb(b.amount)
AND (
(e.event_type = 'auctionOpen' AND e.payload->>'auctionType' = 'UNIQUE_ITEM')
OR (e.event_type = 'auctionBid' AND e.payload->'auctionId' = to_jsonb(b.auction_id))
)
AND e.actor_user_id IS NOT NULL
AND e.actor_user_id = e.payload->>'userId'
LIMIT 2
`
);
return owners.length === 1 ? (owners[0]?.userId ?? null) : null;
};
export const createAuctionFinalizer = async (options: {
databaseUrl: string;
world: InMemoryTurnWorld;
@@ -493,7 +528,54 @@ export const createAuctionFinalizer = async (options: {
return { type: 'auctionFinalize', ok: true, auctionId };
}
const bidder = world.getGeneralById(highestBid.generalId);
if (auction.type === 'UNIQUE_ITEM') {
const escrowOwner = await findUniqueAuctionEscrowOwner(db, auctionId, highestBid);
if (!bidder || (escrowOwner !== null && bidder.userId !== escrowOwner)) {
// Only the current escrow is outstanding. Earlier bids were refunded when outbid.
const refunded =
escrowOwner !== null && highestBid.amount > 0
? await db.inheritancePoint.updateManyAndReturn({
where: { userId: escrowOwner, key: 'previous' },
data: { value: { increment: highestBid.amount } },
select: { value: true },
})
: [];
if (escrowOwner !== null && refunded[0]) {
const liveGeneral = world.listGenerals().find((general) => general.userId === escrowOwner);
if (liveGeneral) {
world.updateGeneral(liveGeneral.id, {
inheritancePoints: { ...liveGeneral.inheritancePoints, previous: refunded[0].value },
});
}
const state = world.getState();
await db.inheritanceLog.create({
data: {
userId: escrowOwner,
year: state.currentYear,
month: state.currentMonth,
text: `경매 ${auctionId}번 취소로 유산 ${highestBid.amount}포인트 환불`,
},
});
} else {
await db.errorLog.create({
data: {
category: 'AUCTION',
source: 'auction-finalizer',
message:
'최고 입찰 장수가 없는 유니크 경매를 취소했으나 유산 환불을 확인할 수 없습니다.',
context: { auctionId, bidId: highestBid.id, amount: highestBid.amount },
},
});
}
globalLogger.pushGlobalActionLog(
`경매 ${auctionId}번이 최고 입찰 장수 부재로 취소되었습니다.`,
LogFormat.PLAIN
);
pushLogs(world, globalLogger.flush());
await finalizeStatus('CANCELED');
return { type: 'auctionFinalize', ok: true, auctionId };
}
const bidMeta = parseDetail(highestBid.meta);
const remainExtension = detail.remainCloseDateExtensionCnt ?? 0;
if (bidMeta.tryExtendCloseDate === true && remainExtension > 0) {
@@ -530,7 +612,6 @@ export const createAuctionFinalizer = async (options: {
}
}
const bidder = world.getGeneralById(highestBid.generalId);
if (!bidder) {
return {
type: 'auctionFinalize',
+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';
@@ -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 (!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 (decision) {
const chunks = await tx.playAuditDecisionChunk.findMany({
where: { decisionId: decision.id },
orderBy: { ordinal: 'asc' },
take: AUDIT_RETENTION_BATCH_SIZE,
select: { ordinal: true },
});
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 };
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,
});
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를 멈추면 안 된다. 그 밖의 초기화 실패는
+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 },
+336
View File
@@ -0,0 +1,336 @@
import { JosaUtil } from '@sammo-ts/common';
import {
isValidTroopNameWidth,
LogCategory,
LogFormat,
LogScope,
normalizeTroopName,
resolveTroopSecretPermission,
} from '@sammo-ts/logic';
import type { TurnDaemonCommand, TurnDaemonCommandResult } from '../lifecycle/types.js';
import type { InMemoryTurnWorld } from './inMemoryWorld.js';
import {
hasScenarioStaticEventHandler,
IMMEDIATE_TROOP_JOIN_MOVE_HANDLER,
LEGACY_TROOP_JOIN_EVENT,
} from './scenarioStaticEvents.js';
const TROOP_COMMAND_TYPES = ['troopCreate', 'troopJoin', 'troopExit', 'troopKick', 'troopRename'] as const;
const troopCommandTypes = new Set<TurnDaemonCommand['type']>(TROOP_COMMAND_TYPES);
export type TroopCommand = Extract<TurnDaemonCommand, { type: (typeof TROOP_COMMAND_TYPES)[number] }>;
export const isTroopCommand = (command: TurnDaemonCommand): command is TroopCommand =>
troopCommandTypes.has(command.type);
export const handleTroopCommand = (world: InMemoryTurnWorld, command: TroopCommand): TurnDaemonCommandResult => {
switch (command.type) {
case 'troopCreate':
return handleTroopCreate(world, command);
case 'troopJoin':
return handleTroopJoin(world, command);
case 'troopExit':
return handleTroopExit(world, command);
case 'troopKick':
return handleTroopKick(world, command);
case 'troopRename':
return handleTroopRename(world, command);
}
};
function handleTroopJoin(
world: InMemoryTurnWorld,
command: Extract<TurnDaemonCommand, { type: 'troopJoin' }>
): TurnDaemonCommandResult {
const general = world.getGeneralById(command.generalId);
if (!general) {
return {
type: 'troopJoin',
ok: false,
generalId: command.generalId,
troopId: command.troopId,
reason: '장수 정보를 찾을 수 없습니다.',
};
}
if (general.troopId !== 0) {
return {
type: 'troopJoin',
ok: false,
generalId: command.generalId,
troopId: command.troopId,
reason: '이미 부대에 소속되어 있습니다.',
};
}
if (general.nationId <= 0) {
return {
type: 'troopJoin',
ok: false,
generalId: command.generalId,
troopId: command.troopId,
reason: '국가에 소속되어 있지 않습니다.',
};
}
const troop = world.getTroopById(command.troopId);
if (!troop || troop.nationId !== general.nationId) {
return {
type: 'troopJoin',
ok: false,
generalId: command.generalId,
troopId: command.troopId,
reason: '부대가 올바르지 않습니다.',
};
}
world.updateGeneral(command.generalId, {
troopId: command.troopId,
});
if (
hasScenarioStaticEventHandler(
world.getScenarioConfig(),
LEGACY_TROOP_JOIN_EVENT,
IMMEDIATE_TROOP_JOIN_MOVE_HANDLER
)
) {
const leader = world.getGeneralById(troop.id);
if (
leader &&
leader.troopId === leader.id &&
leader.nationId === general.nationId &&
leader.cityId !== general.cityId
) {
const city = world.getCityById(leader.cityId);
if (city) {
world.updateGeneral(command.generalId, {
troopId: command.troopId,
cityId: leader.cityId,
});
const josaRo = JosaUtil.pick(city.name, '로');
world.pushLog({
scope: LogScope.GENERAL,
category: LogCategory.ACTION,
format: LogFormat.PLAIN,
text: `부대 주둔지인 <G><b>${city.name}</b></>${josaRo} 즉시 이동합니다.`,
generalId: general.id,
meta: {},
});
}
}
}
return {
type: 'troopJoin',
ok: true,
generalId: command.generalId,
troopId: command.troopId,
};
}
function handleTroopCreate(
world: InMemoryTurnWorld,
command: Extract<TurnDaemonCommand, { type: 'troopCreate' }>
): TurnDaemonCommandResult {
const general = world.getGeneralById(command.generalId);
if (!general) {
return {
type: 'troopCreate',
ok: false,
generalId: command.generalId,
reason: '장수 정보를 찾을 수 없습니다.',
};
}
const troopName = normalizeTroopName(command.troopName);
if (!troopName) {
return { type: 'troopCreate', ok: false, generalId: command.generalId, reason: '부대 이름이 없습니다.' };
}
if (!isValidTroopNameWidth(troopName)) {
return {
type: 'troopCreate',
ok: false,
generalId: command.generalId,
reason: '부대 이름은 전각 9자 또는 반각 18자 이하여야 합니다.',
};
}
if (general.troopId !== 0 || world.getTroopById(general.id)) {
return {
type: 'troopCreate',
ok: false,
generalId: command.generalId,
reason: '이미 부대에 소속되어 있습니다.',
};
}
if (general.nationId <= 0 || !world.getNationById(general.nationId)) {
return {
type: 'troopCreate',
ok: false,
generalId: command.generalId,
reason: '국가에 소속되어 있지 않습니다.',
};
}
const troop = world.createTroop({
id: general.id,
nationId: general.nationId,
name: troopName,
});
if (!troop) {
return {
type: 'troopCreate',
ok: false,
generalId: command.generalId,
reason: '부대가 생성되지 않았습니다. 버그일 수 있습니다.',
};
}
world.updateGeneral(general.id, { troopId: general.id });
return {
type: 'troopCreate',
ok: true,
generalId: general.id,
troopId: troop.id,
troopName: troop.name,
};
}
function handleTroopExit(
world: InMemoryTurnWorld,
command: Extract<TurnDaemonCommand, { type: 'troopExit' }>
): TurnDaemonCommandResult {
const general = world.getGeneralById(command.generalId);
if (!general) {
return {
type: 'troopExit',
ok: false,
generalId: command.generalId,
reason: '장수 정보를 찾을 수 없습니다.',
};
}
if (general.troopId === 0) {
return {
type: 'troopExit',
ok: false,
generalId: command.generalId,
reason: '부대에 소속되어 있지 않습니다.',
};
}
if (general.troopId !== general.id) {
world.updateGeneral(command.generalId, {
troopId: 0,
});
return {
type: 'troopExit',
ok: true,
generalId: command.generalId,
wasLeader: false,
};
}
const troopId = general.troopId;
const members = world.listGenerals().filter((entry) => entry.troopId === troopId);
for (const member of members) {
world.updateGeneral(member.id, { troopId: 0 });
}
world.removeTroop(troopId);
return {
type: 'troopExit',
ok: true,
generalId: command.generalId,
wasLeader: true,
};
}
function handleTroopKick(
world: InMemoryTurnWorld,
command: Extract<TurnDaemonCommand, { type: 'troopKick' }>
): TurnDaemonCommandResult {
const fail = (reason: string): TurnDaemonCommandResult => ({
type: 'troopKick',
ok: false,
generalId: command.generalId,
troopId: command.troopId,
targetGeneralId: command.targetGeneralId,
reason,
});
const actor = world.getGeneralById(command.generalId);
if (!actor) {
return fail('장수 정보를 찾을 수 없습니다.');
}
const troop = world.getTroopById(command.troopId);
if (
command.generalId !== command.troopId ||
actor.troopId !== actor.id ||
!troop ||
troop.id !== actor.id ||
troop.nationId !== actor.nationId
) {
return fail('권한이 부족합니다.');
}
const target = world.getGeneralById(command.targetGeneralId);
if (!target) {
return fail('장수 정보를 찾을 수 없습니다.');
}
if (target.troopId === 0) {
return fail('부대에 소속되어 있지 않습니다.');
}
if (target.troopId !== command.troopId) {
return fail('다른 부대에 소속되어 있습니다.');
}
if (target.id === command.troopId) {
return fail('부대장을 추방할 수 없습니다.');
}
world.updateGeneral(target.id, { troopId: 0 });
return {
type: 'troopKick',
ok: true,
generalId: actor.id,
troopId: troop.id,
targetGeneralId: target.id,
};
}
function handleTroopRename(
world: InMemoryTurnWorld,
command: Extract<TurnDaemonCommand, { type: 'troopRename' }>
): TurnDaemonCommandResult {
const fail = (reason: string): TurnDaemonCommandResult => ({
type: 'troopRename',
ok: false,
generalId: command.generalId,
troopId: command.troopId,
reason,
});
const actor = world.getGeneralById(command.generalId);
if (!actor) {
return fail('장수 정보를 찾을 수 없습니다.');
}
const nation = world.getNationById(actor.nationId);
const permission = resolveTroopSecretPermission(actor, nation?.meta ?? {}, false);
if (actor.id !== command.troopId && permission < 4) {
return fail('권한이 부족합니다.');
}
const troopName = normalizeTroopName(command.troopName);
if (!troopName) {
return fail('부대 이름이 없습니다.');
}
if (!isValidTroopNameWidth(troopName)) {
return fail('부대 이름은 전각 9자 또는 반각 18자 이하여야 합니다.');
}
const troop = world.getTroopById(command.troopId);
if (!troop || actor.nationId <= 0 || troop.nationId !== actor.nationId) {
return fail('부대가 없습니다.');
}
world.updateTroop(troop.id, { name: troopName });
return {
type: 'troopRename',
ok: true,
generalId: actor.id,
troopId: troop.id,
troopName,
};
}
+35 -13
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();
await adminActionConsumer?.stop();
} finally {
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,
+16 -325
View File
@@ -1,3 +1,4 @@
import { existingRowIdOrNext } from '@sammo-ts/infra';
import { handleCityOfficeRequest, settleCityOfficeRequests } from './cityOfficeRequests.js';
import type {
TurnDaemonCommandHandler,
@@ -25,10 +26,7 @@ import {
createItemModuleRegistry,
GeneralActionPipeline,
isDefenceTrainPenaltyWaivedByScenarioEffect,
isValidTroopNameWidth,
loadItemModules,
normalizeTroopName,
resolveTroopSecretPermission,
resolveMessageTargetIcon,
readDiplomacyMeta,
type GeneralActionModule,
@@ -41,6 +39,7 @@ import {
type TurnCommandProfile,
} from '@sammo-ts/logic';
import { resolveLegacyCompatibleUniqueConfig } from '@sammo-ts/logic/rewards/legacyUniqueItemPool.js';
import { appendJoinedNationIds } from '@sammo-ts/logic/actions/turn/general/joinedNations.js';
import { round as roundLegacyInteger, simpleSerialize } from '@sammo-ts/logic/war/utils.js';
import {
cloneItemInventory,
@@ -58,11 +57,7 @@ import {
} from './reservedTurnHandler.js';
import { buildCommandEnv } from './reservedTurnCommands.js';
import { openAuction } from '../auction/opener.js';
import {
hasScenarioStaticEventHandler,
IMMEDIATE_TROOP_JOIN_MOVE_HANDLER,
LEGACY_TROOP_JOIN_EVENT,
} from './scenarioStaticEvents.js';
import { handleTroopCommand, isTroopCommand, type TroopCommand } from './troopCommands.js';
import {
createGeneralFromSelectionPool,
reserveSelectionPool,
@@ -176,11 +171,6 @@ const requireCommandDatabase = (ctx: CommandHandlerContext): DatabaseClient => {
const ACTOR_BOUND_GENERAL_COMMAND_TYPE_LIST = [
'tournamentAdjustGeneral',
'troopCreate',
'troopJoin',
'troopExit',
'troopKick',
'troopRename',
'vacation',
'setMySetting',
'dropItem',
@@ -197,7 +187,7 @@ const ACTOR_BOUND_GENERAL_COMMAND_TYPE_LIST = [
type ActorBoundGeneralCommandType = (typeof ACTOR_BOUND_GENERAL_COMMAND_TYPE_LIST)[number];
const ACTOR_BOUND_GENERAL_COMMAND_TYPES = new Set<ActorBoundGeneralCommandType>(ACTOR_BOUND_GENERAL_COMMAND_TYPE_LIST);
type ActorBoundGeneralCommand = Extract<TurnDaemonCommand, { type: ActorBoundGeneralCommandType }>;
type ActorBoundGeneralCommand = TroopCommand | Extract<TurnDaemonCommand, { type: ActorBoundGeneralCommandType }>;
const isActorBoundGeneralCommand = (command: TurnDaemonCommand): command is ActorBoundGeneralCommand =>
ACTOR_BOUND_GENERAL_COMMAND_TYPES.has(command.type as ActorBoundGeneralCommandType);
@@ -213,7 +203,7 @@ const rejectActorBoundGeneralCommand = (
});
const validateActorBoundGeneralCommand = async (
ctx: CommandHandlerContext,
ctx: Pick<CommandHandlerContext, 'world' | 'commandDb'>,
command: ActorBoundGeneralCommand
): Promise<TurnDaemonCommandResult | null> => {
if (!ctx.commandDb) {
@@ -1347,307 +1337,6 @@ async function handleUpdateRuntimeSettings(
};
}
async function handleTroopJoin(
ctx: CommandHandlerContext,
command: Extract<TurnDaemonCommand, { type: 'troopJoin' }>
): Promise<TurnDaemonCommandResult> {
const { world } = ctx;
const general = world.getGeneralById(command.generalId);
if (!general) {
return {
type: 'troopJoin',
ok: false,
generalId: command.generalId,
troopId: command.troopId,
reason: '장수 정보를 찾을 수 없습니다.',
};
}
if (general.troopId !== 0) {
return {
type: 'troopJoin',
ok: false,
generalId: command.generalId,
troopId: command.troopId,
reason: '이미 부대에 소속되어 있습니다.',
};
}
if (general.nationId <= 0) {
return {
type: 'troopJoin',
ok: false,
generalId: command.generalId,
troopId: command.troopId,
reason: '국가에 소속되어 있지 않습니다.',
};
}
const troop = world.getTroopById(command.troopId);
if (!troop || troop.nationId !== general.nationId) {
return {
type: 'troopJoin',
ok: false,
generalId: command.generalId,
troopId: command.troopId,
reason: '부대가 올바르지 않습니다.',
};
}
world.updateGeneral(command.generalId, {
troopId: command.troopId,
});
if (
hasScenarioStaticEventHandler(
world.getScenarioConfig(),
LEGACY_TROOP_JOIN_EVENT,
IMMEDIATE_TROOP_JOIN_MOVE_HANDLER
)
) {
const leader = world.getGeneralById(troop.id);
if (
leader &&
leader.troopId === leader.id &&
leader.nationId === general.nationId &&
leader.cityId !== general.cityId
) {
const city = world.getCityById(leader.cityId);
if (city) {
world.updateGeneral(command.generalId, {
troopId: command.troopId,
cityId: leader.cityId,
});
const josaRo = JosaUtil.pick(city.name, '로');
world.pushLog({
scope: LogScope.GENERAL,
category: LogCategory.ACTION,
format: LogFormat.PLAIN,
text: `부대 주둔지인 <G><b>${city.name}</b></>${josaRo} 즉시 이동합니다.`,
generalId: general.id,
meta: {},
});
}
}
}
return {
type: 'troopJoin',
ok: true,
generalId: command.generalId,
troopId: command.troopId,
};
}
async function handleTroopCreate(
ctx: CommandHandlerContext,
command: Extract<TurnDaemonCommand, { type: 'troopCreate' }>
): Promise<TurnDaemonCommandResult> {
const { world } = ctx;
const general = world.getGeneralById(command.generalId);
if (!general) {
return {
type: 'troopCreate',
ok: false,
generalId: command.generalId,
reason: '장수 정보를 찾을 수 없습니다.',
};
}
const troopName = normalizeTroopName(command.troopName);
if (!troopName) {
return { type: 'troopCreate', ok: false, generalId: command.generalId, reason: '부대 이름이 없습니다.' };
}
if (!isValidTroopNameWidth(troopName)) {
return {
type: 'troopCreate',
ok: false,
generalId: command.generalId,
reason: '부대 이름은 전각 9자 또는 반각 18자 이하여야 합니다.',
};
}
if (general.troopId !== 0 || world.getTroopById(general.id)) {
return {
type: 'troopCreate',
ok: false,
generalId: command.generalId,
reason: '이미 부대에 소속되어 있습니다.',
};
}
if (general.nationId <= 0 || !world.getNationById(general.nationId)) {
return {
type: 'troopCreate',
ok: false,
generalId: command.generalId,
reason: '국가에 소속되어 있지 않습니다.',
};
}
const troop = world.createTroop({
id: general.id,
nationId: general.nationId,
name: troopName,
});
if (!troop) {
return {
type: 'troopCreate',
ok: false,
generalId: command.generalId,
reason: '부대가 생성되지 않았습니다. 버그일 수 있습니다.',
};
}
world.updateGeneral(general.id, { troopId: general.id });
return {
type: 'troopCreate',
ok: true,
generalId: general.id,
troopId: troop.id,
troopName: troop.name,
};
}
async function handleTroopExit(
ctx: CommandHandlerContext,
command: Extract<TurnDaemonCommand, { type: 'troopExit' }>
): Promise<TurnDaemonCommandResult> {
const { world } = ctx;
const general = world.getGeneralById(command.generalId);
if (!general) {
return {
type: 'troopExit',
ok: false,
generalId: command.generalId,
reason: '장수 정보를 찾을 수 없습니다.',
};
}
if (general.troopId === 0) {
return {
type: 'troopExit',
ok: false,
generalId: command.generalId,
reason: '부대에 소속되어 있지 않습니다.',
};
}
if (general.troopId !== general.id) {
world.updateGeneral(command.generalId, {
troopId: 0,
});
return {
type: 'troopExit',
ok: true,
generalId: command.generalId,
wasLeader: false,
};
}
const troopId = general.troopId;
const members = world.listGenerals().filter((entry) => entry.troopId === troopId);
for (const member of members) {
world.updateGeneral(member.id, { troopId: 0 });
}
world.removeTroop(troopId);
return {
type: 'troopExit',
ok: true,
generalId: command.generalId,
wasLeader: true,
};
}
async function handleTroopKick(
ctx: CommandHandlerContext,
command: Extract<TurnDaemonCommand, { type: 'troopKick' }>
): Promise<TurnDaemonCommandResult> {
const fail = (reason: string): TurnDaemonCommandResult => ({
type: 'troopKick',
ok: false,
generalId: command.generalId,
troopId: command.troopId,
targetGeneralId: command.targetGeneralId,
reason,
});
const { world } = ctx;
const actor = world.getGeneralById(command.generalId);
if (!actor) {
return fail('장수 정보를 찾을 수 없습니다.');
}
const troop = world.getTroopById(command.troopId);
if (
command.generalId !== command.troopId ||
actor.troopId !== actor.id ||
!troop ||
troop.id !== actor.id ||
troop.nationId !== actor.nationId
) {
return fail('권한이 부족합니다.');
}
const target = world.getGeneralById(command.targetGeneralId);
if (!target) {
return fail('장수 정보를 찾을 수 없습니다.');
}
if (target.troopId === 0) {
return fail('부대에 소속되어 있지 않습니다.');
}
if (target.troopId !== command.troopId) {
return fail('다른 부대에 소속되어 있습니다.');
}
if (target.id === command.troopId) {
return fail('부대장을 추방할 수 없습니다.');
}
world.updateGeneral(target.id, { troopId: 0 });
return {
type: 'troopKick',
ok: true,
generalId: actor.id,
troopId: troop.id,
targetGeneralId: target.id,
};
}
async function handleTroopRename(
ctx: CommandHandlerContext,
command: Extract<TurnDaemonCommand, { type: 'troopRename' }>
): Promise<TurnDaemonCommandResult> {
const fail = (reason: string): TurnDaemonCommandResult => ({
type: 'troopRename',
ok: false,
generalId: command.generalId,
troopId: command.troopId,
reason,
});
const { world } = ctx;
const actor = world.getGeneralById(command.generalId);
if (!actor) {
return fail('장수 정보를 찾을 수 없습니다.');
}
const nation = world.getNationById(actor.nationId);
const permission = resolveTroopSecretPermission(actor, nation?.meta ?? {}, false);
if (actor.id !== command.troopId && permission < 4) {
return fail('권한이 부족합니다.');
}
const troopName = normalizeTroopName(command.troopName);
if (!troopName) {
return fail('부대 이름이 없습니다.');
}
if (!isValidTroopNameWidth(troopName)) {
return fail('부대 이름은 전각 9자 또는 반각 18자 이하여야 합니다.');
}
const troop = world.getTroopById(command.troopId);
if (!troop || actor.nationId <= 0 || troop.nationId !== actor.nationId) {
return fail('부대가 없습니다.');
}
world.updateTroop(troop.id, { name: troopName });
return {
type: 'troopRename',
ok: true,
generalId: actor.id,
troopId: troop.id,
troopName,
};
}
const ensurePrestartDeleteAfter = async (
ctx: CommandHandlerContext,
command: Extract<TurnDaemonCommand, { type: 'dieOnPrestart' | 'ensureDieOnPrestartStatus' }>,
@@ -2346,6 +2035,7 @@ async function handleKick(
const targetMeta = target.meta;
const nextMeta: TurnGeneral['meta'] = {
...targetMeta,
joinedNations: appendJoinedNationIds(targetMeta, target.nationId),
officerCity: 0,
officer_city: 0,
belong: 0,
@@ -2864,8 +2554,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),
@@ -3288,13 +2978,6 @@ export const createTurnDaemonCommandHandler = (options: {
>;
const handlers: HandlerMap = {
troopCreate: (command) =>
handleTroopCreate(ctx, command as Extract<TurnDaemonCommand, { type: 'troopCreate' }>),
troopJoin: (command) => handleTroopJoin(ctx, command as Extract<TurnDaemonCommand, { type: 'troopJoin' }>),
troopExit: (command) => handleTroopExit(ctx, command as Extract<TurnDaemonCommand, { type: 'troopExit' }>),
troopKick: (command) => handleTroopKick(ctx, command as Extract<TurnDaemonCommand, { type: 'troopKick' }>),
troopRename: (command) =>
handleTroopRename(ctx, command as Extract<TurnDaemonCommand, { type: 'troopRename' }>),
ensureDieOnPrestartStatus: (command) =>
handleEnsureDieOnPrestartStatus(
ctx,
@@ -3391,6 +3074,14 @@ export const createTurnDaemonCommandHandler = (options: {
command,
executionContext?: TurnDaemonCommandExecutionContext
): Promise<TurnDaemonCommandResult | null> => {
if (isTroopCommand(command)) {
const rejected = await validateActorBoundGeneralCommand(
{ world: options.world, commandDb: executionContext?.db },
command
);
return rejected ?? handleTroopCommand(options.world, command);
}
const handler = handlers[command.type];
if (!handler) {
return null;
@@ -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,
@@ -153,6 +153,61 @@ describe('unique auction inheritance log compatibility', () => {
expect(resolveAuctionResourceAmount(undefined, 'invalid')).toBeNull();
});
it.each([
{ description: '장수 ID를 새 소유자가 사용함', provenOwner: 'original-account', refund: true },
{ description: '사라진 장수의 입찰 계정을 확인할 수 없음', provenOwner: null, refund: false },
])('유니크 경매를 끝낸다. $description', async ({ provenOwner, refund }) => {
const closeAt = new Date('0193-07-01T00:00:00.000Z');
const reusedGeneral = { id: 7, userId: 'new-account' };
const db = {
$queryRaw: vi.fn(async (query: { strings: readonly string[] }) => {
const sql = query.strings.join(' ');
if (sql.includes('JOIN input_event')) return provenOwner ? [{ userId: provenOwner }] : [];
if (sql.includes('FROM auction_bid')) return [{ id: 9, generalId: 7, amount: 5_100, meta: {} }];
return [{ id: 31, type: 'UNIQUE_ITEM', status: 'FINALIZING', detail: {}, closeAt }];
}),
$executeRaw: vi.fn(async () => 1),
inheritancePoint: { updateManyAndReturn: vi.fn(async () => [{ value: 6_100 }]) },
inheritanceLog: { create: vi.fn(async () => undefined) },
errorLog: { create: vi.fn(async () => undefined) },
};
const world = {
getGeneralById: () => (provenOwner ? reusedGeneral : null),
getState: () => ({ currentYear: 193, currentMonth: 7 }),
gameTickToDate: () => closeAt,
listGenerals: () => [reusedGeneral],
updateGeneral: vi.fn(),
pushLog: vi.fn(),
};
const finalizer = await createAuctionFinalizer({
databaseUrl: 'postgresql://unused',
world: world as unknown as Parameters<typeof createAuctionFinalizer>[0]['world'],
});
await expect(
finalizer.finalize(
withDaemonBoundary({ type: 'auctionFinalize', auctionId: 31, expectedCloseTick: 72_000_000 }),
db as unknown as NonNullable<Parameters<typeof finalizer.finalize>[1]>
)
).resolves.toMatchObject({ ok: true });
expect(db.$executeRaw).toHaveBeenCalledWith(expect.objectContaining({ values: ['CANCELED', 31] }));
expect(world.updateGeneral).not.toHaveBeenCalled();
if (refund) {
expect(db.inheritancePoint.updateManyAndReturn).toHaveBeenCalledWith(
expect.objectContaining({
where: { userId: provenOwner, key: 'previous' },
data: { value: { increment: 5_100 } },
})
);
expect(db.inheritanceLog.create).toHaveBeenCalledOnce();
expect(db.errorLog.create).not.toHaveBeenCalled();
} else {
expect(db.inheritancePoint.updateManyAndReturn).not.toHaveBeenCalled();
expect(db.errorLog.create).toHaveBeenCalledOnce();
}
await finalizer.close();
});
it('uses the Ref-inclusive close boundary and the logical tick as the deadline generation', () => {
const closeAt = new Date('0193-07-01T00:00:00.000Z');
const auction = { closeAt, closeTick: 72_000_000n };
@@ -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();
});
});
@@ -1,6 +1,13 @@
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { SystemClock } from '@sammo-ts/common';
import {
hasRealtimeReadModelInvalidation,
parseReadModelOutboxPayload,
readModelOutboxPayloadToChanges,
resolveRealtimeReadModelInvalidation,
SystemClock,
type TurnDaemonCommand,
} from '@sammo-ts/common';
import { createGamePostgresConnector, type GamePrisma, type GamePrismaClient } from '@sammo-ts/infra';
import type { MapDefinition, ScenarioConfig, ScenarioMeta, TurnSchedule } from '@sammo-ts/logic';
@@ -182,6 +189,7 @@ integration('immediate general action persistence', () => {
},
});
await db.message.deleteMany({ where: { mailbox: { in: [generalId, generalId + 1] } } });
await db.troop.deleteMany({ where: { troopLeaderId: generalId } });
await db.general.deleteMany({ where: { id: { in: [generalId, generalId + 1] } } });
await db.city.deleteMany({ where: { id: cityId } });
await db.nation.deleteMany({ where: { id: { gte: existingNationId } } });
@@ -292,6 +300,7 @@ integration('immediate general action persistence', () => {
},
});
await db.message.deleteMany({ where: { mailbox: { in: [generalId, generalId + 1] } } });
await db.troop.deleteMany({ where: { troopLeaderId: generalId } });
await db.general.deleteMany({ where: { id: { in: [generalId, generalId + 1] } } });
await db.city.deleteMany({ where: { id: cityId } });
await db.nation.deleteMany({ where: { id: { gte: existingNationId } } });
@@ -299,6 +308,167 @@ integration('immediate general action persistence', () => {
await disconnect?.();
});
it('commits troop commands with world state, read-model changes, and no lobby refresh', async () => {
const memberId = generalId + 1;
const memberUserId = 'immediate-troop-member';
const leaderUserId = general.userId!;
await db.general.update({ where: { id: generalId }, data: { nationId: existingNationId } });
await db.general.create({
data: {
id: memberId,
userId: memberUserId,
name: '부대원',
nationId: existingNationId,
cityId,
turnTime: general.turnTime,
meta: { killturn: 24 },
},
});
const loaded = await loadTurnWorldFromDatabase({ databaseUrl: databaseUrl! });
const world = new InMemoryTurnWorld(loaded.state, loaded.snapshot, {
schedule: { entries: [{ startMinute: 0, tickMinutes: 10 }] },
});
const handler = createTurnDaemonCommandHandler({ world });
const queue = new DatabaseTurnDaemonCommandQueue(db);
await queue.initialize();
const hooks = await createDatabaseTurnHooks(databaseUrl!, world);
const stateManager = new EngineStateManager();
stateManager.register('world', {
capture: () => world.captureState(),
restore: (saved) => world.restoreState(saved),
});
type TroopCommand = Extract<TurnDaemonCommand, { type: `troop${string}` }>;
const execute = (id: string, command: TroopCommand) =>
stateManager.transaction(() =>
hooks.hooks.executeCommand!(id, async (context) => {
const result = await handler.handle({ ...command, requestId: id }, context);
if (!result) throw new Error('Missing troop command result.');
return result;
})
);
const checkWorld = async (name: string | null, memberTroopId: number) => {
const reloaded = await loadTurnWorldFromDatabase({ databaseUrl: databaseUrl! });
const expectedTroop = name === null ? null : { id: generalId, nationId: existingNationId, name };
expect(world.getTroopById(generalId)).toEqual(expectedTroop);
expect(reloaded.snapshot.troops.find(({ id }) => id === generalId) ?? null).toEqual(expectedTroop);
for (const [id, troopId] of [
[generalId, name === null ? 0 : generalId],
[memberId, memberTroopId],
]) {
expect(world.getGeneralById(id)?.troopId).toBe(troopId);
expect(reloaded.snapshot.generals.find((entry) => entry.id === id)?.troopId).toBe(troopId);
}
};
const leader = { generalId, userId: leaderUserId };
const member = { generalId: memberId, userId: memberUserId };
const join = { type: 'troopJoin', ...member, troopId: generalId } as const;
const steps: {
command: TroopCommand;
name: string | null;
memberTroopId: number;
changedGenerals: number[];
}[] = [
{
command: { type: 'troopCreate', ...leader, troopName: '백마대' },
name: '백마대',
memberTroopId: 0,
changedGenerals: [generalId],
},
{ command: join, name: '백마대', memberTroopId: generalId, changedGenerals: [memberId] },
{
command: { type: 'troopRename', ...leader, troopId: generalId, troopName: '청룡대' },
name: '청룡대',
memberTroopId: generalId,
changedGenerals: [],
},
{
command: { type: 'troopKick', ...leader, troopId: generalId, targetGeneralId: memberId },
name: '청룡대',
memberTroopId: 0,
changedGenerals: [memberId],
},
{ command: join, name: '청룡대', memberTroopId: generalId, changedGenerals: [memberId] },
{
command: { type: 'troopExit', ...member },
name: '청룡대',
memberTroopId: 0,
changedGenerals: [memberId],
},
{ command: join, name: '청룡대', memberTroopId: generalId, changedGenerals: [memberId] },
{
command: { type: 'troopExit', ...leader },
name: null,
memberTroopId: 0,
changedGenerals: [generalId, memberId],
},
];
try {
for (const [index, { command, name, memberTroopId, changedGenerals }] of steps.entries()) {
const id = `${requestId}:troop:${index}`;
await db.inputEvent.create({
data: {
requestId: id,
target: 'ENGINE',
eventType: command.type,
actorUserId: command.userId,
payload: { ...command, requestId: id },
},
});
expect(await queue.drain()).toMatchObject([{ ...command, requestId: id }]);
if (command.type === 'troopRename') {
const outboxCount = await db.readModelOutbox.count();
await db.$executeRaw`ALTER TABLE read_model_outbox ADD CONSTRAINT troop_command_rollback CHECK (false) NOT VALID`;
try {
await expect(execute(id, command)).rejects.toThrow('troop_command_rollback');
await checkWorld('백마대', generalId);
expect(hooks.takeCommittedReadModelChangeReceipt()).toBeNull();
await expect(db.readModelOutbox.count()).resolves.toBe(outboxCount);
await expect(
db.inputEvent.findUniqueOrThrow({ where: { requestId: id } })
).resolves.toMatchObject({
status: 'PROCESSING',
result: null,
});
} finally {
await db.$executeRaw`ALTER TABLE read_model_outbox DROP CONSTRAINT troop_command_rollback`;
}
}
const result = await execute(id, command);
expect(result).toMatchObject({ type: command.type, ok: true, generalId: command.generalId });
await expect(db.inputEvent.findUniqueOrThrow({ where: { requestId: id } })).resolves.toMatchObject({
status: 'SUCCEEDED',
result,
});
await checkWorld(name, memberTroopId);
const receipt = hooks.takeCommittedReadModelChangeReceipt()!;
expect(receipt.invalidation.revisions.map(({ domain, entityId }) => [domain, entityId])).toEqual([
['dashboard.global', 0],
...changedGenerals.map((id) => ['general.content', id]),
]);
const row = await db.readModelOutbox.findUniqueOrThrow({ where: { id: receipt.outboxId } });
const changes = readModelOutboxPayloadToChanges(parseReadModelOutboxPayload(row.payload)!);
for (const id of [generalId, memberId, null]) {
const invalidation = resolveRealtimeReadModelInvalidation(changes, {
generalId: id,
cityId,
nationId: existingNationId,
});
expect(invalidation.lobby).toBe(false);
expect(hasRealtimeReadModelInvalidation(invalidation)).toBe(
id !== null && changedGenerals.includes(id)
);
}
}
} finally {
await hooks.close();
}
});
it.each([
'normal',
'resigned',
@@ -378,7 +378,7 @@ describe('nation personnel world commands', () => {
rice: 1_000,
experience: 850,
dedication: 1_700,
meta: expect.objectContaining({ belong: 0, permission: 'normal', betray: 2 }),
meta: expect.objectContaining({ belong: 0, permission: 'normal', betray: 2, joinedNations: [1] }),
});
expect(fixture.world.getGeneralById(4)?.troopId).toBe(0);
expect(fixture.world.getTroopById(3)).toBeNull();
@@ -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,
+100
View File
@@ -7,7 +7,9 @@ import {
type RandomAppointmentResolveContext,
} from '@sammo-ts/logic/actions/turn/general/che_랜덤임관.js';
import type { ActionContextWorldRef } from '@sammo-ts/logic/actions/turn/actionContext.js';
import { createDatabaseTurnHooks } from '../src/turn/databaseHooks.js';
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
import { createMonthlyBoundaryPreHandler } from '../src/turn/monthlyBoundaryPreHandler.js';
import { InMemoryReservedTurnStore } from '../src/turn/reservedTurnStore.js';
import { createReservedTurnHandler } from '../src/turn/reservedTurnHandler.js';
import { buildCommandEnv } from '../src/turn/reservedTurnCommands.js';
@@ -320,6 +322,104 @@ describeDb('scenario database seed', () => {
}
});
test('persists and reloads random appointment history across reserved joins and resignations', async () => {
await seedScenarioToDatabase({
scenarioId: 1031,
databaseUrl,
resetTables: true,
now: new Date('2030-01-01T00:00:00.000Z'),
installOptions: { fiction: 1 },
});
const connector = createGamePostgresConnector({ url: databaseUrl });
try {
await connector.connect();
const db = connector.prisma;
const loaded = await loadTurnWorldFromDatabase({ databaseUrl });
const [visited, unvisited] = loaded.snapshot.nations.filter((nation) => nation.id > 0).slice(0, 2);
const actor = loaded.snapshot.generals.find((general) => general.nationId === 0);
if (!visited || !unvisited || !actor) throw new Error('Expected two nations and a neutral general.');
for (const nation of loaded.snapshot.nations.filter((nation) => nation.id > 0)) {
const eligible = nation.id === visited.id || nation.id === unvisited.id;
await db.nation.update({
where: { id: nation.id },
data: { meta: { ...nation.meta, scout: !eligible, gennum: 1 } },
});
}
const eligibleIds = [visited.id, unvisited.id];
await db.general.update({
where: { id: actor.id },
data: { npcState: 0, meta: { ...actor.meta, killturn: 100, joinedNations: [visited.id] } },
});
const executeAndReload = async (action: 'che_랜덤임관' | 'che_하야', waitMonths = 0) => {
const { state, snapshot } = await loadTurnWorldFromDatabase({ databaseUrl });
const store = new InMemoryReservedTurnStore(db, { maxGeneralTurns: 30, maxNationTurns: 12 });
await store.loadAll();
let world: InMemoryTurnWorld | null = null;
const handler = await createReservedTurnHandler({
reservedTurns: store,
scenarioConfig: snapshot.scenarioConfig,
scenarioMeta: snapshot.scenarioMeta,
map: snapshot.map,
unitSet: snapshot.unitSet,
getWorld: () => world,
});
world = new InMemoryTurnWorld(state, snapshot, {
schedule: { entries: [{ startMinute: 0, tickMinutes: 10 }] },
generalTurnHandler: handler,
calendarHandler: createMonthlyBoundaryPreHandler({
getWorld: () => world,
startYear: snapshot.scenarioMeta?.startYear ?? state.currentYear,
commandEnv: buildCommandEnv(snapshot.scenarioConfig, snapshot.unitSet),
}),
});
for (let month = 0; month < waitMonths; month++) {
const next = new Date(world.getState().lastTurnTime.getTime() + state.tickSeconds * 1000);
await world.advanceMonth(next);
}
store.setGeneralTurn(actor.id, 0, { action, args: {} });
world.executeGeneralTurn(world.getGeneralById(actor.id)!);
const hooks = await createDatabaseTurnHooks(databaseUrl, world, { reservedTurns: store });
try {
await hooks.hooks.flushChanges?.({
lastTurnTime: world.getState().lastTurnTime.toISOString(),
processedGenerals: 1,
processedTurns: 1,
durationMs: 0,
partial: false,
});
} finally {
await hooks.close();
}
const reloaded = await loadTurnWorldFromDatabase({ databaseUrl });
return reloaded.snapshot.generals.find(({ id }) => id === actor.id)!;
};
expect(await executeAndReload('che_랜덤임관')).toMatchObject({
nationId: unvisited.id,
meta: { joinedNations: eligibleIds },
});
expect(await executeAndReload('che_하야')).toMatchObject({
nationId: 0,
meta: { joinedNations: eligibleIds, makelimit: 12 },
});
const reset = await executeAndReload('che_랜덤임관', 12);
expect(eligibleIds).toContain(reset.nationId);
expect(reset.meta.joinedNations).toEqual([reset.nationId]);
expect(await executeAndReload('che_하야')).toMatchObject({
nationId: 0,
meta: { joinedNations: [reset.nationId], makelimit: 12 },
});
const otherId = eligibleIds.find((id) => id !== reset.nationId);
expect(await executeAndReload('che_랜덤임관', 12)).toMatchObject({
nationId: otherId,
meta: { joinedNations: [reset.nationId, otherId] },
});
} finally {
await connector.disconnect();
}
});
test.each([
{ sync: true, turnMinutes: 60, hour: 10, month: 10, yearOffset: -1 },
{ sync: true, turnMinutes: 60, hour: 1, month: 1, yearOffset: 0 },
@@ -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, {
@@ -1545,6 +1545,77 @@ test('shows speciality reset cooldowns and reserves special user commands from t
await picker.screenshot({ path: test.info().outputPath('special-user-commands-mobile-500.png') });
});
test('shows stat experience next to strategy commands and preserves reservation on desktop and mobile', async ({
page,
}, testInfo) => {
const strategy = commandTable.general.find(({ category }) => category === '계략')!;
const requests = await install(page, false, {
general: [
{
...strategy,
values: strategy.values.map((command, index) => ({
...command,
statExperienceText: ['지력 경험', '통솔 경험', '무력 경험', '무력 경험'][index],
costText: '금 500 · 쌀 500',
})),
},
],
nation: [],
inputOptions,
});
for (const viewport of [
{ width: 1365, height: 900 },
{ width: 390, height: 844 },
]) {
await page.setViewportSize(viewport);
await page.goto(gamePath('/'));
await page.getByRole('button', { name: '1턴 명령 입력', exact: true }).click();
const picker = page.getByTestId('command-picker');
const fire = picker.getByRole('button', { name: /화계.*지력 경험/ });
await expect(picker.locator('.command-stat-experience')).toHaveText([
'(지력 경험)',
'(통솔 경험)',
'(무력 경험)',
'(무력 경험)',
]);
await expect(fire.locator('.command-cost')).toHaveText('금 500 · 쌀 500');
await expect(fire).toHaveClass(/blocked reservable/);
await expect(fire).toHaveAttribute('title', '현재 조건에서는 실행할 수 없습니다.');
await expect(fire).toBeEnabled();
await page.evaluate(() => document.fonts.ready);
await fire.hover();
await fire.focus();
await expect(fire).toBeFocused();
const geometry = await picker.locator('.command-item').evaluateAll((buttons) =>
buttons.map((button) => {
const experience = button.querySelector('.command-stat-experience')!;
return {
button: button.getBoundingClientRect().toJSON(),
hint: experience.getBoundingClientRect().toJSON(),
overflow: button.scrollWidth - button.clientWidth,
hintFont: getComputedStyle(experience).font,
};
})
);
expect(geometry.every(({ button, hint, overflow }) => overflow <= 0 && hint.right <= button.right)).toBe(true);
const artifact = `general-stat-experience-${viewport.width}`;
await writeFile(
testInfo.outputPath(`${artifact}.json`),
JSON.stringify({ url: page.url(), geometry }, null, 2)
);
await writeFile(testInfo.outputPath(`${artifact}.html`), await picker.evaluate((element) => element.outerHTML));
await picker.screenshot({ path: testInfo.outputPath(`${artifact}.png`) });
await fire.click();
const form = page.getByTestId('command-argument-form');
await form.locator('select').first().selectOption('2');
await page.getByRole('button', { name: '화계 입력', exact: true }).click();
await expect(page.locator('[data-command-scope="general"] .action-column > div').first()).toHaveText(
'【허창】에 화계실행'
);
}
expect(JSON.stringify(requests)).toContain('"action":"che_화계","args":{"destCityId":2}');
});
test('shows general command durations from metadata on desktop and mobile', async ({ page }) => {
const requests = await install(page, false, {
general: [
@@ -710,6 +710,106 @@ test('trait and injury explanations appear on pointer hover and keyboard focus',
await page.screenshot({ path: testInfo.outputPath('directory-trait-injury-tooltips.png'), fullPage: true });
});
for (const width of [1200, 500]) {
test(`catalog description line breaks stay safe on hover and focus at ${width}px`, async ({ page }, testInfo) => {
await page.setViewportSize({ width, height: 900 });
const warInfo =
'[계략] 화계·탈취·파괴·선동 : 성공률 +10%p<br>[전투] 계략 시도 확률 +20%p, 계략 성공 확률 +20%p';
const literalMarkup = '<img src=x onerror="alert(1)"><b>설명</b>';
const directoryRows = generals.map((general) =>
general.id === 10
? {
...general,
specialDomestic: {
...general.specialDomestic,
info: `상업 특기<br/>수익 증가<BR />매매 효율\r\n${literalMarkup}`,
},
specialWar: { key: 'che_신산', name: '신산', info: warInfo },
}
: general
);
await install(page, 'general', [], [], directoryRows);
await page.goto('general-list');
await page.reload();
const prefix = width <= 600 ? 'card-' : '';
const container = page
.locator(width <= 600 ? '[data-general-card-id="10"]' : 'tr[data-general-id="10"]')
.first();
await expect(container).toBeVisible();
await expect(page.getByRole('button', { name: '갱 신' })).not.toHaveAttribute('aria-busy');
await page.evaluate(async () => {
await document.fonts.ready;
await Promise.all(Array.from(document.images, (image) => image.decode().catch(() => undefined)));
});
const before = await container.boundingBox();
const evidence: Record<string, unknown> = { width, url: page.url(), before };
for (const [kind, expected] of [
['special-domestic', ['상업 특기', '수익 증가', '매매 효율', literalMarkup]],
['special-war', warInfo.split('<br>')],
] as const) {
const trigger = page.locator(`[data-directory-tooltip="${prefix}${kind}-10"]`);
const tooltip = trigger.getByRole('tooltip');
await page.mouse.move(0, 0);
await trigger.hover();
await expect(tooltip).toBeVisible();
await trigger.focus();
await expect(tooltip).toBeVisible();
await expect(trigger).toHaveCSS('text-decoration-line', 'none');
await expect(trigger).toHaveCSS('outline-style', 'solid');
const description = tooltip.locator('.directory-tooltip__description');
await expect(description.locator('br')).toHaveCount(expected.length - 1);
await expect(description.locator('img, b, script')).toHaveCount(0);
expect(await description.innerText()).not.toMatch(/<br\s*\/?\s*>/iu);
const metrics = await description.evaluate((element) => {
const lines = Array.from(element.childNodes).filter(
(node) => node.nodeType === Node.TEXT_NODE && node.textContent?.trim()
);
return {
lines: lines.map((node) => {
const range = document.createRange();
range.selectNodeContents(node);
return { text: node.textContent?.trim(), top: range.getBoundingClientRect().top };
}),
html: element.outerHTML,
};
});
expect(metrics.lines.map((line) => line.text)).toEqual(expected);
for (let index = 1; index < metrics.lines.length; index += 1) {
expect(metrics.lines[index]!.top).toBeGreaterThan(metrics.lines[index - 1]!.top);
}
const geometry = await tooltip.evaluate((element) => {
const rect = element.getBoundingClientRect();
const style = getComputedStyle(element);
return {
left: rect.left,
right: rect.right,
top: rect.top,
bottom: rect.bottom,
font: style.font,
background: style.backgroundColor,
position: style.position,
};
});
expect(geometry.left).toBeGreaterThanOrEqual(8);
expect(geometry.right).toBeLessThanOrEqual(width - 8);
expect(geometry.top).toBeGreaterThanOrEqual(0);
expect(geometry.bottom).toBeLessThanOrEqual(900);
expect(await container.boundingBox()).toEqual(before);
evidence[kind] = { ...metrics, geometry };
await page.screenshot({ path: testInfo.outputPath(`catalog-${kind}-${width}.png`), fullPage: true });
await trigger.blur();
}
const empty = page.locator(`[data-directory-tooltip="${prefix}special-war-20"]`);
await expect(empty).not.toHaveAttribute('tabindex');
await expect(empty.getByRole('tooltip')).toHaveCount(0);
await writeFile(testInfo.outputPath('catalog-description.json'), JSON.stringify(evidence, null, 2));
await writeFile(
testInfo.outputPath('catalog-description.html'),
await page.locator('main').evaluate((element) => element.outerHTML)
);
});
}
test('npc directory reuses the dark sort controls and sorts from a table header', async ({ page }, testInfo) => {
await install(page);
await page.goto('npc-list');
+157 -5
View File
@@ -332,8 +332,14 @@ const battleCenter = (state: FixtureState) => ({
crewTypeId: 1,
crewTypeName: '보병',
equipment: { weapon: 'None', book: 'None', horse: 'None', item: 'None' },
equipmentNames: { weapon: '-', book: '-', horse: '-', item: '-' },
traits: { personal: '-', specialDomestic: '-', specialWar: '-' },
equipmentNames: state.richMyInfo
? { weapon: '단도', book: '효경전', horse: '적토마(+15)', item: '납금박산로' }
: { weapon: '-', book: '-', horse: '-', item: '-' },
itemInfo: state.richMyInfo
? { weapon: '무력 +1', book: '지력 +1', horse: '통솔 +15', item: '내정 성공률 +15%p' }
: undefined,
traits: state.mainTraits ?? { personal: '-', specialDomestic: '-', specialWar: '-' },
traitInfo: state.richMyInfo ? myGeneral(state).general.traitInfo : undefined,
progression: {
experienceLevel: 1,
dedicationLevel: 2,
@@ -387,7 +393,7 @@ const battleCenter = (state: FixtureState) => ({
],
});
const install = async (page: Page, state: FixtureState) => {
const install = async (page: Page, state: FixtureState, includeAuxiliaryWindows = false) => {
await page.addInitScript(
({ basePath, profile }) => {
if (location.pathname.startsWith(`${basePath}/`)) {
@@ -397,7 +403,8 @@ const install = async (page: Page, state: FixtureState) => {
},
{ basePath: gameBasePath, profile: gameProfile }
);
await page.route('**/image/game/**', async (route) => {
const routeTarget = includeAuxiliaryWindows ? page.context() : page;
await routeTarget.route('**/image/game/**', async (route) => {
const filename = basename(new URL(route.request().url()).pathname);
if (
legacyImageRoot &&
@@ -414,7 +421,7 @@ const install = async (page: Page, state: FixtureState) => {
}
await route.fulfill({ status: 200, contentType: 'image/jpeg', body: Buffer.from('') });
});
await page.route(gameTrpcRoute, async (route) => {
await routeTarget.route(gameTrpcRoute, async (route) => {
const operations = operationNames(route);
const rawRequestBody: unknown = route.request().postData() ? route.request().postDataJSON() : {};
const requestBody =
@@ -671,6 +678,28 @@ const install = async (page: Page, state: FixtureState) => {
if (pageName) state.accessPages.push(pageName);
return response({ recorded: true });
}
if (operation === 'nation.getGeneralList') {
const center = battleCenter(state);
return response({
nation: center.nation,
viewer: { generalId: center.me.id, permission: center.me.permissionLevel },
generals: center.generals.map((general) => ({
...general,
experienceLevel: general.progression.experienceLevel,
dedicationText: general.progression.dedicationText,
honorText: '무명',
cityName: '업',
belong: general.serviceYears,
refreshScoreTotal: 0,
reservedCommands: [],
battleStats: {
...general.battleStats,
battles: general.warnum,
wins: general.battleStats.kills,
},
})),
});
}
if (operation === 'nation.getBattleCenter') {
if (state.permission === 'member' && !state.battleTenured) {
return {
@@ -2627,6 +2656,129 @@ test('감찰부 keeps the selector interaction and shows the permission error pa
await expect(page.getByRole('alert')).toContainText('권한이 부족합니다.');
});
test('세력장수 이름 링크는 선택한 장수의 감찰부를 열고 목록 검색을 보존한다', async ({ page, context }) => {
const state: FixtureState = {
permission: 'member',
battleTenured: true,
myset: 3,
settingMutations: [],
accessPages: [],
};
await install(page, state, true);
for (const viewport of [
{ width: 1365, height: 900 },
{ width: 390, height: 844 },
]) {
await page.setViewportSize(viewport);
await page.goto('nation/generals');
const filter = page.getByLabel('장수명 필터');
await expect(filter).toBeVisible();
await filter.fill('검증장수');
const link = page.getByRole('link', { name: '검증장수' });
await expect(link).toHaveAttribute('href', `${gameBasePath}/battle-center?generalId=7`);
await expect(link).toHaveCSS('text-decoration-line', 'underline');
await link.hover();
await expect(link).toHaveCSS('cursor', 'pointer');
await page.keyboard.press('Tab');
await link.focus();
await expect(link).toHaveCSS('outline-style', 'solid');
await waitForVisualAssets(page);
await persistParityArtifact(
page,
`nation-generals-battle-link-${viewport.width}`,
await link.evaluate((element) => ({
url: location.href,
link: element.outerHTML,
cell: element.parentElement!.getBoundingClientRect().toJSON(),
rect: element.getBoundingClientRect().toJSON(),
color: getComputedStyle(element).color,
outline: getComputedStyle(element).outline,
}))
);
const opened = context.waitForEvent('page');
if (viewport.width > 500) await link.press('Enter');
else await link.click();
const battle = await opened;
await battle.setViewportSize(viewport);
await expect(battle).toHaveURL(new RegExp(`${gameBasePath}/battle-center\\?generalId=7$`));
await expect(battle.locator('.selector-row select').nth(1)).toHaveValue('7');
await expect(battle.locator('.battle-general-card')).toContainText('검증장수');
await battle.reload();
await expect(battle.locator('.battle-general-card')).toContainText('검증장수');
await Promise.all([
battle.waitForEvent('close'),
battle.getByRole('button', { name: '창 닫기' }).first().click(),
]);
await expect(filter).toHaveValue('검증장수');
await expect(page.locator('#nation-general-list tbody tr')).toHaveCount(1);
}
state.battleTenured = false;
await page.reload();
await expect(page.locator('#nation-general-list [data-general-name]').first()).toBeVisible();
await expect(page.locator('#nation-general-list a[data-general-name]')).toHaveCount(0);
});
test('감찰부 특기와 장비는 마우스와 키보드로 설명을 확인할 수 있다', async ({ page }) => {
const state: FixtureState = {
permission: 'head',
myset: 3,
richMyInfo: true,
mainTraits: { personal: '안전', specialDomestic: '상재', specialWar: '신산' },
settingMutations: [],
accessPages: [],
};
await install(page, state);
const card = page.locator('.battle-general-card');
const tooltip = page.locator('.tippy-box[data-state="visible"]');
for (const viewport of [
{ width: 1365, height: 900 },
{ width: 390, height: 844 },
]) {
await page.setViewportSize(viewport);
await page.goto('battle-center?generalId=7');
await expect(card).toContainText('검증장수');
await waitForVisualAssets(page);
const cardBefore = await card.boundingBox();
for (const [id, description] of [
['special-domestic', '상업 내정 효율이 증가합니다.'],
['special-war', '계략 성공률이 증가합니다.'],
['horse', '통솔 +15'],
['item', '내정 성공률 +15%p'],
]) {
const trigger = card.locator(`[data-rich-tooltip="${id}"]`);
await trigger.hover();
await expect(trigger).toHaveCSS('cursor', 'help');
await expect(tooltip).toContainText(description);
await page.mouse.move(1, 1);
await expect(tooltip).toHaveCount(0);
}
const war = card.locator('[data-rich-tooltip="special-war"]');
await war.focus();
await expect(war).toBeFocused();
await expect(tooltip.locator('.rich-tooltip-content__line')).toHaveText([
'계략 성공률이 증가합니다.',
'발동 순서는 레거시와 같습니다.',
]);
const cardAfter = await card.boundingBox();
expect(cardAfter?.width).toBe(cardBefore?.width);
expect(cardAfter?.height).toBe(cardBefore?.height);
await persistParityArtifact(page, `battle-center-description-${viewport.width}`, {
url: page.url(),
card: cardAfter,
trigger: await war.boundingBox(),
tooltip: await tooltip.boundingBox(),
font: await tooltip.evaluate((element) => getComputedStyle(element).font),
markup: await tooltip.innerHTML(),
});
await page.locator('.selector-row select').nth(1).selectOption('8');
await expect(card).toContainText('다른장수');
await expect(war).not.toHaveAttribute('tabindex', '0');
await expect(tooltip).toHaveCount(0);
}
});
test('감찰부 하단 창 닫기 버튼은 상단 버튼과 같은 크기를 유지한다', async ({ page }) => {
const head: FixtureState = { permission: 'head', myset: 3, settingMutations: [], accessPages: [] };
await install(page, head);
+14 -2
View File
@@ -27,6 +27,10 @@ const history = [
id: 3,
text: '이번 수입은 금 <C>158</>입니다.',
},
{
id: 4,
text: '<D><b>풍년F&B</b></> &#60;img src=x onerror=globalThis.__legacyLogXss=4&#62;',
},
];
const publicResponse = (operation: string): unknown => {
@@ -36,7 +40,12 @@ const publicResponse = (operation: string): unknown => {
return response({ year: 200, month: 1, cityList: [], nationList: [], history });
}
if (operation === 'public.getWorldTrend') return response({ year: 200, month: 1, turnTerm: 10 });
if (operation === 'public.getNationList' || operation === 'public.getGeneralList') return response([]);
if (operation === 'public.getNationList') {
return response([
{ id: 13, name: '풍년F&B', color: '#330000', level: 1, capitalCityId: 0, generalCount: 1, cityCount: 0 },
]);
}
if (operation === 'public.getGeneralList') return response([]);
throw new Error(`Unhandled legacy log fixture operation: ${operation}`);
};
@@ -64,12 +73,15 @@ for (const viewport of [
await page.goto('public');
const lines = page.locator('.recent-log-line');
await expect(lines).toHaveCount(3);
await expect(lines).toHaveCount(4);
await expect(lines.nth(0).locator('b')).toHaveText('안전 강조');
await expect(lines.nth(1).locator('.small_war_log .war_type_attack')).toHaveText('→');
await expect(lines.nth(1).locator('.ev_highlight')).toHaveText('강조');
await expect(lines.nth(2)).toHaveText('이번 수입은 금 158입니다.');
await expect(lines.nth(2)).not.toContainText('157.5');
await expect(lines.nth(3).locator('b')).toHaveText('풍년F&B');
await expect(lines.nth(3)).toContainText('&#60;img');
await expect(page.getByRole('cell', { name: '풍년F&B', exact: true })).toBeVisible();
await expect(lines.locator('script, img, svg, a, [onerror], [onclick], [style*="url"]')).toHaveCount(0);
await expect(lines.nth(0)).toContainText('<img src=x onerror=');
await expect(lines.nth(1)).toContainText('<span class="name" onclick=');
@@ -1,4 +1,7 @@
import { expect, test, type Page, type Route } from '@playwright/test';
import { writeFile } from 'node:fs/promises';
import type { trpc } from '../src/utils/trpc.js';
import { gameProfile, gameTrpcRoute } from './gameTestPaths.js';
import { expectLumenButtonStates } from './lumenButton.js';
@@ -306,7 +309,11 @@ const personnelFixture = (state: FixtureState) => {
};
};
const install = async (page: Page, state: FixtureState): Promise<void> => {
const install = async (
page: Page,
state: FixtureState,
overviewCities?: Awaited<ReturnType<typeof trpc.nation.getCityOverview.query>>['cities']
): Promise<void> => {
await page.addInitScript((profile) => {
localStorage.setItem('sammo-game-token', 'ga_city_office');
localStorage.setItem('sammo-game-profile', profile);
@@ -316,7 +323,10 @@ const install = async (page: Page, state: FixtureState): Promise<void> => {
if (operation === 'auth.status') return response({ ok: true });
if (operation === 'lobby.info') return response({ myGeneral: { id: 20, name: '순욱' } });
if (operation === 'join.getConfig') return response({});
if (operation === 'nation.getCityOverview') return response(overviewFixture(state));
if (operation === 'nation.getCityOverview') {
const overview = overviewFixture(state);
return response({ ...overview, cities: overviewCities ?? overview.cities });
}
if (operation === 'nation.getSecretGeneralList') {
return state.secretForbidden
? errorResponse(
@@ -491,3 +501,88 @@ test('NPC prefixes stay single in city names and linked secret rows', async ({ p
await page.screenshot({ path: testInfo.outputPath(`npc-city-prefix-${width}.png`), fullPage: true });
}
});
for (const width of [1200, 500]) {
test(`세력도시 기본 정렬은 지역별로 묶고 같은 지역 안에서 규모순으로 표시한다 (${width}px)`, async ({
page,
}, testInfo) => {
const state: FixtureState = { role: 'head', appointed: false, appointmentInputs: [] };
const baseCity = overviewFixture(state).cities[0]!;
// ID·시세·규모순이 지역 우선 정렬과 서로 다르게 되는 입력이다.
const overviewCities = [
{ id: 10, name: '허창', region: 2, level: 8, trade: 60 },
{ id: 20, name: '상당', region: 1, level: 5, trade: 130 },
{ id: 30, name: '진류', region: 2, level: 5, trade: 110 },
{ id: 40, name: '업', region: 1, level: 8, trade: 80 },
{ id: 50, name: '북평', region: 1, level: 8, trade: 90 },
].map((city) => ({ ...baseCity, ...city }));
await install(page, state, overviewCities);
await page.setViewportSize({ width, height: 900 });
await page.goto('nation/cities');
const tables = page.locator('.city');
await expect(tables).toHaveCount(5);
await page.evaluate(() => document.fonts.ready);
const cityOrder = () => tables.evaluateAll((elements) => elements.map((el) => Number(el.dataset.cityId)));
const regionStarts = () =>
page
.locator('.city.region-break')
.evaluateAll((elements) => elements.map((el) => Number(el.dataset.cityId)));
const expectedOrder = [40, 50, 20, 10, 30];
const select = page.locator('#nation-city-sort');
const submit = page.getByRole('button', { name: '정렬하기' });
await page.screenshot({ path: testInfo.outputPath('default-region-order.png'), fullPage: true });
await writeFile(
testInfo.outputPath('default-region-order.html'),
await page.locator('main').evaluate((el) => el.outerHTML)
);
const geometry = await tables.evaluateAll((elements) =>
elements.map((el) => {
const rect = el.getBoundingClientRect();
const style = getComputedStyle(el);
return {
id: Number(el.dataset.cityId),
title: el.querySelector('.city-title')?.textContent?.trim(),
x: rect.x,
y: rect.y,
width: rect.width,
height: rect.height,
marginTop: style.marginTop,
fontSize: style.fontSize,
borderCollapse: style.borderCollapse,
};
})
);
await writeFile(
testInfo.outputPath('default-region-order.json'),
JSON.stringify({ url: page.url(), width, geometry }, null, 2)
);
await expect(select).toHaveValue('1');
expect(await cityOrder()).toEqual(expectedOrder);
expect(await regionStarts()).toEqual([40, 10]);
expect(geometry.map((city) => city.marginTop)).toEqual(['18px', '0px', '0px', '18px', '0px']);
await expect(tables.locator('.city-title')).toContainText(['하북', '하북', '하북', '중원', '중원']);
// 선택만으로는 적용하지 않고 submit 뒤에만 기존 명시적 정렬을 적용한다.
await select.selectOption('12');
expect(await cityOrder()).toEqual(expectedOrder);
await submit.click();
expect(await cityOrder()).toEqual([40, 50, 10, 20, 30]);
expect(await regionStarts()).toEqual([]);
await page.getByRole('button', { name: '시세 기준 정렬' }).first().click();
await expect(select).toHaveValue('10');
expect(await cityOrder()).toEqual([20, 30, 50, 40, 10]);
expect(await regionStarts()).toEqual([]);
for (const sort of ['11', '1']) {
await select.selectOption(sort);
await submit.click();
expect(await cityOrder()).toEqual(expectedOrder);
expect(await regionStarts()).toEqual([40, 10]);
}
await page.reload();
await expect(select).toHaveValue('1');
await expect(tables).toHaveCount(5);
expect(await cityOrder()).toEqual(expectedOrder);
expect(state.appointmentInputs).toEqual([]);
});
}
+64 -1
View File
@@ -461,12 +461,29 @@ test('personnel selects an informed general and reports the JosaUtil-composed re
/허저/,
/장료/,
]);
await picker.getByPlaceholder('장수명·도시·관직·특성 검색').fill('장료');
const search = picker.getByPlaceholder('장수명·도시·관직·특성 검색');
const vacancy = picker.getByRole('button', { name: /공석으로 두기/ });
await expect(vacancy).toBeVisible();
await search.fill(' ');
await expect(vacancy).toBeVisible();
await search.fill('허창');
await expect(vacancy).toHaveCount(0);
expect(await picker.locator('.personnel-picker-card').count()).toBeGreaterThan(1);
await search.fill('없는장수');
await expect(vacancy).toHaveCount(0);
await expect(picker.getByText('검색 조건에 맞는 후보가 없습니다.')).toBeVisible();
await search.clear();
await expect(vacancy).toBeVisible();
await search.fill('장료');
await expect(vacancy).toHaveCount(0);
const candidate = picker.getByRole('button', { name: /장료/ });
await expect(candidate).toContainText('허창 · 일반 장수');
await expect(candidate).toContainText('통솔70');
await expect(candidate).toContainText('소속10년');
await expect(candidate).toContainText('병력100');
await search.press('Tab');
await expect(candidate).toBeFocused();
expect(state.appointedGeneralId).toBeUndefined();
await candidate.hover();
expect(await candidate.evaluate((button) => getComputedStyle(button).cursor)).toBe('pointer');
await candidate.focus();
@@ -590,6 +607,52 @@ test('personnel reflows row-level appointments at 500px and 390px without gradie
await screenshot(page, 'core-personnel-mobile-rows.png');
});
test('personnel hides vacancy during mobile search and keeps intentional vacancy available after clearing', async ({
page,
}, testInfo) => {
const state: FixtureState = { role: 'head', rate: 20 };
await installFixture(page, state);
await page.setViewportSize({ width: 390, height: 844 });
await gotoOffice(page, 'nation/personnel');
const change = page.getByRole('button', { name: '허창 태수 변경하기', exact: true });
await change.click();
const picker = page.getByTestId('personnel-selection-dialog');
const search = picker.getByRole('searchbox');
const vacancy = picker.getByRole('button', { name: /공석으로 두기/ });
await expect(search).toBeFocused();
await expect(vacancy).toBeVisible();
await search.fill('장료');
await expect(picker.getByRole('button', { name: /장료/ })).toBeVisible();
await expect(vacancy).toHaveCount(0);
await expect(picker).toHaveCSS('transform', 'none');
await page.evaluate(() => document.fonts.ready);
const geometry = await picker.evaluate((element) => ({
url: location.href,
rect: element.getBoundingClientRect().toJSON(),
overflow: element.scrollWidth - element.clientWidth,
candidateFont: getComputedStyle(element.querySelector('.personnel-picker-card')!).font,
}));
expect(geometry.overflow).toBeLessThanOrEqual(0);
await writeFile(testInfo.outputPath('personnel-search-mobile.json'), JSON.stringify(geometry, null, 2));
await writeFile(testInfo.outputPath('personnel-search-mobile.html'), await picker.evaluate((el) => el.outerHTML));
await screenshot(page, 'personnel-search-mobile.png');
await search.press('Escape');
await expect(picker).toBeHidden();
await expect(change).toBeFocused();
expect(state.appointedGeneralId).toBeUndefined();
await change.click();
await search.fill('장료');
await expect(vacancy).toHaveCount(0);
await search.clear();
await vacancy.click();
await acceptAppConfirmation(page, '허창 태수직을 비우시겠습니까?');
await expect(page.getByTestId('game-toast')).toContainText('관직을 비웠습니다.');
expect(state.appointedGeneralId).toBe(0);
expect(state.appointedCityId).toBe(1);
expect(state.appointedOfficerLevel).toBe(4);
});
test('personnel chooses a kick target in the informed picker and double-confirms a user general', async ({ page }) => {
const state: FixtureState = { role: 'head', rate: 20 };
await installFixture(page, state);
@@ -86,6 +86,7 @@ export type CommandAvailability = {
name: string;
turnDurationText?: string;
costText?: string;
statExperienceText?: string;
reqArg: boolean;
status: 'available' | 'blocked' | 'needsInput' | 'unknown';
possible: boolean;
@@ -1,9 +1,14 @@
<script setup lang="ts">
defineProps<{
import { computed } from 'vue';
import { splitLegacyLineBreaks } from '../../utils/legacyDescription';
const props = defineProps<{
title: string;
description?: string | null;
testId?: string;
}>();
const descriptionLines = computed(() => splitLegacyLineBreaks(props.description ?? ''));
</script>
<template>
@@ -16,7 +21,10 @@ defineProps<{
<slot />
<span v-if="description" class="directory-tooltip__content" role="tooltip">
<strong>{{ title }}</strong>
<span>{{ description }}</span>
<span class="directory-tooltip__description"
><template v-for="(line, index) in descriptionLines" :key="index"
>{{ line }}<br v-if="index < descriptionLines.length - 1" /></template
></span>
</span>
</span>
</template>
@@ -1,30 +1,10 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import type { CommandAvailability, CommandGroup, CommandTable } from '../command/types';
import SkeletonLines from '../ui/SkeletonLines.vue';
type CommandAvailability = {
key: string;
name: string;
turnDurationText?: string;
costText?: string;
reqArg: boolean;
status: 'available' | 'blocked' | 'needsInput' | 'unknown';
possible: boolean;
reason?: string;
};
type CommandGroup = {
category: string;
values: CommandAvailability[];
};
type CommandTable = {
general: CommandGroup[];
nation: CommandGroup[];
};
const props = defineProps<{
commandTable: CommandTable | null;
commandTable: Pick<CommandTable, 'general' | 'nation'> | null;
loading: boolean;
activeCategory?: string;
scope?: 'all' | 'general' | 'nation';
@@ -162,7 +142,12 @@ const commandTitle = (command: CommandAvailability) =>
:title="commandTitle(command)"
@click="emit('select', command.key)"
>
<span class="command-heading">
<span class="command-name">{{ command.name }}</span>
<small v-if="command.statExperienceText" class="command-stat-experience">
({{ command.statExperienceText }})
</small>
</span>
<small v-if="command.turnDurationText" class="command-duration">
/{{ command.turnDurationText }}
</small>
@@ -249,6 +234,13 @@ const commandTitle = (command: CommandAvailability) =>
font-weight: 600;
}
.command-stat-experience {
display: inline-block;
margin-inline-start: 0.3em;
font-size: var(--sammo-font-size-smaller);
white-space: nowrap;
}
.command-duration {
display: block;
font-size: var(--sammo-font-size-small);
@@ -142,7 +142,7 @@ onBeforeUnmount(() => {
<div class="personnel-picker-results" aria-label="선택 후보">
<button
v-if="vacancyLabel"
v-if="vacancyLabel && !normalizedQuery"
type="button"
class="personnel-picker-card vacancy-card"
:class="{ selected: selectedId === 0 }"
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, useSlots, watch } from 'vue';
import { splitLegacyLineBreaks } from '../../utils/legacyDescription';
import tippy, { type Instance, type Placement } from 'tippy.js';
import 'tippy.js/dist/tippy.css';
@@ -28,7 +29,7 @@ let instance: Instance | null = null;
const descriptionLines = computed(() => {
const source = Array.isArray(props.description) ? props.description : [props.description ?? ''];
return source
.flatMap((line) => line.split(/<br\s*\/?\s*>|\r?\n/giu))
.flatMap(splitLegacyLineBreaks)
.map((line) => line.trim())
.filter(Boolean);
});
@@ -0,0 +1,5 @@
/**
* 카탈로그 설명의 Ref 줄바꿈만 해석한다. 반환값은 반드시 text interpolation으로
* 렌더링하며 HTML로 삽입하지 않는다. 빈 줄과 공백의 표시 정책은 소비자가 정한다.
*/
export const splitLegacyLineBreaks = (value: string): string[] => value.split(/<br\s*\/?\s*>|\r\n?|\n/giu);
+1 -1
View File
@@ -4,6 +4,7 @@ import { usePageExit } from '../composables/usePageExit';
import { formatServerDateTime } from '@sammo-ts/common/time/ServerDateTime';
import { JosaUtil } from '@sammo-ts/common/util/JosaUtil';
import { computed, onMounted, reactive, ref } from 'vue';
import { splitLegacyLineBreaks } from '../utils/legacyDescription';
import { trpc } from '../utils/trpc';
import { useGameFeedback } from '../composables/useGameFeedback';
@@ -207,7 +208,6 @@ const specialNameMap = computed(() => {
}
return map;
});
const splitLegacyLineBreaks = (value: string): string[] => value.split(/<br\s*\/?\s*>|\r?\n/giu);
const selectedSpecialWarInfo = computed(
() => status.value?.availableSpecialWar.find((entry) => entry.key === nextSpecialKey.value)?.info ?? ''
);
@@ -34,8 +34,8 @@ const integrationError = ref('');
const secretLoading = ref(false);
const personnelLoading = ref(false);
const pendingAppointment = ref('');
const sort = ref<Sort>(10);
const selectedSort = ref<Sort>(10);
const sort = ref<Sort>(1);
const selectedSort = ref<Sort>(1);
const extraSort = ref<
| 'name'
| 'populationRate'
@@ -95,7 +95,7 @@ const cities = computed(() => {
}
return values.sort((a, b) => {
const key = sort.value;
if (key === 1) return a.id - b.id;
if (key === 1 || key === 11) return a.region - b.region || b.level - a.level;
if (key === 2) return b.population - a.population;
if (key === 3) return b.population / b.populationMax - a.population / a.populationMax;
if (key === 4) return b.trust - a.trust;
@@ -105,7 +105,6 @@ const cities = computed(() => {
if (key === 8) return b.defence - a.defence;
if (key === 9) return b.wall - a.wall;
if (key === 10) return (b.trade ?? -1) - (a.trade ?? -1);
if (key === 11) return a.region - b.region || b.level - a.level;
return b.level - a.level || a.region - b.region;
});
});
@@ -148,7 +147,9 @@ const developmentClass = (
return ratio > 0.8 ? 'development-high' : ratio > 0.4 ? 'development-mid' : 'development-low';
};
const isRegionBreak = (city: City, index: number) =>
sort.value === 10 && extraSort.value === null && (index === 0 || cities.value[index - 1]?.region !== city.region);
(sort.value === 1 || sort.value === 11) &&
extraSort.value === null &&
(index === 0 || cities.value[index - 1]?.region !== city.region);
const officer = (city: City, level: 2 | 3 | 4) => city.officers[level]?.name ?? '-';
const officerIsStationed = (city: City, level: OfficerLevel): boolean =>
secretData.value !== null && city.officers[level]?.cityId === city.id;
@@ -978,10 +978,21 @@ onBeforeUnmount(() => {
<template v-else-if="column.id === 'belong'">{{ general.belong }}년</template>
<template v-else-if="column.id === 'age'">{{ general.age }}세</template>
<template v-else-if="column.id === 'name'">
<span data-general-name :style="{ color: getNpcColor(general.npcState) }">{{
<RouterLink
v-if="data && data.viewer.permission >= 1"
class="general-name-link"
:to="{ name: 'battle-center', query: { generalId: general.id } }"
:style="{ color: getNpcColor(general.npcState) }"
target="_blank"
rel="noopener"
title="감찰부에서 보기 (새 탭)"
data-general-name
>{{ general.name }}</RouterLink
>
<span v-else data-general-name :style="{ color: getNpcColor(general.npcState) }">{{
general.name
}}</span
><template v-if="general.ownerName"
}}</span>
<template v-if="general.ownerName"
><br /><small>({{ general.ownerName }})</small></template
>
</template>
@@ -1370,6 +1381,14 @@ td {
color: skyblue;
text-align: left;
}
.general-name-link {
color: inherit;
text-decoration: underline;
}
.general-name-link:focus-visible {
outline: 1px solid currentColor;
outline-offset: 2px;
}
.numeric-cell {
text-align: right;
}
@@ -0,0 +1,28 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { splitLegacyLineBreaks } from '../src/utils/legacyDescription.ts';
void describe('legacy catalog description line breaks', () => {
void it('accepts catalog br variants and platform newlines', () => {
assert.deepEqual(splitLegacyLineBreaks('가<br>나<BR/>다<br />라\r\n마\n바\r사'), [
'가',
'나',
'다',
'라',
'마',
'바',
'사',
]);
});
void it('preserves empty lines, whitespace, and unformatted descriptions', () => {
assert.deepEqual(splitLegacyLineBreaks(''), ['']);
assert.deepEqual(splitLegacyLineBreaks(' 일반 설명 '), [' 일반 설명 ']);
assert.deepEqual(splitLegacyLineBreaks('<br>첫 줄<br><br>끝 줄\n'), ['', '첫 줄', '', '끝 줄', '']);
});
void it('leaves other markup, attributes, and entities as literal text', () => {
const text = '<img src=x onerror="alert(1)"><b>문구</b>&lt;br&gt;<br onclick="alert(1)">';
assert.deepEqual(splitLegacyLineBreaks(text), [text]);
});
});
Loaded 100 of 177 files, more files were not shown because too many files have changed in this diff. Show more