All files / app-play/src option-settings-sync.ts

92.72% Statements 102/110
87.64% Branches 78/89
94.73% Functions 18/19
94.56% Lines 87/92

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                        3x 3x 3x     3x 3x             16x               18x 18x 18x     18x     18x 18x 18x         13x 12x 12x 12x 12x 12x         9x 9x 9x 9x 9x 9x 8x 8x 8x 8x 8x 8x 6x     9x         6x 6x 5x 5x       5x   5x 5x       5x 5x 6x 5x 4x 2x 1x 1x                     5x           5x 5x 5x 5x 5x 5x 5x 5x       5x 5x         47x       36x 36x 36x             18x           18x       19x     19x       8x 8x 7x       19x 8x 8x 4x 4x   1x   4x   4x       4x             17x 17x               14x 13x 13x 13x   3x         3x  
// Local edits are synchronous. Remote operations run in order; resets retain a durable retry marker and the server
// retains only a version barrier, so an older request cannot recreate settings that were reset.
import {
  optionSettingsFromLegacy,
  hasLegacyOptionSettings,
  parseOptionSettingsDocument,
  readStoredOptionSettings,
  writeOptionSettings,
  type OptionSettingsDocument,
} from './option-settings.ts';
import { clearPlayerSettings, type PlayerStorage } from './player-storage.ts';
 
export const PLAYER_SETTINGS_PATH = '/api/player-settings';
export const RESET_PENDING_KEY = 'be-music.settings-reset-pending';
const REQUEST_TIMEOUT_MS = 2500;
 
function defaultStorage(): Storage | undefined {
  try {
    return globalThis.localStorage;
  } catch {
    return undefined;
  }
}
 
function sameDocument(left: OptionSettingsDocument | undefined, right: OptionSettingsDocument | undefined): boolean {
  return JSON.stringify(left) === JSON.stringify(right);
}
 
/** One owner for immediate browser persistence and ordered, debounced remote publication. */
export class OptionSettingsSync {
  private readonly storage: PlayerStorage | undefined;
  private readonly doFetch: typeof fetch;
  private readonly now: () => number;
  private clock = 0;
  private generation = 0;
  private resetting = false;
  private pending: OptionSettingsDocument | undefined;
  private timer: ReturnType<typeof setTimeout> | undefined;
  private queue: Promise<void> = Promise.resolve();
 
  public constructor(options: { storage?: PlayerStorage; fetch?: typeof fetch; now?: () => number } = {}) {
    this.storage = options.storage ?? defaultStorage();
    this.doFetch = options.fetch ?? globalThis.fetch.bind(globalThis);
    this.now = options.now ?? Date.now;
  }
 
  /** Persists immediately, even when the page closes before the remote debounce expires. */
  public save(document: OptionSettingsDocument): void {
    if (this.resetting) return;
    const saved = { ...document, updatedAt: this.nextTimestamp(document.updatedAt) };
    writeOptionSettings(saved, this.storage);
    this.pending = saved;
    if (this.timer !== undefined) clearTimeout(this.timer);
    this.timer = setTimeout(() => void this.flush(), 300);
  }
 
  /** Publishes the latest pending edit, after earlier requests. Safe to call when the page is hidden. */
  public flush(): Promise<void> {
    if (this.timer !== undefined) clearTimeout(this.timer);
    this.timer = undefined;
    const document = this.pending;
    this.pending = undefined;
    const generation = this.generation;
    if (document)
      void this.enqueue(async () => {
        Iif (generation !== this.generation || this.resetting) return;
        Iif (!(await this.retryReset())) return;
        const outgoing = this.local() ?? document;
        const stored = await this.request('PUT', outgoing);
        if (stored && generation === this.generation && !this.resetting && sameDocument(this.local(), outgoing)) {
          this.apply(stored);
        }
      });
    return this.queue;
  }
 
  /** Reconciles before constructing the UI. A request never overwrites an edit made while it was in flight. */
  public async reconcile(): Promise<void> {
    await this.enqueue(async () => {
      if (this.resetting || !(await this.retryReset())) return;
      let local = this.local();
      Iif (!local && hasLegacyOptionSettings(this.storage)) {
        local = optionSettingsFromLegacy(this.storage, this.nextTimestamp(this.now()));
        writeOptionSettings(local, this.storage);
      }
      const generation = this.generation;
      let response: Response;
      try {
        response = await this.doFetch(PLAYER_SETTINGS_PATH, {
          credentials: 'same-origin',
          signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
        });
        Iif (!response.ok) return;
        const remote = response.status === 204 ? undefined : parseOptionSettingsDocument(await response.text());
        if (remote) this.clock = Math.max(this.clock, remote.updatedAt);
        if (generation !== this.generation || this.resetting || !sameDocument(this.local(), local)) return;
        if (remote && (!local || remote.updatedAt > local.updatedAt)) this.apply(remote);
        else if (local && (!remote || local.updatedAt > remote.updatedAt)) {
          const stored = await this.request('PUT', local);
          Iif (stored && generation === this.generation && !this.resetting && sameDocument(this.local(), local))
            this.apply(stored);
        }
      } catch {
        // Offline: the immediate local copy remains authoritative for this visit.
      }
    });
  }
 
  /** Clears locally first, invalidates queued saves, then deletes remotely after any in-flight request finishes. */
  public async reset(): Promise<void> {
    const reset: OptionSettingsDocument = {
      version: 0,
      updatedAt: this.nextTimestamp(this.now()),
      settings: {},
      deleted: true,
    };
    this.generation++;
    this.resetting = true;
    if (this.timer !== undefined) clearTimeout(this.timer);
    this.timer = undefined;
    this.pending = undefined;
    clearPlayerSettings(this.storage);
    try {
      this.storage?.setItem(RESET_PENDING_KEY, JSON.stringify(reset));
    } catch {
      // Blocked storage cannot retain a retry marker, but still resets the current visit.
    }
    await this.enqueue(async () => {
      await this.retryReset(reset);
    });
  }
 
  private local(): OptionSettingsDocument | undefined {
    return readStoredOptionSettings(this.storage);
  }
 
  private resetPending(): OptionSettingsDocument | undefined {
    try {
      const document = parseOptionSettingsDocument(this.storage?.getItem(RESET_PENDING_KEY));
      return document?.deleted ? document : undefined;
    } catch {
      return undefined;
    }
  }
 
  private nextTimestamp(now: number): number {
    this.clock = Math.max(
      now,
      this.clock + 1,
      (this.local()?.updatedAt ?? 0) + 1,
      (this.resetPending()?.updatedAt ?? 0) + 1,
    );
    return this.clock;
  }
 
  private enqueue(operation: () => Promise<void>): Promise<void> {
    this.queue = this.queue.then(operation).catch(() => {
      /* A failed request must not block later local edits or reset. */
    });
    return this.queue;
  }
 
  private apply(document: OptionSettingsDocument): void {
    this.clock = Math.max(this.clock, document.updatedAt);
    if (document.deleted) clearPlayerSettings(this.storage);
    else writeOptionSettings(document, this.storage);
  }
 
  private async retryReset(document = this.resetPending()): Promise<boolean> {
    if (!document) return true;
    const stored = await this.request('DELETE', document);
    if (!stored?.deleted) return false;
    const local = this.local();
    if (local && local.updatedAt > document.updatedAt) {
      // Edits made after an offline reset must remain causally newer than the acknowledged remote reset.
      writeOptionSettings({ ...local, updatedAt: this.nextTimestamp(stored.updatedAt) }, this.storage);
    }
    try {
      // A newer reset from another tab still needs its own acknowledgement.
      Eif (sameDocument(this.resetPending(), document)) this.storage?.removeItem(RESET_PENDING_KEY);
    } catch {
      /* Retry again next visit if storage is blocked. */
    }
    return true;
  }
 
  private async request(
    method: 'PUT' | 'DELETE',
    document: OptionSettingsDocument,
  ): Promise<OptionSettingsDocument | undefined> {
    try {
      const response = await this.doFetch(PLAYER_SETTINGS_PATH, {
        method,
        credentials: 'same-origin',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify(document),
        signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
        keepalive: true,
      });
      if (!response.ok) return undefined;
      const stored = parseOptionSettingsDocument(await response.text());
      if (stored) this.clock = Math.max(this.clock, stored.updatedAt);
      return stored;
    } catch {
      return undefined;
    }
  }
}
 
export const optionSettingsSync = new OptionSettingsSync();