feat(admin): apply durable runtime clock shifts

This commit is contained in:
2026-07-30 17:21:01 +00:00
parent d6904f2c9d
commit 7f31459385
23 changed files with 1889 additions and 93 deletions
@@ -0,0 +1,97 @@
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { createGatewayPostgresConnector, type GatewayPrismaClient } from '@sammo-ts/infra';
import { createGatewayAdminActionConsumer } from '../src/turn/gatewayAdminActions.js';
const databaseUrl = process.env.GATEWAY_RUNTIME_ACTION_DATABASE_URL;
const integration = describe.skipIf(!databaseUrl);
const profileName = 'runtime:consumer-integration';
const actionId = '924f40ec-e9d2-432f-9867-e9fb3199f14a';
const waitForApplied = async (db: GatewayPrismaClient): Promise<void> => {
const deadline = Date.now() + 4_000;
while (Date.now() < deadline) {
const action = await db.gatewayRuntimeAction.findUnique({
where: { id: actionId },
select: { status: true },
});
if (action?.status === 'APPLIED') {
return;
}
await new Promise((resolve) => setTimeout(resolve, 25));
}
throw new Error('gateway runtime action did not reach APPLIED');
};
integration('gateway runtime action consumer', () => {
let db: GatewayPrismaClient;
let closeDb: (() => Promise<void>) | undefined;
beforeAll(async () => {
const connector = createGatewayPostgresConnector({ url: databaseUrl! });
await connector.connect();
db = connector.prisma;
closeDb = () => connector.disconnect();
await db.gatewayProfile.upsert({
where: { profileName },
update: { status: 'RUNNING' },
create: {
profileName,
profile: 'runtime',
scenario: 'consumer-integration',
apiPort: 15998,
status: 'RUNNING',
},
});
await db.gatewayRuntimeAction.deleteMany({ where: { profileName } });
});
afterAll(async () => {
await db.gatewayRuntimeAction.deleteMany({ where: { profileName } });
await db.gatewayProfile.deleteMany({ where: { profileName } });
await closeDb?.();
});
it('backs off a partial projection and publishes one terminal callback', async () => {
await db.gatewayRuntimeAction.create({
data: {
id: actionId,
profileName,
action: 'ACCELERATE',
durationMinutes: 15,
requestedBy: 'integration-admin',
},
});
const handler = vi
.fn()
.mockResolvedValueOnce({ status: 'PARTIAL', detail: 'redis unavailable' })
.mockResolvedValue({ status: 'APPLIED', detail: 'projection complete' });
const onActionApplied = vi.fn(async () => {});
const consumer = await createGatewayAdminActionConsumer({
databaseUrl: databaseUrl!,
gatewayDatabaseUrl: databaseUrl!,
profileName,
pollIntervalMs: 10,
handler,
onActionApplied,
});
consumer.start();
try {
await waitForApplied(db);
} finally {
await consumer.stop();
}
expect(await db.gatewayRuntimeAction.findUniqueOrThrow({ where: { id: actionId } })).toMatchObject({
status: 'APPLIED',
attempts: 2,
nextAttemptAt: null,
detail: 'projection complete',
handler: 'turn-daemon',
});
expect(handler).toHaveBeenCalledTimes(2);
expect(onActionApplied).toHaveBeenCalledTimes(1);
});
});
@@ -305,8 +305,8 @@ describe('input event atomicity', () => {
lastError: 'injected commit failure',
});
expect(publishCommandResult).not.toHaveBeenCalled();
expect(engineState).toEqual({ value: 'calculated' });
expect(stateManager.getRevision()).toBe(1);
expect(engineState).toEqual({ value: 'before' });
expect(stateManager.getRevision()).toBe(0);
await lifecycle.stop('done');
await loop;
@@ -0,0 +1,254 @@
import { describe, expect, it, vi } from 'vitest';
import type { GamePrismaClient } from '@sammo-ts/infra';
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
import { applyRuntimeClockShift } from '../src/turn/runtimeClockShift.js';
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
const buildGeneral = (id: number, turnTime: string): TurnGeneral =>
({
id,
name: `General_${id}`,
nationId: 1,
cityId: 1,
troopId: 0,
stats: { leadership: 50, strength: 50, intelligence: 50 },
turnTime: new Date(turnTime),
role: {
items: { horse: null, weapon: null, book: null, item: null },
personality: null,
specialDomestic: null,
specialWar: null,
},
triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} },
meta: { killturn: 24 },
officerLevel: 5,
experience: 0,
dedication: 0,
injury: 0,
gold: 1000,
rice: 1000,
crew: 0,
crewTypeId: 0,
train: 0,
atmos: 0,
age: 30,
npcState: 0,
}) as TurnGeneral;
const buildWorld = (): InMemoryTurnWorld => {
const state: TurnWorldState = {
id: 1,
currentYear: 190,
currentMonth: 1,
tickSeconds: 600,
lastTurnTime: new Date('2026-07-30T10:00:00.000Z'),
meta: {
lastTurnTime: '2026-07-30T10:00:00.000Z',
turntime: '2026-07-30 10:00:00.123456',
starttime: '2026-07-01 00:00:00',
tnmt_time: '2026-07-30 11:30:00',
untouched: 'keep',
},
};
const snapshot: TurnWorldSnapshot = {
generals: [buildGeneral(1, '2026-07-30T10:10:00.000Z'), buildGeneral(2, '2026-07-30T10:20:00.000Z')],
cities: [],
nations: [],
troops: [],
diplomacy: [],
events: [],
initialEvents: [],
map: {
id: 'test',
name: 'test',
cities: [],
defaults: { trust: 50, trade: 100, supplyState: 1, frontState: 0 },
},
scenarioConfig: {
stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 50, npcMin: 10, chiefMin: 70 },
iconPath: '',
map: {},
const: {},
environment: { mapName: 'test', unitSet: 'default' },
},
};
return new InMemoryTurnWorld(state, snapshot, {
schedule: { entries: [{ startMinute: 0, tickMinutes: 10 }] },
});
};
describe('runtime clock shift', () => {
it.each([
['accelerates', -15, '2026-07-30T09:45:00.000Z', '2026-07-30T09:55:00.000Z'],
['delays', 15, '2026-07-30T10:15:00.000Z', '2026-07-30T10:25:00.000Z'],
] as const)('%s the world, every general, checkpoint, and pending auction together', (_, delta, last, general) => {
const world = buildWorld();
world.setCheckpoint({ turnTime: '2026-07-30T10:10:00.000Z', generalId: 1, year: 190, month: 1 });
world.queueNeutralAuction({
registrationKey: 'test',
type: 'BUY_RICE',
targetCode: 'rice',
hostGeneralId: 0,
hostName: '상인',
detail: {},
closeAt: new Date('2026-07-30T12:00:00.000Z'),
});
const result = world.shiftSchedule(delta);
expect(result).toEqual({ shiftedGenerals: 2, lastTurnTime: last });
expect(world.getState()).toMatchObject({
currentYear: 190,
currentMonth: 1,
lastTurnTime: new Date(last),
meta: {
lastTurnTime: last,
untouched: 'keep',
},
});
expect(world.getGeneralById(1)?.turnTime.toISOString()).toBe(general);
expect(world.getCheckpoint()?.turnTime).toBe(general);
const pendingCloseAt = world.peekDirtyState().pendingNeutralAuctions[0]?.closeAt;
expect(pendingCloseAt?.toISOString()).toBe(
new Date(new Date('2026-07-30T12:00:00.000Z').getTime() + delta * 60_000).toISOString()
);
expect(world.peekDirtyState().generals.map((entry) => entry.id)).toEqual([1, 2]);
});
it.each([0, 1.5, Number.NaN])('rejects an invalid shift without mutation: %s', (delta) => {
const world = buildWorld();
expect(() => world.shiftSchedule(delta)).toThrow();
expect(world.getState().lastTurnTime.toISOString()).toBe('2026-07-30T10:00:00.000Z');
expect(world.peekDirtyState().generals).toEqual([]);
});
it('keeps legacy wall-clock metadata independent from the process timezone', () => {
const world = buildWorld();
world.shiftSchedule(-15);
expect(world.getState().meta).toMatchObject({
turntime: '2026-07-30 09:45:00.123456',
starttime: '2026-06-30 23:45:00',
tnmt_time: '2026-07-30 11:15:00',
});
});
});
describe('runtime clock shift projection', () => {
it('waits for the durable engine event and applies Redis projections idempotently', async () => {
const actionId = '68f1f0e4-3b95-4aeb-9925-c7e93caf1ba7';
let eventStatus: 'PENDING' | 'SUCCEEDED' = 'PENDING';
let created = false;
const inputEventCreate = vi.fn(async () => {
if (created) {
throw { code: 'P2002' };
}
created = true;
return {};
});
const db = {
inputEvent: {
create: inputEventCreate,
findUniqueOrThrow: vi.fn(async () =>
eventStatus === 'PENDING'
? {
eventType: 'shiftSchedule',
payload: {
type: 'shiftSchedule',
actionId,
deltaMinutes: -15,
},
status: 'PENDING',
result: null,
error: null,
}
: {
eventType: 'shiftSchedule',
payload: {
type: 'shiftSchedule',
actionId,
deltaMinutes: -15,
},
status: 'SUCCEEDED',
result: {
type: 'shiftSchedule',
ok: true,
actionId,
deltaMinutes: -15,
lastTurnTime: '2026-07-30T09:45:00.000Z',
shiftedGenerals: 2,
shiftedAuctions: 1,
},
error: null,
}
),
},
auction: {
findMany: vi.fn(async () => [{ id: 7, closeAt: new Date('2026-07-30T11:45:00.000Z') }]),
},
} as unknown as GamePrismaClient;
const values = new Map<string, string>([
[
'sammo:hwe:default:tournament:state',
JSON.stringify({
stage: 1,
nextAt: '2026-07-30T12:00:00.000Z',
bettingCloseAt: '2026-07-30T11:30:00.000Z',
}),
],
]);
const zAdd = vi.fn(async () => 1);
const redis = {
get: async (key: string) => values.get(key) ?? null,
set: async (
key: string,
value: string,
options?: {
NX?: boolean;
PX?: number;
}
) => {
if (options?.NX && values.has(key)) {
return null;
}
values.set(key, value);
return 'OK';
},
del: async (key: string) => (values.delete(key) ? 1 : 0),
zAdd,
};
const action = {
id: actionId,
profileName: 'hwe:default',
action: 'ACCELERATE',
durationMinutes: 15,
};
await expect(applyRuntimeClockShift({ action, profileName: 'hwe:default', db, redis })).resolves.toMatchObject({
status: 'REQUESTED',
});
expect(zAdd).not.toHaveBeenCalled();
eventStatus = 'SUCCEEDED';
await expect(applyRuntimeClockShift({ action, profileName: 'hwe:default', db, redis })).resolves.toMatchObject({
status: 'APPLIED',
});
await expect(applyRuntimeClockShift({ action, profileName: 'hwe:default', db, redis })).resolves.toMatchObject({
status: 'APPLIED',
});
const tournament = JSON.parse(values.get('sammo:hwe:default:tournament:state') ?? '{}') as Record<
string,
unknown
>;
expect(tournament).toMatchObject({
nextAt: '2026-07-30T11:45:00.000Z',
bettingCloseAt: '2026-07-30T11:15:00.000Z',
runtimeClockShiftActionIds: [actionId],
});
expect(zAdd).toHaveBeenCalledTimes(2);
expect(inputEventCreate).toHaveBeenCalledTimes(3);
});
});
@@ -0,0 +1,264 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { createGamePostgresConnector, type GamePrisma, type GamePrismaClient } from '@sammo-ts/infra';
import { SystemClock } from '../src/lifecycle/clock.js';
import { DatabaseTurnDaemonCommandQueue } from '../src/lifecycle/databaseCommandQueue.js';
import { getNextTickTime } from '../src/lifecycle/getNextTickTime.js';
import { TurnDaemonLifecycle } from '../src/lifecycle/turnDaemonLifecycle.js';
import { createDatabaseTurnHooks } from '../src/turn/databaseHooks.js';
import { EngineStateManager } from '../src/turn/engineStateManager.js';
import { InMemoryTurnStateStore } from '../src/turn/inMemoryStateStore.js';
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
import { createTurnDaemonCommandHandler } from '../src/turn/worldCommandHandler.js';
const databaseUrl = process.env.INPUT_EVENT_DATABASE_URL;
const integration = describe.skipIf(!databaseUrl);
const requestId = 'integration:engine:runtime-clock-shift';
const actionId = 'b9f68480-dba9-4e03-a62b-499e6234f18a';
const generalIds = [990_301, 990_302] as const;
const buildGeneral = (id: number, turnTime: Date): TurnGeneral =>
({
id,
name: `시간조정${id}`,
nationId: 0,
cityId: 1,
troopId: 0,
stats: { leadership: 50, strength: 50, intelligence: 50 },
turnTime,
role: {
items: { horse: null, weapon: null, book: null, item: null },
personality: null,
specialDomestic: null,
specialWar: null,
},
triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} },
meta: { killturn: 24 },
officerLevel: 0,
experience: 0,
dedication: 0,
injury: 0,
gold: 1000,
rice: 1000,
crew: 0,
crewTypeId: 0,
train: 0,
atmos: 0,
age: 30,
npcState: 0,
}) as TurnGeneral;
const waitForSucceeded = async (db: GamePrismaClient): Promise<void> => {
const deadline = Date.now() + 5_000;
while (Date.now() < deadline) {
const event = await db.inputEvent.findUnique({ where: { requestId }, select: { status: true } });
if (event?.status === 'SUCCEEDED') {
return;
}
await new Promise((resolve) => setTimeout(resolve, 25));
}
throw new Error('runtime clock shift input event did not complete');
};
integration('runtime clock shift persistence', () => {
let db: GamePrismaClient;
let closeDb: (() => Promise<void>) | undefined;
beforeAll(async () => {
const connector = createGamePostgresConnector({ url: databaseUrl! });
await connector.connect();
db = connector.prisma;
closeDb = () => connector.disconnect();
await db.inputEvent.deleteMany({ where: { requestId } });
await db.auction.deleteMany({ where: { hostGeneralId: { in: [...generalIds] } } });
await db.general.deleteMany({ where: { id: { in: [...generalIds] } } });
});
afterAll(async () => {
await db.inputEvent.deleteMany({ where: { requestId } });
await db.auction.deleteMany({ where: { hostGeneralId: { in: [...generalIds] } } });
await db.general.deleteMany({ where: { id: { in: [...generalIds] } } });
await closeDb?.();
});
it('atomically shifts world, generals, and only OPEN auctions through the durable command path', async () => {
const base = new Date('2099-07-30T10:00:00.000Z');
const row = await db.worldState.create({
data: {
scenarioCode: 'runtime-clock-shift',
currentYear: 190,
currentMonth: 1,
tickSeconds: 600,
config: {},
meta: {
lastTurnTime: base.toISOString(),
turntime: '2099-07-30 10:00:00',
starttime: '2099-07-01 00:00:00',
},
},
});
const generals = [
buildGeneral(generalIds[0], new Date('2099-07-30T10:10:00.000Z')),
buildGeneral(generalIds[1], new Date('2099-07-30T10:20:00.000Z')),
];
await db.general.createMany({
data: generals.map((general) => ({
id: general.id,
name: general.name,
nationId: general.nationId,
cityId: general.cityId,
troopId: general.troopId,
turnTime: general.turnTime,
})),
});
const auctionRows = await Promise.all(
(['OPEN', 'FINALIZING', 'FINISHED', 'CANCELED'] as const).map((status, index) =>
db.auction.create({
data: {
type: 'BUY_RICE',
hostGeneralId: generalIds[index % generalIds.length]!,
detail: {},
status,
closeAt: new Date(`2099-07-30T1${index}:00:00.000Z`),
},
})
)
);
const state: TurnWorldState = {
id: row.id,
currentYear: 190,
currentMonth: 1,
tickSeconds: 600,
lastTurnTime: base,
meta: row.meta as Record<string, unknown>,
};
const snapshot: TurnWorldSnapshot = {
scenarioConfig: {
stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 50, npcMin: 10, chiefMin: 70 },
iconPath: '',
map: {},
const: {},
environment: { mapName: 'test', unitSet: 'default' },
},
map: {
id: 'test',
name: 'test',
cities: [],
defaults: { trust: 50, trade: 100, supplyState: 1, frontState: 0 },
},
generals,
cities: [],
nations: [],
troops: [],
diplomacy: [],
events: [],
initialEvents: [],
};
const world = new InMemoryTurnWorld(state, snapshot, {
schedule: { entries: [{ startMinute: 0, tickMinutes: 10 }] },
});
const stateStore = new InMemoryTurnStateStore(world);
await stateStore.saveCheckpoint({
turnTime: '2099-07-30T10:00:00.000Z',
generalId: 0,
year: 190,
month: 1,
});
const hooks = await createDatabaseTurnHooks(databaseUrl!, world);
const queue = new DatabaseTurnDaemonCommandQueue(db);
await queue.initialize();
const stateManager = new EngineStateManager();
stateManager.register('world', {
capture: () => world.captureState(),
restore: (saved) => world.restoreState(saved),
});
const lifecycle = new TurnDaemonLifecycle(
{
clock: new SystemClock(),
controlQueue: queue,
commandResponder: queue,
commandHandler: createTurnDaemonCommandHandler({ world }),
hooks: hooks.hooks,
stateManager,
stateStore,
getNextTickTime: (lastTurnTime) => getNextTickTime(lastTurnTime, 60),
processor: {
run: async () => ({
lastTurnTime: world.getState().lastTurnTime.toISOString(),
processedGenerals: 0,
processedTurns: 0,
durationMs: 0,
partial: false,
}),
},
},
{
profile: 'integration',
defaultBudget: { budgetMs: 1000, maxGenerals: 10, catchUpCap: 1 },
}
);
await db.inputEvent.create({
data: {
requestId,
target: 'ENGINE',
eventType: 'shiftSchedule',
payload: {
type: 'shiftSchedule',
requestId,
actionId,
deltaMinutes: -15,
} as GamePrisma.InputJsonValue,
},
});
const loop = lifecycle.start();
try {
await waitForSucceeded(db);
} finally {
await lifecycle.stop('test complete');
await loop;
await hooks.close();
}
expect(world.getState().lastTurnTime.toISOString()).toBe('2099-07-30T09:45:00.000Z');
expect(world.getGeneralById(generalIds[0])?.turnTime.toISOString()).toBe('2099-07-30T09:55:00.000Z');
expect(await stateStore.loadCheckpoint()).toMatchObject({
turnTime: '2099-07-30T09:45:00.000Z',
generalId: 0,
});
expect(lifecycle.getStatus().nextTurnTime).toBe('2099-07-30T09:55:00.000Z');
expect((await db.worldState.findUniqueOrThrow({ where: { id: row.id } })).meta).toMatchObject({
lastTurnTime: '2099-07-30T09:45:00.000Z',
starttime: '2099-06-30 23:45:00',
});
expect((await db.general.findUniqueOrThrow({ where: { id: generalIds[1] } })).turnTime.toISOString()).toBe(
'2099-07-30T10:05:00.000Z'
);
const storedAuctions = await db.auction.findMany({
where: { id: { in: auctionRows.map((auction) => auction.id) } },
});
const closeAtById = new Map(storedAuctions.map((auction) => [auction.id, auction.closeAt.toISOString()]));
expect(auctionRows.map((auction) => closeAtById.get(auction.id))).toEqual([
'2099-07-30T09:45:00.000Z',
'2099-07-30T11:00:00.000Z',
'2099-07-30T12:00:00.000Z',
'2099-07-30T13:00:00.000Z',
]);
expect(await db.inputEvent.findUniqueOrThrow({ where: { requestId } })).toMatchObject({
status: 'SUCCEEDED',
attempts: 1,
result: {
type: 'shiftSchedule',
ok: true,
actionId,
deltaMinutes: -15,
shiftedGenerals: 2,
shiftedAuctions: 1,
},
});
await db.worldState.delete({ where: { id: row.id } });
});
});