feat(ui): preload ongoing games and cache the draft for an instant, jump-free game open
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Has been skipped
CI / integration (pull_request) Has been skipped
CI / ui (pull_request) Successful in 46s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m2s
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Has been skipped
CI / integration (pull_request) Has been skipped
CI / ui (pull_request) Successful in 46s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m2s
Opening a game from the lobby for the first time this session showed a brief loading flash, and every open showed a two-step rack->board jump: the saved draft (pending composition) was fetched separately and applied only after the board had already painted the full rack. Both stem from the full state and the draft not being available synchronously at first paint. Cache the draft alongside view+history (CachedGame.draft), make applyDraft take the already-fetched JSON so it runs synchronously, and fetch the draft in the same Promise.all as state+history. setCachedGame preserves the cached draft when the delta path omits it and clears it on a committed move (mirroring the server). A new preload module warms the per-game cache (state, history, draft) for the lobby's ongoing games with bounded concurrency, so opening any of them is instant. Tests: gamecache (preserve/clear/setCachedDraft) and preload (warm/skip) units; existing draft-restore e2e still green.
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { clearGameCache, getCachedGame, setCachedDraft, setCachedGame } from './gamecache';
|
||||
import type { GameView, MoveRecord, StateView } from './model';
|
||||
|
||||
function gameView(id: string): GameView {
|
||||
return {
|
||||
id,
|
||||
variant: 'scrabble_en',
|
||||
dictVersion: 'v1',
|
||||
status: 'active',
|
||||
players: 2,
|
||||
toMove: 0,
|
||||
turnTimeoutSecs: 300,
|
||||
multipleWordsPerTurn: true,
|
||||
moveCount: 0,
|
||||
endReason: '',
|
||||
lastActivityUnix: 0,
|
||||
seats: [],
|
||||
};
|
||||
}
|
||||
|
||||
function view(id: string, rack: string[] = ['A', 'B']): StateView {
|
||||
return { game: gameView(id), seat: 0, rack, bagLen: 50, hintsRemaining: 1 };
|
||||
}
|
||||
|
||||
function move(player: number): MoveRecord {
|
||||
return { player, action: 'play', dir: 'H', mainRow: 7, mainCol: 7, tiles: [], words: ['AB'], count: 0, score: 10, total: 10 };
|
||||
}
|
||||
|
||||
beforeEach(() => clearGameCache());
|
||||
|
||||
describe('setCachedGame', () => {
|
||||
it('stores state, history and draft', () => {
|
||||
setCachedGame('g1', view('g1'), [move(0)], '{"x":1}');
|
||||
const c = getCachedGame('g1');
|
||||
expect(c?.view.game.id).toBe('g1');
|
||||
expect(c?.moves).toHaveLength(1);
|
||||
expect(c?.draft).toBe('{"x":1}');
|
||||
});
|
||||
|
||||
it('leaves draft undefined when none is given for a new entry', () => {
|
||||
setCachedGame('g1', view('g1'), []);
|
||||
expect(getCachedGame('g1')?.draft).toBeUndefined();
|
||||
});
|
||||
|
||||
it('preserves the cached draft when draft is omitted (the live-event delta path)', () => {
|
||||
setCachedGame('g1', view('g1'), [], 'DRAFT');
|
||||
// A delta advances view+moves without refetching the draft; it must not be dropped.
|
||||
setCachedGame('g1', view('g1', ['C', 'D']), [move(1)]);
|
||||
const c = getCachedGame('g1');
|
||||
expect(c?.draft).toBe('DRAFT'); // preserved
|
||||
expect(c?.view.rack).toEqual(['C', 'D']); // view advanced
|
||||
expect(c?.moves).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('clears the draft when passed an empty string (a committed move)', () => {
|
||||
setCachedGame('g1', view('g1'), [], 'DRAFT');
|
||||
setCachedGame('g1', view('g1'), [move(0)], '');
|
||||
expect(getCachedGame('g1')?.draft).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('setCachedDraft', () => {
|
||||
it('updates only the draft of an already-cached game', () => {
|
||||
setCachedGame('g1', view('g1', ['A']), [move(0)], 'OLD');
|
||||
setCachedDraft('g1', 'NEW');
|
||||
const c = getCachedGame('g1');
|
||||
expect(c?.draft).toBe('NEW');
|
||||
expect(c?.view.rack).toEqual(['A']); // unchanged
|
||||
expect(c?.moves).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('is a no-op when the game is not cached', () => {
|
||||
setCachedDraft('absent', 'X');
|
||||
expect(getCachedGame('absent')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('clearGameCache', () => {
|
||||
it('drops every cached game', () => {
|
||||
setCachedGame('g1', view('g1'), []);
|
||||
setCachedGame('g2', view('g2'), []);
|
||||
clearGameCache();
|
||||
expect(getCachedGame('g1')).toBeUndefined();
|
||||
expect(getCachedGame('g2')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
+28
-9
@@ -1,15 +1,21 @@
|
||||
// In-memory per-game cache. A game the player has opened once is kept here so a
|
||||
// later re-entry renders instantly from the cache while a fresh fetch updates it in
|
||||
// the background — removing the blank "loading" flash and the full redraw on every
|
||||
// lobby <-> game navigation. It is intentionally process-memory only (no persistence):
|
||||
// stale entries are corrected by the background refresh, and the cache is cleared on
|
||||
// logout.
|
||||
// In-memory per-game cache. A game the player has opened once — or one warmed ahead of time
|
||||
// by the lobby preload (see lib/preload) — is kept here so opening it renders instantly from
|
||||
// the cache while a fresh fetch updates it in the background, removing the blank "loading"
|
||||
// flash and the full redraw on every lobby <-> game navigation. It is intentionally
|
||||
// process-memory only (no persistence): stale entries are corrected by the background
|
||||
// refresh, and the cache is cleared on logout.
|
||||
|
||||
import type { MoveRecord, StateView } from './model';
|
||||
|
||||
export interface CachedGame {
|
||||
view: StateView;
|
||||
moves: MoveRecord[];
|
||||
/**
|
||||
* The player's saved draft (composition) as the opaque JSON the server stores, so a warm
|
||||
* open paints the pending tiles already on the board with no rack→board jump. An empty
|
||||
* string means no draft; undefined means it has not been fetched for this entry yet.
|
||||
*/
|
||||
draft?: string;
|
||||
}
|
||||
|
||||
const cache = new Map<string, CachedGame>();
|
||||
@@ -19,9 +25,22 @@ export function getCachedGame(id: string): CachedGame | undefined {
|
||||
return cache.get(id);
|
||||
}
|
||||
|
||||
/** setCachedGame stores the latest state+history for a game. */
|
||||
export function setCachedGame(id: string, view: StateView, moves: MoveRecord[]): void {
|
||||
cache.set(id, { view, moves });
|
||||
/**
|
||||
* setCachedGame stores the latest state+history for a game. Omitting draft preserves the
|
||||
* cached composition: the live-event delta path advances view+moves without refetching the
|
||||
* draft and must not drop it, while passing an empty string clears it (a committed move does,
|
||||
* mirroring the server).
|
||||
*/
|
||||
export function setCachedGame(id: string, view: StateView, moves: MoveRecord[], draft?: string): void {
|
||||
const prev = cache.get(id);
|
||||
cache.set(id, { view, moves, draft: draft ?? prev?.draft });
|
||||
}
|
||||
|
||||
/** setCachedDraft updates only the saved draft of an already-cached game (a no-op otherwise),
|
||||
* keeping the cache coherent with the draft persisted while composing. */
|
||||
export function setCachedDraft(id: string, draft: string): void {
|
||||
const prev = cache.get(id);
|
||||
if (prev) cache.set(id, { ...prev, draft });
|
||||
}
|
||||
|
||||
/** clearGameCache drops every cached game (called on logout). */
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { GameView, StateView } from './model';
|
||||
|
||||
// Mock the gateway singleton so preload's fan-out is observed without a transport.
|
||||
const mocks = vi.hoisted(() => ({
|
||||
gameState: vi.fn(),
|
||||
gameHistory: vi.fn(),
|
||||
draftGet: vi.fn(),
|
||||
}));
|
||||
vi.mock('./gateway', () => ({
|
||||
gateway: { gameState: mocks.gameState, gameHistory: mocks.gameHistory, draftGet: mocks.draftGet },
|
||||
}));
|
||||
|
||||
import { preloadGames } from './preload';
|
||||
import { clearGameCache, getCachedGame, setCachedGame } from './gamecache';
|
||||
|
||||
function gameView(id: string, status: GameView['status'] = 'active'): GameView {
|
||||
return {
|
||||
id,
|
||||
variant: 'scrabble_en',
|
||||
dictVersion: 'v1',
|
||||
status,
|
||||
players: 2,
|
||||
toMove: 0,
|
||||
turnTimeoutSecs: 300,
|
||||
multipleWordsPerTurn: true,
|
||||
moveCount: 0,
|
||||
endReason: '',
|
||||
lastActivityUnix: 0,
|
||||
seats: [],
|
||||
};
|
||||
}
|
||||
|
||||
function stateView(id: string): StateView {
|
||||
return { game: gameView(id), seat: 0, rack: ['A', 'B'], bagLen: 50, hintsRemaining: 1 };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
clearGameCache();
|
||||
mocks.gameState.mockReset().mockImplementation((id: string) => Promise.resolve(stateView(id)));
|
||||
mocks.gameHistory.mockReset().mockImplementation((id: string) => Promise.resolve({ gameId: id, moves: [] }));
|
||||
mocks.draftGet.mockReset().mockImplementation((id: string) => Promise.resolve(id === 'g1' ? 'DRAFT1' : ''));
|
||||
});
|
||||
|
||||
describe('preloadGames', () => {
|
||||
it('warms ongoing, uncached games with state, history and draft', async () => {
|
||||
await preloadGames([gameView('g1'), gameView('g2')]);
|
||||
expect(getCachedGame('g1')?.view.game.id).toBe('g1');
|
||||
expect(getCachedGame('g1')?.draft).toBe('DRAFT1');
|
||||
expect(getCachedGame('g2')?.draft).toBe('');
|
||||
});
|
||||
|
||||
it('skips finished games', async () => {
|
||||
await preloadGames([gameView('done', 'finished')]);
|
||||
expect(getCachedGame('done')).toBeUndefined();
|
||||
expect(mocks.gameState).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('skips games already in the cache (kept fresh by the live stream)', async () => {
|
||||
setCachedGame('g1', stateView('g1'), [], 'KEEP');
|
||||
await preloadGames([gameView('g1'), gameView('g2')]);
|
||||
expect(mocks.gameState).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.gameState).toHaveBeenCalledWith('g2', expect.any(Boolean));
|
||||
expect(getCachedGame('g1')?.draft).toBe('KEEP'); // untouched
|
||||
});
|
||||
|
||||
it('does nothing for an empty list', async () => {
|
||||
await preloadGames([]);
|
||||
expect(mocks.gameState).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
// Lobby preload: warm the per-game cache for the player's ongoing games ahead of time, so
|
||||
// opening one from the lobby renders instantly — no "loading" flash and no rack→board jump
|
||||
// (the saved draft is fetched and cached alongside state and history). It is best-effort and
|
||||
// bounded; finished games are skipped (rarely reopened, no draft), as are games already cached
|
||||
// (the live stream keeps those fresh) or currently being warmed.
|
||||
|
||||
import { gateway } from './gateway';
|
||||
import { getCachedGame, setCachedGame } from './gamecache';
|
||||
import { hasAlphabet } from './alphabet';
|
||||
import type { GameView } from './model';
|
||||
|
||||
// Cap on games warmed at once: enough to cover a typical lobby quickly without a request burst.
|
||||
const MAX_CONCURRENT = 4;
|
||||
// Games being warmed right now, so overlapping calls (the lobby refreshes on every live event)
|
||||
// never fetch the same game twice.
|
||||
const inflight = new Set<string>();
|
||||
|
||||
/**
|
||||
* preloadGames warms the cache for the given ongoing games: it fetches each game's state,
|
||||
* history and saved draft in parallel and stores them, skipping finished games and any already
|
||||
* cached or in flight. Concurrency is bounded and failures are swallowed (the game just
|
||||
* cold-loads on open). It resolves once every queued game has settled.
|
||||
*/
|
||||
export async function preloadGames(games: GameView[]): Promise<void> {
|
||||
const queue = games.filter(
|
||||
(g) => g.status !== 'finished' && !getCachedGame(g.id) && !inflight.has(g.id),
|
||||
);
|
||||
if (queue.length === 0) return;
|
||||
for (const g of queue) inflight.add(g.id);
|
||||
let next = 0;
|
||||
const worker = async (): Promise<void> => {
|
||||
while (next < queue.length) {
|
||||
const g = queue[next++];
|
||||
try {
|
||||
const [st, hist, draft] = await Promise.all([
|
||||
gateway.gameState(g.id, !hasAlphabet(g.variant)),
|
||||
gateway.gameHistory(g.id),
|
||||
gateway.draftGet(g.id).catch(() => ''),
|
||||
]);
|
||||
// A live event may have seeded or advanced this entry while we fetched; don't clobber it.
|
||||
if (!getCachedGame(g.id)) setCachedGame(g.id, st, hist.moves, draft);
|
||||
} catch {
|
||||
/* best-effort: leave the game to cold-load on open */
|
||||
} finally {
|
||||
inflight.delete(g.id);
|
||||
}
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: Math.min(MAX_CONCURRENT, queue.length) }, worker));
|
||||
}
|
||||
Reference in New Issue
Block a user