mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 16:22:20 +00:00
Hand the session off on Back/Forward and roll failed globe switches back to the last working engine
The engine switch moves out of main.js into src/standalone/engineSwitch.js: every engine change in the page hands the session off (layers, Director, Contacts, directions and satellite cameras), whether it came from the picker or from history. Each attempt has a generation; a failure rolls back to the last engine that started, requests made during a switch or recovery are reconciled once it settles, and a picked engine adds its history entry only after it starts. The first-frame wait only lifts the cover and never fails a started engine; a hidden tab does not wait. Nothing starts after pagehide, and a failed recovery leaves the picker usable.
This commit is contained in:
1 parent
64c5cd25e6
commit
4d2b061e3b
5 files changed
+1320
-201
No files matched your search
@@ -0,0 +1,308 @@
|
||||
// The page's engine switch: one layer session, one engine at a time.
|
||||
//
|
||||
// The address (?engine=) is the source of truth. A switch from the picker
|
||||
// (select) and a history visit (Back/Forward, a pasted address) are the same
|
||||
// operation: the running engine hands the session off and is released, the
|
||||
// requested engine starts on the retained session. Requests that arrive while
|
||||
// a switch or a recovery runs are never dropped: once the current attempt
|
||||
// settles, the address is read again and reconciled.
|
||||
|
||||
const ENGINES = Object.freeze(['cesium', 'navara']);
|
||||
|
||||
/** A started engine whose first frame takes longer than this is shown anyway. */
|
||||
export const FIRST_FRAME_WAIT_MS = 10_000;
|
||||
|
||||
/**
|
||||
* Drive engine switches for one page session.
|
||||
*
|
||||
* Every attempt has a generation. A failed attempt rolls back to the last
|
||||
* engine that actually started (never to the one that just failed) and, when
|
||||
* that recovery fails too, leaves the page without an engine but still able
|
||||
* to take the next request. A page lifetime abort (pagehide) stops the
|
||||
* machine: nothing starts after it.
|
||||
*
|
||||
* @param {object} options
|
||||
* @param {string} options.kind The engine already running.
|
||||
* @param {() => string} options.requested The engine the address asks for now.
|
||||
* @param {AbortSignal} options.signal The page lifetime.
|
||||
* @param {(from: string, to: string) => Promise<void>} options.leave Hand the
|
||||
* session off from the running engine and release that engine.
|
||||
* @param {(kind: string, attempt: {generation: number, recovery: boolean}) => Promise<void>} options.enter
|
||||
* Start an engine on the retained session. It resolves once the engine runs
|
||||
* with the session attached; when it rejects it has already released what
|
||||
* it started.
|
||||
* @param {{select: (from: ?string, to: string) => *, commit: (token: *) => void, restore: (kind: string) => void}} options.address
|
||||
* @param {(state: {failed: boolean}) => Promise<void>|void} [options.settle] Runs
|
||||
* once the address is reconciled, before the machine reports idle.
|
||||
* @param {(kind: string) => void} [options.remember] Store a picked engine.
|
||||
* @param {(state: object) => void} [options.onChange]
|
||||
* @param {(error: unknown, outcome: {recovered: boolean, kind: ?string}) => void} [options.onFailure]
|
||||
*/
|
||||
export function createEngineSwitch({
|
||||
kind,
|
||||
requested,
|
||||
signal,
|
||||
leave,
|
||||
enter,
|
||||
address,
|
||||
settle,
|
||||
remember,
|
||||
onChange,
|
||||
onFailure,
|
||||
}) {
|
||||
// The engine whose session is live, null while none is.
|
||||
let current = kind;
|
||||
// The engine whose application exists or is starting: what a history visit
|
||||
// would leave.
|
||||
let live = kind;
|
||||
// The last engine that started successfully: the rollback target.
|
||||
let working = kind;
|
||||
let failed = false;
|
||||
let busy = false;
|
||||
let generation = 0;
|
||||
// Every request (select or address visit) bumps this; a visit also bumps
|
||||
// `visits`, which retires a select's pending history entry.
|
||||
let requests = 0;
|
||||
let visits = 0;
|
||||
let queued = null;
|
||||
let pending = null;
|
||||
let running = null;
|
||||
|
||||
const state = () =>
|
||||
Object.freeze({
|
||||
kind: current ?? working,
|
||||
engine: live,
|
||||
busy,
|
||||
failed,
|
||||
generation,
|
||||
});
|
||||
const publish = () => onChange?.(state());
|
||||
|
||||
function prepare(next) {
|
||||
pending = { to: next, visits, token: address.select(current, next) };
|
||||
}
|
||||
|
||||
/** The picker's choice. While a switch runs it is queued, not dropped. */
|
||||
function select(next) {
|
||||
if (!ENGINES.includes(next) || signal.aborted) return null;
|
||||
requests++;
|
||||
if (busy) {
|
||||
queued = next;
|
||||
return running;
|
||||
}
|
||||
if (next === current) return null;
|
||||
prepare(next);
|
||||
return run();
|
||||
}
|
||||
|
||||
/** The address changed (history visit) or should be checked again. */
|
||||
function reconcile() {
|
||||
if (signal.aborted) return Promise.resolve();
|
||||
requests++;
|
||||
visits++;
|
||||
// A later visit supersedes a select queued before it.
|
||||
queued = null;
|
||||
return busy ? running : run();
|
||||
}
|
||||
|
||||
function run() {
|
||||
busy = true;
|
||||
publish();
|
||||
running = drive()
|
||||
.catch((error) => onFailure?.(error, { recovered: false, kind: null }))
|
||||
.finally(() => {
|
||||
busy = false;
|
||||
running = null;
|
||||
publish();
|
||||
});
|
||||
return running;
|
||||
}
|
||||
|
||||
async function drive() {
|
||||
for (;;) {
|
||||
await reconcileAddress();
|
||||
if (signal.aborted) return;
|
||||
const seen = requests;
|
||||
await settle?.({ failed });
|
||||
if (signal.aborted || seen === requests) return;
|
||||
}
|
||||
}
|
||||
|
||||
async function reconcileAddress() {
|
||||
let handled = null;
|
||||
for (;;) {
|
||||
if (signal.aborted) return;
|
||||
if (queued !== null) {
|
||||
const next = queued;
|
||||
queued = null;
|
||||
if (next !== current) prepare(next);
|
||||
}
|
||||
const target = requested();
|
||||
if (target === current) return;
|
||||
// After a failed recovery, wait for the person's next request instead
|
||||
// of retrying the same address in a loop.
|
||||
if (failed && handled === requests) return;
|
||||
handled = requests;
|
||||
await attempt(target);
|
||||
}
|
||||
}
|
||||
|
||||
async function attempt(target) {
|
||||
const id = ++generation;
|
||||
const visitsAtStart = visits;
|
||||
publish();
|
||||
try {
|
||||
if (current !== null) {
|
||||
const from = current;
|
||||
try {
|
||||
await leave(from, target);
|
||||
} finally {
|
||||
current = null;
|
||||
}
|
||||
}
|
||||
if (signal.aborted) return;
|
||||
live = target;
|
||||
await enter(target, { generation: id, recovery: false });
|
||||
if (signal.aborted) return;
|
||||
current = working = target;
|
||||
failed = false;
|
||||
if (pending?.to === target && pending.visits === visits) {
|
||||
address.commit(pending.token);
|
||||
remember?.(target);
|
||||
}
|
||||
pending = null;
|
||||
} catch (error) {
|
||||
if (signal.aborted) return;
|
||||
pending = null;
|
||||
// Point this history entry back at the working engine unless the
|
||||
// person has since moved to another entry. Nothing is pushed, so a
|
||||
// failed switch leaves no extra entry behind.
|
||||
if (visits === visitsAtStart && requested() === target)
|
||||
address.restore(working);
|
||||
if (working === target) {
|
||||
live = null;
|
||||
failed = true;
|
||||
onFailure?.(error, { recovered: false, kind: null });
|
||||
return;
|
||||
}
|
||||
live = working;
|
||||
try {
|
||||
await enter(working, { generation: id, recovery: true });
|
||||
if (signal.aborted) return;
|
||||
current = working;
|
||||
failed = false;
|
||||
onFailure?.(error, { recovered: true, kind: working });
|
||||
} catch (recoveryError) {
|
||||
if (signal.aborted) return;
|
||||
live = null;
|
||||
failed = true;
|
||||
onFailure?.(recoveryError, { recovered: false, kind: null });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Object.freeze({ select, reconcile, state });
|
||||
}
|
||||
|
||||
/**
|
||||
* The engine choice in the page address. A picked engine replaces the
|
||||
* current entry while it starts; only a successful switch adds the history
|
||||
* entry (the earlier entry keeps the outgoing engine and view), so Back
|
||||
* returns to the previous engine and a failed switch adds nothing.
|
||||
*/
|
||||
export function createEngineAddress({ location, history, flush = () => {} }) {
|
||||
const withEngine = (engine) => {
|
||||
const url = new URL(location.href);
|
||||
url.searchParams.set('engine', engine);
|
||||
return url.href;
|
||||
};
|
||||
return Object.freeze({
|
||||
select(from, to) {
|
||||
flush();
|
||||
const previous = from ? withEngine(from) : null;
|
||||
history.replaceState(history.state, '', withEngine(to));
|
||||
return previous;
|
||||
},
|
||||
commit(previous) {
|
||||
if (!previous) return;
|
||||
const next = location.href;
|
||||
history.replaceState(history.state, '', previous);
|
||||
history.pushState(null, '', next);
|
||||
},
|
||||
restore(engine) {
|
||||
history.replaceState(history.state, '', withEngine(engine));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Hand the session off before the running engine is released: record which
|
||||
* layers run so the next engine retains them, and park the cameras and the
|
||||
* Director scene instead of ending them. Every engine change in this page
|
||||
* hands off, whatever started it; the incoming engine reads the view
|
||||
* (camera, style, map) from the address it starts with, which for a history
|
||||
* visit may differ from the view that was showing.
|
||||
*/
|
||||
export function handOffSession(session) {
|
||||
const manager = session.manager;
|
||||
session.handoffLayers = new Map(
|
||||
[...manager.layers].map(([id, entry]) => [
|
||||
id,
|
||||
{
|
||||
entry: entry.module.attachRenderer ? entry : null,
|
||||
enabled: manager.isEffectivelyEnabled(id),
|
||||
},
|
||||
]),
|
||||
);
|
||||
manager.layers.get('directions')?.module.suspendCamera?.();
|
||||
manager.layers.get('satellites')?.module.suspendCamera?.();
|
||||
session.director?.suspendScene();
|
||||
}
|
||||
|
||||
/** Resume what handOffSession parked, once the incoming view is restored. */
|
||||
export function resumeSession(session) {
|
||||
for (const { module } of session.manager.layers.values())
|
||||
module.resumeViewport?.();
|
||||
if (session.handoffLayers)
|
||||
session.manager.layers.get('directions')?.module.resumeCamera?.();
|
||||
session.director?.resumeScene();
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for a started engine's first frame before the cover over it goes.
|
||||
*
|
||||
* A switch succeeds when the engine has started with the session attached;
|
||||
* this wait never fails it. It resolves true on the first drawn frame and
|
||||
* false when the tab is hidden (a hidden tab draws nothing and shows nothing,
|
||||
* so there is nothing to wait for) or after `timeoutMs` of visible time
|
||||
* without a frame, so a slow GPU leaves the new globe uncovered rather than
|
||||
* rolling a healthy engine back.
|
||||
*/
|
||||
export function waitForFirstFrame(
|
||||
engine,
|
||||
{
|
||||
document = globalThis.document,
|
||||
timeoutMs = FIRST_FRAME_WAIT_MS,
|
||||
setTimer = setTimeout,
|
||||
clearTimer = clearTimeout,
|
||||
} = {},
|
||||
) {
|
||||
if (document?.hidden) return Promise.resolve(false);
|
||||
return new Promise((resolve) => {
|
||||
let timer = null;
|
||||
let remove = () => {};
|
||||
const finish = (drawn) => {
|
||||
remove();
|
||||
clearTimer(timer);
|
||||
document?.removeEventListener?.('visibilitychange', hidden);
|
||||
resolve(drawn);
|
||||
};
|
||||
function hidden() {
|
||||
if (document.hidden) finish(false);
|
||||
}
|
||||
remove = engine.frames.postRender.addEventListener(() => finish(true));
|
||||
timer = setTimer(() => finish(false), timeoutMs);
|
||||
document?.addEventListener?.('visibilitychange', hidden);
|
||||
engine.render.request('engine-switch');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,556 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
createEngineAddress,
|
||||
createEngineSwitch,
|
||||
handOffSession,
|
||||
resumeSession,
|
||||
waitForFirstFrame,
|
||||
} from './engineSwitch.js';
|
||||
|
||||
const ORIGIN = 'https://gev.test/';
|
||||
|
||||
/** A browser history with entries, Back/Forward and the page address. */
|
||||
function fakeBrowser(urls) {
|
||||
const entries = urls.map((url) => ({
|
||||
url: new URL(url, ORIGIN).href,
|
||||
state: null,
|
||||
}));
|
||||
let index = entries.length - 1;
|
||||
const location = {
|
||||
get href() {
|
||||
return entries[index].url;
|
||||
},
|
||||
};
|
||||
const history = {
|
||||
get state() {
|
||||
return entries[index].state;
|
||||
},
|
||||
replaceState(state, _title, url) {
|
||||
entries[index] = { url: new URL(url, location.href).href, state };
|
||||
},
|
||||
pushState(state, _title, url) {
|
||||
entries.splice(index + 1);
|
||||
entries.push({ url: new URL(url, location.href).href, state });
|
||||
index += 1;
|
||||
},
|
||||
};
|
||||
return {
|
||||
location,
|
||||
history,
|
||||
entries,
|
||||
go(delta) {
|
||||
index += delta;
|
||||
},
|
||||
get index() {
|
||||
return index;
|
||||
},
|
||||
engines: () =>
|
||||
entries.map(({ url }) => new URL(url).searchParams.get('engine')),
|
||||
requested: () =>
|
||||
new URL(location.href).searchParams.get('engine') ?? 'cesium',
|
||||
};
|
||||
}
|
||||
|
||||
function deferred() {
|
||||
let resolve;
|
||||
let reject;
|
||||
const promise = new Promise((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
/** A layer session with the parts a handoff parks and resumes. */
|
||||
function fakeSession(log) {
|
||||
const module = (id, extra = {}) => ({
|
||||
attachRenderer() {},
|
||||
resumeViewport: () => log.push(`viewport:${id}`),
|
||||
...extra,
|
||||
});
|
||||
const layers = new Map([
|
||||
['flights', { module: module('flights') }],
|
||||
[
|
||||
'directions',
|
||||
{
|
||||
module: module('directions', {
|
||||
suspendCamera: () => log.push('suspend:directions'),
|
||||
resumeCamera: () => log.push('resume:directions'),
|
||||
}),
|
||||
},
|
||||
],
|
||||
[
|
||||
'satellites',
|
||||
{
|
||||
module: module('satellites', {
|
||||
suspendCamera: () => log.push('suspend:satellites'),
|
||||
}),
|
||||
},
|
||||
],
|
||||
]);
|
||||
return {
|
||||
handoffLayers: null,
|
||||
manager: {
|
||||
layers,
|
||||
isEffectivelyEnabled: (id) => id === 'flights',
|
||||
},
|
||||
director: {
|
||||
suspendScene: () => log.push('suspend:director'),
|
||||
resumeScene: () => log.push('resume:director'),
|
||||
destroy: () => log.push('destroy:director'),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The machine wired to a fake browser, session and renderers. `outcome(kind,
|
||||
* attempt)` may return a promise or throw to script each start.
|
||||
*/
|
||||
function harness({
|
||||
urls = ['/?engine=cesium'],
|
||||
kind = 'cesium',
|
||||
outcome,
|
||||
} = {}) {
|
||||
const browser = fakeBrowser(urls);
|
||||
const lifetime = new AbortController();
|
||||
const log = [];
|
||||
const remembered = [];
|
||||
const failures = [];
|
||||
const session = fakeSession(log);
|
||||
// Parked renderers: a start of a parked engine is warm, any other cold.
|
||||
const parked = new Set();
|
||||
let running = kind;
|
||||
const machine = createEngineSwitch({
|
||||
kind,
|
||||
requested: browser.requested,
|
||||
signal: lifetime.signal,
|
||||
async leave(from, to) {
|
||||
log.push(`leave:${from}->${to}`);
|
||||
handOffSession(session);
|
||||
parked.add(from);
|
||||
running = null;
|
||||
},
|
||||
async enter(next, attempt) {
|
||||
const warm = parked.delete(next);
|
||||
log.push(
|
||||
`enter:${next}:${warm ? 'warm' : 'cold'}${attempt.recovery ? ':recovery' : ''}`,
|
||||
);
|
||||
await outcome?.(next, { ...attempt, warm });
|
||||
running = next;
|
||||
resumeSession(session);
|
||||
},
|
||||
address: createEngineAddress({
|
||||
location: browser.location,
|
||||
history: browser.history,
|
||||
flush: () => log.push('flush'),
|
||||
}),
|
||||
settle: () => {
|
||||
if (running) session.handoffLayers = null;
|
||||
},
|
||||
remember: (next) => remembered.push(next),
|
||||
onFailure: (error, outcome) =>
|
||||
failures.push({ message: error.message, ...outcome }),
|
||||
});
|
||||
return {
|
||||
browser,
|
||||
lifetime,
|
||||
log,
|
||||
remembered,
|
||||
failures,
|
||||
session,
|
||||
parked,
|
||||
machine,
|
||||
};
|
||||
}
|
||||
|
||||
test('a picked engine hands the session off and adds one history entry', async () => {
|
||||
const h = harness({ urls: ['/?welcome=0#lat=1'] });
|
||||
await h.machine.select('navara');
|
||||
assert.deepEqual(h.browser.engines(), ['cesium', 'navara']);
|
||||
assert.equal(new URL(h.browser.entries[0].url).hash, '#lat=1');
|
||||
assert.deepEqual(h.remembered, ['navara']);
|
||||
assert.deepEqual(h.log, [
|
||||
'flush',
|
||||
'leave:cesium->navara',
|
||||
'suspend:directions',
|
||||
'suspend:satellites',
|
||||
'suspend:director',
|
||||
'enter:navara:cold',
|
||||
'viewport:flights',
|
||||
'viewport:directions',
|
||||
'viewport:satellites',
|
||||
'resume:directions',
|
||||
'resume:director',
|
||||
]);
|
||||
assert.equal(h.machine.state().kind, 'navara');
|
||||
assert.equal(h.machine.state().busy, false);
|
||||
});
|
||||
|
||||
test('Back and Forward hand the session off exactly like the picker', async () => {
|
||||
const h = harness();
|
||||
await h.machine.select('navara');
|
||||
const picked = h.log.splice(0).filter((line) => line !== 'flush');
|
||||
let captured;
|
||||
h.session.director.suspendScene = () => {
|
||||
captured = h.session.handoffLayers;
|
||||
h.log.push('suspend:director');
|
||||
};
|
||||
h.browser.go(-1);
|
||||
await h.machine.reconcile();
|
||||
assert.equal(h.machine.state().kind, 'cesium');
|
||||
// The same handoff, mirrored: layers retained, cameras and Director parked
|
||||
// and resumed, nothing destroyed.
|
||||
assert.deepEqual(
|
||||
h.log,
|
||||
picked.map((line) =>
|
||||
line
|
||||
.replace('leave:cesium->navara', 'leave:navara->cesium')
|
||||
.replace('enter:navara:cold', 'enter:cesium:warm'),
|
||||
),
|
||||
);
|
||||
assert.ok(!h.log.includes('destroy:director'));
|
||||
assert.deepEqual(captured.get('flights').enabled, true);
|
||||
assert.equal(
|
||||
captured.get('flights').entry,
|
||||
h.session.manager.layers.get('flights'),
|
||||
);
|
||||
h.browser.go(1);
|
||||
await h.machine.reconcile();
|
||||
assert.equal(h.machine.state().kind, 'navara');
|
||||
assert.ok(h.log.includes('leave:cesium->navara'));
|
||||
// History visits neither add entries nor change the stored choice.
|
||||
assert.deepEqual(h.browser.engines(), ['cesium', 'navara']);
|
||||
assert.deepEqual(h.remembered, ['navara']);
|
||||
});
|
||||
|
||||
test('a visit during a switch is reconciled once the attempt settles', async () => {
|
||||
const gate = deferred();
|
||||
const h = harness({
|
||||
urls: ['/?engine=cesium#before', '/?engine=cesium#now'],
|
||||
outcome: (kind) => (kind === 'navara' ? gate.promise : undefined),
|
||||
});
|
||||
const switching = h.machine.select('navara');
|
||||
assert.equal(h.machine.state().busy, true);
|
||||
// Back while Navara starts: the earlier entry asks for Cesium.
|
||||
h.browser.go(-1);
|
||||
const visit = h.machine.reconcile();
|
||||
gate.resolve();
|
||||
await Promise.all([switching, visit]);
|
||||
assert.equal(h.machine.state().kind, 'cesium');
|
||||
assert.deepEqual(
|
||||
h.log.filter(
|
||||
(line) => line.startsWith('enter') || line.startsWith('leave'),
|
||||
),
|
||||
[
|
||||
'leave:cesium->navara',
|
||||
'enter:navara:cold',
|
||||
'leave:navara->cesium',
|
||||
'enter:cesium:warm',
|
||||
],
|
||||
);
|
||||
// The pick was superseded before it settled: no entry was pushed for it.
|
||||
assert.equal(h.browser.entries.length, 2);
|
||||
assert.deepEqual(h.remembered, []);
|
||||
});
|
||||
|
||||
test('rollback goes to the last engine that worked, not the one that just failed', async () => {
|
||||
const gate = deferred();
|
||||
const h = harness({
|
||||
urls: ['/?engine=cesium#before', '/?engine=cesium#now'],
|
||||
outcome: (kind, { recovery }) => {
|
||||
if (kind === 'navara' && !recovery) return gate.promise;
|
||||
if (kind === 'cesium') throw new Error('Cesium refused');
|
||||
},
|
||||
});
|
||||
const switching = h.machine.select('navara');
|
||||
h.browser.go(-1);
|
||||
void h.machine.reconcile();
|
||||
gate.resolve();
|
||||
await switching;
|
||||
assert.deepEqual(
|
||||
h.log.filter((line) => line.startsWith('enter')),
|
||||
['enter:navara:cold', 'enter:cesium:warm', 'enter:navara:warm:recovery'],
|
||||
);
|
||||
assert.equal(h.machine.state().kind, 'navara');
|
||||
assert.equal(h.machine.state().failed, false);
|
||||
assert.deepEqual(h.failures, [
|
||||
{ message: 'Cesium refused', recovered: true, kind: 'navara' },
|
||||
]);
|
||||
// The visited entry now names the engine that runs; no entry was added.
|
||||
assert.equal(h.browser.index, 0);
|
||||
assert.deepEqual(h.browser.engines(), ['navara', 'navara']);
|
||||
});
|
||||
|
||||
test('a pick made during a switch is queued, not dropped', async () => {
|
||||
const gate = deferred();
|
||||
const h = harness({
|
||||
outcome: (kind, { warm }) =>
|
||||
kind === 'navara' && !warm ? gate.promise : undefined,
|
||||
});
|
||||
const switching = h.machine.select('navara');
|
||||
assert.equal(h.machine.select('cesium'), switching);
|
||||
gate.resolve();
|
||||
await switching;
|
||||
assert.equal(h.machine.state().kind, 'cesium');
|
||||
assert.deepEqual(h.browser.engines(), ['cesium', 'navara', 'cesium']);
|
||||
assert.deepEqual(h.remembered, ['navara', 'cesium']);
|
||||
});
|
||||
|
||||
for (const [from, to] of [
|
||||
['cesium', 'navara'],
|
||||
['navara', 'cesium'],
|
||||
]) {
|
||||
test(`a failed ${from} to ${to} switch rolls back without a history entry`, async () => {
|
||||
let refuse = true;
|
||||
const h = harness({
|
||||
urls: [`/?engine=${from}#view`],
|
||||
kind: from,
|
||||
outcome: (kind) => {
|
||||
if (kind === to && refuse) throw new Error(`${to} refused`);
|
||||
},
|
||||
});
|
||||
await h.machine.select(to);
|
||||
assert.equal(h.machine.state().kind, from);
|
||||
assert.deepEqual(h.browser.engines(), [from]);
|
||||
assert.equal(new URL(h.browser.entries[0].url).hash, '#view');
|
||||
assert.deepEqual(h.remembered, []);
|
||||
assert.deepEqual(h.failures, [
|
||||
{ message: `${to} refused`, recovered: true, kind: from },
|
||||
]);
|
||||
// The recovery restarts the parked engine on the retained session.
|
||||
assert.deepEqual(
|
||||
h.log.filter(
|
||||
(line) =>
|
||||
line.startsWith('enter') || line.startsWith('resume:director'),
|
||||
),
|
||||
[`enter:${to}:cold`, `enter:${from}:warm:recovery`, 'resume:director'],
|
||||
);
|
||||
// An ordinary retry afterwards works.
|
||||
refuse = false;
|
||||
await h.machine.select(to);
|
||||
assert.equal(h.machine.state().kind, to);
|
||||
assert.deepEqual(h.browser.engines(), [from, to]);
|
||||
});
|
||||
}
|
||||
|
||||
test('a warm start that fails rolls back warm and later starts cold', async () => {
|
||||
let refuseWarmNavara = false;
|
||||
const h = harness({
|
||||
outcome: (kind, { warm, recovery }) => {
|
||||
if (kind === 'navara' && warm && refuseWarmNavara && !recovery)
|
||||
throw new Error('parked Navara lost');
|
||||
},
|
||||
});
|
||||
await h.machine.select('navara');
|
||||
await h.machine.select('cesium');
|
||||
refuseWarmNavara = true;
|
||||
await h.machine.select('navara');
|
||||
assert.equal(h.machine.state().kind, 'cesium');
|
||||
await h.machine.select('navara');
|
||||
assert.equal(h.machine.state().kind, 'navara');
|
||||
assert.deepEqual(
|
||||
h.log.filter((line) => line.startsWith('enter')),
|
||||
[
|
||||
'enter:navara:cold',
|
||||
'enter:cesium:warm',
|
||||
'enter:navara:warm',
|
||||
'enter:cesium:warm:recovery',
|
||||
'enter:navara:cold',
|
||||
],
|
||||
);
|
||||
assert.deepEqual(h.browser.engines(), [
|
||||
'cesium',
|
||||
'navara',
|
||||
'cesium',
|
||||
'navara',
|
||||
]);
|
||||
});
|
||||
|
||||
test('after a failed recovery the page stays usable and the next pick starts an engine', async () => {
|
||||
let refuse = true;
|
||||
const h = harness({
|
||||
outcome: () => {
|
||||
if (refuse) throw new Error('no WebGL');
|
||||
},
|
||||
});
|
||||
await h.machine.select('navara');
|
||||
assert.equal(h.machine.state().failed, true);
|
||||
assert.equal(h.machine.state().busy, false);
|
||||
assert.deepEqual(
|
||||
h.failures.map(({ recovered }) => recovered),
|
||||
[false],
|
||||
);
|
||||
assert.deepEqual(h.browser.engines(), ['cesium']);
|
||||
refuse = false;
|
||||
// No running engine to leave: the pick starts one directly.
|
||||
await assert.doesNotReject(async () => h.machine.select('navara'));
|
||||
assert.equal(h.machine.state().kind, 'navara');
|
||||
assert.equal(h.machine.state().failed, false);
|
||||
assert.equal(h.log.filter((line) => line.startsWith('leave')).length, 1);
|
||||
});
|
||||
|
||||
test('pagehide during a start neither rolls back nor starts another engine', async () => {
|
||||
const gate = deferred();
|
||||
const entered = deferred();
|
||||
const h = harness({
|
||||
outcome: (kind) => {
|
||||
if (kind !== 'navara') return undefined;
|
||||
entered.resolve();
|
||||
return gate.promise;
|
||||
},
|
||||
});
|
||||
const switching = h.machine.select('navara');
|
||||
await entered.promise;
|
||||
h.lifetime.abort();
|
||||
gate.reject(new DOMException('aborted', 'AbortError'));
|
||||
await switching;
|
||||
assert.deepEqual(
|
||||
h.log.filter((line) => line.startsWith('enter')),
|
||||
['enter:navara:cold'],
|
||||
);
|
||||
assert.deepEqual(h.failures, []);
|
||||
assert.equal(h.machine.select('cesium'), null);
|
||||
});
|
||||
|
||||
test('pagehide while the outgoing engine is released starts nothing', async () => {
|
||||
const gate = deferred();
|
||||
const h = harness();
|
||||
const enter = [];
|
||||
const machine = createEngineSwitch({
|
||||
kind: 'cesium',
|
||||
requested: h.browser.requested,
|
||||
signal: h.lifetime.signal,
|
||||
leave: () => gate.promise,
|
||||
enter: async (kind) => enter.push(kind),
|
||||
address: createEngineAddress({
|
||||
location: h.browser.location,
|
||||
history: h.browser.history,
|
||||
}),
|
||||
});
|
||||
const switching = machine.select('navara');
|
||||
h.lifetime.abort();
|
||||
gate.resolve();
|
||||
await switching;
|
||||
assert.deepEqual(enter, []);
|
||||
});
|
||||
|
||||
test('a slow first frame never rolls back a started engine', async () => {
|
||||
const timers = [];
|
||||
const engine = {
|
||||
frames: { postRender: { addEventListener: () => () => {} } },
|
||||
render: { request() {} },
|
||||
};
|
||||
const h = harness();
|
||||
let frame;
|
||||
const machine = createEngineSwitch({
|
||||
kind: 'cesium',
|
||||
requested: h.browser.requested,
|
||||
signal: h.lifetime.signal,
|
||||
leave: async () => {},
|
||||
enter: async () => {},
|
||||
settle: async () => {
|
||||
frame = waitForFirstFrame(engine, {
|
||||
document: {
|
||||
hidden: false,
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
},
|
||||
setTimer: (fn) => timers.push(fn),
|
||||
clearTimer() {},
|
||||
});
|
||||
timers.shift()();
|
||||
await frame;
|
||||
},
|
||||
address: createEngineAddress({
|
||||
location: h.browser.location,
|
||||
history: h.browser.history,
|
||||
}),
|
||||
onFailure: () => assert.fail('a slow frame must not fail the switch'),
|
||||
});
|
||||
await machine.select('navara');
|
||||
assert.equal(await frame, false);
|
||||
assert.equal(machine.state().kind, 'navara');
|
||||
assert.deepEqual(h.browser.engines(), ['cesium', 'navara']);
|
||||
});
|
||||
|
||||
test('the first-frame wait resolves on a frame, on a hidden tab and on timeout', async () => {
|
||||
const listeners = new Set();
|
||||
const doc = {
|
||||
hidden: false,
|
||||
addEventListener: (_type, fn) => listeners.add(fn),
|
||||
removeEventListener: (_type, fn) => listeners.delete(fn),
|
||||
};
|
||||
let draw;
|
||||
let requests = 0;
|
||||
const engine = {
|
||||
frames: {
|
||||
postRender: {
|
||||
addEventListener(fn) {
|
||||
draw = fn;
|
||||
return () => {
|
||||
draw = null;
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
render: {
|
||||
request: () => requests++,
|
||||
},
|
||||
};
|
||||
const timers = new Map();
|
||||
const options = {
|
||||
document: doc,
|
||||
setTimer: (fn) => {
|
||||
const id = Symbol('timer');
|
||||
timers.set(id, fn);
|
||||
return id;
|
||||
},
|
||||
clearTimer: (id) => timers.delete(id),
|
||||
};
|
||||
// A drawn frame.
|
||||
const drawn = waitForFirstFrame(engine, options);
|
||||
draw();
|
||||
assert.equal(await drawn, true);
|
||||
assert.equal(timers.size, 0);
|
||||
assert.equal(listeners.size, 0);
|
||||
// The tab hides while waiting.
|
||||
const hiding = waitForFirstFrame(engine, options);
|
||||
doc.hidden = true;
|
||||
for (const fn of [...listeners]) fn();
|
||||
assert.equal(await hiding, false);
|
||||
assert.equal(draw, null);
|
||||
// Already hidden: nothing to wait for and no frame requested.
|
||||
const before = requests;
|
||||
assert.equal(await waitForFirstFrame(engine, options), false);
|
||||
assert.equal(requests, before);
|
||||
// No frame in time: resolved, never rejected.
|
||||
doc.hidden = false;
|
||||
const slow = waitForFirstFrame(engine, options);
|
||||
[...timers.values()][0]();
|
||||
assert.equal(await slow, false);
|
||||
});
|
||||
|
||||
test('the address keeps the outgoing view on the earlier entry', () => {
|
||||
const browser = fakeBrowser(['/?look=cinematic#lat=1']);
|
||||
const address = createEngineAddress({
|
||||
location: browser.location,
|
||||
history: browser.history,
|
||||
});
|
||||
const token = address.select('cesium', 'navara');
|
||||
assert.deepEqual(browser.engines(), ['navara']);
|
||||
// The incoming engine writes its own view while it starts.
|
||||
browser.history.replaceState(
|
||||
null,
|
||||
'',
|
||||
'/?look=cinematic&engine=navara#lat=2',
|
||||
);
|
||||
address.commit(token);
|
||||
assert.deepEqual(
|
||||
browser.entries.map(({ url }) => url.replace(ORIGIN, '/')),
|
||||
[
|
||||
'/?look=cinematic&engine=cesium#lat=1',
|
||||
'/?look=cinematic&engine=navara#lat=2',
|
||||
],
|
||||
);
|
||||
});
|
||||
Reference in new issue
Block a user