Files
fruit-pop-googleplay/assets/orchard/scripts/OrchardRuntime.ts
T

136 lines
5.2 KiB
TypeScript

import { assetManager, SceneAsset, sys } from 'cc';
import { GUEST_SERVICE } from '../../login/scripts/GuestRuntime';
import { GameRepository } from './GameRepository';
import { GameSession } from './GameSession';
interface ExclusiveGameLock {
scope: string;
acquired: Promise<void>;
release(): void;
}
/** Authenticated, local-only game composition root. Never restore authentication from a token. */
export class OrchardRuntime {
static readonly LOCK_IN_USE = 'This saved game is already open in another tab. Close it and tap the guest button to retry.';
static readonly LOCK_UNAVAILABLE = 'Exclusive saved game access is unavailable on this platform. Please use a supported browser and retry.';
static session: GameSession | null = null;
private static exclusive: ExclusiveGameLock | null = null;
private static preparation = 0;
private static detachCancellation: (() => void) | null = null;
/** Synchronous composition for pure tests. Browser entry points must use prepareExclusive. */
static prepare(guestId: string): GameSession {
this.clear();
this.session = this.restore(this.scopeFor(guestId));
return this.session;
}
static async prepareExclusive(guestId: string, signal?: AbortSignal): Promise<GameSession> {
if (signal?.aborted) throw new Error('Game preparation was cancelled.');
const operation = ++this.preparation;
this.detachCancellation?.();
this.detachCancellation = null;
this.session = null;
try {
const scope = this.scopeFor(guestId);
if (typeof globalThis.navigator?.locks?.request !== 'function') throw new Error(this.LOCK_UNAVAILABLE);
if (this.exclusive?.scope !== scope) {
const previous = this.exclusive;
this.exclusive = null;
previous?.release();
}
const exclusive = this.exclusive ?? this.requestExclusive(scope);
const cancel = (): void => {
if (operation === this.preparation && this.exclusive === exclusive) this.clear();
};
signal?.addEventListener('abort', cancel, { once: true });
this.detachCancellation = () => signal?.removeEventListener('abort', cancel);
await exclusive.acquired;
if (signal?.aborted || operation !== this.preparation || this.exclusive !== exclusive) {
throw new Error('Game preparation was cancelled.');
}
this.session = this.restore(scope);
return this.session;
} catch (error) {
if (operation === this.preparation) this.clear();
throw error;
}
}
private static requestExclusive(scope: string): ExclusiveGameLock {
let acquired!: () => void;
let failed!: (error: Error) => void;
let release!: () => void;
const holding = new Promise<void>(resolve => { release = resolve; });
const exclusive: ExclusiveGameLock = {
scope,
acquired: new Promise<void>((resolve, reject) => { acquired = resolve; failed = reject; }),
release: () => { failed(new Error('Game preparation was cancelled.')); release(); },
};
this.exclusive = exclusive;
try {
void globalThis.navigator.locks.request(`fruit-pop:game:v1:${encodeURIComponent(scope)}`,
{ mode: 'exclusive', ifAvailable: true }, lock => {
if (this.exclusive !== exclusive) return;
if (!lock) { failed(new Error(this.LOCK_IN_USE)); return; }
acquired();
// The request promise lasts for the session lifetime, not just preparation.
return holding;
}).catch(() => { failed(new Error(this.LOCK_UNAVAILABLE)); });
} catch {
failed(new Error(this.LOCK_UNAVAILABLE));
}
return exclusive;
}
private static scopeFor(guestId: string): string {
if (typeof guestId !== 'string' || !/^[a-zA-Z0-9-]{16,128}$/.test(guestId)) {
throw new Error('Sign in to continue.');
}
if (typeof globalThis.crypto?.getRandomValues !== 'function') {
throw new Error('Secure game preparation is unavailable on this platform.');
}
return `${GUEST_SERVICE.origin.replace(/\/+$/, '')}|${GUEST_SERVICE.product}|${guestId}`;
}
private static restore(scope: string): GameSession {
const random = (): number => globalThis.crypto.getRandomValues(new Uint32Array(1))[0] / 0x100000000;
try {
return new GameSession(new GameRepository(sys.localStorage, scope), random);
} catch {
// Never replace unreadable/corrupt data with a fresh balance or expose adapter errors.
throw new Error('Unable to open saved game data. Please retry. Your saved game has not been reset.');
}
}
static getSession(): GameSession {
if (this.session === null) throw new Error('Sign in to continue.');
return this.session;
}
/** An expected session prevents late loading callbacks from clearing a newer owner. */
static clear(expectedSession?: GameSession): void {
if (expectedSession !== undefined && this.session !== expectedSession) return;
this.preparation++;
this.detachCancellation?.();
this.detachCancellation = null;
this.session = null;
const exclusive = this.exclusive;
this.exclusive = null;
exclusive?.release();
}
static loadScene(): Promise<SceneAsset> {
return new Promise((resolve, reject) => {
const failed = (): void => reject(new Error('Unable to load the game. Please tap the guest button to retry.'));
try {
if (!assetManager.main) { failed(); return; }
assetManager.main.loadScene('Orchard', (error, scene) => {
if (error || !scene) failed();
else resolve(scene);
});
} catch { failed(); }
});
}
}