mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-05 19:04:02 +00:00
Merge branch 'main' into upstream/wind-stale
This commit is contained in:
18 files changed
+432
-65
No files matched your search
@@ -13,6 +13,7 @@ export function createApplicationData({
|
||||
// Initialize data layer manager
|
||||
const dataManager = new LayerLifecycle(viewer, {
|
||||
allowQaRegistration,
|
||||
visibilityTarget: document,
|
||||
getSourceAvailability: catalog?.getSourceAvailability,
|
||||
});
|
||||
defer(async () => {
|
||||
|
||||
+60
-17
@@ -72,13 +72,20 @@ function refreshFailureFromStats(stats, label) {
|
||||
/**
|
||||
* LayerLifecycle — Manages registration, toggling, and update loops
|
||||
* for real-time data overlays on the CesiumJS globe.
|
||||
* Hosts may inject a visibilityTarget with hidden/visibilityState and event
|
||||
* listener methods. Without one, periodic work retains its headless behavior.
|
||||
*/
|
||||
export class LayerLifecycle {
|
||||
constructor(
|
||||
viewer,
|
||||
{ allowQaRegistration = false, getSourceAvailability } = {},
|
||||
{
|
||||
allowQaRegistration = false,
|
||||
getSourceAvailability,
|
||||
visibilityTarget = null,
|
||||
} = {},
|
||||
) {
|
||||
this._catalogSourceAvailability = getSourceAvailability;
|
||||
this._visibilityTarget = visibilityTarget;
|
||||
this.viewer = viewer;
|
||||
this._activityListeners = new Set();
|
||||
this.layers = new Map(); // id → { module, enabled, initialized, intervalId, lifecycleState, lifecycleUncertain }
|
||||
@@ -528,6 +535,13 @@ export class LayerLifecycle {
|
||||
}
|
||||
}
|
||||
|
||||
_stopUpdateLoop(entry) {
|
||||
clearInterval(entry.intervalId);
|
||||
entry.intervalId = null;
|
||||
entry.removeVisibilityListener?.();
|
||||
entry.removeVisibilityListener = null;
|
||||
}
|
||||
|
||||
_armUpdateLoop(layerId, entry) {
|
||||
const configuredRefreshInterval = Number(entry.module.refreshInterval);
|
||||
const updateInterval = Number(entry.module.updateInterval);
|
||||
@@ -538,9 +552,45 @@ export class LayerLifecycle {
|
||||
? updateInterval
|
||||
: 0;
|
||||
if (refreshInterval > 0) {
|
||||
entry.intervalId = setInterval(() => {
|
||||
const visibilityDocument = this._visibilityTarget;
|
||||
let intervalId = null;
|
||||
let dueAt = 0;
|
||||
const canPoll = () =>
|
||||
!visibilityDocument?.hidden &&
|
||||
visibilityDocument?.visibilityState !== 'hidden' &&
|
||||
entry.enabled &&
|
||||
!entry.destroying &&
|
||||
!entry.refreshing &&
|
||||
entry.intervalId === intervalId;
|
||||
// dueAt and the interval phase share one origin, so every interval tick
|
||||
// is a due poll. A visibility catch-up re-arms the interval at the new
|
||||
// deadline; otherwise the old phase would skip its next tick.
|
||||
const schedule = () => {
|
||||
clearInterval(intervalId);
|
||||
dueAt = Date.now() + refreshInterval;
|
||||
intervalId = setInterval(onInterval, refreshInterval);
|
||||
entry.intervalId = intervalId;
|
||||
};
|
||||
const onInterval = () => {
|
||||
if (!canPoll()) return;
|
||||
dueAt = Date.now() + refreshInterval;
|
||||
void this._runPeriodicUpdate(layerId, entry);
|
||||
}, refreshInterval);
|
||||
};
|
||||
const onVisibilityChange = () => {
|
||||
if (!canPoll() || Date.now() < dueAt) return;
|
||||
schedule();
|
||||
void this._runPeriodicUpdate(layerId, entry);
|
||||
};
|
||||
schedule();
|
||||
visibilityDocument?.addEventListener?.(
|
||||
'visibilitychange',
|
||||
onVisibilityChange,
|
||||
);
|
||||
entry.removeVisibilityListener = () =>
|
||||
visibilityDocument?.removeEventListener?.(
|
||||
'visibilitychange',
|
||||
onVisibilityChange,
|
||||
);
|
||||
} else if (updateInterval === 0) {
|
||||
entry.intervalId = setInterval(() => {
|
||||
if (!entry.enabled) return;
|
||||
@@ -772,8 +822,7 @@ export class LayerLifecycle {
|
||||
entry.lifecycleUncertain = !compensated && !cleanupConfirmed;
|
||||
settleLifecycle();
|
||||
if (!entry.enabled && entry.intervalId) {
|
||||
clearInterval(entry.intervalId);
|
||||
entry.intervalId = null;
|
||||
this._stopUpdateLoop(entry);
|
||||
}
|
||||
this._publishActivity({ type: 'status' });
|
||||
if (!compensated) {
|
||||
@@ -833,8 +882,7 @@ export class LayerLifecycle {
|
||||
}
|
||||
if (signal?.aborted) return finishCancelledDisable('disable');
|
||||
if (entry.intervalId) {
|
||||
clearInterval(entry.intervalId);
|
||||
entry.intervalId = null;
|
||||
this._stopUpdateLoop(entry);
|
||||
}
|
||||
entry.enabled = false;
|
||||
entry.lifecycleUncertain = false;
|
||||
@@ -845,8 +893,7 @@ export class LayerLifecycle {
|
||||
let abortCleanup = null;
|
||||
const cancelEnable = () => {
|
||||
if (entry.intervalId) {
|
||||
clearInterval(entry.intervalId);
|
||||
entry.intervalId = null;
|
||||
this._stopUpdateLoop(entry);
|
||||
}
|
||||
// Disable immediately so modules with their own AbortController (Radio)
|
||||
// cancel pending update work at the same turn boundary. A second
|
||||
@@ -876,8 +923,7 @@ export class LayerLifecycle {
|
||||
// a later abort cannot revoke a successful retry.
|
||||
signal?.removeEventListener('abort', cancelEnable);
|
||||
if (entry.intervalId) {
|
||||
clearInterval(entry.intervalId);
|
||||
entry.intervalId = null;
|
||||
this._stopUpdateLoop(entry);
|
||||
}
|
||||
await abortCleanup;
|
||||
let cleanupConfirmed = false;
|
||||
@@ -918,8 +964,7 @@ export class LayerLifecycle {
|
||||
};
|
||||
const finishFailedEnable = async (phase, error) => {
|
||||
if (entry.intervalId) {
|
||||
clearInterval(entry.intervalId);
|
||||
entry.intervalId = null;
|
||||
this._stopUpdateLoop(entry);
|
||||
}
|
||||
let cleanupConfirmed = false;
|
||||
try {
|
||||
@@ -1029,8 +1074,7 @@ export class LayerLifecycle {
|
||||
// Always clear any stale interval before assigning a new one, so we never
|
||||
// orphan a running timer and end up double-polling.
|
||||
if (entry.intervalId) {
|
||||
clearInterval(entry.intervalId);
|
||||
entry.intervalId = null;
|
||||
this._stopUpdateLoop(entry);
|
||||
}
|
||||
|
||||
// Manager-owned periodic refresh work has one normalized loading/error
|
||||
@@ -2158,8 +2202,7 @@ export class LayerLifecycle {
|
||||
return false;
|
||||
}
|
||||
if (entry.intervalId) {
|
||||
clearInterval(entry.intervalId);
|
||||
entry.intervalId = null;
|
||||
this._stopUpdateLoop(entry);
|
||||
}
|
||||
entry.enabled = false;
|
||||
}
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ export { layerFeedState } from '../ui/layers.js';
|
||||
/** Compatibility facade for callers that construct a manager with its panel. */
|
||||
export class DataLayerManager extends LayerLifecycle {
|
||||
constructor(viewer, options) {
|
||||
super(viewer, options);
|
||||
super(viewer, { visibilityTarget: globalThis.document, ...options });
|
||||
this._presentation = new LayerPresentation(this);
|
||||
}
|
||||
buildTogglePanel(container) {
|
||||
|
||||
@@ -3492,3 +3492,92 @@ test('refreshLayerStats reaches presentation through the bare lifecycle', async
|
||||
lifecycle.refreshLayerStats();
|
||||
assert.deepEqual(changes, ['status']);
|
||||
});
|
||||
|
||||
test('periodic polls pause hidden, catch up once when due, and dispose visibility listeners', async (t) => {
|
||||
const listeners = new Set();
|
||||
const doc = {
|
||||
hidden: false,
|
||||
addEventListener: (_name, fn) => listeners.add(fn),
|
||||
removeEventListener: (_name, fn) => listeners.delete(fn),
|
||||
};
|
||||
t.mock.timers.enable({ apis: ['setInterval', 'Date'], now: 1000 });
|
||||
const { LayerLifecycle } = await import('./lifecycle.js');
|
||||
const manager = new LayerLifecycle({}, { visibilityTarget: doc });
|
||||
const { module, calls } = makeSlowLayer('hidden-poll');
|
||||
manager.register(module);
|
||||
await manager.setEnabled('hidden-poll', true);
|
||||
assert.equal(calls.update, 1);
|
||||
doc.hidden = true;
|
||||
t.mock.timers.tick(10000);
|
||||
assert.equal(calls.update, 1);
|
||||
assert.equal(await manager.refreshLayer('hidden-poll'), true);
|
||||
assert.equal(calls.update, 2, 'explicit refresh remains allowed');
|
||||
doc.hidden = false;
|
||||
for (const fn of listeners) fn();
|
||||
for (const fn of listeners) fn();
|
||||
assert.equal(calls.update, 3);
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await manager.destroyAll();
|
||||
assert.equal(listeners.size, 0);
|
||||
t.mock.timers.tick(10000);
|
||||
assert.equal(calls.update, 3);
|
||||
});
|
||||
|
||||
async function resumeBetweenTicks(t, { failResume = false } = {}) {
|
||||
const listeners = new Set();
|
||||
const doc = {
|
||||
hidden: false,
|
||||
addEventListener: (_name, fn) => listeners.add(fn),
|
||||
removeEventListener: (_name, fn) => listeners.delete(fn),
|
||||
};
|
||||
t.mock.timers.enable({ apis: ['setInterval', 'Date'], now: 1000 });
|
||||
const { LayerLifecycle } = await import('./lifecycle.js');
|
||||
const manager = new LayerLifecycle({}, { visibilityTarget: doc });
|
||||
const { module, calls } = makeSlowLayer('resume-poll');
|
||||
const updates = [];
|
||||
module.update = async () => {
|
||||
calls.update++;
|
||||
updates.push(Date.now());
|
||||
await Promise.resolve();
|
||||
if (failResume && updates.length === 2) throw new Error('resume failed');
|
||||
};
|
||||
manager.register(module);
|
||||
await manager.setEnabled('resume-poll', true);
|
||||
assert.deepEqual(updates, [1000]);
|
||||
doc.hidden = true;
|
||||
t.mock.timers.tick(1000); // 2000: due tick skipped while hidden
|
||||
t.mock.timers.tick(500); // 2500: return between ticks
|
||||
doc.hidden = false;
|
||||
for (const fn of listeners) fn();
|
||||
assert.deepEqual(updates, [1000, 2500], 'overdue poll runs once on return');
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
const managerRefreshError = manager.layers.get('resume-poll').managerRefreshError;
|
||||
if (failResume) assert.equal(managerRefreshError, 'resume failed');
|
||||
else assert.equal(managerRefreshError, null);
|
||||
t.mock.timers.tick(999); // 3499: the old 3000 phase must not fire
|
||||
assert.deepEqual(updates, [1000, 2500]);
|
||||
t.mock.timers.tick(1); // 3500: one interval after the resume poll
|
||||
assert.deepEqual(updates, [1000, 2500, 3500]);
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
t.mock.timers.tick(1000);
|
||||
assert.deepEqual(updates, [1000, 2500, 3500, 4500], 'new phase keeps one interval');
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await manager.destroyAll();
|
||||
assert.equal(listeners.size, 0);
|
||||
t.mock.timers.tick(5000);
|
||||
assert.equal(updates.length, 4);
|
||||
}
|
||||
|
||||
test('periodic polls realign to the deadline after a between-ticks resume', async (t) => {
|
||||
await resumeBetweenTicks(t);
|
||||
});
|
||||
|
||||
test('periodic polls realign to the deadline after a failed resume refresh', async (t) => {
|
||||
await resumeBetweenTicks(t, { failResume: true });
|
||||
});
|
||||
@@ -97,6 +97,7 @@ export function createLifecycle({ state, services, parts }) {
|
||||
else if (hidden) {
|
||||
hidden = false;
|
||||
parts.rendering.resumePlayback();
|
||||
parts.viewport.runProximityCheck();
|
||||
}
|
||||
}
|
||||
function bindVisibility() {
|
||||
|
||||
@@ -75,6 +75,11 @@ export function createViewport({ state, services, parts }) {
|
||||
}
|
||||
|
||||
function runProximityCheck() {
|
||||
if (
|
||||
globalThis.document?.hidden ||
|
||||
globalThis.document?.visibilityState === 'hidden'
|
||||
)
|
||||
return;
|
||||
if (!state._enabled || !state._viewer) return;
|
||||
refreshViewBounds();
|
||||
const altitude = getCameraAltitude();
|
||||
|
||||
@@ -99,6 +99,18 @@ function stubTerrainUpstream(t) {
|
||||
return asked;
|
||||
}
|
||||
|
||||
/**
|
||||
* A cache file of the test's own, removed when the test ends. Without one the
|
||||
* proxy falls back to this checkout's `.gev-cache/terrain-heights.json`, and a
|
||||
* point the app has already cached there would answer a request the test
|
||||
* expects to reach the stubbed upstream (#1242).
|
||||
*/
|
||||
async function isolatedCachePath(t) {
|
||||
const dir = await mkdtemp(path.join(tmpdir(), 'gev-terrain-'));
|
||||
t.after(() => rm(dir, { recursive: true, force: true }));
|
||||
return path.join(dir, 'terrain-heights.json');
|
||||
}
|
||||
|
||||
test('a coordinate off the globe is not a cache key', () => {
|
||||
// Finite but not on Earth — the old guard accepted every one of these.
|
||||
for (const raw of [
|
||||
@@ -122,7 +134,9 @@ test('an out-of-range point is refused before it reaches upstream or the cache',
|
||||
upstreamCalls += 1;
|
||||
return new Response('[]', { status: 200 });
|
||||
});
|
||||
const route = install(terrainHeightsProxy()).get('/api/terrain/heights');
|
||||
const route = install(
|
||||
terrainHeightsProxy({ cachePath: await isolatedCachePath(t) }),
|
||||
).get('/api/terrain/heights');
|
||||
|
||||
const refused = await request(route, { url: '/?points=0,91' });
|
||||
assert.equal(refused.statusCode, 400);
|
||||
@@ -135,7 +149,9 @@ test('an out-of-range point is refused before it reaches upstream or the cache',
|
||||
|
||||
test('one out-of-range point rejects the batch it is hidden in', async (t) => {
|
||||
stubFetch(t, async () => new Response('[]', { status: 200 }));
|
||||
const route = install(terrainHeightsProxy()).get('/api/terrain/heights');
|
||||
const route = install(
|
||||
terrainHeightsProxy({ cachePath: await isolatedCachePath(t) }),
|
||||
).get('/api/terrain/heights');
|
||||
const mixed = await request(route, {
|
||||
url: '/?points=-97.74,30.26;0,999;-97.75,30.27',
|
||||
});
|
||||
@@ -145,9 +161,12 @@ test('one out-of-range point rejects the batch it is hidden in', async (t) => {
|
||||
test('the point cache stops growing, and an evicted point is simply refetched', async (t) => {
|
||||
const asked = stubTerrainUpstream(t);
|
||||
// A ceiling of 3 exercises the same code path 50,000 does, in four requests.
|
||||
const route = install(terrainHeightsProxy({ cacheMaxEntries: 3 })).get(
|
||||
'/api/terrain/heights',
|
||||
);
|
||||
const route = install(
|
||||
terrainHeightsProxy({
|
||||
cachePath: await isolatedCachePath(t),
|
||||
cacheMaxEntries: 3,
|
||||
}),
|
||||
).get('/api/terrain/heights');
|
||||
|
||||
const point = (i) => `-97.7${i}000,30.26000`;
|
||||
for (let i = 1; i <= 4; i += 1)
|
||||
@@ -168,9 +187,7 @@ test('the point cache stops growing, and an evicted point is simply refetched',
|
||||
test('an over-large cache file is not read back into memory', async (t) => {
|
||||
const asked = stubTerrainUpstream(t);
|
||||
const point = '-97.74000,30.26000';
|
||||
const dir = await mkdtemp(path.join(tmpdir(), 'gev-terrain-'));
|
||||
const cachePath = path.join(dir, 'terrain-heights.json');
|
||||
t.after(() => rm(dir, { recursive: true, force: true }));
|
||||
const cachePath = await isolatedCachePath(t);
|
||||
|
||||
// A cache file holding the answer, but larger than the ceiling allows.
|
||||
const padded = {
|
||||
@@ -201,7 +218,9 @@ test('an over-large cache file is not read back into memory', async (t) => {
|
||||
|
||||
test('the route refuses a flood of requests from one client', async (t) => {
|
||||
stubTerrainUpstream(t);
|
||||
const route = install(terrainHeightsProxy()).get('/api/terrain/heights');
|
||||
const route = install(
|
||||
terrainHeightsProxy({ cachePath: await isolatedCachePath(t) }),
|
||||
).get('/api/terrain/heights');
|
||||
|
||||
let refusedAt = 0;
|
||||
for (let i = 1; i <= 95; i += 1) {
|
||||
@@ -218,7 +237,9 @@ test('the route refuses a flood of requests from one client', async (t) => {
|
||||
|
||||
test('a cross-site page cannot fill the cache or spend the visitor quota', async (t) => {
|
||||
const asked = stubTerrainUpstream(t);
|
||||
const route = install(terrainHeightsProxy()).get('/api/terrain/heights');
|
||||
const route = install(
|
||||
terrainHeightsProxy({ cachePath: await isolatedCachePath(t) }),
|
||||
).get('/api/terrain/heights');
|
||||
const host = 'localhost:5173';
|
||||
const refused = [
|
||||
{ host, 'sec-fetch-site': 'cross-site' }, // <img src> from any web page
|
||||
@@ -253,7 +274,9 @@ test('a cross-site page cannot fill the cache or spend the visitor quota', async
|
||||
|
||||
test('the app served behind a reverse proxy still gets terrain', async (t) => {
|
||||
const asked = stubTerrainUpstream(t);
|
||||
const route = install(terrainHeightsProxy()).get('/api/terrain/heights');
|
||||
const route = install(
|
||||
terrainHeightsProxy({ cachePath: await isolatedCachePath(t) }),
|
||||
).get('/api/terrain/heights');
|
||||
const host = 'globe.example.lan';
|
||||
// What nginx/Caddy/Cloudflare add in front of a same-origin app fetch. The
|
||||
// cost-bearing routes refuse these; terrain is keyless and needed to render,
|
||||
@@ -347,7 +370,9 @@ test('a second client keeps its own quota', async (t) => {
|
||||
stubFetch(t, async () =>
|
||||
Response.json([{ lng: -97.74, lat: 30.26, height: 150 }]),
|
||||
);
|
||||
const route = install(terrainHeightsProxy()).get('/api/terrain/heights');
|
||||
const route = install(
|
||||
terrainHeightsProxy({ cachePath: await isolatedCachePath(t) }),
|
||||
).get('/api/terrain/heights');
|
||||
|
||||
for (let i = 0; i < 90; i += 1)
|
||||
await request(route, {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { getTransitFeed } from '../data/transitFeeds.js';
|
||||
import {
|
||||
chooseLiveCities,
|
||||
selectStyle,
|
||||
@@ -101,6 +102,18 @@ test('live visual cities follow local operating hours in summer and winter', ()
|
||||
const cities = chooseLiveCities(now);
|
||||
assert.ok(cities.length >= 1);
|
||||
for (const city of cities) {
|
||||
const feed = getTransitFeed(city.feedId);
|
||||
assert.ok(feed, `${city.id} has a registered feed`);
|
||||
const distanceKm =
|
||||
111.32 *
|
||||
Math.hypot(
|
||||
feed.center.lat - city.lat,
|
||||
(feed.center.lon - city.lon) * Math.cos((city.lat * Math.PI) / 180),
|
||||
);
|
||||
assert.ok(
|
||||
distanceKm < feed.loadRadiusKm,
|
||||
`${city.id} is inside its feed's admission region`,
|
||||
);
|
||||
const local = Number(
|
||||
new Intl.DateTimeFormat('en', {
|
||||
timeZone: city.zone,
|
||||
|
||||
Reference in new issue
Block a user