"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.gameWsHub = exports.GameWsHub = void 0; const index_1 = require("../../domain/candle-predict/index"); const config_1 = require("../../config"); const roleAccess_1 = require("../../utils/roleAccess"); const client_1 = require("../redis/client"); const onlinePresence_1 = require("../redis/onlinePresence"); const pubsub_1 = require("../redis/pubsub"); const protocol_1 = require("./protocol"); const USER_CHANNEL_PREFIX = 'prediqo:pubsub:cp:user:'; function enrichRoundPayload(round, pools, includePoolAmounts = false) { if (!pools) return round; const short = Number(pools.short ?? 0); const long = Number(pools.long ?? 0); const total = short + long; if (total <= 0) { // Empty pools must clear previous client state (do not omit zero amounts). return { ...round, shortPoolPercent: Number(round.shortPoolPercent ?? 0), longPoolPercent: Number(round.longPoolPercent ?? 0), ...(includePoolAmounts ? { shortPool: 0, longPool: 0 } : {}), }; } 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 } : {}), }; } class GameWsHub { constructor() { this.clients = new Set(); /** Live authenticated sockets per user (this WS process). */ this.liveSocketsByUser = new Map(); } trackClient(state) { 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 (0, onlinePresence_1.touchGamePresence)(userId); void (0, onlinePresence_1.touchAppPresence)(userId); } untrackClient(state) { 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 (0, onlinePresence_1.removeGamePresence)(userId); } } async start() { if (!config_1.config.redis.enabled) { console.warn('[ws] Redis disabled — realtime push unavailable'); return; } await (0, client_1.connectRedis)(); const sub = (0, client_1.getRedisSubscriber)(); if (!sub) return; sub.on('pmessage', (_pattern, channel, message) => { try { this.dispatchRedisMessage(channel, message); } catch (e) { // Never let a bad pub/sub payload crash the WS process (nginx 502 otherwise). console.error('[ws] redis pmessage handler failed:', e instanceof Error ? e.message : e, { channel, }); } }); await sub.psubscribe('prediqo:pubsub:cp:round:*'); await sub.psubscribe(`${USER_CHANNEL_PREFIX}*`); console.log('[ws] Subscribed to Redis round + user channels'); } dispatchRedisMessage(channel, message) { const event = (0, pubsub_1.parseRealtimeEvent)(message); if (!event) return; const payload = event.payload ?? {}; 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(payload.idempotencyKey ?? '').trim(); this.send(client, { type: 'bet.accepted', bet: payload.bet ?? {}, ...(idempotencyKey ? { idempotencyKey } : {}), versions: payload.versions, }); } else if (event.type === 'bet.rejected') { const idempotencyKey = String(payload.idempotencyKey ?? '').trim(); this.send(client, { type: 'bet.rejected', idempotencyKey, error: String(payload.error ?? 'Bet rejected'), }); } else if (event.type === 'multi.updated') { this.send(client, { type: 'multi.updated', intervalMinutes: Number(payload.intervalMinutes ?? 0), userMultiBet: payload.userMultiBet ?? null, versions: payload.versions, }); } else if (event.type === 'auto.updated') { this.send(client, { type: 'auto.updated', autoSettings: payload.autoSettings ?? {}, versions: payload.versions, }); } } return; } const intervalMatch = channel.match(/round:(\d+)m$/); const intervalMinutes = intervalMatch ? Number(intervalMatch[1]) : event.intervalMinutes; const pools = payload.pools; const baseRound = payload.round ?? {}; for (const client of this.clients) { if (intervalMinutes != null && !client.intervals.has(intervalMinutes)) continue; const isAdmin = client.auth ? (0, roleAccess_1.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, versions: payload.versions, }); } else if (event.type === 'round.settled') { this.send(client, { type: 'round.settled', intervalMinutes: intervalMinutes ?? 0, round, candle: payload.candle, versions: payload.versions, }); } else if (event.type === 'candle.append') { this.send(client, { type: 'candle.append', intervalMinutes: intervalMinutes ?? 0, candle: payload.candle ?? {}, }); } else if (event.type === 'config.updated') { this.send(client, { type: 'config.updated', intervalMinutes: intervalMinutes ?? 0, versions: payload.versions, }); } } } register(socket, auth) { const state = { 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 = (0, protocol_1.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 }); } }); } async handleMessage(client, msg) { if (msg.type === 'ping') { if (client.auth?.userId) { void (0, onlinePresence_1.touchGamePresence)(client.auth.userId); void (0, onlinePresence_1.touchAppPresence)(client.auth.userId); } this.send(client, { type: 'pong', ts: msg.ts }); return; } if (msg.type === 'subscribe') { if (client.auth?.userId) { void (0, onlinePresence_1.touchGamePresence)(client.auth.userId); void (0, onlinePresence_1.touchAppPresence)(client.auth.userId); } client.intervals.add(msg.intervalMinutes); const snapshot = await (0, index_1.getGameState)(client.auth?.userId, msg.intervalMinutes, { includeInternal: client.auth ? (0, roleAccess_1.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 (0, onlinePresence_1.touchGamePresence)(client.auth.userId); void (0, onlinePresence_1.touchAppPresence)(client.auth.userId); try { const result = await (0, index_1.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 }); } catch (e) { const error = e instanceof Error ? e.message : 'Bet rejected'; this.send(client, { type: 'bet.rejected', idempotencyKey: msg.idempotencyKey, error }); } } } send(client, msg) { if (client.socket.readyState !== client.socket.OPEN) return; client.socket.send((0, protocol_1.serializeServerMessage)(msg)); } } exports.GameWsHub = GameWsHub; exports.gameWsHub = new GameWsHub(); //# sourceMappingURL=hub.js.map