diff --git a/prediqo_web/src/features/candle-predict/hooks/useCandlePredict.ts b/prediqo_web/src/features/candle-predict/hooks/useCandlePredict.ts index 4cbcbfad..316d65e2 100644 --- a/prediqo_web/src/features/candle-predict/hooks/useCandlePredict.ts +++ b/prediqo_web/src/features/candle-predict/hooks/useCandlePredict.ts @@ -42,6 +42,25 @@ export function updateCachedStateEtag( stateEtagCache.set(key, { ...cached, etag }); } +/** Drop ETag so the next /state fetch cannot 304 against stale body. */ +export function bustCachedStateEtag(intervalMinutes?: number): void { + stateEtagCache.delete(stateCacheKeyFor(intervalMinutes)); +} + +/** Replace cached /state body (+ optional etag) after a live WS snapshot/update. */ +export function replaceCachedState( + intervalMinutes: number | undefined, + data: GameState, + etag?: string +): void { + const key = stateCacheKeyFor(intervalMinutes); + const prev = stateEtagCache.get(key); + stateEtagCache.set(key, { + etag: etag || prev?.etag || '', + data, + }); +} + function parseVersionEtag( etag: string ): { config: number; round: number; bet: number; auto: number; intervalMinutes: number } | null { @@ -96,24 +115,6 @@ export function useCandlePredictState(intervalMinutes?: number, _pollMs = 3000) return cached.data; } const next = res.data; - // Avoid re-render when payload is timer-only churn (same round/status/pools). - if ( - cached?.data?.round?.id && - next?.round?.id === cached.data.round.id && - next?.round?.status === cached.data.round.status && - next?.round?.outcome === cached.data.round.outcome && - next?.round?.shortPool === cached.data.round.shortPool && - next?.round?.longPool === cached.data.round.longPool && - next?.userBet?.id === cached.data.userBet?.id && - next?.userMultiBet?.id === cached.data.userMultiBet?.id && - next?.autoSettings?.enabled === cached.data.autoSettings?.enabled - ) { - stateEtagCache.set(stateCacheKey, { - etag: String(res.headers.etag ?? cached.etag), - data: cached.data, - }); - return cached.data; - } stateEtagCache.set(stateCacheKey, { etag: String(res.headers.etag ?? ''), data: next, @@ -125,18 +126,17 @@ export function useCandlePredictState(intervalMinutes?: number, _pollMs = 3000) if (status === 429) return failureCount < 2; return failureCount < 1; }, - refetchInterval: (query) => { - // WS is primary for round transitions; HTTP is a rare safety net only. + refetchInterval: () => { + // Keep page calm, but always have a healing HTTP net (WS ticks alone can desync ETag/body). if (wsEnabled && socket.status === 'connected') { - return withLightJitter(60_000, 0.05); + return withLightJitter(15_000, 0.05); } if (wsEnabled && (socket.status === 'reconnecting' || socket.status === 'stale')) { - return withLightJitter(8_000, 0.08); + return withLightJitter(5_000, 0.08); } - const status = query.state.data?.round?.status; - return withLightJitter(status === 'betting' ? 5_000 : 15_000, 0.08); + return withLightJitter(5_000, 0.08); }, - refetchOnWindowFocus: false, + refetchOnWindowFocus: true, structuralSharing: true, }); } diff --git a/prediqo_web/src/features/candle-predict/hooks/useGameSocket.ts b/prediqo_web/src/features/candle-predict/hooks/useGameSocket.ts index 035d20f0..3c5a9440 100644 --- a/prediqo_web/src/features/candle-predict/hooks/useGameSocket.ts +++ b/prediqo_web/src/features/candle-predict/hooks/useGameSocket.ts @@ -2,7 +2,11 @@ import { useEffect, useState } from 'react'; import { useQueryClient } from '@tanstack/react-query'; import { useAuth } from '../../../shared/auth/AuthContext'; -import { mergeCachedStateVersions } from './useCandlePredict'; +import { + bustCachedStateEtag, + mergeCachedStateVersions, + replaceCachedState, +} from './useCandlePredict'; import type { CandlePredictPrediction, GameState, MultiCandlePrediction } from '../types'; import { emitBetOutcome } from '../ws/betOutcomeBus'; import { gameSocketClient } from '../ws/GameSocketClient'; @@ -113,6 +117,8 @@ function applyBetAccepted(prev: GameState, bet: CandlePredictPrediction): GameSt } function syncAfterSettlement(qc: ReturnType, key: readonly unknown[]): void { + const intervalMinutes = key[1] as number | undefined; + bustCachedStateEtag(intervalMinutes); void qc.invalidateQueries({ queryKey: key }); void qc.invalidateQueries({ queryKey: ['candle-predict-predictions'] }); void qc.invalidateQueries({ queryKey: ['wallet-balances'] }); @@ -139,6 +145,7 @@ export function useGameSocket( return gameSocketClient.onStatusChange((next) => { setStatus(next); if (next === 'connected' && intervalMinutes != null) { + bustCachedStateEtag(intervalMinutes); void qc.invalidateQueries({ queryKey: ['candle-predict-state', intervalMinutes] }); void qc.invalidateQueries({ queryKey: ['wallet-balances'] }); } @@ -157,6 +164,8 @@ export function useGameSocket( if (msg.type === 'subscribed') { qc.setQueryData(key, msg.snapshot); + // Snapshot is source of truth — drop any poisoned ETag so HTTP cannot 304 stale body. + replaceCachedState(intervalMinutes, msg.snapshot, ''); return; } @@ -165,42 +174,46 @@ export function useGameSocket( if (msg.versions?.config != null) { mergeCachedStateVersions(intervalMinutes, { config: msg.versions.config }); } + bustCachedStateEtag(intervalMinutes); void qc.invalidateQueries({ queryKey: key }); return; } if (msg.type === 'round.updated') { - if (msg.versions?.round != null) { - mergeCachedStateVersions(intervalMinutes, { round: msg.versions.round }); - } qc.setQueryData(key, (prev) => { if (!prev) return prev; const round = mergeRound(prev.round, msg.round); if (!roundUiChanged(prev.round, round)) { - // Timer-only engine ticks: keep same object so the page does not re-render. + // Timer-only tick: do NOT advance ETag (that caused permanent 304 with stale pools). return prev; } - return { + const next = { ...prev, round, userBet: userBetForRound(prev.userBet, round), }; + if (msg.versions?.round != null) { + replaceCachedState(intervalMinutes, next); + mergeCachedStateVersions(intervalMinutes, { round: msg.versions.round }); + } else { + replaceCachedState(intervalMinutes, next, ''); + } + return next; }); return; } if (msg.type === 'round.settled') { - if (msg.versions?.round != null) { - mergeCachedStateVersions(intervalMinutes, { round: msg.versions.round }); - } qc.setQueryData(key, (prev) => { if (!prev) return prev; const round = mergeRound(prev.round, msg.round); - return { + const next = { ...prev, round, userBet: userBetForRound(prev.userBet, round), }; + replaceCachedState(intervalMinutes, next, ''); + return next; }); void qc.invalidateQueries({ queryKey: ['candle-predict-candles', intervalMinutes] }); syncAfterSettlement(qc, key); diff --git a/prediqo_web/src/features/candle-predict/ws/protocol.ts b/prediqo_web/src/features/candle-predict/ws/protocol.ts index 2c1c6912..b6a98325 100644 --- a/prediqo_web/src/features/candle-predict/ws/protocol.ts +++ b/prediqo_web/src/features/candle-predict/ws/protocol.ts @@ -46,8 +46,28 @@ export type WsServerMessage = | { type: 'error'; code: string; message: string }; export function resolveWsBaseUrl(): string { - const explicit = import.meta.env.VITE_WS_URL as string | undefined; - if (explicit) return explicit.replace(/\/$/, ''); + const explicit = (import.meta.env.VITE_WS_URL as string | undefined)?.replace(/\/$/, ''); + + if (typeof window !== 'undefined') { + const pageHost = window.location.host; + if (explicit) { + try { + const configured = new URL(explicit); + // Use baked URL only when it targets the same host the user is browsing. + if (configured.host === pageHost) return explicit; + } catch { + /* fall through to same-origin */ + } + } + // Prefer same-origin /ws/ (nginx on :9080 or :9443) so a stale build URL cannot break live updates. + const u = new URL(window.location.origin); + u.protocol = u.protocol === 'https:' ? 'wss:' : 'ws:'; + u.pathname = '/ws/v1/games/candle-predict'; + u.search = ''; + return u.toString().replace(/\/$/, ''); + } + + if (explicit) return explicit; const api = import.meta.env.VITE_API_BASE_URL || 'http://localhost:4000'; const url = new URL(api);