All files / player-browser/src/collection parsed-chart-cache.ts

100% Statements 57/57
100% Branches 46/46
100% Functions 12/12
100% Lines 43/43

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                                                                43x 39x 36x 35x 32x         153x 153x 144x 283x 283x 283x   11x         31x                                               9x   8x 8x     4x   1x   7x 14x 14x                             114x   114x 28x 28x   28x 2x 4x     28x 28x 28x 27x 28x         110x 114x 110x 114x 24x 24x         110x         41x 14x 14x                  
import { sha256HexAsync } from '@be-music/shared-utils/hash';
import { runBrowserTask } from '../compute/index.ts';
import { parseChartTask, type ParseChartTaskInput, type ParseChartTaskResult } from '../compute/tasks.ts';
 
/**
 * Where a host keeps parsed charts across page loads, keyed by {@link parsedChartCacheKey}. The collection loader
 * looks a chart up before parsing it and hands every chart it parsed to {@link ParsedChartCache.set}.
 *
 * Both methods may fail; the loader then parses the chart as if nothing were cached.
 */
export interface ParsedChartCache {
  get(key: string): Promise<ParseChartTaskResult | undefined>;
  /**
   * The values of `keys`, in their order, read together: a host whose lookups each cost a round trip (IndexedDB)
   * answers a library's worth of keys in one. Without it the keys are looked up one by one.
   */
  getMany?(keys: readonly string[]): Promise<Array<ParseChartTaskResult | undefined>>;
  /**
   * Keeps a parse result. The loader goes on to change the chart it holds once the returned promise settles, so the
   * implementation must have copied `value` by then (IndexedDB's `put` copies it when it is called); it need not wait
   * for the write to land.
   */
  set(key: string, value: ParseChartTaskResult): Promise<void>;
}
 
/**
 * What of a chart's path its parse result depends on: bmson, LRX, BMS text or a Nanasi Groove 2 `.n2s` container, and
 * the `.pms` extension that decides the play variant (an `.n2s` chart is PMS too). Two files with the same bytes under
 * the same kind of name parse the same.
 */
export function parsedChartPathKind(path: string): 'bmson' | 'lrx' | 'n2s' | 'pms' | 'bms' {
  // The extension is compared in place, without lowercasing a copy of the path.
  if (endsWithASCIIIgnoringCase(path, '.bmson')) return 'bmson';
  if (endsWithASCIIIgnoringCase(path, '.lrs')) return 'lrx';
  if (endsWithASCIIIgnoringCase(path, '.n2s')) return 'n2s';
  if (endsWithASCIIIgnoringCase(path, '.pms')) return 'pms';
  return 'bms';
}
 
/** Whether `text` ends with `suffix` (lowercase ASCII), ignoring the case of ASCII letters. */
function endsWithASCIIIgnoringCase(text: string, suffix: string): boolean {
  const offset = text.length - suffix.length;
  if (offset < 0) return false;
  for (let index = 0; index < suffix.length; index += 1) {
    const code = text.charCodeAt(offset + index);
    const lower = code >= 0x41 && code <= 0x5a ? code + 0x20 : code;
    if (lower !== suffix.charCodeAt(index)) return false;
  }
  return true;
}
 
/** The cache key of a chart file: the SHA-256 (lowercase hex) of its bytes and {@link parsedChartPathKind}. */
export function parsedChartCacheKey(sha256: string, path: string): string {
  return `${sha256}:${parsedChartPathKind(path)}`;
}
 
/**
 * The cache keys of chart files a host has seen before, by chart path, so a file it knows is unchanged (the same size
 * and modification time as when it was last read) is looked up in the {@link ParsedChartCache} without being read and
 * hashed again. The collection loader asks {@link ChartCacheKeyBook.known} before reading a chart file and reports
 * every key it works out from a file's bytes to {@link ChartCacheKeyBook.learned}.
 */
export interface ChartCacheKeyBook {
  /** The key the chart file at `path` had when it was last read, when the file is known not to have changed since. */
  known(path: string): string | undefined;
  /** The key of the chart file at `path`, worked out from its bytes now. */
  learned(path: string, key: string): void;
}
 
/**
 * The charts kept under `keys`, in their order: the charts a {@link ChartCacheKeyBook} names, without their files'
 * bytes. A key the cache has nothing for (or cannot read) gives `undefined`.
 */
export async function readParsedCharts(
  cache: ParsedChartCache | undefined,
  keys: readonly string[],
): Promise<Array<ParseChartTaskResult | undefined>> {
  if (cache === undefined || keys.length === 0) return keys.map(() => undefined);
  let values: readonly unknown[];
  try {
    values =
      cache.getMany !== undefined
        ? await cache.getMany(keys)
        : await Promise.all(keys.map((key) => cache.get(key).catch(() => undefined)));
  } catch {
    return keys.map(() => undefined);
  }
  return keys.map((_, index) => {
    const value = values[index];
    return isParseChartTaskResult(value) ? value : undefined;
  });
}
 
/**
 * Parses a chart file, through `cache` when one is given: a chart already parsed under the same key comes back from
 * the cache, and a chart parsed now is kept in it. Hashing or cache failures fall back to parsing. `onKey` receives
 * the file's cache key once it is worked out.
 */
export async function parseChartThroughCache(
  input: ParseChartTaskInput,
  cache: ParsedChartCache | undefined,
  onKey?: (key: string) => void,
  signal?: AbortSignal,
): Promise<ParseChartTaskResult> {
  signal?.throwIfAborted();
  let key: string | undefined;
  if (cache !== undefined) {
    try {
      let hashed = parsedChartCacheKey(await sha256HexAsync(input.bytes), input.path);
      // An LRX chart also reads its header and BGA file, so those take part in the key.
      if (input.siblings !== undefined) {
        for (const sibling of [input.siblings.lrh, input.siblings.lrm]) {
          hashed += `:${sibling === undefined ? '-' : await sha256HexAsync(sibling)}`;
        }
      }
      key = hashed;
      onKey?.(hashed);
      const cached = await cache.get(key);
      signal?.throwIfAborted();
      if (isParseChartTaskResult(cached)) return cached;
    } catch {
      // Unhashable or unreadable: parse it.
    }
  }
  signal?.throwIfAborted();
  const result = await runBrowserTask('parse-chart', input, () => parseChartTask(input));
  signal?.throwIfAborted();
  if (cache !== undefined && key !== undefined) {
    try {
      await cache.set(key, result);
    } catch {
      // A cache that cannot keep it costs only the next load's parse.
    }
  }
  return result;
}
 
/** Whether a cached value has the shape of a parse result, so an entry from another build cannot break the load. */
function isParseChartTaskResult(value: unknown): value is ParseChartTaskResult {
  if (typeof value !== 'object' || value === null) return false;
  const result = value as Partial<ParseChartTaskResult>;
  return (
    typeof result.chart === 'object' &&
    result.chart !== null &&
    typeof result.scored === 'object' &&
    result.scored !== null &&
    typeof result.scored.notes === 'number' &&
    Array.isArray(result.strings)
  );
}