Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 5 additions & 8 deletions src/api/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,18 @@ jest.mock('./guest', () => ({
const { requestAccount } = jest.requireMock('./guest')

describe('the account request', () => {
it("says whether the player's games are held by the server", async () => {
it("gives the account's ids and name", async () => {
requestAccount.mockResolvedValue({
client_id: 'c1',
display_name: 'Guest',
lichess_id: null,
// Still sent by the backend; no longer read.
server_games: true,
})
expect(await fetchAccount()).toMatchObject({
expect(await fetchAccount()).toEqual({
clientId: 'c1',
serverGames: true,
displayName: 'Guest',
lichessId: null,
})
})

it('takes an older answer, without the field, as no', async () => {
requestAccount.mockResolvedValue({ client_id: 'c1', display_name: 'Guest' })
expect((await fetchAccount()).serverGames).toBe(false)
})
})
2 changes: 0 additions & 2 deletions src/api/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ const parseAccountInfo = (data: { [x: string]: string }) => {
clientId: clientId,
displayName: displayName,
lichessId: lichessId,
// A boolean in the answer, whatever the type above says.
serverGames: (data['server_games'] as unknown) === true,
}
}

Expand Down
104 changes: 0 additions & 104 deletions src/api/play.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ import {
fetchPlayPlayerStats,
MoveRequestError,
retryUnlessRejected,
startGame,
startGameWithRetry,
} from './play'

const respond = (status: number, body: unknown) => {
Expand Down Expand Up @@ -65,105 +63,3 @@ describe('fetchGameMove', () => {
expect(retryUnlessRejected(new TypeError('Failed to fetch'))).toBe(true)
})
})

const reply = (status: number, body: unknown) =>
Promise.resolve({
ok: status >= 200 && status < 300,
status,
json: () => Promise.resolve(body),
})

describe('startGame', () => {
const start = (retried = false) =>
(retried ? startGameWithRetry : startGame)(
'white',
'maia_kdd_600',
'play',
true,
'unlimited',
)

it("returns the new game's id", async () => {
respond(200, { game_id: 'abc', opponent_elo: 1500 })
await expect(start()).resolves.toEqual({
gameId: 'abc',
opponentElo: 1500,
})
})

it('throws, with the status, when the server fails', async () => {
respond(502, null)
const error = await start().catch((e) => e)
expect(error).toBeInstanceOf(MoveRequestError)
expect(error.status).toBe(502)
})

it('retries a dropped connection until the game starts', async () => {
const fetchMock = jest
.fn()
.mockRejectedValueOnce(new TypeError('Load failed'))
.mockReturnValueOnce(reply(503, null))
.mockReturnValueOnce(reply(200, { game_id: 'abc', opponent_elo: 1500 }))
global.fetch = fetchMock as unknown as typeof fetch

await expect(start(true)).resolves.toMatchObject({ gameId: 'abc' })
expect(fetchMock).toHaveBeenCalledTimes(3)
})

it('does not retry a request the server rejected', async () => {
// 401 twice: fetchAsGuest's retry after the account request, which
// answers 401 too (its body is not read).
const fetchMock = jest.fn().mockImplementation(() => reply(401, {}))
global.fetch = fetchMock as unknown as typeof fetch

const error = await start(true).catch((e) => e)
expect(error).toBeInstanceOf(MoveRequestError)
expect(error.status).toBe(401)
// start_game, the account request, start_game again: once only.
expect(fetchMock).toHaveBeenCalledTimes(3)
})
})

describe('fetchPlayPlayerStats', () => {
// play/get_player_stats (CSSLab/maia-platform-backend#293).
const STATS = {
play_games_played: 3,
hand_games_played: 40,
brain_games_played: 0,
play_won: 1,
play_drawn: 0,
hand_won: 22,
hand_drawn: 3,
brain_won: 0,
brain_drawn: 0,
play_elo: 1540,
hand_elo: 1610,
brain_elo: 1500,
}

it('reads whether each rating is provisional', async () => {
respond(200, {
...STATS,
play_provisional: true,
hand_provisional: false,
brain_provisional: true,
})
expect(await fetchPlayPlayerStats()).toMatchObject({
playElo: 1540,
playProvisional: true,
handElo: 1610,
handProvisional: false,
brainElo: 1500,
brainProvisional: true,
})
})

it('takes a rating as settled when the backend does not say', async () => {
respond(200, STATS)
expect(await fetchPlayPlayerStats()).toMatchObject({
playProvisional: false,
handProvisional: false,
brainProvisional: false,
})
})
})
158 changes: 3 additions & 155 deletions src/api/play.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { backOff } from 'exponential-backoff'
import { buildUrl } from './utils'
import { fetchAsGuest } from './guest'
import { Color, TimeControl } from 'src/types'

const normalizeOpeningBookFen = (fen: string) => {
const parts = fen.trim().split(/\s+/)
Expand All @@ -11,111 +10,6 @@ const normalizeOpeningBookFen = (fen: string) => {
return fen.trim()
}

export const startGame = async (
playerColor: Color,
maiaVersion: string,
gameType: 'play' | 'hand' | 'brain',
sampleMoves: boolean,
timeControl: TimeControl,
maiaPartnerVersion: string | undefined = undefined,
) => {
const params: Record<string, string> = maiaPartnerVersion
? {
maia_name: maiaVersion,
maia_friendly_name: maiaPartnerVersion,
player_color: playerColor,
game_type: gameType,
sample_moves: sampleMoves.toString(),
time_control: timeControl,
}
: {
maia_name: maiaVersion,
player_color: playerColor,
game_type: gameType,
sample_moves: sampleMoves.toString(),
time_control: timeControl,
}

const res = await fetchAsGuest(
buildUrl('play/start_game?' + new URLSearchParams(params)),
{
method: 'GET',
headers: {
Accept: 'application/json',
},
},
)

const data = await res.json().catch(() => null)
if (!res.ok || typeof data?.game_id !== 'string') {
// A 401 here: the guest cookie couldn't be set (see fetchAsGuest).
throw new MoveRequestError(res.status, `start_game: HTTP ${res.status}`)
}

return {
gameId: data['game_id'] as string,
opponentElo: data['opponent_elo'] as number,
}
}

/**
* startGame, retried a few times (a second or two in all) unless the server
* rejected the request: most failed starts fail at once, on phones, which is
* what a dropped connection looks like. Throws if it still fails.
*/
export const startGameWithRetry = (...args: Parameters<typeof startGame>) =>
backOff(() => startGame(...args), {
jitter: 'full',
numOfAttempts: 4,
retry: retryUnlessRejected,
})

// A game against Maia started by the setup dialog as the visitor chose a
// side, so that start_game runs while /play/maia loads and renders rather
// than after. /play/maia takes it if its settings match, or starts its own.
let earlyStart: {
key: string
response: ReturnType<typeof startGame>
} | null = null

export const startGameEarly = (
playerColor: Color,
maiaVersion: string,
sampleMoves: boolean,
timeControl: TimeControl,
) => {
const response = startGame(
playerColor,
maiaVersion,
'play',
sampleMoves,
timeControl,
)
response.catch(() => undefined)
earlyStart = {
key: JSON.stringify([playerColor, maiaVersion, sampleMoves, timeControl]),
response,
}
}

export const takeEarlyGame = (
playerColor: Color,
maiaVersion: string,
sampleMoves: boolean,
timeControl: TimeControl,
) => {
const key = JSON.stringify([
playerColor,
maiaVersion,
sampleMoves,
timeControl,
])
if (!earlyStart || earlyStart.key !== key) return null
const { response } = earlyStart
earlyStart = null
return response
}

export const fetchGameMove = async (
moves: string[],
maiaVersion = 'maia_kdd_1900',
Expand Down Expand Up @@ -161,7 +55,7 @@ export const fetchGameMove = async (
return body
}

/** The server answered, but not with a move (or a new game). */
/** The server answered, but not with what was asked for (a move, a game). */
export class MoveRequestError extends Error {
constructor(
readonly status: number,
Expand Down Expand Up @@ -218,41 +112,6 @@ export const fetchOpeningBookMoves = async (fen: string) => {
return res.json()
}

export const logGameMove = async (
gameId: string,
moves: string[],
moveTimes: number[],
gameOverState: 'not_over' | 'rules' | 'resign' | 'time',
gameType: 'play' | 'hand' | 'brain',
fen: string | undefined = undefined,
winner: string | undefined = undefined,
brainMoves: string[] = [],
// For a page being hidden or left: the request outlives the page.
{ keepalive = false }: { keepalive?: boolean } = {},
) => {
const res = await fetch(buildUrl('play/submit_move'), {
method: 'POST',
keepalive,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
game_id: gameId,
moves: moves,
game_over_state: gameOverState,
game_type: gameType,
move_times: moveTimes,
fen: fen,
brain_moves: brainMoves,

...(winner && winner !== 'none' ? { winner: winner } : {}),
}),
})

return res.json()
}

export const fetchPlayPlayerStats = async () => {
const res = await fetch(buildUrl('play/get_player_stats'))
const data = await res.json()
Expand All @@ -275,17 +134,6 @@ export const fetchPlayPlayerStats = async () => {
}
}

/**
* fetchGameMove, retried a few times (a few seconds in all) unless the server
* rejected the request. Throws if it still fails.
*/
export const fetchMaiaMove = (...args: Parameters<typeof fetchGameMove>) =>
backOff(() => fetchGameMove(...args), {
jitter: 'full',
numOfAttempts: 6,
retry: retryUnlessRejected,
})

/** How strong Maia felt for its rating. */
export type FeedbackStrength = 'too_weak' | 'about_right' | 'too_strong'

Expand All @@ -302,8 +150,8 @@ export interface GameFeedback {
/**
* Sends the player's feedback on a game (play/game_feedback). Each call sets
* what it sends and the server keeps the rest, so a rating is sent as soon as
* it is picked. Retried a little: the end of a game the browser runs may not
* have reached the server yet (a 409).
* it is picked. Retried a little, and again if the server says the game
* isn't over yet (a 409).
*/
export const sendGameFeedback = (gameId: string, feedback: GameFeedback) =>
backOff(
Expand Down
Loading
Loading