All files / app-play/src leaderboard.ts

92.08% Statements 128/139
83.46% Branches 106/127
87.5% Functions 28/32
96.46% Lines 109/113

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455                                                                                                    7x 7x 2x   5x 5x 4x                         10x     10x 10x 10x 10x       2x   8x                                                                                                   3x         3x 2x 1x           1x   1x                           4x 4x 4x     4x 3x 3x 4x 2x 2x   1x                             4x 4x 4x   1x 4x 2x     2x 2x 2x 3x 2x   1x                       4x 4x 4x 4x   3x 5x                     3x 3x 2x   1x                                                               8x 8x 2x   6x 6x 6x 6x 6x 11x 11x 11x 5x           5x 4x 4x   6x 1x   5x 5x   4x                       16x 16x                                                                 2x   2x           1x 1x 1x           1x             3x 2x                       12x 10x   10x 2x                         12x 12x 12x   9x   12x 9x       27x 12x   12x 12x 12x     12x 12x         3x 3x         4x             5x       5x 5x       4x 4x 4x               1x 1x    
import type { LibraryChart } from '@be-music/player-scene-model';
import { leaderboardLink } from './service-links.ts';
import type { RankingPage } from './services/ranking-target.ts';
import { playerText } from './player-copy.ts';
import {
  computeChartFingerprint,
  computeFingerprintOfDocument,
  createChartFingerprintDocument,
  createPlayFingerprintDocument,
  hasControlFlow,
  isPMSChartPath,
  type BeMusicFingerprintDocument,
} from '@be-music/chart-model';
import type { BeMusicJSON } from '@be-music/chart-source';
import { resolveBMSControlFlowWithDraws } from '@be-music/chart-parser/core';
import {
  checkCourseReplayEligibility,
  checkReplayEligibility,
  resolveCourseStageChartFingerprints,
  type BeMusicCourseReplay,
  type BeMusicReplay,
  parseReplay,
  type CourseReplayIneligibleReason,
  type RulesetId,
} from '@be-music/player-engine/replay';
 
/** What the Leaderboard API needs for one play (docs/leaderboard.md section 5.1). */
export interface LeaderboardSubmission {
  replay: BeMusicReplay;
  playDocument: BeMusicFingerprintDocument;
  chartDocument: BeMusicFingerprintDocument;
}
 
export type SubmissionPreparation =
  | { ok: true; submission: LeaderboardSubmission }
  | { ok: false; reason: 'auto-play' | 'two-player' | 'missing-fingerprint' | 'fingerprint-mismatch' };
 
/**
 * Builds the submission of a finished play from its replay and the song's chart as loaded. The play document is
 * rebuilt the way the recorder fingerprinted the play (the source chart resolved with the log's `#RANDOM` / `#SWITCH`
 * draws, the chart path as the lane-mode input), then checked against the log's play fingerprint, so a play the server would
 * reject as a mismatch is never sent. Only auto plays and logs without fingerprints are skipped here: a play the
 * Leaderboard does not rank (another tempo) is still sent, and the Leaderboard decides what it shows.
 */
export function prepareLeaderboardSubmission(
  replay: BeMusicReplay,
  sourceChart: BeMusicJSON,
  chartPath: string | undefined,
): SubmissionPreparation {
  // The server applies the same check (`checkReplayEligibility`); it ranks assists apart and stores unranked plays.
  const eligibility = checkReplayEligibility(replay);
  if (!eligibility.eligible) {
    return { ok: false, reason: eligibility.reason };
  }
  const documents = rebuildDocuments(replay, sourceChart, chartPath, eligibility);
  if (documents === undefined) return { ok: false, reason: 'fingerprint-mismatch' };
  return { ok: true, submission: { replay, ...documents } };
}
 
/**
 * Both fingerprint documents of a play, rebuilt from the source chart as the recorder fingerprinted it, or `undefined`
 * when they would not hash to the replay's fingerprints.
 */
function rebuildDocuments(
  replay: BeMusicReplay,
  sourceChart: BeMusicJSON,
  chartPath: string | undefined,
  fingerprints: { chartFingerprint: string; playFingerprint: string },
): { playDocument: BeMusicFingerprintDocument; chartDocument: BeMusicFingerprintDocument } | undefined {
  const playedChart = hasControlFlow(sourceChart)
    ? resolveBMSControlFlowWithDraws(sourceChart, replay.play.randomDraws ?? [])
    : sourceChart;
  const options = { chartPath };
  const playDocument = createPlayFingerprintDocument(playedChart, options);
  const chartDocument = createChartFingerprintDocument(sourceChart, options);
  if (
    computeFingerprintOfDocument(playDocument) !== fingerprints.playFingerprint ||
    computeFingerprintOfDocument(chartDocument) !== fingerprints.chartFingerprint
  ) {
    return undefined;
  }
  return { playDocument, chartDocument };
}
 
/** The API's answer for one ruleset (`RulesetOutcome` in `@be-music/app-leaderboard`). */
export interface LeaderboardRulesetResult {
  ruleset: RulesetId;
  exScore: number;
  clearLamp: number;
  missCount: number;
  /** 0 for a play the Leaderboard stores but does not rank. */
  rank: number;
  players: number;
  improved: { exScore: boolean; lamp: boolean; missCount: boolean };
  /** `truncated`: judged only up to where the play stopped on failure, unranked (ADR 0019). */
  outcome?: 'truncated';
}
 
/** A ruleset the Leaderboard cannot judge the play under (`NotSimulatedOutcome` in `@be-music/app-leaderboard`). */
export interface LeaderboardNotSimulated {
  ruleset: RulesetId;
  reason: string;
}
 
export type LeaderboardSubmitResult =
  | {
      status: 'accepted' | 'duplicate';
      scoreId: string;
      results: LeaderboardRulesetResult[];
      /** The rulesets the Leaderboard cannot judge the play under. */
      notSimulated?: LeaderboardNotSimulated[];
      /** Why the Leaderboard stored the play without ranking it (`tempo`, `course-stage`, ...). */
      unranked?: string;
    }
  | { status: 'failed'; httpStatus: number; error: string };
 
export interface LeaderboardClientOptions {
  /** Defaults to the global `fetch`. Requests are same-origin, so the session cookie rides along. */
  fetch?: typeof fetch;
  /** Sent as `Be-Music-Client` (docs/leaderboard.md section 5.1). */
  client?: string;
}
 
/**
 * Sends one play to the Leaderboard: requires an Accounts session, posts the replay gzipped
 * with its play document, and resends with the chart document when the server does not know the chart (409).
 */
export async function submitToLeaderboard(
  submission: LeaderboardSubmission,
  options: LeaderboardClientOptions = {},
): Promise<LeaderboardSubmitResult> {
  const response = await postWithChartDocuments('/api/v0/scores', options, (withChartDocument) => ({
    replay: submission.replay,
    playDocument: submission.playDocument,
    ...(withChartDocument ? { chartDocument: submission.chartDocument } : {}),
  }));
  if (!(response instanceof Response)) return response;
  if (response.status === 201 || response.status === 200) {
    const body = (await response.json()) as {
      scoreId: string;
      results: LeaderboardRulesetResult[];
      notSimulated?: LeaderboardNotSimulated[];
      unranked?: string;
    };
    return { status: response.status === 201 ? 'accepted' : 'duplicate', ...body };
  }
  return { status: 'failed', httpStatus: response.status, error: (await readError(response)) ?? 'unknown' };
}
 
/**
 * Fetches the replay of the top run on a chart's Leaderboard ranking under `ruleset` (unassisted plays): the ranking's
 * first entry (`GET /api/v0/charts/:chartFingerprint/leaderboard?limit=1`), then the replay of the score that set it
 * (`GET /api/v0/scores/:id/replay`, gzip-compressed on the wire). `undefined` when the chart has no ranked run or its
 * replay cannot be read; a replay ghost then plays without one. No session is needed for a public replay.
 */
export async function fetchLeaderboardTopReplay(
  chartFingerprint: string,
  ruleset: RulesetId,
  options: Pick<LeaderboardClientOptions, 'fetch'> = {},
): Promise<BeMusicReplay | undefined> {
  const doFetch = options.fetch ?? fetch.bind(globalThis);
  const query = new URLSearchParams({ ruleset, limit: '1' });
  const ranking = await doFetch(`/api/v0/charts/${encodeURIComponent(chartFingerprint)}/leaderboard?${query}`, {
    credentials: 'same-origin',
  });
  if (!ranking.ok) return undefined;
  const body = (await ranking.json().catch(() => undefined)) as { entries?: { exScoreId?: unknown }[] } | undefined;
  const scoreId = body?.entries?.[0]?.exScoreId;
  if (typeof scoreId !== 'string' || scoreId.length === 0) return undefined;
  const replay = await doFetch(`/api/v0/scores/${encodeURIComponent(scoreId)}/replay`, { credentials: 'same-origin' });
  if (!replay.ok) return undefined;
  // The browser undoes the `content-encoding: gzip` the replay is served with.
  return parseReplay(await replay.text());
}
 
/**
 * Reads a stretch of a chart's Leaderboard ranking under `ruleset` (unassisted plays): the EX scores from `offset`,
 * best first, and the ranking's player count (`GET /api/v0/charts/:chartFingerprint/leaderboard`). `undefined` when
 * the ranking cannot be read. No session is needed.
 */
export async function fetchLeaderboardRankingPage(
  chartFingerprint: string,
  ruleset: RulesetId,
  offset: number,
  limit: number,
  options: Pick<LeaderboardClientOptions, 'fetch'> = {},
): Promise<RankingPage | undefined> {
  const doFetch = options.fetch ?? fetch.bind(globalThis);
  const query = new URLSearchParams({ ruleset, offset: String(offset), limit: String(limit) });
  const response = await doFetch(`/api/v0/charts/${encodeURIComponent(chartFingerprint)}/leaderboard?${query}`, {
    credentials: 'same-origin',
  }).catch(() => undefined);
  if (response === undefined || !response.ok) return undefined;
  const body = (await response.json().catch(() => undefined)) as
    | { entries?: { exScore?: unknown }[]; players?: unknown }
    | undefined;
  Iif (!Array.isArray(body?.entries) || typeof body.players !== 'number') return undefined;
  const exScores: number[] = [];
  for (const entry of body.entries) {
    if (typeof entry.exScore !== 'number') return undefined;
    exScores.push(entry.exScore);
  }
  return { exScores, players: body.players };
}
 
/**
 * Requires a session, posts `body(false)` gzipped, and resends `body(true)` (with
 * the chart documents) when the server does not know a chart (409 `chart-document-required`).
 */
async function postWithChartDocuments(
  path: string,
  options: LeaderboardClientOptions,
  body: (withChartDocuments: boolean) => unknown,
): Promise<Response | { status: 'failed'; httpStatus: number; error: string }> {
  const doFetch = options.fetch ?? fetch.bind(globalThis);
  const session = await doFetch('/api/auth/get-session', { credentials: 'same-origin' });
  const signedIn = session.ok && (await session.json().catch(() => null)) !== null;
  if (!signedIn) return { status: 'failed', httpStatus: 401, error: 'sign-in-required' };
 
  const post = async (withChartDocuments: boolean): Promise<Response> =>
    doFetch(path, {
      method: 'POST',
      credentials: 'same-origin',
      headers: {
        'content-type': 'application/json',
        'content-encoding': 'gzip',
        ...(options.client !== undefined ? { 'be-music-client': options.client } : {}),
      },
      body: await gzipJSON(body(withChartDocuments)),
    });
 
  const response = await post(false);
  if (response.status === 409 && (await readError(response.clone())) === 'chart-document-required') {
    return await post(true);
  }
  return response;
}
 
/**
 * What the Leaderboard API needs for one course run: the course replay, each played stage's documents, and the charts
 * of the stages the server rebuilds (every unreached stage, and every stage of a NONSTOP run).
 */
export interface CourseLeaderboardSubmission {
  courseReplay: BeMusicCourseReplay;
  /** One entry per played stage; none for a NONSTOP run. */
  stages: Array<{ playDocument: BeMusicFingerprintDocument; chartDocument: BeMusicFingerprintDocument }>;
  stageCharts: Array<{ stage: number; chart: BeMusicJSON; pms?: boolean }>;
}
 
export type CourseSubmissionPreparation =
  | { ok: true; submission: CourseLeaderboardSubmission }
  | { ok: false; reason: CourseReplayIneligibleReason | 'fingerprint-mismatch' };
 
/**
 * Builds the submission of a finished course run: the course replay, with the fingerprint documents of each played
 * stage rebuilt from the stage's chart as the course played it (`stageCharts`, one per course stage, in order) and
 * checked like a single play's, and the chart of each stage the server rebuilds itself: every stage the run never
 * reached (the server checks the notes they count as BP), and every stage of a NONSTOP run (the server stitches them
 * again; a NONSTOP run sends no documents). Each such chart must hash to the chart fingerprint the log names for its
 * stage. Runs the server would refuse outright (auto play, an aborted stage, a stage chart without its fingerprint) are
 * skipped here (`checkCourseReplayEligibility`); a run the Leaderboard stores without ranking (another tempo, an
 * unreleased course) is sent.
 */
export function prepareCourseLeaderboardSubmission(
  courseReplay: BeMusicCourseReplay,
  stageCharts: ReadonlyArray<{ chart: BeMusicJSON; chartPath: string | undefined }>,
): CourseSubmissionPreparation {
  const eligibility = checkCourseReplayEligibility(courseReplay);
  if (!eligibility.eligible) {
    return { ok: false, reason: eligibility.reason };
  }
  const nonstop = eligibility.nonstop !== undefined;
  const stages: CourseLeaderboardSubmission['stages'] = [];
  const rebuilt: CourseLeaderboardSubmission['stageCharts'] = [];
  const chartFingerprints = resolveCourseStageChartFingerprints(courseReplay);
  for (const [index, entry] of courseReplay.stages.entries()) {
    const stageChart = stageCharts[index];
    Iif (stageChart === undefined) return { ok: false, reason: 'fingerprint-mismatch' };
    if (entry.played && !nonstop) {
      const documents = rebuildDocuments(
        entry.replay,
        stageChart.chart,
        stageChart.chartPath,
        eligibility.stages[index]!,
      );
      if (documents === undefined) return { ok: false, reason: 'fingerprint-mismatch' };
      stages.push(documents);
      continue;
    }
    if (courseStageChartFingerprint(stageChart) !== chartFingerprints[index]) {
      return { ok: false, reason: 'fingerprint-mismatch' };
    }
    const pms = isPMSChartPath(stageChart.chartPath);
    rebuilt.push({ stage: index, chart: stageChart.chart, ...(pms ? { pms } : {}) });
  }
  return { ok: true, submission: { courseReplay, stages, stageCharts: rebuilt } };
}
 
/**
 * The chart fingerprint of a course stage's chart, as the recorder would record it had the stage been played (the
 * chart as the course plays it, the chart path as the lane-mode input). It keys an unreached stage of a course play
 * log; `undefined` when the chart cannot be fingerprinted.
 */
export function courseStageChartFingerprint(stage: {
  chart: BeMusicJSON;
  chartPath: string | undefined;
}): string | undefined {
  try {
    return computeChartFingerprint(stage.chart, { chartPath: stage.chartPath });
  } catch {
    return undefined;
  }
}
 
/** The API's answer for one ruleset of a course run (`CourseRulesetOutcome` in `@be-music/app-leaderboard`). */
export interface CourseLeaderboardRulesetResult extends LeaderboardRulesetResult {
  stagesPlayed: number;
  trophy: string | null;
}
 
export type CourseLeaderboardSubmitResult =
  | {
      status: 'accepted' | 'duplicate';
      courseScoreId: string;
      results: CourseLeaderboardRulesetResult[];
      /** The rulesets the Leaderboard cannot judge the run under. */
      notSimulated?: LeaderboardNotSimulated[];
      /** Why the Leaderboard stored the run without ranking it (`tempo`, `unreleased`). */
      unranked?: string;
    }
  | { status: 'failed'; httpStatus: number; error: string };
 
/**
 * Sends one course run to the Leaderboard (`POST /api/v0/course-scores`), using the existing Accounts session and
 * resending with every stage's chart document when the server does not know a stage chart. The stage charts the server
 * rebuilds go with every request.
 */
export async function submitCourseToLeaderboard(
  submission: CourseLeaderboardSubmission,
  options: LeaderboardClientOptions = {},
): Promise<CourseLeaderboardSubmitResult> {
  const response = await postWithChartDocuments('/api/v0/course-scores', options, (withChartDocuments) => ({
    courseReplay: submission.courseReplay,
    stages: submission.stages.map((stage) => ({
      playDocument: stage.playDocument,
      ...(withChartDocuments ? { chartDocument: stage.chartDocument } : {}),
    })),
    stageCharts: submission.stageCharts,
  }));
  Iif (!(response instanceof Response)) return response;
  Eif (response.status === 201 || response.status === 200) {
    const body = (await response.json()) as {
      courseScoreId: string;
      results: CourseLeaderboardRulesetResult[];
      notSimulated?: LeaderboardNotSimulated[];
      unranked?: string;
    };
    return { status: response.status === 201 ? 'accepted' : 'duplicate', ...body };
  }
  return { status: 'failed', httpStatus: response.status, error: (await readError(response)) ?? 'unknown' };
}
 
/** {@link describeLeaderboardResult} for a course run: the course rank under the ruleset the run was played with. */
export function describeCourseLeaderboardResult(result: CourseLeaderboardSubmitResult, playedRuleset: string): string {
  if (result.status === 'failed') return playerText().lb.courseNotSubmitted(result.error);
  return describeRankedResult(result, playedRuleset, true);
}
 
/**
 * One status-line summary of a submission, for the ruleset the play was judged under: rank, players, EX score, and
 * which personal bests it improved.
 */
export function describeLeaderboardResult(
  result: LeaderboardSubmitResult,
  playedRuleset: string,
  board?: 'main' | 'assisted' | 'unranked',
): string {
  if (result.status === 'failed') return playerText().lb.notSubmitted(result.error);
  const line = describeRankedResult(result, playedRuleset, false);
  // A ranked play names the board it is ranked on; a stored one already says it is not ranked.
  if (result.unranked !== undefined || board === undefined || board === 'unranked') return line;
  return `${line} ยท ${playerText().record.board[board]}`;
}
 
function describeRankedResult(
  result: {
    status: 'accepted' | 'duplicate';
    results: readonly LeaderboardRulesetResult[];
    notSimulated?: readonly LeaderboardNotSimulated[];
    unranked?: string;
  },
  playedRuleset: string,
  course: boolean,
): string {
  const copy = playerText().lb;
  const again = result.status === 'duplicate' ? copy.already : '';
  if (result.unranked !== undefined) return copy.stored(describeUnranked(result.unranked), again);
  const mine =
    result.results.find((entry) => entry.ruleset === playedRuleset) ??
    result.results.find((entry) => entry.outcome === undefined);
  Iif (mine === undefined) return copy.submitted;
  const improved = [
    mine.improved.exScore ? 'EX' : undefined,
    mine.improved.lamp ? copy.lamp : undefined,
    mine.improved.missCount ? 'BP' : undefined,
  ].filter((part) => part !== undefined);
  const best = result.status === 'accepted' && improved.length > 0 ? copy.newBest(improved.join(' / ')) : '';
  // The other rulesets that could not judge the play in full (ADR 0019): a skipped judgment must never pass silently.
  const truncated = result.results.filter((entry) => entry.outcome === 'truncated').map((entry) => entry.ruleset);
  const notSimulated = (result.notSimulated ?? []).map((entry) => entry.ruleset);
  const others =
    (truncated.length > 0 ? copy.truncated(truncated.join(', ')) : '') +
    (notSimulated.length > 0 ? copy.notSimulated(notSimulated.join(', ')) : '');
  const line = course ? copy.courseRanked : copy.ranked;
  return line(mine.ruleset, mine.rank, mine.players, mine.exScore, best + others, again);
}
 
/** Why the Leaderboard stored a play without ranking it, for the status line. */
function describeUnranked(reason: string): string {
  const reasons = playerText().lb.unranked;
  return reason in reasons ? reasons[reason as keyof typeof reasons] : reason;
}
 
/** Why a play was not sent, for the status line (a skipped play must never pass silently). */
export function describeSkippedSubmission(reason: Exclude<SubmissionPreparation, { ok: true }>['reason']): string {
  return playerText().lb.skipped[reason];
}
 
/** Why a course run was not sent, for the status line. */
export function describeSkippedCourseSubmission(
  reason: Exclude<CourseSubmissionPreparation, { ok: true }>['reason'],
): string {
  return playerText().lb.courseSkipped[reason];
}
 
async function gzipJSON(value: unknown): Promise<Blob> {
  const stream = new Blob([JSON.stringify(value)]).stream().pipeThrough(new CompressionStream('gzip'));
  return await new Response(stream).blob();
}
 
async function readError(response: Response): Promise<string | undefined> {
  try {
    const body = (await response.json()) as { error?: unknown };
    return typeof body.error === 'string' ? body.error : undefined;
  } catch {
    return undefined;
  }
}
 
/** The Leaderboard page of `chart`'s ranking (`/charts/:chartFingerprint`), LR2's IR page for it. */
export function chartRankingURL(chart: Pick<LibraryChart, 'chart' | 'chartPath'>, hostname: string): string {
  const fingerprint = computeChartFingerprint(chart.chart, { chartPath: chart.chartPath });
  return leaderboardLink(`/charts/${encodeURIComponent(fingerprint)}`, hostname);
}