All files / app-play/src/services records.ts

97.18% Statements 69/71
95.23% Branches 40/42
93.75% Functions 15/16
96.92% Lines 63/65

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                                                                                        27x   27x                           27x   27x         27x 27x                   15x 15x 13x 13x 3x   10x 10x 3x   7x     7x 7x   7x 7x 7x         2x                 7x 1x   6x 2x   6x                 16x     16x 16x             4x               7x 7x 7x               1x 1x 1x                         6x 6x 5x 6x 6x 6x 6x               4x 4x 4x 2x 1x 1x                     3x 2x 2x 2x 2x                   5x 4x 4x 4x 4x         4x 4x 4x   4x      
// The player's best records and the chart hashes they are keyed by: each chart's SHA-256 and MD5, hashed once per chart,
// and the record keys of the play in flight, latched as it takes the stage. `chart-best-records.ts` keys and stores the
// records; `@be-music/player-engine/records` says how a play merges into them.
 
import {
  computeChartFileHashes,
  resolveChartSource,
  seededChartFileHashes,
  type BrowserChartCollection,
  type ChartFileHashes,
} from '@be-music/player-browser/collection';
import {
  mergeBestRecord,
  mergeCourseStageRecord,
  resolveReplayRecordPolicy,
  type AssistReplay,
  type BestRecord,
  type DanRank,
  type RecordPlay,
} from '@be-music/player-engine/records';
import type { RulesetId } from '@be-music/player-engine/ruleset';
import type { LibraryChart } from '@be-music/player-scene-model';
import type { BeMusicChartBestRecord, BeMusicDanRank } from '@be-music/player-skin-sdk';
import {
  readStoredChartBestRecords,
  recordKeyRuleset,
  rulesetRecordKey,
  slotRecordKey,
  rulesetRecords,
  chartBestRecordKey,
  storeChartBestRecords,
} from '../chart-best-records.ts';
import { listDanRanks, mergeDanRank, readStoredDanRanks, storeDanRanks } from '../dan-ranks.ts';
 
export interface RecordsServiceOptions {
  /** The library the charts are hashed from: the sources their files are in. */
  readonly collection: () => BrowserChartCollection;
  /** The judge ruleset whose records the select screen shows (Options dialog → Judgment windows). */
  readonly judgeRuleset: () => RulesetId;
}
 
/** The best records, kept per chart and course and judge ruleset, and the chart-file hashes they are keyed by. */
export class RecordsService {
  /** Best record per chart ({@link chartBestRecordKey}), persisted in `localStorage` and shown to Be-Music select skins. */
  public readonly chartBestRecords: Map<string, BestRecord> = readStoredChartBestRecords();
  /** The highest dan cleared per judge ruleset and key mode (`danRankKey`), persisted in `localStorage`. */
  public readonly danRanks: Map<string, DanRank> = readStoredDanRanks();
  /** {@link currentDanRanks}'s answer, kept until a rank changes or the judge ruleset does. */
  private danRankList: { ruleset: RulesetId; list: readonly BeMusicDanRank[] } | undefined;
  /**
   * Record key of the play in flight when it counts towards the chart's best record, latched at song start. `undefined`
   * for autoplay and replay plays, which never touch the records.
   */
  public activePlayRecordKey: string | undefined;
  /**
   * Record key of the running EXPERT / GRADE course stage's chart, latched at stage start ({@link courseStageRecordKey}):
   * as LR2 does, the stage also updates that chart's best EX score, max combo, BP and FULL COMBO lamp.
   */
  public activeStageRecordKey: string | undefined;
  /** Per-entry chart-file hash cache (`null` = lookup failed) — see {@link resolveChartHashes}. */
  private readonly chartHashCache = new Map<string, ChartFileHashes | null>();
  /** In-flight {@link resolveChartHashes} lookups, so a chart is hashed once however often it is asked for. */
  private readonly chartHashPending = new Map<string, Promise<ChartFileHashes | undefined>>();
  private readonly collection: () => BrowserChartCollection;
  private readonly judgeRuleset: () => RulesetId;
 
  public constructor(options: RecordsServiceOptions) {
    this.collection = options.collection;
    this.judgeRuleset = options.judgeRuleset;
  }
 
  /**
   * SHA-256 and MD5 (lowercase hex) of a song's source chart file, cached per entry id — the hashes feed the replay
   * recording (`chart.sha256` / `chart.md5`) and dropped-log matching, and chart files are small enough that hashing
   * the whole library on a dropped log stays cheap.
   */
  public async resolveChartHashes(chartEntry: LibraryChart): Promise<ChartFileHashes | undefined> {
    // The hashes the load kept with the chart, when it hashed the file or took its parse from the cache.
    const seeded = seededChartFileHashes(chartEntry.chart);
    if (seeded !== undefined) return seeded;
    const cached = this.chartHashCache.get(chartEntry.id);
    if (cached !== undefined) {
      return cached ?? undefined;
    }
    const pending = this.chartHashPending.get(chartEntry.id);
    if (pending !== undefined) {
      return pending;
    }
    const lookup = computeChartFileHashes(resolveChartSource(this.collection(), chartEntry), chartEntry.chartPath)
      .catch(() => undefined)
      .then((hashes) => {
        this.chartHashCache.set(chartEntry.id, hashes ?? null);
        return hashes;
      })
      .finally(() => this.chartHashPending.delete(chartEntry.id));
    this.chartHashPending.set(chartEntry.id, lookup);
    return lookup;
  }
 
  /** The SHA-256 half of {@link resolveChartHashes}. */
  public async resolveChartSHA256(chartEntry: LibraryChart): Promise<string | undefined> {
    return (await this.resolveChartHashes(chartEntry))?.sha256;
  }
 
  /**
   * A chart's best record for the select skin's `frame.chartBestRecord`. Records are keyed by chart hash, which is only known
   * once the chart has been hashed: the first lookup starts hashing it and answers from the path key meanwhile (where a
   * chart that could not be hashed keeps its record), so a skin sees the record a frame or two later.
   */
  public lookupChartBestRecord(chartEntry: LibraryChart): BeMusicChartBestRecord | undefined {
    if (this.chartBestRecords.size === 0) {
      return undefined;
    }
    if (seededChartFileHashes(chartEntry.chart) === undefined && !this.chartHashCache.has(chartEntry.id)) {
      void this.resolveChartHashes(chartEntry);
    }
    return this.peekChartBestRecord(chartEntry);
  }
 
  /**
   * A chart's best record as far as its hash is known already, without hashing it: by its hash once it is known (kept
   * with the chart by its load, or hashed by {@link lookupChartBestRecord} or {@link resolveChartHashes}), by its path
   * before. For readers that must start nothing, such as the test hook.
   */
  public peekChartBestRecord(chartEntry: LibraryChart): BeMusicChartBestRecord | undefined {
    Iif (this.chartBestRecords.size === 0) {
      return undefined;
    }
    const hashes = seededChartFileHashes(chartEntry.chart) ?? this.chartHashCache.get(chartEntry.id);
    return this.chartBestRecords.get(
      rulesetRecordKey(this.judgeRuleset(), chartBestRecordKey(chartEntry, hashes?.sha256)),
    );
  }
 
  /** The best records of the current judge ruleset, by chart or course key: the ones the select screen shows. */
  public currentRulesetRecords(): { get(key: string): BeMusicChartBestRecord | undefined } {
    return rulesetRecords(this.chartBestRecords, this.judgeRuleset());
  }
 
  /**
   * Records the running play's result under its chart, when the play counts ({@link playRecordKey}). Returns the record
   * as it was before the play (`previous`, absent for a first play), or `undefined` when the play did not count.
   */
  public recordActivePlay(play: RecordPlay, replay?: AssistReplay): { previous: BestRecord | undefined } | undefined {
    const key = this.activePlayRecordKey;
    this.activePlayRecordKey = undefined;
    return key === undefined ? undefined : this.recordPlayUnder(key, play, replay);
  }
 
  /**
   * Takes the record key of the play in flight, for a play whose replay comes later (one given up with ESC): pass it to
   * {@link recordPlayUnder} once the replay is there.
   */
  public takeActivePlayRecordKey(): string | undefined {
    const key = this.activePlayRecordKey;
    this.activePlayRecordKey = undefined;
    return key;
  }
 
  /**
   * Records a play under `key` by its record policy (`resolveReplayRecordPolicy`, #602): a play whose options' source
   * saves nothing keeps no record, an LR2 separate-lamp play keeps its own slot ({@link slotRecordKey}), and an assisted
   * play moves only its limited lamp and its play count. Without a replay the play counts as unassisted.
   */
  public recordPlayUnder(
    key: string,
    play: RecordPlay,
    replay?: AssistReplay,
  ): { previous: BestRecord | undefined } | undefined {
    const policy = replay === undefined ? undefined : resolveReplayRecordPolicy(replay, recordKeyRuleset(key));
    if (policy !== undefined && !policy.keepsRecord) return undefined;
    const slotKey = slotRecordKey(key, policy?.recordSlot ?? 'main');
    const previous = this.chartBestRecords.get(slotKey);
    this.chartBestRecords.set(slotKey, mergeBestRecord(previous, play, policy));
    storeChartBestRecords(this.chartBestRecords);
    return { previous };
  }
 
  /**
   * Folds the running course stage into its chart's record ({@link mergeCourseStageRecord}), when the stage counts: an
   * assisted stage (`RecordPolicy.keepsCourseRecord`) writes nothing, as LR2 saves none (`CheckScoreSaveConditon`).
   */
  public recordActiveCourseStage(play: RecordPlay, replay?: AssistReplay): void {
    const key = this.activeStageRecordKey;
    this.activeStageRecordKey = undefined;
    if (key === undefined) return;
    if (replay !== undefined && !resolveReplayRecordPolicy(replay, recordKeyRuleset(key)).keepsCourseRecord) return;
    this.chartBestRecords.set(key, mergeCourseStageRecord(this.chartBestRecords.get(key), play));
    storeChartBestRecords(this.chartBestRecords);
  }
 
  /**
   * Keeps a course run's best lamp, EX score, course max combo and BP under the course's key, when the run keeps a
   * record ({@link resolveCourseBestRecordUpdate}). Returns the record as it was before the run, or `undefined` when
   * the run kept none.
   */
  public recordCourseResult(
    update: { key: string; play: RecordPlay } | undefined,
  ): { previous: BestRecord | undefined } | undefined {
    if (update === undefined) return undefined;
    const previous = this.chartBestRecords.get(update.key);
    this.chartBestRecords.set(update.key, mergeBestRecord(previous, update.play));
    storeChartBestRecords(this.chartBestRecords);
    return { previous };
  }
 
  /**
   * Keeps the dan rank a GRADE course run certified (`resolveDanRankUpdate`), when it is higher than the one held in its
   * key mode. Returns the rank as it was before, or `undefined` when the run certified none.
   */
  public recordDanRank(
    update: { key: string; rank: DanRank } | undefined,
  ): { previous: DanRank | undefined } | undefined {
    if (update === undefined) return undefined;
    const kept = mergeDanRank(this.danRanks, update);
    this.danRankList = undefined;
    storeDanRanks(this.danRanks);
    return kept;
  }
 
  /** The dan ranks of the current judge ruleset, by key mode: the ones the select screen shows. */
  public currentDanRanks(): readonly BeMusicDanRank[] {
    const ruleset = this.judgeRuleset();
    Eif (this.danRankList?.ruleset !== ruleset) {
      this.danRankList = { ruleset, list: listDanRanks(this.danRanks, ruleset) };
    }
    return this.danRankList.list;
  }
}