Merge remote-tracking branch 'origin/master' into feat/pricing-plan
Project CI / AI game creator shell Rust lane 1/2 (pull_request) Has been cancelled
Project CI / AI game creator shell Rust lane 2/2 (pull_request) Has been cancelled
Project CI / AI game creator shell Rust crates (pull_request) Has been cancelled
Project CI / Backend tests (pull_request) Has been cancelled
Project CI / Native shell tests (pull_request) Has been cancelled
Project CI / Frontend tests (pull_request) Has been cancelled
Project CI / Repository checks (pull_request) Has been cancelled
Project CI / AI game creator shell web tests (pull_request) Has been cancelled
Project CI / AI game creator shell Rust lane 1/2 (pull_request) Has been cancelled
Project CI / AI game creator shell Rust lane 2/2 (pull_request) Has been cancelled
Project CI / AI game creator shell Rust crates (pull_request) Has been cancelled
Project CI / Backend tests (pull_request) Has been cancelled
Project CI / Native shell tests (pull_request) Has been cancelled
Project CI / Frontend tests (pull_request) Has been cancelled
Project CI / Repository checks (pull_request) Has been cancelled
Project CI / AI game creator shell web tests (pull_request) Has been cancelled
# Conflicts: # docs/project-memory/shared-memory/decision-log.md
This commit is contained in:
@@ -11,6 +11,7 @@ import {
|
||||
listGameReviews,
|
||||
listGames,
|
||||
listMyGames,
|
||||
recordGamePlay,
|
||||
saveMyGameReview,
|
||||
unpublishGame,
|
||||
uploadGamePackage,
|
||||
@@ -83,6 +84,38 @@ describe('gameDistributionClient', () => {
|
||||
expect(await getGame('')).toBeNull();
|
||||
});
|
||||
|
||||
it('游玩上报携带稳定的匿名 clientId,且不携带未登录 bearer', async () => {
|
||||
const fetchMock = vi.fn().mockImplementation(() =>
|
||||
Promise.resolve(
|
||||
new Response(JSON.stringify({ recorded: true }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}),
|
||||
),
|
||||
);
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await recordGamePlay('game-1');
|
||||
await recordGamePlay('game-1');
|
||||
|
||||
const playCalls = fetchMock.mock.calls.filter(([url]) =>
|
||||
String(url).includes('/plays'),
|
||||
);
|
||||
expect(playCalls).toHaveLength(2);
|
||||
expect(playCalls[0]?.[0]).toBe('/api/game-distribution/games/game-1/plays');
|
||||
expect(playCalls[0]?.[1]).toMatchObject({
|
||||
method: 'POST',
|
||||
cache: 'no-store',
|
||||
});
|
||||
expect(playCalls[0]?.[1]?.headers?.Authorization).toBeUndefined();
|
||||
const clientIds = playCalls.map(
|
||||
([, init]) =>
|
||||
(JSON.parse(String(init?.body)) as { clientId?: string }).clientId,
|
||||
);
|
||||
expect(clientIds[0]).toBeTruthy();
|
||||
expect(clientIds).toEqual([clientIds[0], clientIds[0]]);
|
||||
});
|
||||
|
||||
it('版本创建携带幂等键并保留后端失败状态', async () => {
|
||||
setStoredAccessToken('test-access-token', { emit: false });
|
||||
vi.stubGlobal(
|
||||
|
||||
@@ -16,8 +16,10 @@ import type {
|
||||
} from '../../packages/shared/src/contracts/gameDistribution';
|
||||
import {
|
||||
type ApiRequestOptions,
|
||||
BACKGROUND_AUTH_REQUEST_OPTIONS,
|
||||
requestJson as requestApiJson,
|
||||
} from './apiClient';
|
||||
import { getGamePlayClientId } from './gamePlayClientId';
|
||||
|
||||
export type {
|
||||
GameDistributionAuthor,
|
||||
@@ -67,6 +69,11 @@ const PUBLIC_GAME_REQUEST_OPTIONS: ApiRequestOptions = {
|
||||
clearAuthOnUnauthorized: false,
|
||||
};
|
||||
|
||||
/**
|
||||
* 游玩上报是后台尽力而为的请求:带上已登录 bearer(后端据此按 userId 去重),但即使遇到 401
|
||||
* 也不刷新会话、不改动全局登录态——直接复用后台请求已有的同一份鉴权降级策略。
|
||||
*/
|
||||
|
||||
async function requestJson<T>(
|
||||
path: string,
|
||||
init: RequestInit,
|
||||
@@ -171,6 +178,26 @@ export async function getGame(gameId: string) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上报一次「开始游戏」。调用方按 fire-and-forget 处理:失败只静默忽略,绝不阻断进入游戏。
|
||||
*/
|
||||
export function recordGamePlay(
|
||||
gameId: string,
|
||||
): Promise<{ recorded?: boolean }> {
|
||||
const normalizedId = gameId.trim();
|
||||
if (!normalizedId) return Promise.resolve({ recorded: false });
|
||||
return requestJson<{ recorded?: boolean }>(
|
||||
`/games/${encodeURIComponent(normalizedId)}/plays`,
|
||||
{
|
||||
method: 'POST',
|
||||
cache: 'no-store',
|
||||
body: JSON.stringify({ clientId: getGamePlayClientId() }),
|
||||
},
|
||||
'游玩上报失败',
|
||||
BACKGROUND_AUTH_REQUEST_OPTIONS,
|
||||
);
|
||||
}
|
||||
|
||||
export function listGameReviews(gameId: string, page = 1) {
|
||||
return requestJson<GameDistributionReviewsResponse>(
|
||||
`/games/${encodeURIComponent(gameId)}/reviews?page=${page}&pageSize=20`,
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* 匿名游玩身份。
|
||||
*
|
||||
* 登录用户由后端从 bearer 取 `userId`,匿名用户只能靠前端持久一个随机 `clientId`。这里把
|
||||
* 生成、读取与降级收在一个小模块里:`localStorage` 不可用(隐私模式、SSR、被禁用)时退化为
|
||||
* 当前会话内存值,保证一次会话内多次点击仍去重。
|
||||
*/
|
||||
|
||||
const GAME_PLAY_CLIENT_ID_STORAGE_KEY = 'genarrative.game-play.client-id.v1';
|
||||
|
||||
let cachedClientId: string | null = null;
|
||||
|
||||
/** 返回稳定的匿名游玩身份;同一标签页内重复调用返回同一个值。 */
|
||||
export function getGamePlayClientId(): string {
|
||||
if (cachedClientId) return cachedClientId;
|
||||
|
||||
try {
|
||||
const stored = window.localStorage
|
||||
.getItem(GAME_PLAY_CLIENT_ID_STORAGE_KEY)
|
||||
?.trim();
|
||||
if (stored) {
|
||||
cachedClientId = stored;
|
||||
return stored;
|
||||
}
|
||||
const created = createGamePlayClientId();
|
||||
window.localStorage.setItem(GAME_PLAY_CLIENT_ID_STORAGE_KEY, created);
|
||||
cachedClientId = created;
|
||||
return created;
|
||||
} catch {
|
||||
cachedClientId = cachedClientId ?? createGamePlayClientId();
|
||||
return cachedClientId;
|
||||
}
|
||||
}
|
||||
|
||||
function createGamePlayClientId(): string {
|
||||
if (
|
||||
typeof crypto !== 'undefined' &&
|
||||
typeof crypto.randomUUID === 'function'
|
||||
) {
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
return `gp-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
}
|
||||
Reference in New Issue
Block a user