All files / app-leaderboard/src/scores submit.ts

95.94% Statements 71/74
84.31% Branches 43/51
100% Functions 17/17
95.89% Lines 70/73

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                                                                                                                                                                                      180x 180x 180x 3x   177x   177x   177x 177x 177x   1x   176x 2x             8x 8x             174x           174x 2x     172x 172x     172x       172x     172x 172x 688x 688x       688x 688x                 172x 172x 172x     172x     172x           172x 180x   688x           688x 688x 688x 688x 688x     688x   180x                                             688x       672x           672x                 180x   172x 688x       172x 4x                     168x       672x 672x       672x                           168x 168x         174x         20x                     20x                                       271x 271x                     688x                                               2x 2x   8x 4x         4x             4x 4x                         2x    
import { eq } from 'drizzle-orm';
import type { BatchItem } from 'drizzle-orm/batch';
import {
  checkReplayEligibility,
  findReplayNotSimulatedReason,
  rejudgeReplay,
  REPLAY_ENGINE_VERSION,
  resolveRulesetResultLamp,
  resolveRulesetResultMissCount,
  type BeMusicReplay,
  type ReplayNotSimulatedReason,
  type RulesetId,
  type ReplayRulesetResult,
  type ReplayUnrankedReason,
} from '@be-music/player-engine/replay';
import { refreshChartListing } from '../charts.ts';
import type { Database } from '../db/client.ts';
import { bestScore, score, scoreResult } from '../db/schema.ts';
import { rankOfExScore, countPlayers } from '../ranking.ts';
import { mergeBestScores } from '../scoring/best.ts';
import { applyRecordPolicyLamp, resolveReplayRecordPolicy } from '@be-music/player-engine/records';
import { clearLampRank } from '@be-music/player-engine/ruleset';
import { sha256HexAsync as sha256Hex } from '@be-music/shared-utils/hash';
import { playedFileOf } from './played-file.ts';
import { checkChartPlayOptions } from './chart-play-options.ts';
import { checkPlayedChart, gzipText, playedChartStatements, putChartDocument } from './played-chart.ts';
import { byRulesetOrder, RULESET_IDS } from '../rulesets.ts';
import { loadBestScores, toBestScoreRow } from './bests.ts';
 
export interface SubmissionInput {
  userId: string;
  replay: BeMusicReplay;
  /** The replay as stored (canonical JSON text). */
  replayText: string;
  playDocument: unknown;
  chartDocument?: unknown;
  /** The `Be-Music-Client` header of the request, if any. */
  submittedBy?: string;
}
 
export interface SubmissionDeps {
  db: Database;
  blobs: R2Bucket;
  now: () => number;
  newId: () => string;
}
 
export interface RulesetOutcome {
  ruleset: RulesetId;
  rulesetRevision: string;
  exScore: number;
  noteCount: number;
  /** The clear lamp, by its rank (`clearLampRank`). */
  clearLamp: number;
  missCount: number;
  rank: number;
  players: number;
  improved: { exScore: boolean; lamp: boolean; missCount: boolean };
  /**
   * `truncated` when the play stopped where its played gauge emptied and this ruleset's would have carried on: its
   * figures go only up to that point, unranked (ADR 0019). Absent for a play simulated in full.
   */
  outcome?: 'truncated';
}
 
/** A ruleset a play cannot be judged under, with the reason (ADR 0019): it has no figures. */
export interface NotSimulatedOutcome {
  ruleset: RulesetId;
  reason: ReplayNotSimulatedReason;
}
 
export type SubmissionOutcome =
  | {
      status: 'accepted' | 'duplicate';
      scoreId: string;
      chartFingerprint: string;
      results: RulesetOutcome[];
      /** The rulesets the play cannot be judged under; absent when it is judged under every one. */
      notSimulated?: NotSimulatedOutcome[];
      /** Why the play was stored without ranking it; its results then carry rank and players 0. */
      unranked?: ReplayUnrankedReason;
    }
  | { status: 'rejected'; httpStatus: 409 | 422; reason: string };
 
/**
 * Accepts one play (docs/leaderboard.md section 5). Rejections never write anything; an accepted play writes its
 * replay to R2 before the D1 batch, so a failed batch leaves only an unreferenced object. A play that does not rank
 * (another tempo, a course stage: `checkReplayEligibility`'s `unranked`) is stored and simulated all the same, but
 * moves no personal best and takes no place in a ranking (docs/leaderboard.md section 6).
 */
export async function submitScore(deps: SubmissionDeps, input: SubmissionInput): Promise<SubmissionOutcome> {
  const { db, blobs } = deps;
  const eligibility = checkReplayEligibility(input.replay);
  if (!eligibility.eligible) {
    return { status: 'rejected', httpStatus: 422, reason: eligibility.reason };
  }
  const { chartFingerprint, playFingerprint, assistFlags, assistClass, unranked } = eligibility;
  // A light or assist play ranks on the assisted board; a no-save play is stored unranked (#602).
  const assisted = assistClass !== 'none';
 
  const submissionId = await sha256Hex(identifyPlay(input.replay, playFingerprint));
  const existing = await db.query.score.findFirst({ where: eq(score.submissionId, submissionId) });
  if (existing !== undefined && existing.userId !== input.userId) {
    // The same inputs on the same chart from another account: a copied replay, not a play.
    return { status: 'rejected', httpStatus: 409, reason: 'play-already-submitted' };
  }
  if (existing !== undefined) {
    return {
      status: 'duplicate',
      scoreId: existing.id,
      chartFingerprint: existing.chartFingerprint,
      results: await loadOutcomes(db, existing.id, existing.chartFingerprint, existing.assisted, existing.unranked),
      ...notSimulatedOf(
        RULESET_IDS.flatMap((ruleset) => {
          const reason = findReplayNotSimulatedReason(input.replay, ruleset);
          return reason === undefined ? [] : [{ ruleset, reason }];
        }),
      ),
      ...(existing.unranked !== null ? { unranked: existing.unranked } : {}),
    };
  }
 
  const played = await checkPlayedChart(db, {
    chartFingerprint,
    playFingerprint,
    playDocument: input.playDocument,
    chartDocument: input.chartDocument,
  });
  if (!played.ok) {
    return { status: 'rejected', httpStatus: played.httpStatus, reason: played.reason };
  }
  // The chart's own gameplay options are part of the chart: the replay must record the ones its chart runs.
  const chartOptions = checkChartPlayOptions(input.replay, input.playDocument);
  Iif (!chartOptions.ok) {
    return { status: 'rejected', httpStatus: 422, reason: chartOptions.reason };
  }
  const { verification } = played;
 
  // A play given up with ESC did not clear, whatever its gauge stood at: it is ranked as a failed play, as LR2 and
  // beatoraja save one, its BP counting the notes it never reached.
  const givenUp = input.replay.play.aborted === true;
  // Each ruleset re-judges the play by ADR 0019's rules: one that cannot read it stores nothing, and one under which a
  // run that ended on failure would have survived stores its truncated figures, unranked.
  const notSimulated: NotSimulatedOutcome[] = [];
  const simulated = RULESET_IDS.flatMap((ruleset) => {
    const outcome = rejudgeReplay(input.replay, { ruleset });
    Iif (outcome.status === 'not-simulated') {
      notSimulated.push({ ruleset, reason: outcome.reason });
      return [];
    }
    const { result } = outcome;
    return [
      {
        ruleset,
        truncated: outcome.status === 'truncated',
        result: givenUp ? { ...result, gauge: { ...result.gauge, cleared: false } } : result,
      },
    ];
  });
 
  const now = deps.now();
  const scoreId = deps.newId();
  const replayKey = `replays/${scoreId}.bmplay.json.gz`;
  // The stored files and the current bests do not depend on each other: one wait for all of them. The play's rows are
  // written only once every file is stored, as before.
  const [currentBests] = await Promise.all([
    unranked === undefined ? loadBestScores(db, input.userId, chartFingerprint, assisted) : new Map(),
    gzipText(input.replayText).then((compressed) =>
      blobs.put(replayKey, compressed, {
        httpMetadata: { contentType: 'application/json', contentEncoding: 'gzip' },
      }),
    ),
    putChartDocument(blobs, played),
  ]);
  const playedRuleset = input.replay.play.judgeRuleset ?? 'lr2';
  const figures = simulated.map(({ ruleset, truncated, result }) => {
    // The lamp each ruleset gives the play, limited by its assisted options under that ruleset's rules (#602).
    const lamp = clearLampRank(
      applyRecordPolicyLamp(
        resolveRulesetResultLamp(result, ruleset),
        resolveReplayRecordPolicy(input.replay, ruleset),
      ),
    );
    const missCount = resolveRulesetResultMissCount(result);
    const current = currentBests.get(ruleset);
    const update = mergeBestScores(current, { scoreId, playedAt: now, exScore: result.exScore, lamp, missCount });
    const playedHere = (current?.playedHere ?? false) || playedRuleset === ruleset;
    return { ruleset, truncated, result, lamp, missCount, update, playedHere };
  });
  // A truncated result moves no personal best and takes no place in a ranking.
  const ranked = figures.filter(({ truncated }) => !truncated);
 
  const statements: BatchItem<'sqlite'>[] = [
    ...playedChartStatements(db, input.replay, played, now),
    db.insert(score).values({
      id: scoreId,
      submissionId,
      userId: input.userId,
      chartFingerprint,
      playFingerprint,
      ...playedFileOf(input.replay),
      playedRuleset,
      gauge: input.replay.play.gauge,
      assisted,
      assistFlags,
      verification,
      recordedBy: input.replay.recorder !== undefined ? { ...input.replay.recorder } : null,
      submittedBy: input.submittedBy ?? null,
      serverEngine: REPLAY_ENGINE_VERSION,
      replayKey,
      unranked: unranked ?? null,
      createdAt: new Date(now),
      updatedAt: new Date(now),
    }),
    ...figures.map(({ ruleset, truncated, result, lamp, missCount }) =>
      db.insert(scoreResult).values(toScoreResultRow(scoreId, ruleset, result, lamp, missCount, truncated)),
    ),
    // An unranked play moves no personal best.
    ...(unranked !== undefined ? [] : ranked).map(({ ruleset, update, playedHere }) => {
      const row = toBestScoreRow(
        { userId: input.userId, chartFingerprint, ruleset, assisted },
        update.next,
        playedHere,
        now,
      );
      return db
        .insert(bestScore)
        .values(row)
        .onConflictDoUpdate({
          target: [bestScore.userId, bestScore.chartFingerprint, bestScore.ruleset, bestScore.assisted],
          set: row,
        });
    }),
  ];
  await db.batch(statements as [BatchItem<'sqlite'>, ...BatchItem<'sqlite'>[]]);
  // The results that take no place in a ranking: every one of an unranked play, and the truncated ones.
  const unrankedOutcomes = figures.flatMap(({ ruleset, truncated, result, lamp, missCount }) =>
    truncated || unranked !== undefined
      ? [{ ...unrankedOutcome(ruleset, result.ruleset, result, lamp, missCount), ...outcomeOf(truncated) }]
      : [],
  );
  if (unranked !== undefined) {
    return {
      status: 'accepted',
      scoreId,
      chartFingerprint,
      results: unrankedOutcomes,
      ...notSimulatedOf(notSimulated),
      unranked,
    };
  }
 
  // The listing and each ruleset's rank and player count read the rows just written and not each other: asked at once.
  const [, rankedOutcomes] = await Promise.all([
    refreshChartListing(db, chartFingerprint),
    Promise.all(
      ranked.map(async ({ ruleset, result, lamp, missCount, update }): Promise<RulesetOutcome> => {
        const filter = { chartFingerprint, ruleset, assisted, includeAnonymous: true, playedHereOnly: false };
        const [rank, players] = await Promise.all([
          rankOfExScore(db, filter, update.next.bestEx),
          countPlayers(db, filter),
        ]);
        return {
          ruleset,
          rulesetRevision: result.ruleset,
          exScore: result.exScore,
          noteCount: result.noteCount,
          clearLamp: lamp,
          missCount,
          rank,
          players,
          improved: update.improved,
        };
      }),
    ),
  ]);
  const results = [...rankedOutcomes, ...unrankedOutcomes].sort(byRulesetOrder);
  return { status: 'accepted', scoreId, chartFingerprint, results, ...notSimulatedOf(notSimulated) };
}
 
/** The `notSimulated` field of an outcome: absent when every ruleset judged the play. */
function notSimulatedOf(notSimulated: NotSimulatedOutcome[]): { notSimulated?: NotSimulatedOutcome[] } {
  return notSimulated.length > 0 ? { notSimulated } : {};
}
 
/** The `outcome` field of a result: absent for a play simulated in full. */
function outcomeOf(truncated: boolean): { outcome?: 'truncated' } {
  return truncated ? { outcome: 'truncated' } : {};
}
 
/** The outcome of an unranked play under one ruleset: its figures, with no rank, players or best moved. */
function unrankedOutcome(
  ruleset: RulesetId,
  rulesetRevision: string,
  figures: { exScore: number; noteCount: number },
  clearLamp: number,
  missCount: number,
): RulesetOutcome {
  return {
    ruleset,
    rulesetRevision,
    exScore: figures.exScore,
    noteCount: figures.noteCount,
    clearLamp,
    missCount,
    rank: 0,
    players: 0,
    improved: { exScore: false, lamp: false, missCount: false },
  };
}
 
/**
 * What identifies a play regardless of who recorded it or when: the chart that was played, the play settings that
 * affect scoring, and the input stream. Its hash is the submission id, so a retry of the same play is recognised, and
 * the same play submitted from a second account (a downloaded replay) is refused. Recording time, the recorder and the
 * host's `native` extras are left out.
 */
export function identifyPlay(replay: BeMusicReplay, playFingerprint: string): string {
  const { native: _native, ...play } = replay.play;
  return JSON.stringify({ playFingerprint, play, inputs: replay.inputs });
}
 
function toScoreResultRow(
  scoreId: string,
  ruleset: RulesetId,
  result: ReplayRulesetResult,
  lamp: number,
  missCount: number,
  truncated: boolean,
): typeof scoreResult.$inferInsert {
  return {
    scoreId,
    ruleset,
    rulesetRevision: result.ruleset,
    exScore: result.exScore,
    noteCount: result.noteCount,
    clearLamp: lamp,
    missCount,
    maxCombo: result.maxCombo,
    gaugeType: result.gauge.type,
    gaugeFinal: result.gauge.final,
    judges: { ...result.judge, fast: result.fast, slow: result.slow },
    outcome: truncated ? 'truncated' : null,
  };
}
 
/** The outcome of an already stored play, for a resubmission. Ranks reflect the current standings. */
async function loadOutcomes(
  db: Database,
  scoreId: string,
  chartFingerprint: string,
  assisted: boolean,
  unranked: string | null,
): Promise<RulesetOutcome[]> {
  const rows = await db.select().from(scoreResult).where(eq(scoreResult.scoreId, scoreId));
  const outcomes = await Promise.all(
    rows.map(async (row): Promise<RulesetOutcome> => {
      if (unranked !== null || row.outcome !== null) {
        return {
          ...unrankedOutcome(row.ruleset, row.rulesetRevision, row, row.clearLamp, row.missCount),
          ...outcomeOf(row.outcome === 'truncated'),
        };
      }
      const filter = {
        chartFingerprint,
        ruleset: row.ruleset,
        assisted,
        includeAnonymous: true,
        playedHereOnly: false,
      };
      const [rank, players] = await Promise.all([rankOfExScore(db, filter, row.exScore), countPlayers(db, filter)]);
      return {
        ruleset: row.ruleset,
        rulesetRevision: row.rulesetRevision,
        exScore: row.exScore,
        noteCount: row.noteCount,
        clearLamp: row.clearLamp,
        missCount: row.missCount,
        rank,
        players,
        improved: { exScore: false, lamp: false, missCount: false },
      };
    }),
  );
  return outcomes.sort(byRulesetOrder);
}