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