266 lines
8.8 KiB
TypeScript
266 lines
8.8 KiB
TypeScript
import type WebSocket from 'ws';
|
|
|
|
import { getGameState, placeBet } from '../../domain/candle-predict/index';
|
|
import { config } from '../../config';
|
|
import { hasAdminAccess } from '../../utils/roleAccess';
|
|
import { connectRedis, getRedisSubscriber } from '../redis/client';
|
|
import { removeGamePresence, touchAppPresence, touchGamePresence } from '../redis/onlinePresence';
|
|
import { parseRealtimeEvent } from '../redis/pubsub';
|
|
import type { WsAuthContext } from './auth';
|
|
import {
|
|
parseClientMessage,
|
|
serializeServerMessage,
|
|
type WsServerMessage,
|
|
} from './protocol';
|
|
|
|
type ClientState = {
|
|
socket: WebSocket;
|
|
auth: WsAuthContext | null;
|
|
intervals: Set<number>;
|
|
};
|
|
|
|
const USER_CHANNEL_PREFIX = 'prediqo:pubsub:cp:user:';
|
|
|
|
function enrichRoundPayload(
|
|
round: Record<string, unknown>,
|
|
pools?: { short?: number; long?: number },
|
|
includePoolAmounts = false
|
|
): Record<string, unknown> {
|
|
if (!pools) return round;
|
|
const short = Number(pools.short ?? 0);
|
|
const long = Number(pools.long ?? 0);
|
|
const total = short + long;
|
|
if (total <= 0) return round;
|
|
const shortPoolPercent = Math.round((short / total) * 1000) / 10;
|
|
const longPoolPercent = Math.round((long / total) * 1000) / 10;
|
|
return {
|
|
...round,
|
|
shortPoolPercent: round.shortPoolPercent ?? shortPoolPercent,
|
|
longPoolPercent: round.longPoolPercent ?? longPoolPercent,
|
|
...(includePoolAmounts ? { shortPool: short, longPool: long } : {}),
|
|
};
|
|
}
|
|
|
|
export class GameWsHub {
|
|
private clients = new Set<ClientState>();
|
|
/** Live authenticated sockets per user (this WS process). */
|
|
private liveSocketsByUser = new Map<string, Set<ClientState>>();
|
|
|
|
private trackClient(state: ClientState): void {
|
|
const userId = state.auth?.userId;
|
|
if (!userId) return;
|
|
let set = this.liveSocketsByUser.get(userId);
|
|
if (!set) {
|
|
set = new Set();
|
|
this.liveSocketsByUser.set(userId, set);
|
|
}
|
|
set.add(state);
|
|
void touchGamePresence(userId);
|
|
void touchAppPresence(userId);
|
|
}
|
|
|
|
private untrackClient(state: ClientState): void {
|
|
this.clients.delete(state);
|
|
const userId = state.auth?.userId;
|
|
if (!userId) return;
|
|
const set = this.liveSocketsByUser.get(userId);
|
|
if (!set) return;
|
|
set.delete(state);
|
|
if (set.size === 0) {
|
|
this.liveSocketsByUser.delete(userId);
|
|
void removeGamePresence(userId);
|
|
}
|
|
}
|
|
|
|
async start(): Promise<void> {
|
|
if (!config.redis.enabled) {
|
|
console.warn('[ws] Redis disabled — realtime push unavailable');
|
|
return;
|
|
}
|
|
await connectRedis();
|
|
const sub = getRedisSubscriber();
|
|
if (!sub) return;
|
|
|
|
sub.on('pmessage', (_pattern, channel, message) => {
|
|
const event = parseRealtimeEvent(message);
|
|
if (!event) return;
|
|
|
|
if (channel.startsWith(USER_CHANNEL_PREFIX)) {
|
|
const userId = channel.slice(USER_CHANNEL_PREFIX.length);
|
|
for (const client of this.clients) {
|
|
if (client.auth?.userId !== userId) continue;
|
|
if (event.type === 'bet.accepted') {
|
|
const idempotencyKey = String(event.payload.idempotencyKey ?? '').trim();
|
|
this.send(client, {
|
|
type: 'bet.accepted',
|
|
bet: (event.payload.bet as Record<string, unknown>) ?? {},
|
|
...(idempotencyKey ? { idempotencyKey } : {}),
|
|
});
|
|
} else if (event.type === 'bet.rejected') {
|
|
const idempotencyKey = String(event.payload.idempotencyKey ?? '').trim();
|
|
this.send(client, {
|
|
type: 'bet.rejected',
|
|
idempotencyKey,
|
|
error: String(event.payload.error ?? 'Bet rejected'),
|
|
});
|
|
} else if (event.type === 'multi.updated') {
|
|
this.send(client, {
|
|
type: 'multi.updated',
|
|
intervalMinutes: Number(event.payload.intervalMinutes ?? 0),
|
|
userMultiBet:
|
|
(event.payload.userMultiBet as Record<string, unknown> | null | undefined) ?? null,
|
|
});
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
|
|
const intervalMatch = channel.match(/round:(\d+)m$/);
|
|
const intervalMinutes = intervalMatch ? Number(intervalMatch[1]) : event.intervalMinutes;
|
|
|
|
const pools = event.payload.pools as { short?: number; long?: number } | undefined;
|
|
const baseRound = (event.payload.round as Record<string, unknown>) ?? {};
|
|
|
|
for (const client of this.clients) {
|
|
if (intervalMinutes != null && !client.intervals.has(intervalMinutes)) continue;
|
|
const isAdmin = client.auth ? hasAdminAccess({ role: client.auth.role }) : false;
|
|
const round = enrichRoundPayload(baseRound, pools, isAdmin);
|
|
|
|
if (event.type === 'round.updated') {
|
|
this.send(client, {
|
|
type: 'round.updated',
|
|
intervalMinutes: intervalMinutes ?? 0,
|
|
round,
|
|
});
|
|
} else if (event.type === 'round.settled') {
|
|
this.send(client, {
|
|
type: 'round.settled',
|
|
intervalMinutes: intervalMinutes ?? 0,
|
|
round,
|
|
candle: event.payload.candle as Record<string, unknown> | undefined,
|
|
});
|
|
} else if (event.type === 'candle.append') {
|
|
this.send(client, {
|
|
type: 'candle.append',
|
|
intervalMinutes: intervalMinutes ?? 0,
|
|
candle: (event.payload.candle as Record<string, unknown>) ?? {},
|
|
});
|
|
} else if (event.type === 'config.updated') {
|
|
this.send(client, {
|
|
type: 'config.updated',
|
|
intervalMinutes: intervalMinutes ?? 0,
|
|
});
|
|
}
|
|
}
|
|
});
|
|
|
|
await sub.psubscribe('prediqo:pubsub:cp:round:*');
|
|
await sub.psubscribe(`${USER_CHANNEL_PREFIX}*`);
|
|
|
|
console.log('[ws] Subscribed to Redis round + user channels');
|
|
}
|
|
|
|
register(socket: WebSocket, auth: WsAuthContext | null): void {
|
|
const state: ClientState = { socket, auth, intervals: new Set() };
|
|
this.clients.add(state);
|
|
this.trackClient(state);
|
|
|
|
socket.on('close', () => {
|
|
this.untrackClient(state);
|
|
});
|
|
|
|
socket.on('message', async (data) => {
|
|
const raw = typeof data === 'string' ? data : data.toString('utf8');
|
|
const msg = parseClientMessage(raw);
|
|
if (!msg) {
|
|
this.send(state, { type: 'error', code: 'invalid_message', message: 'Invalid JSON message' });
|
|
return;
|
|
}
|
|
|
|
try {
|
|
await this.handleMessage(state, msg);
|
|
} catch (e) {
|
|
const message = e instanceof Error ? e.message : 'Unexpected error';
|
|
this.send(state, { type: 'error', code: 'handler_error', message });
|
|
}
|
|
});
|
|
}
|
|
|
|
private async handleMessage(
|
|
client: ClientState,
|
|
msg: ReturnType<typeof parseClientMessage> & object
|
|
): Promise<void> {
|
|
if (msg.type === 'ping') {
|
|
if (client.auth?.userId) {
|
|
void touchGamePresence(client.auth.userId);
|
|
void touchAppPresence(client.auth.userId);
|
|
}
|
|
this.send(client, { type: 'pong', ts: msg.ts });
|
|
return;
|
|
}
|
|
|
|
if (msg.type === 'subscribe') {
|
|
if (client.auth?.userId) {
|
|
void touchGamePresence(client.auth.userId);
|
|
void touchAppPresence(client.auth.userId);
|
|
}
|
|
client.intervals.add(msg.intervalMinutes);
|
|
const snapshot = await getGameState(client.auth?.userId, msg.intervalMinutes, {
|
|
includeInternal: client.auth ? hasAdminAccess({ role: client.auth.role }) : false,
|
|
});
|
|
this.send(client, {
|
|
type: 'subscribed',
|
|
intervalMinutes: msg.intervalMinutes,
|
|
snapshot,
|
|
});
|
|
return;
|
|
}
|
|
|
|
if (msg.type === 'unsubscribe') {
|
|
client.intervals.delete(msg.intervalMinutes);
|
|
return;
|
|
}
|
|
|
|
if (msg.type === 'place_bet') {
|
|
if (!client.auth?.userId) {
|
|
this.send(client, {
|
|
type: 'bet.rejected',
|
|
idempotencyKey: msg.idempotencyKey,
|
|
error: 'Authentication required',
|
|
});
|
|
return;
|
|
}
|
|
void touchGamePresence(client.auth.userId);
|
|
void touchAppPresence(client.auth.userId);
|
|
try {
|
|
const result = await placeBet(
|
|
client.auth.userId,
|
|
msg.direction,
|
|
msg.stakeAmount,
|
|
msg.intervalMinutes,
|
|
msg.stakeAccountKind,
|
|
{ idempotencyKey: msg.idempotencyKey, source: 'ws' }
|
|
);
|
|
if (result.status === 'queued') {
|
|
this.send(client, {
|
|
type: 'bet.pending',
|
|
idempotencyKey: result.idempotencyKey,
|
|
});
|
|
return;
|
|
}
|
|
this.send(client, { type: 'bet.accepted', bet: result.bet as Record<string, unknown> });
|
|
} catch (e) {
|
|
const error = e instanceof Error ? e.message : 'Bet rejected';
|
|
this.send(client, { type: 'bet.rejected', idempotencyKey: msg.idempotencyKey, error });
|
|
}
|
|
}
|
|
}
|
|
|
|
private send(client: ClientState, msg: WsServerMessage): void {
|
|
if (client.socket.readyState !== client.socket.OPEN) return;
|
|
client.socket.send(serializeServerMessage(msg));
|
|
}
|
|
}
|
|
|
|
export const gameWsHub = new GameWsHub();
|