All files / app-play/src/services remote-cache.ts

88.13% Statements 52/59
89.74% Branches 35/39
78.57% Functions 11/14
93.61% Lines 44/47

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                                                                      46x 43x   36x 36x                           110x 110x   92x 92x   25x 22x   67x     67x       12x   12x 12x 12x     3x               3x 3x 1x   2x 2x 2x 1x 1x 1x 1x                   1x   1x 1x 1x                   11x 11x   71x   42x                 12x           37x 1x 1x       37x     12x         12x   12x   12x  
// Files the player reads from other sites (difficulty-table pages, headers and song lists, Bemuse server indexes and
// song asset indexes), kept between visits so that opening the player again asks those sites for nothing until an entry
// is due. An entry serves until it is older than its policy's age, was fetched before a refresh the player asked for,
// or was stored for another version of what it describes. A due entry is fetched again, and when that fetch fails the
// entry still serves, so a site that is down or a player offline keeps what was read last time.
 
/** One kept file: its bytes, when they were fetched, and the version of what they describe, if the reader names one. */
export interface RemoteCacheEntry {
  readonly bytes: Uint8Array;
  /** `Date.now()` when the bytes arrived. */
  readonly fetchedAt: number;
  readonly version?: string;
}
 
/** Where the entries are kept, by a key the reader picks (usually the file's URL). */
export interface RemoteCacheStore {
  get(key: string): Promise<RemoteCacheEntry | undefined>;
  put(key: string, entry: RemoteCacheEntry): Promise<void>;
}
 
/** When a kept entry serves without asking the network. */
export interface RemoteCachePolicy {
  /** How long an entry serves; `Infinity` keeps it until its version changes or a refresh asks for it. */
  readonly maxAgeMs: number;
  /** An entry fetched before this time is fetched again: the player asked to refresh then. */
  readonly refreshedSince?: number;
  /** The version the reader expects; an entry stored under another is fetched again. */
  readonly version?: string;
}
 
/** How a read was answered, for the caller's log. */
export type RemoteCacheSource = 'cache' | 'network' | 'stale';
 
/** Whether `entry` serves under `policy` at `nowMs` without asking the network. */
export function isRemoteCacheEntryFresh(entry: RemoteCacheEntry, policy: RemoteCachePolicy, nowMs: number): boolean {
  if (policy.version !== undefined && entry.version !== policy.version) return false;
  if (policy.refreshedSince !== undefined && entry.fetchedAt < policy.refreshedSince) return false;
  // An entry from the future (a clock set back) is due, so a wrong clock never keeps it forever.
  const age = nowMs - entry.fetchedAt;
  return age >= 0 && age < policy.maxAgeMs;
}
 
/**
 * The bytes of `key`: the kept entry while it is fresh, else `fetchBytes()` (kept for next time), else, when that
 * fails, the kept entry however old. Without a store, or without an entry, a failed fetch rejects.
 */
export async function readThroughRemoteCache(
  key: string,
  fetchBytes: () => Promise<Uint8Array>,
  store: RemoteCacheStore | undefined,
  policy: RemoteCachePolicy,
  nowMs: number = Date.now(),
): Promise<{ bytes: Uint8Array; source: RemoteCacheSource }> {
  const kept = await store?.get(key).catch(() => undefined);
  if (kept !== undefined && isRemoteCacheEntryFresh(kept, policy, nowMs)) return { bytes: kept.bytes, source: 'cache' };
  let bytes: Uint8Array;
  try {
    bytes = await fetchBytes();
  } catch (error) {
    if (kept !== undefined) return { bytes: kept.bytes, source: 'stale' };
    throw error;
  }
  await store
    ?.put(key, { bytes, fetchedAt: nowMs, ...(policy.version !== undefined ? { version: policy.version } : {}) })
    .catch(() => undefined);
  return { bytes, source: 'network' };
}
 
/** The Cache Storage cache the entries live in. */
export const REMOTE_CACHE_NAME = 'be-music-remote-v1';
/** The made-up origin the keys are filed under, so a key is never a request the browser could match another way. */
const KEY_ORIGIN = 'https://remote-cache.be-music.invalid/';
const FETCHED_AT_HEADER = 'x-be-music-fetched-at';
const VERSION_HEADER = 'x-be-music-version';
 
function cacheRequestURL(key: string): string {
  return `${KEY_ORIGIN}?key=${encodeURIComponent(key)}`;
}
 
/** A store over Cache Storage, or `undefined` where the page has none (an insecure origin, a worker test). */
export function createCacheStorageRemoteStore(
  storage: CacheStorage | undefined = globalThis.caches,
  cacheName: string = REMOTE_CACHE_NAME,
): RemoteCacheStore | undefined {
  if (storage === undefined) return undefined;
  const open = () => storage.open(cacheName);
  return {
    async get(key) {
      try {
        const response = await (await open()).match(cacheRequestURL(key));
        if (response === undefined) return undefined;
        const fetchedAt = Number(response.headers.get(FETCHED_AT_HEADER));
        Iif (!Number.isFinite(fetchedAt)) return undefined;
        const version = response.headers.get(VERSION_HEADER);
        return {
          bytes: new Uint8Array(await response.arrayBuffer()),
          fetchedAt,
          ...(version !== null ? { version: decodeURIComponent(version) } : {}),
        };
      } catch {
        return undefined;
      }
    },
    async put(key, entry) {
      const headers = new Headers({ [FETCHED_AT_HEADER]: String(entry.fetchedAt) });
      // Header values are Latin-1; a version may be any text.
      Eif (entry.version !== undefined) headers.set(VERSION_HEADER, encodeURIComponent(entry.version));
      try {
        await (await open()).put(cacheRequestURL(key), new Response(new Uint8Array(entry.bytes), { headers }));
      } catch {
        // A full or blocked store: the file is fetched again next time.
      }
    },
  };
}
 
/** A store in memory, for tests and pages without Cache Storage. */
export function createMemoryRemoteStore(): RemoteCacheStore & { readonly entries: Map<string, RemoteCacheEntry> } {
  const entries = new Map<string, RemoteCacheEntry>();
  return {
    entries,
    get: async (key) => entries.get(key),
    put: async (key, entry) => {
      entries.set(key, entry);
    },
  };
}
 
/**
 * Caches earlier builds kept and this store took over: `be-music-bemuse-charts` held Bemuse charts by their index MD5,
 * which some servers list for other bytes than they serve, so those charts were fetched on every visit.
 */
export const RETIRED_CACHE_NAMES: readonly string[] = ['be-music-bemuse-charts'];
 
let pageStore: RemoteCacheStore | null | undefined;
 
/** The page's store, shared by every reader; `undefined` without Cache Storage. Its first use drops the retired caches. */
export function pageRemoteCacheStore(): RemoteCacheStore | undefined {
  if (pageStore === undefined) {
    pageStore = createCacheStorageRemoteStore() ?? null;
    Iif (pageStore !== null) {
      for (const name of RETIRED_CACHE_NAMES) void globalThis.caches.delete(name).catch(() => false);
    }
  }
  return pageStore ?? undefined;
}
 
const HOUR_MS = 60 * 60 * 1000;
/**
 * How long a difficulty table's page, header and song list serve before they are asked for again. Tables change a few
 * times a day at most, and a reload of the folders asks at once.
 */
export const COURSE_TABLE_MAX_AGE_MS = 24 * HOUR_MS;
/** How long a Bemuse server's index serves before it is asked for again; a reload of the folders asks at once. */
export const BEMUSE_INDEX_MAX_AGE_MS = 24 * HOUR_MS;
/** How long a song's missing default preview is believed missing; a preview that exists is kept with the song. */
export const BEMUSE_MISSING_PREVIEW_MAX_AGE_MS = 7 * 24 * HOUR_MS;