import { Injectable } from '@nestjs/common'; import { buildAuctionRedisKeys } from './auction-redis.keys'; import { AuctionRedisService } from './auction-redis.service'; import { assembleAuctionViewFromRedisState } from './auction-redis.state'; const NUMERIC_LIVE_STATE_FIELDS = new Set([ 'bidRoundExpiryPlayerOrderIndex', 'bidRoundExpiryRevision', 'bidRoundExpiryWinningBidPointAmount', 'bidRoundExpiryWinningBidderTeamIndex', 'currentAuctionHistorySequence', 'currentAuctionPlayerOrderIndex', 'currentBidRoundDeadlineTimestampMS', 'currentHighestBidPointAmount', 'currentHighestBidderTeamIndex', 'matchSideEffectRevision', 'revision', ]); export interface AuctionRedisLiveStateIdentity { auctionLifecycleId?: string; revision?: number; } export interface AuctionRedisBidContext { auctionLifecycleId: string; bidderTeamCaptainUserId?: string; currentBidRoundPlayerUserId?: string; phase: string; } export interface AuctionRedisStateViewReadOptions { includeInternalLiveStateFields?: boolean; shouldForceAuctionStateResync?: boolean; } @Injectable() export class AuctionRedisStateReaderService { constructor(private readonly auctionRedisService: AuctionRedisService) {} public async readLiveStateIdentity( matchId: string, ): Promise { const keys = buildAuctionRedisKeys(matchId); const reply = await this.auctionRedisService.raw().sendCommand([ 'HMGET', keys.liveStateKey, 'auctionLifecycleId', 'revision', ]); if (!Array.isArray(reply)) return null; const auctionLifecycleId = typeof reply[0] === 'string' && reply[0] ? reply[0] : undefined; const revision = typeof reply[1] === 'string' || typeof reply[1] === 'number' ? Number(reply[1]) : Number.NaN; if (!auctionLifecycleId && !Number.isFinite(revision)) return null; return { auctionLifecycleId, revision: Number.isFinite(revision) ? revision : undefined, }; } public async readBidContext( matchId: string, bidderTeamIndex: number, ): Promise { const keys = buildAuctionRedisKeys(matchId); const bidderTeamCaptainUserIdField = `team:${bidderTeamIndex}:captainUserId`; const liveReply = await this.auctionRedisService.raw().sendCommand([ 'HMGET', keys.liveStateKey, 'phase', 'auctionLifecycleId', 'currentBidRoundPlayerUserId', bidderTeamCaptainUserIdField, ]); if (!Array.isArray(liveReply)) return null; const phase = stringValue(liveReply[0]); const auctionLifecycleId = stringValue(liveReply[1]); const currentBidRoundPlayerUserId = stringValue(liveReply[2]); const liveCaptainUserId = stringValue(liveReply[3]); if (!phase || !auctionLifecycleId) return null; return { auctionLifecycleId, bidderTeamCaptainUserId: liveCaptainUserId ?? (await this.readBidderTeamCaptainUserIdFromStructure( keys.structureStateKey, bidderTeamIndex, )), currentBidRoundPlayerUserId, phase, }; } public async readAuctionStateView( matchId: string, options: AuctionRedisStateViewReadOptions = {}, ): Promise | null> { const keys = buildAuctionRedisKeys(matchId); const [currentServerTimestampMS, liveReply, structureStateJson, bidEntries] = await Promise.all([ this.auctionRedisService.getCurrentRedisTimestampMS(), this.auctionRedisService.raw().sendCommand(['HGETALL', keys.liveStateKey]), this.auctionRedisService.raw().sendCommand(['GET', keys.structureStateKey]), this.auctionRedisService.raw().sendCommand([ 'LRANGE', keys.bidHistoryKey, '0', '-1', ]), ]); const liveState = parseHashReply(liveReply, { includeInternalLiveStateFields: options.includeInternalLiveStateFields ?? false, }); if (!liveState) return null; if ( typeof liveState.auctionLifecycleId !== 'string' || typeof liveState.phase !== 'string' || typeof liveState.revision !== 'number' ) { return null; } if (typeof structureStateJson !== 'string' || !structureStateJson) { return null; } const view = assembleAuctionViewFromRedisState({ auctionBidHistoryEntries: Array.isArray(bidEntries) ? bidEntries.map(String) : [], currentServerTimestampMS, liveState: liveState as Record & { auctionLifecycleId: string; phase: string; revision: number; }, shouldForceAuctionStateResync: options.shouldForceAuctionStateResync, structureState: JSON.parse(structureStateJson) as Record, }); view.matchId = matchId; if (options.includeInternalLiveStateFields) { view.redisInternalPhase = liveState.phase; } return view; } private async readBidderTeamCaptainUserIdFromStructure( structureStateKey: string, bidderTeamIndex: number, ): Promise { const structureStateJson = await this.auctionRedisService .raw() .sendCommand(['GET', structureStateKey]); if (typeof structureStateJson !== 'string' || !structureStateJson) { return undefined; } const structureState = JSON.parse(structureStateJson) as Record< string, unknown >; const auctionTeams = Array.isArray(structureState.auctionTeams) ? structureState.auctionTeams : []; const bidderTeam = auctionTeams.find((entry) => { if (!entry || typeof entry !== 'object') return false; return ( Number((entry as Record).teamIndex) === bidderTeamIndex ); }); if (!bidderTeam || typeof bidderTeam !== 'object') return undefined; return stringValue((bidderTeam as Record).captainUserId); } } function stringValue(value: unknown): string | undefined { return typeof value === 'string' && value ? value : undefined; } function parseHashReply( reply: unknown, options: { includeInternalLiveStateFields?: boolean } = {}, ): Record | null { if (!reply) return null; if (Array.isArray(reply)) { if (reply.length === 0) return null; const entries: [string, unknown][] = []; for (let index = 0; index < reply.length; index += 2) { entries.push([String(reply[index]), reply[index + 1]]); } return parseHashEntries(entries, options); } if (typeof reply === 'object') { const entries = Object.entries(reply as Record); if (entries.length === 0) return null; return parseHashEntries(entries, options); } return null; } function parseHashEntries( entries: [string, unknown][], options: { includeInternalLiveStateFields?: boolean } = {}, ): Record { const result: Record = {}; for (const [field, rawValue] of entries) { if (!options.includeInternalLiveStateFields && isInternalLiveStateField(field)) { continue; } const value = String(rawValue); if (NUMERIC_LIVE_STATE_FIELDS.has(field)) { const parsed = Number(value); result[field] = Number.isFinite(parsed) ? parsed : 0; continue; } result[field] = value; } return result; } function isInternalLiveStateField(field: string): boolean { return field.startsWith('team:') || field.startsWith('bidRoundExpiry'); }