feat: implement game API with TRPC and Redis transport
- Added GameApiConfig interface and configuration resolver from environment variables. - Created GameApiContext for managing database and transport dependencies. - Implemented InMemoryTurnDaemonTransport for testing purposes. - Developed RedisTurnDaemonTransport for command and status handling via Redis streams. - Defined TurnDaemonStreamKeys for namespacing Redis streams by profile. - Established TRPC router with endpoints for health check, world state retrieval, and turn daemon commands (run, pause, resume, status). - Integrated Fastify server with TRPC and Redis transport. - Added unit tests for router functionality and stream key generation. - Configured Vitest for testing environment.
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
import type {
|
||||
TurnDaemonCommand,
|
||||
TurnDaemonCommandEnvelope,
|
||||
TurnDaemonStatus,
|
||||
} from './types.js';
|
||||
import type { TurnDaemonTransport } from './transport.js';
|
||||
|
||||
const buildDefaultStatus = (): TurnDaemonStatus => ({
|
||||
state: 'idle',
|
||||
running: false,
|
||||
paused: false,
|
||||
queueDepth: 0,
|
||||
});
|
||||
|
||||
// 턴 데몬 통신을 메모리 큐로 흉내 내는 테스트용 전송기.
|
||||
export class InMemoryTurnDaemonTransport implements TurnDaemonTransport {
|
||||
public readonly commands: TurnDaemonCommandEnvelope[] = [];
|
||||
private status: TurnDaemonStatus;
|
||||
|
||||
constructor(initialStatus: TurnDaemonStatus = buildDefaultStatus()) {
|
||||
this.status = initialStatus;
|
||||
}
|
||||
|
||||
// 테스트용: 메모리 큐에 명령을 저장하고 requestId를 반환한다.
|
||||
async sendCommand(command: TurnDaemonCommand): Promise<string> {
|
||||
const requestId = command.type === 'getStatus' ? command.requestId : randomUUID();
|
||||
this.commands.push({
|
||||
requestId,
|
||||
sentAt: new Date().toISOString(),
|
||||
command,
|
||||
});
|
||||
return requestId;
|
||||
}
|
||||
|
||||
async requestStatus(): Promise<TurnDaemonStatus> {
|
||||
return this.status;
|
||||
}
|
||||
|
||||
setStatus(status: TurnDaemonStatus): void {
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
import type { RedisClientType } from 'redis';
|
||||
|
||||
import type { TurnDaemonStreamKeys } from './streamKeys.js';
|
||||
import type { TurnDaemonTransport } from './transport.js';
|
||||
import type {
|
||||
TurnDaemonCommand,
|
||||
TurnDaemonCommandEnvelope,
|
||||
TurnDaemonEventEnvelope,
|
||||
TurnDaemonStatus,
|
||||
} from './types.js';
|
||||
|
||||
interface RedisTurnDaemonTransportOptions {
|
||||
keys: TurnDaemonStreamKeys;
|
||||
requestTimeoutMs: number;
|
||||
}
|
||||
|
||||
type RedisStreamReadResponse = Array<{
|
||||
name: string;
|
||||
messages: Array<{ id: string; message: Record<string, string> }>;
|
||||
}>;
|
||||
|
||||
const buildCommandEnvelope = (command: TurnDaemonCommand): TurnDaemonCommandEnvelope => {
|
||||
const requestId = command.type === 'getStatus' ? command.requestId : randomUUID();
|
||||
return {
|
||||
requestId,
|
||||
sentAt: new Date().toISOString(),
|
||||
command,
|
||||
};
|
||||
};
|
||||
|
||||
const parseEventEnvelope = (raw: string): TurnDaemonEventEnvelope | null => {
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as Partial<TurnDaemonEventEnvelope>;
|
||||
if (!parsed || typeof parsed !== 'object') {
|
||||
return null;
|
||||
}
|
||||
if (!parsed.event || typeof parsed.event !== 'object') {
|
||||
return null;
|
||||
}
|
||||
if (typeof parsed.sentAt !== 'string') {
|
||||
return null;
|
||||
}
|
||||
return parsed as TurnDaemonEventEnvelope;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
// 턴 데몬 제어 스트림을 Redis로 구현한 전송기.
|
||||
export class RedisTurnDaemonTransport implements TurnDaemonTransport {
|
||||
private readonly client: RedisClientType;
|
||||
private readonly keys: TurnDaemonStreamKeys;
|
||||
private readonly requestTimeoutMs: number;
|
||||
|
||||
constructor(client: RedisClientType, options: RedisTurnDaemonTransportOptions) {
|
||||
this.client = client;
|
||||
this.keys = options.keys;
|
||||
this.requestTimeoutMs = options.requestTimeoutMs;
|
||||
}
|
||||
|
||||
// Redis 스트림에 명령을 기록해서 턴 데몬에게 전달한다.
|
||||
async sendCommand(command: TurnDaemonCommand): Promise<string> {
|
||||
const envelope = buildCommandEnvelope(command);
|
||||
await this.client.xAdd(this.keys.commandStream, '*', {
|
||||
payload: JSON.stringify(envelope),
|
||||
});
|
||||
return envelope.requestId;
|
||||
}
|
||||
|
||||
async requestStatus(timeoutMs?: number): Promise<TurnDaemonStatus | null> {
|
||||
const requestId = randomUUID();
|
||||
await this.sendCommand({ type: 'getStatus', requestId });
|
||||
|
||||
const deadline = Date.now() + (timeoutMs ?? this.requestTimeoutMs);
|
||||
let lastId = '$';
|
||||
|
||||
while (Date.now() < deadline) {
|
||||
const remaining = Math.max(1, deadline - Date.now());
|
||||
const response = (await this.client.xRead(
|
||||
{ key: this.keys.eventStream, id: lastId },
|
||||
{ BLOCK: remaining, COUNT: 10 }
|
||||
)) as RedisStreamReadResponse | null;
|
||||
|
||||
if (!response) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const stream of response) {
|
||||
for (const message of stream.messages) {
|
||||
lastId = message.id;
|
||||
const payload = message.message.payload;
|
||||
if (!payload) {
|
||||
continue;
|
||||
}
|
||||
const envelope = parseEventEnvelope(payload);
|
||||
if (!envelope) {
|
||||
continue;
|
||||
}
|
||||
if (envelope.event.type === 'status' && envelope.requestId === requestId) {
|
||||
return envelope.event.status;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
export interface TurnDaemonStreamKeys {
|
||||
commandStream: string;
|
||||
eventStream: string;
|
||||
}
|
||||
|
||||
export const buildTurnDaemonStreamKeys = (profileName: string): TurnDaemonStreamKeys => {
|
||||
return {
|
||||
commandStream: `sammo:${profileName}:turn-daemon:commands`,
|
||||
eventStream: `sammo:${profileName}:turn-daemon:events`,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { TurnDaemonCommand, TurnDaemonStatus } from './types.js';
|
||||
|
||||
export interface TurnDaemonTransport {
|
||||
sendCommand(command: TurnDaemonCommand): Promise<string>;
|
||||
requestStatus(timeoutMs?: number): Promise<TurnDaemonStatus | null>;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
export type TurnDaemonState = 'idle' | 'running' | 'flushing' | 'paused' | 'stopping';
|
||||
|
||||
export type RunReason = 'schedule' | 'manual' | 'poke';
|
||||
|
||||
export interface TurnRunBudget {
|
||||
budgetMs: number;
|
||||
maxGenerals: number;
|
||||
catchUpCap: number;
|
||||
}
|
||||
|
||||
export interface TurnCheckpoint {
|
||||
turnTime: string;
|
||||
generalId?: number;
|
||||
year: number;
|
||||
month: number;
|
||||
}
|
||||
|
||||
export interface TurnRunResult {
|
||||
lastTurnTime: string;
|
||||
processedGenerals: number;
|
||||
processedTurns: number;
|
||||
durationMs: number;
|
||||
partial: boolean;
|
||||
checkpoint?: TurnCheckpoint;
|
||||
}
|
||||
|
||||
export interface TurnDaemonStatus {
|
||||
state: TurnDaemonState;
|
||||
running: boolean;
|
||||
paused: boolean;
|
||||
lastRunAt?: string;
|
||||
lastDurationMs?: number;
|
||||
lastTurnTime?: string;
|
||||
nextTurnTime?: string;
|
||||
pendingReason?: RunReason;
|
||||
queueDepth: number;
|
||||
checkpoint?: TurnCheckpoint;
|
||||
}
|
||||
|
||||
// 턴 데몬 제어 요청은 Redis 스트림으로 전달한다.
|
||||
export type TurnDaemonCommand =
|
||||
| { type: 'run'; reason: RunReason; targetTime?: string; budget?: TurnRunBudget }
|
||||
| { type: 'pause'; reason?: string }
|
||||
| { type: 'resume'; reason?: string }
|
||||
| { type: 'getStatus'; requestId: string };
|
||||
|
||||
// 턴 데몬 이벤트는 상태/실행 결과를 API 서버에 알려준다.
|
||||
export type TurnDaemonEvent =
|
||||
| { type: 'status'; requestId?: string; status: TurnDaemonStatus }
|
||||
| { type: 'runStarted'; at: string; reason: RunReason }
|
||||
| { type: 'runCompleted'; at: string; result: TurnRunResult }
|
||||
| { type: 'runFailed'; at: string; error: string };
|
||||
|
||||
export interface TurnDaemonCommandEnvelope {
|
||||
requestId: string;
|
||||
sentAt: string;
|
||||
command: TurnDaemonCommand;
|
||||
}
|
||||
|
||||
export interface TurnDaemonEventEnvelope {
|
||||
requestId?: string;
|
||||
sentAt: string;
|
||||
event: TurnDaemonEvent;
|
||||
}
|
||||
Reference in New Issue
Block a user