mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-17 00:32:21 +00:00
Merge upstream/main 73c14ac74
This commit is contained in:
commit
a64b41b3f0
1594 files changed
+155855
-24143
No files matched your search
@@ -1,22 +1,27 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { expandApplicationHtml, APPLICATION_TEMPLATES } from '../../build/application-html.js';
|
||||
import { APPLICATION_VIEWS } from '../ui/views/index.js';
|
||||
import { readApplicationHtml } from '../testSupport/applicationHtml.mjs';
|
||||
|
||||
test('the standalone document expands every component once and preserves unique element ids', () => {
|
||||
const source = readFileSync(new URL('../../index.html', import.meta.url), 'utf8');
|
||||
const html = expandApplicationHtml(source);
|
||||
assert.equal([...source.matchAll(/gev:template /g)].length, APPLICATION_TEMPLATES.length);
|
||||
assert.doesNotMatch(html, /gev:template/);
|
||||
const ids = [...html.matchAll(/\sid="([^"]+)"/g)].map(match => match[1]);
|
||||
const source = readFileSync(new URL('../../index.html', import.meta.url), 'utf8');
|
||||
|
||||
test('the standalone document hosts every view once and keeps element ids unique', async () => {
|
||||
const hosts = [...source.matchAll(/data-gev-view="([^"]+)"/g)].map((match) => match[1]);
|
||||
// Order is stacking order for fixed elements that share a z-index.
|
||||
assert.deepEqual(hosts, ['scene-chrome', 'cockpit', 'display-controls', 'command-dock', 'layer-panels', 'context', 'welcome', 'provider-settings', 'intel-hud']);
|
||||
assert.deepEqual([...hosts].sort(), Object.keys(APPLICATION_VIEWS).sort());
|
||||
const html = await readApplicationHtml();
|
||||
const ids = [...html.matchAll(/\sid="([^"]+)"/g)].map((match) => match[1]);
|
||||
assert.equal(new Set(ids).size, ids.length);
|
||||
assert.match(html, /id="cesiumContainer"/);
|
||||
assert.match(html, /type="module" src="\/src\/main.js"/);
|
||||
});
|
||||
|
||||
test('component selection includes only requested markup and refuses filesystem traversal', () => {
|
||||
const html = expandApplicationHtml('<!-- gev:template welcome -->\n');
|
||||
assert.match(html, /id="first-run-launcher"/);
|
||||
assert.doesNotMatch(html, /id="cesiumContainer"/);
|
||||
assert.throws(() => expandApplicationHtml('<!-- gev:template ../../.env -->'), /Unknown application template/);
|
||||
test('the loading screen is static markup, so it paints before any script runs', () => {
|
||||
const loading = source.indexOf('id="loading-screen"');
|
||||
assert.ok(loading > 0);
|
||||
assert.ok(loading < source.indexOf('type="module" src="/src/main.js"'));
|
||||
assert.match(source, /class="loader-status" data-i18n>Initializing photorealistic world\.\.\.</);
|
||||
assert.doesNotMatch(source, /gev:template/);
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
// THE BOUNDED ANSWER CACHE — memory and disk bounds for the Nominatim area
|
||||
// and OSM routes. Every memory insertion is bounded (disk hits included), and
|
||||
// the disk keeps to its entry and byte quotas, removing expired files first.
|
||||
//
|
||||
// Run with: npm test
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { promises as fsp } from 'node:fs';
|
||||
import { createBoundedCache } from '../../server/providers/common/boundedCache.js';
|
||||
|
||||
async function tempDir() {
|
||||
return fsp.mkdtemp(path.join(os.tmpdir(), 'gev-bounded-cache-'));
|
||||
}
|
||||
|
||||
test('disk hits are bounded in memory like fresh answers', async () => {
|
||||
const dir = await tempDir();
|
||||
const writer = createBoundedCache({
|
||||
dir,
|
||||
ttlMs: 60_000,
|
||||
maxMemoryEntries: 100,
|
||||
maxDiskEntries: 200,
|
||||
});
|
||||
for (let i = 0; i < 75; i += 1) await writer.set(`k${i}`, `v${i}`);
|
||||
const reader = createBoundedCache({
|
||||
dir,
|
||||
ttlMs: 60_000,
|
||||
maxMemoryEntries: 10,
|
||||
maxDiskEntries: 200,
|
||||
});
|
||||
for (let i = 0; i < 75; i += 1)
|
||||
assert.equal(await reader.get(`k${i}`), `v${i}`);
|
||||
assert.equal(reader.memorySize, 10);
|
||||
await fsp.rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test('the disk keeps to its entry and byte quotas and drops expired files', async () => {
|
||||
const dir = await tempDir();
|
||||
let clock = 1_000_000;
|
||||
const cache = createBoundedCache({
|
||||
dir,
|
||||
ttlMs: 10_000,
|
||||
maxDiskEntries: 5,
|
||||
maxDiskBytes: 10_000,
|
||||
now: () => clock,
|
||||
});
|
||||
for (let i = 0; i < 12; i += 1) await cache.set(`k${i}`, 'x'.repeat(100));
|
||||
await cache.prune();
|
||||
let files = await fsp.readdir(dir);
|
||||
assert.ok(files.length <= 5, `${files.length} files`);
|
||||
await cache.set('big', 'y'.repeat(20_000));
|
||||
await cache.prune();
|
||||
const sizes = await Promise.all(
|
||||
(await fsp.readdir(dir)).map(
|
||||
async (name) => (await fsp.stat(path.join(dir, name))).size,
|
||||
),
|
||||
);
|
||||
assert.ok(sizes.reduce((a, b) => a + b, 0) <= 10_000, 'byte quota holds');
|
||||
// Age every file past the TTL, then write once more: the old files go.
|
||||
const past = new Date(Date.now() - 3_600_000);
|
||||
for (const name of await fsp.readdir(dir))
|
||||
await fsp.utimes(path.join(dir, name), past, past);
|
||||
clock = Date.now();
|
||||
await cache.set('fresh', 'z');
|
||||
await cache.prune();
|
||||
files = await fsp.readdir(dir);
|
||||
assert.equal(files.length, 1);
|
||||
assert.equal(await cache.get('k0'), undefined);
|
||||
await fsp.rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test('an expired entry is not served', async () => {
|
||||
let clock = 0;
|
||||
const cache = createBoundedCache({ dir: null, ttlMs: 100, now: () => clock });
|
||||
await cache.set('a', 1);
|
||||
clock = 50;
|
||||
assert.equal(await cache.get('a'), 1);
|
||||
clock = 500;
|
||||
assert.equal(await cache.get('a'), undefined);
|
||||
});
|
||||
@@ -6,6 +6,12 @@ import { tomtomProxy } from 'gods-eye-view/server/providers/traffic';
|
||||
import { firmsProxy } from 'gods-eye-view/server/providers/firms';
|
||||
import { gbfsProxy } from 'gods-eye-view/server/providers/gbfs';
|
||||
import { localProviderPlugins } from '../../server/providers/local.js';
|
||||
import { makeFixtureRoot } from './fixtureRoot.mjs';
|
||||
|
||||
const nominatimStorageDir = await makeFixtureRoot(
|
||||
'gev-environment-composition-',
|
||||
);
|
||||
test.after(() => fsp.rm(nominatimStorageDir, { recursive: true, force: true }));
|
||||
|
||||
function install(plugin, hook = 'configureServer') {
|
||||
const routes = new Map();
|
||||
@@ -88,7 +94,7 @@ test('standalone composition mounts every extracted provider exactly once withou
|
||||
t.mock.method(globalThis, 'fetch', () => {
|
||||
throw Error('construction must not fetch');
|
||||
});
|
||||
const plugins = localProviderPlugins();
|
||||
const plugins = localProviderPlugins({ nominatimStorageDir });
|
||||
for (const factory of [
|
||||
terrainHeightsProxy,
|
||||
tomtomProxy,
|
||||
@@ -158,6 +164,7 @@ test('terrain middleware migrates valid legacy disk points without fabricating o
|
||||
test('traffic middleware preserves keyless mode, caching, stale budget fallback and UTC rollover', async (t) => {
|
||||
isolate(t, { TOMTOM_API_KEY: '', TOMTOM_DAILY_TILE_BUDGET: '1' });
|
||||
let now = Date.UTC(2026, 8, 12, 12);
|
||||
const fetchedAt = String(now);
|
||||
t.mock.method(Date, 'now', () => now);
|
||||
let calls = 0;
|
||||
t.mock.method(globalThis, 'fetch', async (raw) => {
|
||||
@@ -182,10 +189,10 @@ test('traffic middleware preserves keyless mode, caching, stale budget fallback
|
||||
assert.equal(json(await request('/status')).dailyCount, 1);
|
||||
assert.equal(calls, 1);
|
||||
now += 120001;
|
||||
assert.equal(
|
||||
(await request('/flow/8/1/1.pbf')).headers['x-tomtom-cache'],
|
||||
'STALE-BUDGET',
|
||||
);
|
||||
const staleTile = await request('/flow/8/1/1.pbf');
|
||||
assert.equal(staleTile.headers['x-tomtom-cache'], 'STALE-BUDGET');
|
||||
// The stale copy still says when TomTom produced it.
|
||||
assert.equal(staleTile.headers['x-tomtom-fetched-at'], fetchedAt);
|
||||
assert.equal((await request('/flow/8/2/1.pbf')).status, 429);
|
||||
assert.equal(calls, 1);
|
||||
now += 86400000;
|
||||
@@ -410,3 +417,156 @@ test('terrain middleware retains successful chunks around a failure and retries
|
||||
);
|
||||
assert.equal(requests.length, 4);
|
||||
});
|
||||
|
||||
test('after a 429 the terrain proxy leaves the upstream alone and logs once', async (t) => {
|
||||
isolate(t);
|
||||
const warnings = [];
|
||||
t.mock.method(console, 'warn', (...args) => warnings.push(args.join(' ')));
|
||||
let calls = 0;
|
||||
t.mock.method(globalThis, 'fetch', async () => {
|
||||
calls += 1;
|
||||
return new Response('', { status: 429 });
|
||||
});
|
||||
t.mock.timers.enable({ apis: ['Date', 'setTimeout'], now: 1_000_000 });
|
||||
const request = install(terrainHeightsProxy());
|
||||
// The retries' backoff runs on mocked time.
|
||||
let settled = false;
|
||||
const first = request('/?points=1,2').then(() => {
|
||||
settled = true;
|
||||
});
|
||||
for (let step = 0; step < 60 && !settled; step += 1) {
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
t.mock.timers.tick(1_000);
|
||||
}
|
||||
assert.ok(settled, 'the first request settles within its retry budget');
|
||||
await first;
|
||||
const afterFirst = calls;
|
||||
assert.ok(afterFirst >= 1);
|
||||
assert.equal(warnings.length, 1);
|
||||
assert.match(warnings[0], /HTTP 429; pausing upstream for 60 s/);
|
||||
// New points during the pause: no upstream call, no new log line.
|
||||
const paused = await request('/?points=3,4');
|
||||
assert.equal(calls, afterFirst);
|
||||
assert.equal(paused.status, 502);
|
||||
assert.equal(warnings.length, 1);
|
||||
});
|
||||
|
||||
test('a far-off Retry-After pauses the terrain upstream for at most 10 minutes', async (t) => {
|
||||
isolate(t);
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
t.mock.timers.enable({ apis: ['Date', 'setTimeout'], now: 1_000_000 });
|
||||
let limited = true;
|
||||
t.mock.method(globalThis, 'fetch', async () =>
|
||||
limited
|
||||
? new Response('', { status: 429, headers: { 'retry-after': '86400' } })
|
||||
: Response.json({ results: [{ ellipsoid: 100 }] }),
|
||||
);
|
||||
const request = install(terrainHeightsProxy());
|
||||
// The first request spends its retry budget on 429s, then the pause begins.
|
||||
let settled = false;
|
||||
const first = request('/?points=1,2').then((res) => {
|
||||
settled = true;
|
||||
return res;
|
||||
});
|
||||
// Bounded: the retry budget is 10 s, so 60 simulated seconds is plenty.
|
||||
for (let step = 0; step < 60 && !settled; step += 1) {
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
t.mock.timers.tick(1_000);
|
||||
}
|
||||
assert.ok(settled, 'the first request settles within its retry budget');
|
||||
assert.equal((await first).status, 502);
|
||||
limited = false;
|
||||
const pausedAt = Date.now();
|
||||
t.mock.timers.setTime(pausedAt + 9 * 60_000);
|
||||
assert.equal((await request('/?points=3,4')).status, 502, 'still paused');
|
||||
t.mock.timers.setTime(pausedAt + 10 * 60_000 + 1);
|
||||
assert.equal((await request('/?points=3,4')).status, 200, 'pause over');
|
||||
});
|
||||
|
||||
/** Drive mocked timers until `promise` settles; the retry budget is 10 s. */
|
||||
async function settleOnMockedTime(t, promise) {
|
||||
let settled = false;
|
||||
const tracked = promise.finally(() => {
|
||||
settled = true;
|
||||
});
|
||||
for (let step = 0; step < 60 && !settled; step += 1) {
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
t.mock.timers.tick(1_000);
|
||||
}
|
||||
assert.ok(settled, 'the request settles within its retry budget');
|
||||
return tracked;
|
||||
}
|
||||
|
||||
test('during a terrain 429 pause fully cached points, even stale ones, are still served', async (t) => {
|
||||
isolate(t);
|
||||
t.mock.timers.enable({ apis: ['Date', 'setTimeout'], now: 1_000_000 });
|
||||
let calls = 0;
|
||||
let limited = false;
|
||||
t.mock.method(globalThis, 'fetch', async () => {
|
||||
calls += 1;
|
||||
return limited
|
||||
? new Response('', { status: 429, headers: { 'retry-after': '300' } })
|
||||
: Response.json({ results: [{ ellipsoid: 100 }] });
|
||||
});
|
||||
const request = install(terrainHeightsProxy());
|
||||
assert.equal((await request('/?points=5,6')).status, 200);
|
||||
// Past the 30-day TTL, so 5,6 is stale and would normally be refreshed.
|
||||
t.mock.timers.setTime(Date.now() + 31 * 24 * 3600_000);
|
||||
limited = true;
|
||||
const first = await settleOnMockedTime(t, request('/?points=1,2'));
|
||||
assert.equal(first.status, 502);
|
||||
assert.equal(calls, 2, 'a Retry-After past the budget is not retried');
|
||||
const stale = await request('/?points=5,6');
|
||||
assert.equal(stale.status, 200);
|
||||
assert.deepEqual(json(stale).results, [{ ellipsoid: 100 }]);
|
||||
assert.equal((await request('/?points=5,6;7,8')).status, 502);
|
||||
assert.equal(calls, 2, 'no upstream call during the pause');
|
||||
});
|
||||
|
||||
test('a terrain upstream failure other than 429 does not pause later requests', async (t) => {
|
||||
isolate(t);
|
||||
t.mock.timers.enable({ apis: ['Date', 'setTimeout'], now: 1_000_000 });
|
||||
let calls = 0;
|
||||
t.mock.method(globalThis, 'fetch', async () => {
|
||||
calls += 1;
|
||||
return new Response('', { status: 503 });
|
||||
});
|
||||
const request = install(terrainHeightsProxy());
|
||||
const first = await settleOnMockedTime(t, request('/?points=1,2'));
|
||||
assert.equal(first.status, 502);
|
||||
const afterFirst = calls;
|
||||
const second = await settleOnMockedTime(t, request('/?points=3,4'));
|
||||
assert.equal(second.status, 502);
|
||||
assert.ok(calls > afterFirst, 'new points still go upstream after a 503');
|
||||
});
|
||||
|
||||
test('a shorter concurrent Retry-After never cuts a terrain 429 pause short', async (t) => {
|
||||
isolate(t);
|
||||
t.mock.timers.enable({ apis: ['Date', 'setTimeout'], now: 1_000_000 });
|
||||
let calls = 0;
|
||||
t.mock.method(globalThis, 'fetch', async (raw) => {
|
||||
calls += 1;
|
||||
const points = new URL(raw).searchParams.get('points');
|
||||
if (points.startsWith('0.'))
|
||||
return Response.json({ results: [{ ellipsoid: 1 }] });
|
||||
const retryAfter = points.startsWith('1.') ? '300' : '30';
|
||||
return new Response('', {
|
||||
status: 429,
|
||||
headers: { 'retry-after': retryAfter },
|
||||
});
|
||||
});
|
||||
const request = install(terrainHeightsProxy());
|
||||
// Load the disk cache first so both requests below reach the upstream in
|
||||
// order: the 300 s answer lands first, the 30 s answer after it.
|
||||
assert.equal((await request('/?points=0,0')).status, 200);
|
||||
const [long, short] = await settleOnMockedTime(
|
||||
t,
|
||||
Promise.all([request('/?points=1,2'), request('/?points=3,4')]),
|
||||
);
|
||||
assert.equal(long.status, 502);
|
||||
assert.equal(short.status, 502);
|
||||
const afterBoth = calls;
|
||||
t.mock.timers.setTime(Date.now() + 120_000);
|
||||
assert.equal((await request('/?points=5,6')).status, 502);
|
||||
assert.equal(calls, afterBoth, 'still paused by the 300 s Retry-After');
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createServer } from 'node:http';
|
||||
import { once } from 'node:events';
|
||||
import { createGoogleTokenSource } from '../maps/googleTokens.js';
|
||||
import { googleTokenUnavailablePlugin } from '../../server/standalone/google-token-unavailable.js';
|
||||
|
||||
async function withServer({ beforeFallback } = {}, check) {
|
||||
const middlewares = [];
|
||||
const app = {
|
||||
middlewares: {
|
||||
use: (handler) => middlewares.push(handler),
|
||||
},
|
||||
};
|
||||
if (beforeFallback) app.middlewares.use(beforeFallback);
|
||||
googleTokenUnavailablePlugin().configureServer(app);
|
||||
app.middlewares.use((_req, res) => {
|
||||
res.writeHead(404, { 'Content-Type': 'application/json' });
|
||||
res.end(JSON.stringify({ error: 'Unknown API route' }));
|
||||
});
|
||||
|
||||
const server = createServer((req, res) => {
|
||||
let index = 0;
|
||||
const next = () => middlewares[index++]?.(req, res, next);
|
||||
next();
|
||||
});
|
||||
server.listen(0, '127.0.0.1');
|
||||
await once(server, 'listening');
|
||||
const address = server.address();
|
||||
const url = 'http://127.0.0.1:' + address.port;
|
||||
try {
|
||||
await check(url);
|
||||
} finally {
|
||||
server.close();
|
||||
await once(server, 'close');
|
||||
}
|
||||
}
|
||||
|
||||
test('keyless GET and HEAD return uncached 204 instead of 404', async () => {
|
||||
await withServer({}, async (url) => {
|
||||
for (const method of ['GET', 'HEAD']) {
|
||||
const response = await fetch(url + '/api/google/tiles-token?probe=1', {
|
||||
method,
|
||||
});
|
||||
assert.equal(response.status, 204);
|
||||
assert.equal(response.headers.get('cache-control'), 'no-store');
|
||||
assert.equal(await response.text(), '');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test('the existing client treats unavailable tokens as null', async () => {
|
||||
await withServer({}, async (url) => {
|
||||
const source = createGoogleTokenSource({
|
||||
fetchImpl: (path, options) => fetch(new URL(path, url), options),
|
||||
});
|
||||
assert.equal(await source.token(), null);
|
||||
});
|
||||
});
|
||||
|
||||
test('unrelated API paths and unsupported methods remain 404', async () => {
|
||||
await withServer({}, async (url) => {
|
||||
for (const [path, method] of [
|
||||
['/api/google/tiles-token/extra', 'GET'],
|
||||
['/api/not-a-token', 'GET'],
|
||||
['/api/google/tiles-token', 'POST'],
|
||||
]) {
|
||||
const response = await fetch(new URL(path, url), { method });
|
||||
assert.equal(response.status, 404);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test('a real token provider registered first still wins', async () => {
|
||||
await withServer(
|
||||
{
|
||||
beforeFallback: (req, res, next) => {
|
||||
if (req.url !== '/api/google/tiles-token') return next();
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end(
|
||||
JSON.stringify({
|
||||
accessToken: 'server-token',
|
||||
expiresAt: 10000000000000,
|
||||
}),
|
||||
);
|
||||
},
|
||||
},
|
||||
async (url) => {
|
||||
const response = await fetch(url + '/api/google/tiles-token');
|
||||
assert.equal(response.status, 200);
|
||||
assert.equal((await response.json()).accessToken, 'server-token');
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -648,6 +648,69 @@ test('the snapshot method check hands each /track route on to its own handler',
|
||||
}
|
||||
});
|
||||
|
||||
test('OpenSky Basic mode no longer sends username and password: it asks anonymously and warns once', async (t) => {
|
||||
environment(t, {
|
||||
OPENSKY_CLIENT_ID: undefined,
|
||||
OPENSKY_CLIENT_SECRET: undefined,
|
||||
OPENSKY_CREDENTIALS_FILE: undefined,
|
||||
OPENSKY_AUTH_MODE: 'basic',
|
||||
OPENSKY_USERNAME: 'fixture-user',
|
||||
OPENSKY_PASSWORD: 'fixture-password',
|
||||
});
|
||||
const warnings = [];
|
||||
t.mock.method(console, 'warn', (message) => warnings.push(message));
|
||||
const authorizations = [];
|
||||
t.mock.method(globalThis, 'fetch', async (url, options) => {
|
||||
if (url.includes('/states/')) {
|
||||
authorizations.push(options.headers.Authorization);
|
||||
return Response.json({ time: Math.floor(Date.now() / 1000), states: [] });
|
||||
}
|
||||
throw Error(`Unexpected URL: ${url}`);
|
||||
});
|
||||
const fresh = await import(
|
||||
`../../server/providers/aircraft/opensky.js?basic=${Math.random()}`
|
||||
);
|
||||
const flights = install(fresh.openSkyProxy());
|
||||
const first = await flights('/api/flights');
|
||||
assert.equal(first.statusCode, 200);
|
||||
assert.equal(first.headers['x-opensky-auth'], 'anon');
|
||||
assert.equal(first.headers['x-opensky-auth-reason'], 'basic_retired');
|
||||
assert.deepEqual(authorizations, [undefined]);
|
||||
assert.equal(warnings.length, 1);
|
||||
assert.match(warnings[0], /retired username\/password sign-in/);
|
||||
assert.ok(!warnings[0].includes('fixture-password'));
|
||||
});
|
||||
|
||||
test('OpenSky auto mode never falls back to Basic, even when OAuth is rejected', async (t) => {
|
||||
environment(t, {
|
||||
OPENSKY_CLIENT_ID: 'fixture-client',
|
||||
OPENSKY_CLIENT_SECRET: 'fixture-secret',
|
||||
OPENSKY_CREDENTIALS_FILE: undefined,
|
||||
OPENSKY_AUTH_MODE: 'auto',
|
||||
OPENSKY_USERNAME: 'fixture-user',
|
||||
OPENSKY_PASSWORD: 'fixture-password',
|
||||
});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'error', () => {});
|
||||
const authorizations = [];
|
||||
t.mock.method(globalThis, 'fetch', async (url, options) => {
|
||||
if (url.includes('/token'))
|
||||
return Response.json({ access_token: 'fixture-token', expires_in: 1800 });
|
||||
if (url.includes('/states/')) {
|
||||
authorizations.push(options.headers.Authorization);
|
||||
return new Response('', { status: 401 });
|
||||
}
|
||||
if (url.includes('/lat/')) return regionalFallback();
|
||||
throw Error(`Unexpected URL: ${url}`);
|
||||
});
|
||||
const fresh = await import(
|
||||
`../../server/providers/aircraft/opensky.js?auto=${Math.random()}`
|
||||
);
|
||||
await install(fresh.openSkyProxy())('/api/flights', '?lat=30&lon=-97');
|
||||
assert.deepEqual(authorizations, ['Bearer fixture-token']);
|
||||
});
|
||||
|
||||
test('retired military history refuses without upstream I/O while validating identifiers', async (t) => {
|
||||
t.mock.method(globalThis, 'fetch', async () => {
|
||||
assert.fail('retired history must not contact the upstream');
|
||||
|
||||
@@ -9,6 +9,8 @@ import {
|
||||
} from '../../server/providers/space/launch-library.js';
|
||||
import { keySetupStatus } from '../keySetupCore.mjs';
|
||||
import { initKeySetup } from '../keySetup.js';
|
||||
import { createPinia } from 'pinia';
|
||||
import { useProviderSettingsStore } from '../ui/stores/providerSettings.js';
|
||||
|
||||
test('LL2 requests from the same UTC minute share a cache key without mutating callers', () => {
|
||||
const first = new Date('2026-10-17T16:20:00.001Z');
|
||||
@@ -57,60 +59,31 @@ test('LL2 headers identify the app and preserve optional server-only authorizati
|
||||
});
|
||||
|
||||
test('actual setup rendering distinguishes optional paid LL2 from unrelated free keys', async () => {
|
||||
const created = [];
|
||||
const node = () => {
|
||||
const value = {
|
||||
dataset: {},
|
||||
children: [],
|
||||
append(...children) {
|
||||
this.children.push(...children);
|
||||
},
|
||||
querySelector() {
|
||||
return null;
|
||||
},
|
||||
querySelectorAll() {
|
||||
return [];
|
||||
},
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
setAttribute() {},
|
||||
remove() {},
|
||||
};
|
||||
created.push(value);
|
||||
return value;
|
||||
};
|
||||
const rows = node();
|
||||
const root = node();
|
||||
root.querySelector = (selector) =>
|
||||
selector === '[data-key-setup-rows]' ? rows : null;
|
||||
const chip = node();
|
||||
const store = useProviderSettingsStore(createPinia());
|
||||
const status = keySetupStatus({});
|
||||
status.keys = status.keys.filter((key) =>
|
||||
['launch-library', 'mapillary'].includes(key.id),
|
||||
);
|
||||
const setup = await initKeySetup({
|
||||
documentRef: {
|
||||
getElementById: (id) => (id === 'key-setup-chip' ? chip : root),
|
||||
createElement: node,
|
||||
getElementById: (id) => (id === 'key-setup' ? { dataset: {} } : null),
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
},
|
||||
store,
|
||||
fetchImpl: async () => ({ ok: true, json: async () => status }),
|
||||
});
|
||||
assert.ok(setup);
|
||||
try {
|
||||
const ll2 = rows.children.find(
|
||||
(row) => row.dataset.keyId === 'launch-library',
|
||||
const row = (id) => store.view.rows.find((key) => key.id === id);
|
||||
const ll2 = row('launch-library');
|
||||
assert.match(ll2.tierTitle, /optional paid token/i);
|
||||
assert.match(ll2.unlocks, /leave blank/i);
|
||||
assert.match(ll2.unlocks, /no key/i);
|
||||
assert.equal(
|
||||
row('mapillary').tierTitle,
|
||||
'Free key — register, paste, done',
|
||||
);
|
||||
const free = rows.children.find((row) => row.dataset.keyId === 'mapillary');
|
||||
const tier = (row) =>
|
||||
row.children[0].children.find(
|
||||
(child) => child.className === 'key-setup-tier',
|
||||
);
|
||||
assert.match(tier(ll2).title, /optional paid token/i);
|
||||
assert.match(ll2.children[1].textContent, /leave blank/i);
|
||||
assert.match(ll2.children[1].textContent, /no key/i);
|
||||
assert.equal(tier(free).title, 'Free key — register, paste, done');
|
||||
const serialized = JSON.stringify(status);
|
||||
assert.ok(!serialized.includes('owned-fixture-token'));
|
||||
} finally {
|
||||
|
||||
@@ -20,7 +20,11 @@ import {
|
||||
import { openAiRealtimeProxy } from 'gods-eye-view/server/providers/openai';
|
||||
import { keySetupEndpoint } from 'gods-eye-view/server/standalone/key-setup';
|
||||
import { realtimeInstructions } from '../../server/providers/openai/instructions.js';
|
||||
import { GEV_REALTIME_TOOLS } from '../../server/providers/openai/tools.js';
|
||||
import {
|
||||
GEV_REALTIME_TOOLS,
|
||||
offeredTools,
|
||||
realtimeTools,
|
||||
} from '../../server/providers/openai/tools.js';
|
||||
import { createDebugLogHandler } from '../../server/providers/openai/debug-log.js';
|
||||
import { attachVoiceResult } from '../voice/speech.js';
|
||||
import { sanitizeDebugValue } from '../voice/realtimeDiagnostics.js';
|
||||
@@ -164,6 +168,7 @@ test('weather-only requests share upstream work and retain fresh and stale respo
|
||||
test('Realtime handler preserves tools and default instructions, isolates supplied annotation guidance, and keeps the upstream key server-side', async (t) => {
|
||||
env(t, 'OPENAI_API_KEY', 'fixture-upstream-secret');
|
||||
env(t, 'GEV_RATELIMIT_OPENAI_PER_MIN', undefined);
|
||||
env(t, 'OVERPASS_UPSTREAMS', undefined);
|
||||
const sent = [];
|
||||
t.mock.method(globalThis, 'fetch', async (url, options) => {
|
||||
assert.equal(url, 'https://api.openai.com/v1/realtime/client_secrets');
|
||||
@@ -194,7 +199,7 @@ test('Realtime handler preserves tools and default instructions, isolates suppli
|
||||
sent.at(-1).session.instructions,
|
||||
realtimeInstructions(guidance),
|
||||
);
|
||||
assert.deepEqual(sent.at(-1).session.tools, GEV_REALTIME_TOOLS);
|
||||
assert.deepEqual(sent.at(-1).session.tools, realtimeTools());
|
||||
}
|
||||
assert.notEqual(sent[0].session.instructions, sent[1].session.instructions);
|
||||
assert.equal(sent[0].session.instructions, sent[2].session.instructions);
|
||||
@@ -580,6 +585,36 @@ test('OAuth login endpoint selects an existing local sign-in without launching C
|
||||
assert.equal(response.body.includes('fixture-existing-secret'), false);
|
||||
});
|
||||
|
||||
test('osm_query is offered only when an operator configured Overpass', async (t) => {
|
||||
env(t, 'OPENAI_API_KEY', 'fixture-upstream-secret');
|
||||
env(t, 'GEV_RATELIMIT_OPENAI_PER_MIN', undefined);
|
||||
const sent = [];
|
||||
t.mock.method(globalThis, 'fetch', async (_url, options) => {
|
||||
sent.push(JSON.parse(options.body).session);
|
||||
return Response.json({ value: 'fixture-ephemeral' });
|
||||
});
|
||||
const mint = () =>
|
||||
request(install(openAiRealtimeProxy({})).get('/api/realtime/token'), {
|
||||
url: '/',
|
||||
});
|
||||
env(t, 'OVERPASS_UPSTREAMS', undefined);
|
||||
await mint();
|
||||
env(t, 'OVERPASS_UPSTREAMS', 'https://overpass.example/api/interpreter');
|
||||
await mint();
|
||||
const [plain, configured] = sent;
|
||||
const names = (session) => session.tools.map((tool) => tool.name);
|
||||
assert.equal(names(plain).includes('osm_query'), false);
|
||||
assert.doesNotMatch(plain.instructions, /osm_query/);
|
||||
assert.ok(names(plain).includes('resolve_area'));
|
||||
assert.ok(names(plain).includes('find_imagery'));
|
||||
assert.deepEqual(configured.tools, GEV_REALTIME_TOOLS);
|
||||
assert.match(configured.instructions, /osm_query/);
|
||||
assert.equal(
|
||||
configured.instructions,
|
||||
realtimeInstructions(undefined, { overpass: true }),
|
||||
);
|
||||
});
|
||||
|
||||
test('caption transcription is on by default, reported to the client meter, and can be turned off', async (t) => {
|
||||
env(t, 'OPENAI_API_KEY', 'fixture-upstream-secret');
|
||||
env(t, 'GEV_RATELIMIT_OPENAI_PER_MIN', undefined);
|
||||
@@ -607,6 +642,7 @@ test('caption transcription is on by default, reported to the client meter, and
|
||||
test('Realtime sessions carry supplied tools, and the standalone voice adds the catalog queries', async (t) => {
|
||||
env(t, 'OPENAI_API_KEY', 'fixture-upstream-secret');
|
||||
env(t, 'GEV_RATELIMIT_OPENAI_PER_MIN', undefined);
|
||||
env(t, 'OVERPASS_UPSTREAMS', undefined);
|
||||
const sent = [];
|
||||
t.mock.method(globalThis, 'fetch', async (url, options) => {
|
||||
sent.push(JSON.parse(options.body));
|
||||
@@ -619,7 +655,11 @@ test('Realtime sessions carry supplied tools, and the standalone voice adds the
|
||||
),
|
||||
);
|
||||
assert.equal(response.status, 200);
|
||||
assert.deepEqual(sent.at(-1).session.tools, tools);
|
||||
// Without an operator Overpass, osm_query is left out of the session.
|
||||
assert.deepEqual(sent.at(-1).session.tools, offeredTools(tools));
|
||||
assert.ok(
|
||||
!sent.at(-1).session.tools.some(({ name }) => name === 'osm_query'),
|
||||
);
|
||||
const names = tools.map((tool) => tool.name);
|
||||
assert.equal(new Set(names).size, names.length);
|
||||
assert.deepEqual(
|
||||
@@ -707,13 +747,18 @@ test('Realtime service configuration selects compatible endpoint/model without f
|
||||
endpoint: 'https://voice.example/client-secrets',
|
||||
models: { standard: 'configured-model' },
|
||||
resolveApiKey: () => 'server-fixture',
|
||||
// Pinned, so the expected tool list never depends on this machine's env.
|
||||
overpassConfigured: () => false,
|
||||
fetchImpl: async (url, options) => {
|
||||
assert.equal(url, 'https://voice.example/client-secrets');
|
||||
assert.equal(options.redirect, 'error');
|
||||
assert.equal(options.headers.Authorization, 'Bearer server-fixture');
|
||||
const payload = JSON.parse(options.body);
|
||||
assert.equal(payload.session.model, 'configured-model');
|
||||
assert.deepEqual(payload.session.tools, GEV_REALTIME_TOOLS);
|
||||
assert.deepEqual(
|
||||
payload.session.tools,
|
||||
realtimeTools({ overpass: false }),
|
||||
);
|
||||
return Response.json({ value: 'short-lived-fixture' });
|
||||
},
|
||||
},
|
||||
@@ -729,6 +774,29 @@ test('Realtime service configuration selects compatible endpoint/model without f
|
||||
assert.doesNotMatch(response.body, /server-fixture|voice\.example/);
|
||||
});
|
||||
|
||||
test('the HUD summary status says whether a summary is configured, without calling OpenAI', async (t) => {
|
||||
t.mock.method(globalThis, 'fetch', async () => {
|
||||
throw new Error('the status probe must not reach OpenAI');
|
||||
});
|
||||
const handler = install(openAiRealtimeProxy()).get('/api/openai/hud-summary');
|
||||
for (const [key, configured] of [
|
||||
[undefined, false],
|
||||
[' ', false],
|
||||
['fixture-key', true],
|
||||
]) {
|
||||
env(t, 'OPENAI_API_KEY', key);
|
||||
const response = await request(handler, { url: '/status' });
|
||||
assert.equal(response.status, 200);
|
||||
assert.deepEqual(response.json(), { configured });
|
||||
assert.equal(response.headers['cache-control'], 'no-store');
|
||||
}
|
||||
assert.equal(
|
||||
(await request(handler, { url: '/' })).status,
|
||||
405,
|
||||
'only the status path answers GET',
|
||||
);
|
||||
});
|
||||
|
||||
test('OpenAI routes answer generically when the upstream or the request fails', async (t) => {
|
||||
env(t, 'OPENAI_API_KEY', 'fixture-upstream-secret');
|
||||
env(t, 'GEV_RATELIMIT_OPENAI_PER_MIN', undefined);
|
||||
|
||||
@@ -6,6 +6,10 @@ import path from 'node:path';
|
||||
import { cctvProxy } from '../../server/providers/cctv.js';
|
||||
import { radioBrowserProxy } from '../../server/providers/radio.js';
|
||||
import { localProviderPlugins } from '../../server/providers/local.js';
|
||||
import { makeFixtureRoot } from './fixtureRoot.mjs';
|
||||
|
||||
const nominatimStorageDir = await makeFixtureRoot('gev-media-composition-');
|
||||
test.after(() => rmSync(nominatimStorageDir, { recursive: true, force: true }));
|
||||
|
||||
function install(plugin, hook = 'configureServer') {
|
||||
let handler;
|
||||
@@ -97,7 +101,7 @@ test('CCTV instances resolve their own application source root and isolate catal
|
||||
|
||||
test('composition creates exactly one CCTV and radio provider without acquisition', (t) => {
|
||||
isolate(t);
|
||||
const plugins = localProviderPlugins();
|
||||
const plugins = localProviderPlugins({ nominatimStorageDir });
|
||||
for (const factory of [cctvProxy, radioBrowserProxy]) {
|
||||
assert.equal(plugins.filter((p) => p.name === factory().name).length, 1);
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,241 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { createGateStateStore } from '../../server/providers/regional/nominatimGate.js';
|
||||
|
||||
const moduleUrl = new URL(
|
||||
'../../server/providers/regional/nominatimGate.js',
|
||||
import.meta.url,
|
||||
).href;
|
||||
|
||||
function startModule(script) {
|
||||
const child = spawn(process.execPath, ['--input-type=module', '-e', script], {
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
});
|
||||
const lines = [];
|
||||
const waiters = [];
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
|
||||
const publish = (line) => {
|
||||
lines.push(line);
|
||||
for (const waiter of [...waiters]) {
|
||||
if (!line.startsWith(waiter.prefix)) continue;
|
||||
waiters.splice(waiters.indexOf(waiter), 1);
|
||||
clearTimeout(waiter.timer);
|
||||
waiter.resolve(line);
|
||||
}
|
||||
};
|
||||
|
||||
child.stdout.on('data', (chunk) => {
|
||||
stdout += chunk;
|
||||
const parts = stdout.split('\n');
|
||||
stdout = parts.pop();
|
||||
for (const line of parts) publish(line);
|
||||
});
|
||||
child.stderr.on('data', (chunk) => {
|
||||
stderr += chunk;
|
||||
});
|
||||
|
||||
return {
|
||||
child,
|
||||
lines,
|
||||
waitFor(prefix, timeoutMs = 3000) {
|
||||
const existing = lines.find((line) => line.startsWith(prefix));
|
||||
if (existing) return Promise.resolve(existing);
|
||||
return new Promise((resolve, reject) => {
|
||||
const waiter = { prefix, resolve, reject, timer: null };
|
||||
waiter.timer = setTimeout(() => {
|
||||
const index = waiters.indexOf(waiter);
|
||||
if (index >= 0) waiters.splice(index, 1);
|
||||
reject(
|
||||
new Error(
|
||||
`timed out waiting for ${prefix}; stderr: ${stderr.trim()}`,
|
||||
),
|
||||
);
|
||||
}, timeoutMs);
|
||||
waiters.push(waiter);
|
||||
});
|
||||
},
|
||||
exited: new Promise((resolve, reject) => {
|
||||
child.once('error', reject);
|
||||
child.once('exit', (code, signal) => resolve({ code, signal }));
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function holderScript(lockFile) {
|
||||
return `
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
const database = new DatabaseSync(${JSON.stringify(lockFile)});
|
||||
database.exec('BEGIN IMMEDIATE');
|
||||
process.stdout.write('LOCKED\\n');
|
||||
process.stdin.once('data', () => {
|
||||
database.exec('ROLLBACK');
|
||||
database.close();
|
||||
process.stdout.write('RELEASED\\n');
|
||||
});
|
||||
process.stdin.resume();
|
||||
`;
|
||||
}
|
||||
|
||||
function contenderScript(stateFile, lockWaitMs) {
|
||||
return `
|
||||
const { createGateStateStore } = await import(${JSON.stringify(moduleUrl)});
|
||||
const store = createGateStateStore({
|
||||
file: ${JSON.stringify(stateFile)},
|
||||
lockWaitMs: ${lockWaitMs},
|
||||
onError: () => {},
|
||||
});
|
||||
process.stdout.write('ATTEMPTING\\n', () => {
|
||||
const result = store.dispatch(
|
||||
'2026-10-01',
|
||||
{ clock: () => 1000, dailyCap: 50, minSpacingMs: 1100 },
|
||||
() => Promise.resolve(),
|
||||
);
|
||||
delete result.value;
|
||||
process.stdout.write('RESULT:' + JSON.stringify(result) + '\\n');
|
||||
});
|
||||
`;
|
||||
}
|
||||
|
||||
test('a crashed lock owner cannot delete or bypass a successor lock', async (t) => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gev-nominatim-lock-'));
|
||||
const stateFile = path.join(dir, 'state.json');
|
||||
const lockFile = `${stateFile}.lock.sqlite`;
|
||||
const children = [];
|
||||
t.after(() => {
|
||||
for (const process of children) {
|
||||
if (process.exitCode == null && process.signalCode == null)
|
||||
process.kill();
|
||||
}
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const crashedOwner = startModule(holderScript(lockFile));
|
||||
children.push(crashedOwner.child);
|
||||
await crashedOwner.waitFor('LOCKED');
|
||||
const originalLock = fs.statSync(lockFile);
|
||||
|
||||
const blockedByCrashedOwner = startModule(contenderScript(stateFile, 0));
|
||||
children.push(blockedByCrashedOwner.child);
|
||||
const blockedResult = JSON.parse(
|
||||
(await blockedByCrashedOwner.waitFor('RESULT:')).slice('RESULT:'.length),
|
||||
);
|
||||
assert.equal(blockedResult.status, 'unavailable');
|
||||
assert.equal((await blockedByCrashedOwner.exited).code, 0);
|
||||
assert.equal(fs.existsSync(stateFile), false);
|
||||
|
||||
crashedOwner.child.kill();
|
||||
await crashedOwner.exited;
|
||||
|
||||
const successorOwner = startModule(holderScript(lockFile));
|
||||
children.push(successorOwner.child);
|
||||
await successorOwner.waitFor('LOCKED');
|
||||
assert.equal(fs.statSync(lockFile).ino, originalLock.ino);
|
||||
|
||||
const refused = startModule(contenderScript(stateFile, 0));
|
||||
children.push(refused.child);
|
||||
const refusedResult = JSON.parse(
|
||||
(await refused.waitFor('RESULT:')).slice('RESULT:'.length),
|
||||
);
|
||||
assert.equal(refusedResult.status, 'unavailable');
|
||||
assert.equal((await refused.exited).code, 0);
|
||||
assert.equal(
|
||||
createGateStateStore({ file: stateFile }).count('2026-10-01'),
|
||||
0,
|
||||
'a timed-out contender fails closed without spending a public slot',
|
||||
);
|
||||
assert.equal(fs.statSync(lockFile).ino, originalLock.ino);
|
||||
|
||||
successorOwner.child.stdin.end('release\n');
|
||||
await successorOwner.waitFor('RELEASED');
|
||||
assert.equal((await successorOwner.exited).code, 0);
|
||||
const released = createGateStateStore({ file: stateFile });
|
||||
const afterRelease = released.dispatch(
|
||||
'2026-10-01',
|
||||
{ clock: () => 2200, dailyCap: 50, minSpacingMs: 1100 },
|
||||
() => Promise.resolve(),
|
||||
);
|
||||
assert.equal(afterRelease.status, 'started');
|
||||
assert.equal(released.count('2026-10-01'), 1);
|
||||
assert.equal(fs.statSync(lockFile).ino, originalLock.ino);
|
||||
});
|
||||
|
||||
test('a public pause stays authoritative while another process owns the lock', async (t) => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gev-nominatim-pause-'));
|
||||
const stateFile = path.join(dir, 'state.json');
|
||||
const lockFile = `${stateFile}.lock.sqlite`;
|
||||
const children = [];
|
||||
t.after(() => {
|
||||
for (const process of children) {
|
||||
if (process.exitCode == null && process.signalCode == null)
|
||||
process.kill();
|
||||
}
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
fs.writeFileSync(
|
||||
stateFile,
|
||||
JSON.stringify({
|
||||
day: '2026-10-01',
|
||||
count: 1,
|
||||
pausedUntil: 0,
|
||||
nextStartAt: 0,
|
||||
}),
|
||||
);
|
||||
const owner = startModule(holderScript(lockFile));
|
||||
children.push(owner.child);
|
||||
await owner.waitFor('LOCKED');
|
||||
|
||||
const errors = [];
|
||||
const blockedWriter = createGateStateStore({
|
||||
file: stateFile,
|
||||
lockWaitMs: 0,
|
||||
onError: (error) => errors.push(error),
|
||||
});
|
||||
blockedWriter.pauseUntil(9000);
|
||||
assert.equal(errors.length, 1, 'the blocked JSON consolidation is reported');
|
||||
assert.equal(
|
||||
JSON.parse(fs.readFileSync(stateFile, 'utf8')).pausedUntil,
|
||||
0,
|
||||
'the lock owner prevents an unsafe JSON overwrite',
|
||||
);
|
||||
|
||||
owner.child.stdin.end('release\n');
|
||||
await owner.waitFor('RELEASED');
|
||||
assert.equal((await owner.exited).code, 0);
|
||||
|
||||
const successor = createGateStateStore({ file: stateFile });
|
||||
let sent = 0;
|
||||
const send = () => {
|
||||
sent += 1;
|
||||
return Promise.resolve();
|
||||
};
|
||||
assert.deepEqual(
|
||||
successor.dispatch(
|
||||
'2026-10-01',
|
||||
{ clock: () => 1000, dailyCap: 50, minSpacingMs: 1100 },
|
||||
send,
|
||||
),
|
||||
{ status: 'paused', retryAfterMs: 8000 },
|
||||
'a fresh process observes the pending refusal pause',
|
||||
);
|
||||
assert.equal(sent, 0, 'a paused dispatch never starts the transport');
|
||||
const resumed = successor.dispatch(
|
||||
'2026-10-01',
|
||||
{ clock: () => 9001, dailyCap: 50, minSpacingMs: 1100 },
|
||||
send,
|
||||
);
|
||||
assert.equal(resumed.status, 'started');
|
||||
assert.equal(sent, 1);
|
||||
assert.equal(successor.count('2026-10-01'), 2);
|
||||
assert.equal(
|
||||
fs.readdirSync(dir).some((name) => name.startsWith('state.json.pause.')),
|
||||
false,
|
||||
'the next successful transaction consolidates and removes the marker',
|
||||
);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -9,16 +9,50 @@
|
||||
// Run with: npm test
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
fetchNominatimSearch,
|
||||
geocodeProxy,
|
||||
NOMINATIM_MAX_PENDING,
|
||||
} from '../../server/providers/regional/place.js';
|
||||
import { fetchRegionalJson } from '../../server/providers/regional/http.js';
|
||||
import {
|
||||
createNominatimGate,
|
||||
resolveNominatimSettings,
|
||||
PUBLIC_NOMINATIM_SEARCH,
|
||||
setSharedNominatimGate,
|
||||
} from '../../server/providers/regional/nominatimGate.js';
|
||||
import { localProviderPlugins } from '../../server/providers/local.js';
|
||||
import { standaloneConfig } from '../../server/standalone/vite.config.js';
|
||||
import { defaultSourceRoot } from '../../server/providers/common/source-root.js';
|
||||
import { createPlaceSearch, createGoogleGeocoder } from '../search/index.js';
|
||||
import { createPhotonGeocoder } from '../keylessGeocoder.js';
|
||||
|
||||
// Each case starts with a fresh shared gate: a pause after one case's
|
||||
// simulated outage must not decide the next case.
|
||||
// Pin the public-policy fixture independently of operator endpoint settings.
|
||||
// Each case's transport fails closed outside its active withUpstream block.
|
||||
let activeUpstream;
|
||||
test.beforeEach(() => {
|
||||
const transport = { fetch: null };
|
||||
activeUpstream = transport;
|
||||
setSharedNominatimGate(
|
||||
createNominatimGate({
|
||||
settings: resolveNominatimSettings({
|
||||
NOMINATIM_URL: PUBLIC_NOMINATIM_SEARCH,
|
||||
}),
|
||||
fetchImpl: (...args) => {
|
||||
if (!transport.fetch) throw new Error('No active test upstream');
|
||||
return transport.fetch(...args);
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
const storageRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'gev-search-route-'));
|
||||
test.after(() => fs.rmSync(storageRoot, { recursive: true, force: true }));
|
||||
|
||||
const HIT = [
|
||||
{
|
||||
lat: '43.1731',
|
||||
@@ -33,13 +67,16 @@ const HIT = [
|
||||
/** Mount the geocode route the way the dev server does. */
|
||||
let clientCounter = 0;
|
||||
|
||||
function mountGeocode(
|
||||
install = (server) => geocodeProxy().configureServer(server),
|
||||
) {
|
||||
function mountGeocode(install = null) {
|
||||
// A fresh client address per mount: the per-client rate limiter is module
|
||||
// state shared by every case in this file, and one case's burst must not
|
||||
// decide another case's outcome.
|
||||
clientCounter += 1;
|
||||
if (!install)
|
||||
install = (server) =>
|
||||
geocodeProxy({
|
||||
storageDir: path.join(storageRoot, `case-${clientCounter}`),
|
||||
}).configureServer(server);
|
||||
const remoteAddress = `10.0.0.${clientCounter % 250}`;
|
||||
const routes = new Map();
|
||||
install({
|
||||
@@ -93,14 +130,17 @@ function mountGeocode(
|
||||
/** Answer the upstream from a stub, counting and optionally stalling calls. */
|
||||
async function withUpstream(respond, run) {
|
||||
const previous = globalThis.fetch;
|
||||
const transport = activeUpstream;
|
||||
const previousUpstream = transport.fetch;
|
||||
const calls = [];
|
||||
globalThis.fetch = async (url, options) => {
|
||||
globalThis.fetch = transport.fetch = async (url, options) => {
|
||||
calls.push({ url: String(url), options });
|
||||
return await respond(String(url), options, calls.length);
|
||||
};
|
||||
try {
|
||||
return await run(calls);
|
||||
} finally {
|
||||
transport.fetch = previousUpstream;
|
||||
globalThis.fetch = previous;
|
||||
}
|
||||
}
|
||||
@@ -111,13 +151,55 @@ const jsonResponse = (value) =>
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
test('the route is part of the application on both dev and preview', () => {
|
||||
const plugin = localProviderPlugins().find(
|
||||
test('the real composition binds durable storage before dev or preview installation, independent of CWD', async () => {
|
||||
const cwd = process.cwd();
|
||||
const expected = path.join(defaultSourceRoot, '.gev-cache', 'nominatim');
|
||||
try {
|
||||
for (const suffix of ['one', 'two']) {
|
||||
const dir = path.join(storageRoot, `cwd-${suffix}`);
|
||||
fs.mkdirSync(dir);
|
||||
process.chdir(dir);
|
||||
const { NOMINATIM_CACHE_DIR } = await import(
|
||||
`../../server/providers/regional/place.js?cwd-${suffix}`
|
||||
);
|
||||
assert.equal(NOMINATIM_CACHE_DIR, expected);
|
||||
assert.equal(fs.existsSync(path.join(dir, '.gev-cache')), false);
|
||||
}
|
||||
} finally {
|
||||
process.chdir(cwd);
|
||||
}
|
||||
const bound = [];
|
||||
setSharedNominatimGate({
|
||||
persistUsage: (file) => bound.push(file),
|
||||
});
|
||||
const storage = path.join(storageRoot, 'composition');
|
||||
const plugin = localProviderPlugins({ nominatimStorageDir: storage }).find(
|
||||
(entry) => entry.name === 'geocode-proxy',
|
||||
);
|
||||
assert.ok(plugin, 'the application must compose the place-search route');
|
||||
assert.equal(typeof plugin.configureServer, 'function');
|
||||
assert.equal(typeof plugin.configurePreviewServer, 'function');
|
||||
assert.deepEqual(bound, [path.join(storage, 'state.json')]);
|
||||
const standaloneStorage = path.join(storageRoot, 'standalone');
|
||||
const config = standaloneConfig(
|
||||
{ command: 'serve', mode: 'test' },
|
||||
{ nominatimStorageDir: standaloneStorage },
|
||||
);
|
||||
assert.ok(config.plugins.some((entry) => entry.name === 'geocode-proxy'));
|
||||
assert.deepEqual(bound, [
|
||||
path.join(storage, 'state.json'),
|
||||
path.join(standaloneStorage, 'state.json'),
|
||||
]);
|
||||
for (const value of [null, '', 'relative'])
|
||||
assert.throws(
|
||||
() => localProviderPlugins({ nominatimStorageDir: value }),
|
||||
/absolute directory/,
|
||||
);
|
||||
assert.equal(
|
||||
bound.length,
|
||||
2,
|
||||
'invalid bindings never construct policy state',
|
||||
);
|
||||
});
|
||||
|
||||
test('a search reaches the upstream identified, and the answer is cached', async () => {
|
||||
@@ -126,7 +208,9 @@ test('a search reaches the upstream identified, and the answer is cached', async
|
||||
async () => jsonResponse(HIT),
|
||||
async (calls) => {
|
||||
const query = `niagara-${Date.now()}`;
|
||||
const first = await request(`/api/geocode?q=${query}`);
|
||||
const first = await request(
|
||||
`/api/geocode?q=${query}&bounds=${encodeURIComponent('-20,170|-10,-171')}`,
|
||||
);
|
||||
assert.equal(first.status, 200);
|
||||
assert.equal(first.body.status, 'OK');
|
||||
assert.deepEqual(first.body.results[0].geometry.location, {
|
||||
@@ -134,6 +218,11 @@ test('a search reaches the upstream identified, and the answer is cached', async
|
||||
lng: -79.0384,
|
||||
});
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(
|
||||
new URL(calls[0].url).searchParams.has('viewbox'),
|
||||
false,
|
||||
'a wrapped hint must not be coarsened into a Greenwich viewbox',
|
||||
);
|
||||
const headers = calls[0].options.headers;
|
||||
assert.match(
|
||||
String(headers['User-Agent']),
|
||||
@@ -147,7 +236,7 @@ test('a search reaches the upstream identified, and the answer is cached', async
|
||||
'a fixed API endpoint may not be redirected elsewhere',
|
||||
);
|
||||
|
||||
// The policy asks that results be cached; a repeat costs no request.
|
||||
// Dropping the invalid hint also shares the unbiased cache entry.
|
||||
const repeat = await request(`/api/geocode?q=${query}`);
|
||||
assert.equal(repeat.status, 200);
|
||||
assert.equal(
|
||||
|
||||
@@ -0,0 +1,590 @@
|
||||
// THE BOUNDED OSM FEATURE SEARCH — `/api/osm/features`.
|
||||
//
|
||||
// A request names a curated preset, a box, a mode and a limit; the server
|
||||
// writes the Overpass query and sends it only to an operator-configured
|
||||
// Overpass (OVERPASS_UPSTREAMS). These cases pin what can never reach Overpass:
|
||||
// unknown kinds, raw tags, oversized boxes, boundary-area scans, and a second
|
||||
// upstream query while one is running. The generic `/api/overpass` guard is
|
||||
// covered by its own tests and is not loosened here.
|
||||
//
|
||||
// Run with: npm test
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import {
|
||||
compileOsmFeatureQuery,
|
||||
OSM_FEATURE_LIMITS,
|
||||
summarizeOsmFeatures,
|
||||
} from '../../server/providers/overpass/osmFeatures.js';
|
||||
import { installOsmFeaturesRoute } from '../../server/providers/overpass/osmFeaturesRoute.js';
|
||||
import { sanitizeOverpassBody } from '../../server/providers/overpass/query.js';
|
||||
import { OSM_QUERY_LIMITS } from '../voice/osmActions.js';
|
||||
|
||||
test('the server finishes its whole search before the voice answer gives up', () => {
|
||||
// When the browser stops waiting, the route aborts the upstream query, so
|
||||
// an OSM_TIMEOUT retry could never be served from the cache.
|
||||
assert.ok(
|
||||
OSM_FEATURE_LIMITS.timeoutS * 1000 < OSM_FEATURE_LIMITS.upstreamTimeoutMs,
|
||||
'Overpass gives up before the server stops waiting for it',
|
||||
);
|
||||
assert.ok(
|
||||
OSM_FEATURE_LIMITS.upstreamTimeoutMs <= OSM_FEATURE_LIMITS.upstreamBudgetMs,
|
||||
);
|
||||
assert.ok(
|
||||
OSM_FEATURE_LIMITS.upstreamBudgetMs + 2_000 <= OSM_QUERY_LIMITS.budgetMs,
|
||||
`server budget ${OSM_FEATURE_LIMITS.upstreamBudgetMs} ms must end before the client's ${OSM_QUERY_LIMITS.budgetMs} ms`,
|
||||
);
|
||||
});
|
||||
|
||||
test('a preset and a small box compile to a bounded query', () => {
|
||||
const compiled = compileOsmFeatureQuery({
|
||||
preset: 'hospital',
|
||||
bbox: '85.2,27.6,85.4,27.8',
|
||||
limit: '50',
|
||||
});
|
||||
assert.equal(compiled.ok, true);
|
||||
assert.equal(
|
||||
compiled.ql,
|
||||
'[out:json][timeout:20][maxsize:67108864];(nwr["amenity"="hospital"](27.6,85.2,27.8,85.4););out center tags 50;',
|
||||
);
|
||||
assert.doesNotMatch(compiled.ql, /area/, 'no boundary-area scan');
|
||||
const count = compileOsmFeatureQuery({
|
||||
preset: 'bar',
|
||||
bbox: [80, 20, 85, 25],
|
||||
mode: 'count',
|
||||
});
|
||||
assert.match(
|
||||
count.ql,
|
||||
/nwr\["amenity"="bar"\].*nwr\["amenity"="pub"\].*out count;$/,
|
||||
);
|
||||
});
|
||||
|
||||
test('unknown kinds, raw tags, bad and oversized boxes are refused', () => {
|
||||
assert.equal(
|
||||
compileOsmFeatureQuery({ preset: 'amenity=hospital', bbox: '0,0,1,1' })
|
||||
.code,
|
||||
'UNKNOWN_PRESET',
|
||||
);
|
||||
assert.equal(
|
||||
compileOsmFeatureQuery({ preset: '__proto__', bbox: '0,0,1,1' }).code,
|
||||
'UNKNOWN_PRESET',
|
||||
);
|
||||
assert.equal(
|
||||
compileOsmFeatureQuery({ preset: 'hospital', bbox: '0,0,1' }).code,
|
||||
'BAD_BOX',
|
||||
);
|
||||
assert.equal(
|
||||
compileOsmFeatureQuery({ preset: 'hospital', bbox: '0,1,1,0' }).code,
|
||||
'BAD_BOX',
|
||||
);
|
||||
assert.equal(
|
||||
compileOsmFeatureQuery({ preset: 'hospital', bbox: '0,0,3,3' }).code,
|
||||
'AREA_TOO_LARGE',
|
||||
);
|
||||
assert.equal(
|
||||
compileOsmFeatureQuery({
|
||||
preset: 'hospital',
|
||||
bbox: '0,0,3,3',
|
||||
mode: 'count',
|
||||
}).ok,
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
compileOsmFeatureQuery({
|
||||
preset: 'hospital',
|
||||
bbox: '0,0,7,7',
|
||||
mode: 'count',
|
||||
}).code,
|
||||
'AREA_TOO_LARGE',
|
||||
);
|
||||
const limited = compileOsmFeatureQuery({
|
||||
preset: 'hospital',
|
||||
bbox: '0,0,1,1',
|
||||
limit: 999999,
|
||||
});
|
||||
assert.match(
|
||||
limited.ql,
|
||||
new RegExp(`out center tags ${OSM_FEATURE_LIMITS.maxLimit};$`),
|
||||
);
|
||||
});
|
||||
|
||||
test('a box across the antimeridian is searched as its two halves', () => {
|
||||
const compiled = compileOsmFeatureQuery({
|
||||
preset: 'hospital',
|
||||
bbox: '179.5,-17,-179.5,-16',
|
||||
});
|
||||
assert.equal(compiled.ok, true);
|
||||
assert.match(compiled.ql, /\(-17,179\.5,-16,180\).*\(-17,-180,-16,-179\.5\)/);
|
||||
});
|
||||
|
||||
test('the generic Overpass guard still refuses boundary-area element scans', () => {
|
||||
const scan =
|
||||
'data=' +
|
||||
encodeURIComponent(
|
||||
'[out:json];area(3600000001)->.a;nwr["amenity"="hospital"](area.a);out;',
|
||||
);
|
||||
assert.equal(sanitizeOverpassBody(scan).ok, false);
|
||||
});
|
||||
|
||||
test('answers are compacted: centres, kept tags, truncation and counts', () => {
|
||||
const compiled = compileOsmFeatureQuery({
|
||||
preset: 'hospital',
|
||||
bbox: '0,0,1,1',
|
||||
limit: 2,
|
||||
});
|
||||
const features = summarizeOsmFeatures(
|
||||
{
|
||||
elements: [
|
||||
{
|
||||
type: 'node',
|
||||
id: 1,
|
||||
lat: 0.5,
|
||||
lon: 0.5,
|
||||
tags: { name: 'A', amenity: 'hospital', 'contact:phone': 'x' },
|
||||
},
|
||||
{
|
||||
type: 'way',
|
||||
id: 2,
|
||||
center: { lat: 0.4, lon: 0.4 },
|
||||
tags: { name: 'B', amenity: 'hospital' },
|
||||
},
|
||||
],
|
||||
},
|
||||
compiled,
|
||||
);
|
||||
assert.equal(features.count, 2);
|
||||
assert.equal(features.truncated, true, 'the limit was reached');
|
||||
assert.deepEqual(features.features[1], {
|
||||
id: 'way/2',
|
||||
lat: 0.4,
|
||||
lon: 0.4,
|
||||
tags: { name: 'B', amenity: 'hospital' },
|
||||
});
|
||||
assert.equal('contact:phone' in features.features[0].tags, false);
|
||||
const count = summarizeOsmFeatures(
|
||||
{
|
||||
elements: [
|
||||
{
|
||||
type: 'count',
|
||||
tags: { nodes: '3', ways: '2', relations: '0', total: '5' },
|
||||
},
|
||||
],
|
||||
},
|
||||
{ ...compiled, mode: 'count' },
|
||||
);
|
||||
assert.equal(count.count, 5);
|
||||
});
|
||||
|
||||
function mount(
|
||||
fetchPayload,
|
||||
{
|
||||
featuresCache,
|
||||
configured = () => true,
|
||||
upstreamTag,
|
||||
upstreamBudgetMs,
|
||||
} = {},
|
||||
) {
|
||||
const routes = new Map();
|
||||
const writes = [];
|
||||
const memoryCache = () => {
|
||||
const held = new Map();
|
||||
return {
|
||||
get: async (key) => held.get(key),
|
||||
set: async (key, value) => {
|
||||
held.set(key, value);
|
||||
writes.push(key);
|
||||
},
|
||||
};
|
||||
};
|
||||
installOsmFeaturesRoute(
|
||||
{ use: (route, handler) => routes.set(route, handler) },
|
||||
{
|
||||
fetchPayload,
|
||||
cacheRoot: null,
|
||||
configured,
|
||||
...(upstreamTag ? { upstreamTag } : {}),
|
||||
...(upstreamBudgetMs ? { upstreamBudgetMs } : {}),
|
||||
featuresCache: featuresCache || memoryCache(),
|
||||
},
|
||||
);
|
||||
let client = 0;
|
||||
const start = (
|
||||
search,
|
||||
route = '/api/osm/features',
|
||||
headers = {},
|
||||
from = null,
|
||||
) => {
|
||||
let req;
|
||||
let res;
|
||||
const promise = new Promise((resolve) => {
|
||||
client += 1;
|
||||
req = Object.assign(new EventEmitter(), {
|
||||
method: 'GET',
|
||||
url: `/?${search}`,
|
||||
headers,
|
||||
socket: { remoteAddress: from || `10.9.0.${client}` },
|
||||
});
|
||||
res = Object.assign(new EventEmitter(), {
|
||||
writableEnded: false,
|
||||
writeHead(status, headers) {
|
||||
res.status = status;
|
||||
res.headers = headers;
|
||||
},
|
||||
setHeader(name, value) {
|
||||
res.headers = { ...(res.headers || {}), [name]: value };
|
||||
},
|
||||
end(body) {
|
||||
res.writableEnded = true;
|
||||
resolve({
|
||||
status: res.status ?? res.statusCode,
|
||||
headers: res.headers,
|
||||
body: JSON.parse(body),
|
||||
});
|
||||
},
|
||||
});
|
||||
routes.get(route)(req, res);
|
||||
});
|
||||
return {
|
||||
promise,
|
||||
disconnect() {
|
||||
res.emit('close');
|
||||
},
|
||||
};
|
||||
};
|
||||
const request = (search, route = '/api/osm/features', headers, from) =>
|
||||
start(search, route, headers, from).promise;
|
||||
return { request, start, writes };
|
||||
}
|
||||
|
||||
test('a search without a limit lists up to 500 features', async () => {
|
||||
const sent = [];
|
||||
const { request } = mount(async (body) => {
|
||||
sent.push(decodeURIComponent(body));
|
||||
return { status: 200, body: JSON.stringify({ elements: [] }) };
|
||||
});
|
||||
for (const search of [
|
||||
'preset=hospital&bbox=0,0,1,1',
|
||||
'preset=school&bbox=0,0,1,1&limit=',
|
||||
]) {
|
||||
const answer = await request(search);
|
||||
assert.equal(answer.status, 200, search);
|
||||
}
|
||||
assert.equal(sent.length, 2);
|
||||
for (const ql of sent) assert.match(ql, /out center tags 500;$/);
|
||||
assert.equal(
|
||||
compileOsmFeatureQuery({ preset: 'hospital', bbox: '0,0,1,1', limit: '7' })
|
||||
.limit,
|
||||
7,
|
||||
);
|
||||
});
|
||||
|
||||
test('one IPv6 /64 is one client for slots and the rate limit', async () => {
|
||||
const release = [];
|
||||
const { request } = mount(async () => {
|
||||
await new Promise((r) => release.push(r));
|
||||
return { status: 200, body: JSON.stringify({ elements: [] }) };
|
||||
});
|
||||
const first = request(
|
||||
'preset=hospital&bbox=0,0,1,1',
|
||||
undefined,
|
||||
{},
|
||||
'2001:db8:1:2::a',
|
||||
);
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
// A rotated address that wrongly got its own slot would wait upstream
|
||||
// too: answer every held search before asserting, so a failure never hangs.
|
||||
const rotated = request(
|
||||
'preset=school&bbox=0,0,1,1',
|
||||
undefined,
|
||||
{},
|
||||
'2001:db8:1:2:ffff::b',
|
||||
);
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
release.splice(0).forEach((r) => r());
|
||||
assert.equal(
|
||||
(await rotated).status,
|
||||
503,
|
||||
'a rotated address waits for its first search',
|
||||
);
|
||||
assert.equal((await first).status, 200);
|
||||
|
||||
// Twelve a minute per /64, wherever in it the requests come from.
|
||||
const { request: limited } = mount(async () => ({
|
||||
status: 200,
|
||||
body: JSON.stringify({ elements: [] }),
|
||||
}));
|
||||
const statuses = [];
|
||||
for (let i = 0; i < 13; i += 1)
|
||||
statuses.push(
|
||||
(
|
||||
await limited(
|
||||
`preset=hospital&bbox=0,0,1,${(i + 1) / 20}`,
|
||||
undefined,
|
||||
{},
|
||||
`2001:db8:5:6::${(i + 1).toString(16)}`,
|
||||
)
|
||||
).status,
|
||||
);
|
||||
assert.deepEqual(statuses.slice(0, 12), Array(12).fill(200));
|
||||
assert.equal(statuses[12], 429);
|
||||
});
|
||||
|
||||
test('the route answers, caches, and shares upstream slots fairly', async () => {
|
||||
const release = [];
|
||||
let upstream = 0;
|
||||
const { request, writes } = mount(async (body) => {
|
||||
upstream += 1;
|
||||
assert.match(decodeURIComponent(body), /^data=\[out:json\]/);
|
||||
await new Promise((r) => release.push(r));
|
||||
return {
|
||||
status: 200,
|
||||
body: JSON.stringify({
|
||||
elements: [{ type: 'node', id: 7, lat: 1, lon: 1, tags: {} }],
|
||||
}),
|
||||
};
|
||||
});
|
||||
const tick = () => new Promise((r) => setTimeout(r, 5));
|
||||
const first = request(
|
||||
'preset=hospital&bbox=0,0,2,2',
|
||||
undefined,
|
||||
{},
|
||||
'10.1.0.1',
|
||||
);
|
||||
await tick();
|
||||
const sameClient = await request(
|
||||
'preset=school&bbox=0,0,2,2',
|
||||
undefined,
|
||||
{},
|
||||
'10.1.0.1',
|
||||
);
|
||||
assert.equal(
|
||||
sameClient.status,
|
||||
503,
|
||||
"one client's second search waits for its first",
|
||||
);
|
||||
const shared = request(
|
||||
'preset=hospital&bbox=0,0,2,2',
|
||||
undefined,
|
||||
{},
|
||||
'10.1.0.2',
|
||||
);
|
||||
const second = request(
|
||||
'preset=school&bbox=0,0,2,2',
|
||||
undefined,
|
||||
{},
|
||||
'10.1.0.3',
|
||||
);
|
||||
await tick();
|
||||
assert.equal(
|
||||
upstream,
|
||||
2,
|
||||
'another client runs alongside; the same search is shared',
|
||||
);
|
||||
const third = await request(
|
||||
'preset=pharmacy&bbox=0,0,2,2',
|
||||
undefined,
|
||||
{},
|
||||
'10.1.0.4',
|
||||
);
|
||||
assert.equal(third.status, 503, 'the global cap holds');
|
||||
release.forEach((r) => r());
|
||||
const answered = await first;
|
||||
assert.equal(answered.status, 200);
|
||||
assert.equal(answered.body.count, 1);
|
||||
assert.equal((await shared).status, 200);
|
||||
assert.equal((await second).status, 200);
|
||||
const again = await request('preset=hospital&bbox=0,0,2,2');
|
||||
assert.equal(again.headers['X-OSM-Cache'], 'HIT');
|
||||
assert.equal(upstream, 2);
|
||||
assert.equal(writes.length, 2);
|
||||
const refused = await request('preset=hospital&bbox=0,0,9,9');
|
||||
assert.equal(refused.status, 400);
|
||||
assert.equal(refused.body.code, 'AREA_TOO_LARGE');
|
||||
});
|
||||
|
||||
test('a hung Overpass is cut off by the overall budget, across every endpoint', async () => {
|
||||
const { request } = mount(
|
||||
(_body, _max, { signal }) =>
|
||||
new Promise((_, reject) =>
|
||||
signal.addEventListener('abort', () => reject(signal.reason), {
|
||||
once: true,
|
||||
}),
|
||||
),
|
||||
{ upstreamBudgetMs: 30 },
|
||||
);
|
||||
const started = Date.now();
|
||||
const answer = await request('preset=hospital&bbox=0,0,2,2');
|
||||
assert.ok(Date.now() - started < 1000);
|
||||
assert.equal(answer.status, 504);
|
||||
});
|
||||
|
||||
test('a cached answer is served only by the Overpass instance that gave it', async () => {
|
||||
let tag = 'instance-a';
|
||||
let upstream = 0;
|
||||
const { request } = mount(
|
||||
async () => {
|
||||
upstream += 1;
|
||||
return {
|
||||
status: 200,
|
||||
body: JSON.stringify({
|
||||
elements: [{ type: 'node', id: 7, lat: 1, lon: 1, tags: {} }],
|
||||
}),
|
||||
};
|
||||
},
|
||||
{ upstreamTag: () => tag },
|
||||
);
|
||||
assert.equal((await request('preset=hospital&bbox=0,0,2,2')).status, 200);
|
||||
const hit = await request('preset=hospital&bbox=0,0,2,2');
|
||||
assert.equal(hit.headers['X-OSM-Cache'], 'HIT');
|
||||
assert.equal(upstream, 1);
|
||||
tag = 'instance-b';
|
||||
const switched = await request('preset=hospital&bbox=0,0,2,2');
|
||||
assert.equal(switched.headers['X-OSM-Cache'], 'MISS');
|
||||
assert.equal(
|
||||
upstream,
|
||||
2,
|
||||
'the new instance is asked, not the old answer served',
|
||||
);
|
||||
});
|
||||
|
||||
test('a cross-site page cannot spend the operator Overpass', async () => {
|
||||
let upstream = 0;
|
||||
const { request } = mount(async () => {
|
||||
upstream += 1;
|
||||
return { status: 200, body: JSON.stringify({ elements: [] }) };
|
||||
});
|
||||
for (const headers of [
|
||||
{ 'sec-fetch-site': 'cross-site', origin: 'https://evil.example' },
|
||||
{ 'sec-fetch-site': 'cross-site' },
|
||||
{ origin: 'https://evil.example' },
|
||||
]) {
|
||||
const refused = await request('preset=hospital&bbox=0,0,2,2', undefined, {
|
||||
host: 'localhost:5173',
|
||||
...headers,
|
||||
});
|
||||
assert.equal(refused.status, 403, JSON.stringify(headers));
|
||||
}
|
||||
assert.equal(upstream, 0, 'no cross-site request reaches Overpass');
|
||||
const own = await request('preset=hospital&bbox=0,0,2,2', undefined, {
|
||||
host: 'localhost:5173',
|
||||
'sec-fetch-site': 'same-origin',
|
||||
});
|
||||
assert.equal(own.status, 200);
|
||||
// Like /api/overpass, it works behind a reverse proxy: forwarding headers
|
||||
// alone are not a refusal.
|
||||
const proxied = await request('preset=school&bbox=0,0,2,2', undefined, {
|
||||
host: 'localhost:5173',
|
||||
'sec-fetch-site': 'same-origin',
|
||||
'x-forwarded-for': '203.0.113.7',
|
||||
});
|
||||
assert.equal(proxied.status, 200);
|
||||
});
|
||||
|
||||
test('an upstream refusal is not an empty answer', async () => {
|
||||
const { request } = mount(async () => ({
|
||||
status: 429,
|
||||
body: 'rate_limited',
|
||||
rateLimited: true,
|
||||
}));
|
||||
const answer = await request('preset=hospital&bbox=0,0,1,1');
|
||||
assert.equal(answer.status, 429);
|
||||
assert.ok(answer.body.error);
|
||||
});
|
||||
|
||||
test('malformed successful answers are refused and never cached', async () => {
|
||||
const payloads = [
|
||||
{},
|
||||
{ elements: [{ type: 'count', tags: { nodes: '2' } }] },
|
||||
{ elements: [{ type: 'way', id: 9, tags: { amenity: 'hospital' } }] },
|
||||
];
|
||||
const { request, writes } = mount(async () => ({
|
||||
status: 200,
|
||||
body: JSON.stringify(payloads.shift()),
|
||||
}));
|
||||
const missingElements = await request('preset=hospital&bbox=0,0,1,1');
|
||||
const missingTotal = await request('preset=hospital&bbox=0,0,1,1&mode=count');
|
||||
const unusableRows = await request('preset=hospital&bbox=1,1,2,2');
|
||||
for (const answer of [missingElements, missingTotal, unusableRows]) {
|
||||
assert.equal(answer.status, 502);
|
||||
assert.match(answer.body.error, /failed/i);
|
||||
}
|
||||
assert.deepEqual(writes, []);
|
||||
});
|
||||
|
||||
test('the last disconnected waiter aborts upstream work and frees the slot', async () => {
|
||||
let calls = 0;
|
||||
let firstStarted;
|
||||
let firstAborted;
|
||||
const started = new Promise((resolve) => {
|
||||
firstStarted = resolve;
|
||||
});
|
||||
const aborted = new Promise((resolve) => {
|
||||
firstAborted = resolve;
|
||||
});
|
||||
const { request, start } = mount(async (_body, _cap, { signal }) => {
|
||||
calls += 1;
|
||||
if (calls === 1) {
|
||||
firstStarted();
|
||||
return new Promise((resolve, reject) => {
|
||||
signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
firstAborted();
|
||||
reject(signal.reason);
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
});
|
||||
}
|
||||
return { status: 200, body: '{"elements":[]}' };
|
||||
});
|
||||
const abandoned = start('preset=hospital&bbox=0,0,1,1');
|
||||
await started;
|
||||
abandoned.disconnect();
|
||||
await aborted;
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
const next = await request('preset=school&bbox=0,0,1,1');
|
||||
assert.equal(next.status, 200);
|
||||
assert.equal(calls, 2);
|
||||
});
|
||||
|
||||
test('one disconnected coalesced waiter does not cancel a live sibling', async () => {
|
||||
let release;
|
||||
let upstreamSignal;
|
||||
let calls = 0;
|
||||
const { start } = mount(async (_body, _cap, { signal }) => {
|
||||
calls += 1;
|
||||
upstreamSignal = signal;
|
||||
await new Promise((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
return { status: 200, body: '{"elements":[]}' };
|
||||
});
|
||||
const first = start('preset=hospital&bbox=0,0,1,1');
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
const second = start('preset=hospital&bbox=0,0,1,1');
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
first.disconnect();
|
||||
assert.equal(upstreamSignal.aborted, false);
|
||||
release();
|
||||
const answer = await second.promise;
|
||||
assert.equal(answer.status, 200);
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
|
||||
test('without a configured Overpass the route refuses and fetches nothing', async () => {
|
||||
let upstream = 0;
|
||||
const { request } = mount(
|
||||
async () => {
|
||||
upstream += 1;
|
||||
return { status: 200, body: '{"elements":[]}' };
|
||||
},
|
||||
{ configured: () => false },
|
||||
);
|
||||
const answer = await request('preset=hospital&bbox=85.2,27.6,85.4,27.8');
|
||||
assert.equal(answer.status, 503);
|
||||
assert.equal(answer.body.code, 'OVERPASS_NOT_CONFIGURED');
|
||||
assert.equal(answer.body.retryable, false);
|
||||
assert.match(answer.body.error, /configured Overpass/);
|
||||
assert.equal(upstream, 0);
|
||||
});
|
||||
@@ -77,13 +77,15 @@ test('the documented outcomes hold: default, stored open, stored shut, and a sha
|
||||
// against the code that decides them.
|
||||
const { PanelPositionControls } =
|
||||
await import('../ui/panelPositionControls.js');
|
||||
const { presentPanelLocally } = await import('../testSupport/panelState.mjs');
|
||||
const { readPanelState } = await import('../ui/rail/panelState.js');
|
||||
const html = await readFile(
|
||||
path.join(root, 'src/ui/templates/layer-panels.html'),
|
||||
path.join(root, 'src/ui/views/panels/CctvPanel.vue'),
|
||||
'utf8',
|
||||
);
|
||||
assert.match(
|
||||
html,
|
||||
/<div id="cctv-panel" class="panel-collapsible collapsed"/,
|
||||
/<RailPanel id="cctv-panel"[^>]*\bstart-collapsed\b/,
|
||||
'the CCTV panel starts collapsed in the markup',
|
||||
);
|
||||
|
||||
@@ -110,7 +112,8 @@ test('the documented outcomes hold: default, stored open, stored shut, and a sha
|
||||
};
|
||||
try {
|
||||
const controls = new PanelPositionControls({
|
||||
syncPanelCollapseButton: () => {},
|
||||
presentPanel: presentPanelLocally,
|
||||
shownPanel: readPanelState,
|
||||
layoutRightPanels: () => {},
|
||||
syncCctvPanelViewport: () => {},
|
||||
showToast: () => {},
|
||||
|
||||
@@ -81,6 +81,24 @@ test('nearby labels rank landmarks, deduplicate names/addresses and bound the pr
|
||||
assert.deepEqual(projectNearbyPlaces({}, 0, 0), []);
|
||||
});
|
||||
|
||||
test('nearby place distances take the short way round 180°', () => {
|
||||
const at = (name, longitude) => ({
|
||||
id: name,
|
||||
displayName: { text: name },
|
||||
location: { latitude: -16.8, longitude },
|
||||
types: ['point_of_interest'],
|
||||
});
|
||||
// From Taveuni at 179.98: 2 km east across 180°, 4 km west on this side.
|
||||
const result = projectNearbyPlaces(
|
||||
{ places: [at('West', 179.942), at('East', -179.999)] },
|
||||
-16.8,
|
||||
179.98,
|
||||
);
|
||||
const byName = Object.fromEntries(result.map((p) => [p.name, p.distanceM]));
|
||||
assert.ok(byName.East > 1500 && byName.East < 2500, String(byName.East));
|
||||
assert.ok(byName.West > 3500 && byName.West < 4500, String(byName.West));
|
||||
});
|
||||
|
||||
test('text search preserves bounds, rejects malformed bounds and tolerates absent locations', () => {
|
||||
const viewport = {
|
||||
low: { latitude: 1, longitude: 2 },
|
||||
|
||||
@@ -7,10 +7,15 @@ import { localProviderPlugins } from '../../server/providers/local.js';
|
||||
import { apiNotFoundPlugin } from '../../server/standalone/api-not-found.js';
|
||||
import { makeFixtureRoot } from './fixtureRoot.mjs';
|
||||
|
||||
const nominatimStorageDir = await makeFixtureRoot('gev-preview-composition-');
|
||||
test.after(() => rm(nominatimStorageDir, { recursive: true, force: true }));
|
||||
|
||||
test('data providers have both hooks; credential editing stays development-only', () => {
|
||||
const plugins = localProviderPlugins();
|
||||
const plugins = localProviderPlugins({ nominatimStorageDir });
|
||||
assert.ok(plugins.some(({ name }) => name === 'fire-perimeters'));
|
||||
assert.ok(plugins.some(({ name }) => name === 'gnss-integrity'));
|
||||
assert.ok(plugins.some(({ name }) => name === 'ghostmaps'));
|
||||
assert.ok(plugins.some(({ name }) => name === 'drone-airspace'));
|
||||
for (const plugin of plugins) {
|
||||
if (plugin.name === 'gev-key-setup') {
|
||||
assert.equal(plugin.configurePreviewServer, undefined);
|
||||
@@ -88,7 +93,10 @@ test('real dev and built-preview servers serve provider JSON and terminate unkno
|
||||
for (const isPreview of [false, true]) {
|
||||
const config = {
|
||||
...base,
|
||||
plugins: [...localProviderPlugins(), apiNotFoundPlugin()],
|
||||
plugins: [
|
||||
...localProviderPlugins({ nominatimStorageDir }),
|
||||
apiNotFoundPlugin(),
|
||||
],
|
||||
server: { host: '127.0.0.1', port: 0, hmr: false },
|
||||
preview: { host: '127.0.0.1', port: 0 },
|
||||
};
|
||||
@@ -105,6 +113,7 @@ test('real dev and built-preview servers serve provider JSON and terminate unkno
|
||||
['/api/firms/status', 200],
|
||||
['/api/fire-perimeters/inciweb/publication/invalid', 400],
|
||||
['/api/gnss-integrity?lat=invalid', 400],
|
||||
['/api/ghostmaps/unknown', 404],
|
||||
['/api/terrain/heights?points=invalid', 400],
|
||||
['/api/overpass', 405],
|
||||
['/api/overpass/status', 200],
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import sharp from 'sharp';
|
||||
import {
|
||||
CUBE_FACES,
|
||||
@@ -24,7 +25,7 @@ test('painted-out planets leave no disc brighter than the sky around them', asyn
|
||||
}));
|
||||
for (const face of CUBE_FACES) {
|
||||
const { data, info } = await sharp(
|
||||
new URL(`milkyway_${FACE_FILE_SUFFIX[face]}.webp`, SKY).pathname,
|
||||
fileURLToPath(new URL(`milkyway_${FACE_FILE_SUFFIX[face]}.webp`, SKY)),
|
||||
)
|
||||
.raw()
|
||||
.toBuffer({ resolveWithObject: true });
|
||||
|
||||
@@ -1,11 +1,27 @@
|
||||
/** A reveal must beat the one-second idle rotation refresh, regardless of FPS. */
|
||||
/**
|
||||
* Wall-clock budget for EACH observed frame, regardless of FPS. Both the settle
|
||||
* frame (measured from the forced moveEnd) and the reveal frame (measured from
|
||||
* the settle frame that hid the contact) must land inside it, so neither can be
|
||||
* repaired by the one-second idle rotation refresh before it is read. The
|
||||
* refresh clock starts at the fleet tick (preRender) of the frame the budget is
|
||||
* measured from, so the budget must leave room for that frame's own render
|
||||
* time: half the refresh interval tolerates frames up to ~500 ms, and a ~300 ms
|
||||
* software-rendered frame (headless SwiftShader) fits with margin.
|
||||
*/
|
||||
export const ARRIVAL_OBSERVATION_MS = 500;
|
||||
|
||||
/** A measured rotation error at or above this fails the arrival check. */
|
||||
export const ARRIVAL_MAX_ERROR_DEG = 10;
|
||||
|
||||
/** Attempts allowed when every earlier one timed out without a wrong angle. */
|
||||
export const ARRIVAL_MAX_ATTEMPTS = 2;
|
||||
|
||||
/**
|
||||
* Observe the first completed moveEnd frame and the first subsequent reveal.
|
||||
* The deadline starts when moveEnd is forced, before its rotation baseline, so
|
||||
* waiting for either frame cannot let the one-second idle refresh mask a bug.
|
||||
* `read` snapshots visibility and rotation error against the current position.
|
||||
* The settle deadline starts when moveEnd is forced, before its rotation
|
||||
* baseline; the reveal deadline restarts at the settle frame, which is where
|
||||
* the contact is hidden. `read` snapshots visibility and rotation error
|
||||
* against the current position.
|
||||
*/
|
||||
export function observeArrivalRotation({
|
||||
scene,
|
||||
@@ -18,6 +34,7 @@ export function observeArrivalRotation({
|
||||
}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const startedAt = now();
|
||||
let phaseStartedAt = startedAt;
|
||||
let moveEnd = null;
|
||||
let moveEndMs = null;
|
||||
let revealFrames = 0;
|
||||
@@ -34,24 +51,42 @@ export function observeArrivalRotation({
|
||||
cleanup();
|
||||
resolve(result);
|
||||
};
|
||||
const expired = () => ({
|
||||
// A timeout keeps every angle it measured: the settle angle before a
|
||||
// reveal timeout, and the angle on a late frame itself (a late frame is
|
||||
// read first; the idle refresh can only repair an angle, so a wrong one
|
||||
// seen late was wrong on time too). `arrivalAngleViolated` then makes the
|
||||
// timeout final instead of retryable.
|
||||
const expired = (late = null) => ({
|
||||
error: `arrival ${moveEnd ? 'reveal' : 'moveEnd'} observation exceeded ${ARRIVAL_OBSERVATION_MS} ms`,
|
||||
elapsedMs: now() - startedAt,
|
||||
moveEndMs,
|
||||
...(moveEnd
|
||||
? { dMoveEnd: moveEnd.rotationError }
|
||||
: late
|
||||
? { dMoveEnd: late.rotationError }
|
||||
: {}),
|
||||
...(moveEnd && late?.shown ? { dReveal: late.rotationError } : {}),
|
||||
flipFrame: -1,
|
||||
});
|
||||
const armDeadline = () => {
|
||||
clearTimer(timer);
|
||||
timer = setTimer(() => finish(expired()), ARRIVAL_OBSERVATION_MS);
|
||||
};
|
||||
remove = scene.postRender.addEventListener(() => {
|
||||
if (done) return;
|
||||
try {
|
||||
const elapsedMs = now() - startedAt;
|
||||
if (elapsedMs >= ARRIVAL_OBSERVATION_MS) {
|
||||
finish(expired());
|
||||
const at = now();
|
||||
const elapsedMs = at - startedAt;
|
||||
const sample = read();
|
||||
if (at - phaseStartedAt >= ARRIVAL_OBSERVATION_MS) {
|
||||
finish(expired(sample));
|
||||
return;
|
||||
}
|
||||
const sample = read();
|
||||
if (moveEnd === null) {
|
||||
moveEnd = sample;
|
||||
moveEndMs = elapsedMs;
|
||||
phaseStartedAt = at;
|
||||
armDeadline();
|
||||
startReveal();
|
||||
} else {
|
||||
revealFrames++;
|
||||
@@ -76,7 +111,7 @@ export function observeArrivalRotation({
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
timer = setTimer(() => finish(expired()), ARRIVAL_OBSERVATION_MS);
|
||||
armDeadline();
|
||||
try {
|
||||
startMoveEnd();
|
||||
scene.requestRender();
|
||||
@@ -87,14 +122,51 @@ export function observeArrivalRotation({
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an observation measured a rotation error over the threshold on any
|
||||
* frame it captured, including the settle frame of a reveal that then timed
|
||||
* out. Such an observation is a demonstrated failure, never inconclusive.
|
||||
*/
|
||||
export function arrivalAngleViolated(observation) {
|
||||
const limit = (ARRIVAL_MAX_ERROR_DEG * Math.PI) / 180;
|
||||
return [observation?.dMoveEnd, observation?.dReveal].some(
|
||||
(error) => Number.isFinite(error) && error >= limit,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Observe arrival rotation, retrying only an inconclusive timeout. A wall-clock
|
||||
* timeout means the frame landed where the idle refresh could already have
|
||||
* repaired it, so it earns another attempt; an observation that measured a
|
||||
* wrong angle (or succeeded) is final, so a later clean attempt can never
|
||||
* replace it. `prepare` runs before every attempt; the result carries
|
||||
* `attempts`.
|
||||
*/
|
||||
export async function observeArrivalRotationWithRetry({
|
||||
prepare = async () => {},
|
||||
observe = observeArrivalRotation,
|
||||
maxAttempts = ARRIVAL_MAX_ATTEMPTS,
|
||||
...options
|
||||
}) {
|
||||
let observed;
|
||||
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
||||
await prepare();
|
||||
observed = { ...(await observe(options)), attempts: attempt };
|
||||
if (!observed.error || arrivalAngleViolated(observed)) break;
|
||||
}
|
||||
return observed;
|
||||
}
|
||||
|
||||
/** Test the captured frames without retrying a bad first observation. */
|
||||
export function arrivalRotationPassed(observation) {
|
||||
return (
|
||||
!!observation &&
|
||||
!observation.error &&
|
||||
observation.shown === true &&
|
||||
observation.elapsedMs < ARRIVAL_OBSERVATION_MS &&
|
||||
(observation.dMoveEnd * 180) / Math.PI < 10 &&
|
||||
(observation.dReveal * 180) / Math.PI < 10
|
||||
observation.moveEndMs < ARRIVAL_OBSERVATION_MS &&
|
||||
observation.revealMs < ARRIVAL_OBSERVATION_MS &&
|
||||
Number.isFinite(observation.dMoveEnd) &&
|
||||
Number.isFinite(observation.dReveal) &&
|
||||
!arrivalAngleViolated(observation)
|
||||
);
|
||||
}
|
||||
@@ -1,19 +1,23 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import * as arrivalModule from './trackArrivalObservation.mjs';
|
||||
import {
|
||||
ARRIVAL_OBSERVATION_MS,
|
||||
arrivalAngleViolated,
|
||||
arrivalRotationPassed,
|
||||
observeArrivalRotation,
|
||||
observeArrivalRotationWithRetry,
|
||||
} from './trackArrivalObservation.mjs';
|
||||
|
||||
function fixture() {
|
||||
function fixture(start = observeArrivalRotation) {
|
||||
let time = 0;
|
||||
let state = { shown: true, rotationError: 0 };
|
||||
const listeners = new Set();
|
||||
const timers = new Map();
|
||||
let renders = 0;
|
||||
let moveEnds = 0;
|
||||
const observation = observeArrivalRotation({
|
||||
const observation = start({
|
||||
scene: {
|
||||
postRender: {
|
||||
addEventListener(listener) {
|
||||
@@ -110,7 +114,8 @@ test('no reveal fails at a deadline before the one-second idle catch-up', async
|
||||
assert.equal(ARRIVAL_OBSERVATION_MS, 500);
|
||||
f.frame(8, { shown: true, rotationError: 0 });
|
||||
f.frame(480);
|
||||
f.expire(500);
|
||||
// The reveal budget is measured from the 8 ms settle frame.
|
||||
f.expire(508);
|
||||
const result = await f.observation;
|
||||
assert.match(result.error, /reveal.*500 ms/);
|
||||
assert.equal(arrivalRotationPassed(result), false);
|
||||
@@ -123,20 +128,46 @@ test('no reveal fails at a deadline before the one-second idle catch-up', async
|
||||
test('a late visible frame fails even if the timeout callback is delayed', async () => {
|
||||
const f = fixture();
|
||||
f.frame(8, { shown: true, rotationError: 0 });
|
||||
f.frame(501, { shown: true, rotationError: 0 });
|
||||
f.frame(509, { shown: true, rotationError: 0 });
|
||||
const result = await f.observation;
|
||||
assert.match(result.error, /reveal.*500 ms/);
|
||||
assert.equal(result.elapsedMs, 501);
|
||||
assert.equal(result.elapsedMs, 509);
|
||||
assert.equal(arrivalRotationPassed(result), false);
|
||||
});
|
||||
|
||||
test('the deadline includes moveEnd setup rather than restarting when hidden', async () => {
|
||||
test('a slow software renderer passes when each frame stays inside its own budget', async () => {
|
||||
// Headless SwiftShader frames run ~300 ms: settle lands at 300 ms and the
|
||||
// reveal at 600 ms from moveEnd. Both stay inside the 1 s idle refresh.
|
||||
const f = fixture();
|
||||
f.frame(400, { shown: true, rotationError: 0 });
|
||||
f.frame(300, { shown: true, rotationError: 0 });
|
||||
f.expire(500); // the settle frame re-armed the deadline to 800 ms
|
||||
f.frame(600, { shown: true, rotationError: 0 });
|
||||
const result = await f.observation;
|
||||
assert.equal(result.moveEndMs, 400);
|
||||
assert.equal(result.moveEndMs, 300);
|
||||
assert.equal(result.revealMs, 300);
|
||||
assert.equal(result.elapsedMs, 600);
|
||||
assert.equal(result.flipFrame, 1);
|
||||
assert.equal(arrivalRotationPassed(result), true);
|
||||
assert.equal(f.resources.timers, 0);
|
||||
});
|
||||
|
||||
test('a settle frame later than its budget fails as a moveEnd timeout', async () => {
|
||||
const f = fixture();
|
||||
f.frame(500, { shown: true, rotationError: 0 });
|
||||
const result = await f.observation;
|
||||
assert.match(result.error, /moveEnd.*500 ms/);
|
||||
assert.equal(result.moveEndMs, null);
|
||||
assert.equal(arrivalRotationPassed(result), false);
|
||||
});
|
||||
|
||||
test('a reveal later than its own budget fails even after a fast settle frame', async () => {
|
||||
const f = fixture();
|
||||
f.frame(400, { shown: true, rotationError: 0 });
|
||||
f.frame(901, { shown: true, rotationError: 0 });
|
||||
const result = await f.observation;
|
||||
assert.match(result.error, /reveal.*500 ms/);
|
||||
assert.equal(result.moveEndMs, 400);
|
||||
assert.equal(result.elapsedMs, 901);
|
||||
assert.equal(arrivalRotationPassed(result), false);
|
||||
});
|
||||
|
||||
@@ -149,3 +180,195 @@ test('missing moveEnd frames fail without waiting for a render callback', async
|
||||
assert.equal(f.resources.listeners, 0);
|
||||
assert.equal(f.resources.timers, 0);
|
||||
});
|
||||
|
||||
// Let a retry's next attempt register its postRender listener.
|
||||
const settle = () => new Promise((resolve) => setImmediate(resolve));
|
||||
|
||||
function retryFixture(extra = {}) {
|
||||
const counts = { prepares: 0 };
|
||||
const f = fixture((options) =>
|
||||
observeArrivalRotationWithRetry({
|
||||
...options,
|
||||
...extra,
|
||||
async prepare() {
|
||||
counts.prepares++;
|
||||
},
|
||||
}),
|
||||
);
|
||||
f.counts = counts;
|
||||
return f;
|
||||
}
|
||||
|
||||
test('a wrong settle angle followed by a reveal timeout is final, not retried into a pass', async () => {
|
||||
const f = retryFixture();
|
||||
await settle();
|
||||
// 0.5 rad ≈ 29°: a real threshold violation on the settle frame.
|
||||
f.frame(8, { shown: true, rotationError: 0.5 });
|
||||
f.expire(508); // the reveal never comes inside its budget
|
||||
await settle();
|
||||
// An otherwise clean second attempt, which must never be started.
|
||||
f.frame(516, { shown: true, rotationError: 0 });
|
||||
f.frame(524, { shown: true, rotationError: 0 });
|
||||
const result = await f.observation;
|
||||
assert.match(result.error, /reveal.*500 ms/);
|
||||
assert.equal(result.dMoveEnd, 0.5, 'the measured settle angle is kept');
|
||||
assert.equal(arrivalAngleViolated(result), true);
|
||||
assert.equal(result.attempts, 1);
|
||||
assert.equal(f.counts.prepares, 1);
|
||||
assert.equal(f.resources.moveEnds, 1);
|
||||
assert.equal(arrivalRotationPassed(result), false);
|
||||
assert.equal(f.resources.listeners, 0);
|
||||
assert.equal(f.resources.timers, 0);
|
||||
});
|
||||
|
||||
test('an inconclusive reveal timeout after a correct settle earns one more attempt', async () => {
|
||||
const f = retryFixture();
|
||||
await settle();
|
||||
f.frame(8, { shown: true, rotationError: 0 });
|
||||
f.expire(508);
|
||||
await settle();
|
||||
f.frame(516, { shown: true, rotationError: 0 });
|
||||
f.frame(596, { shown: true, rotationError: 0 });
|
||||
const result = await f.observation;
|
||||
assert.equal(result.attempts, 2);
|
||||
assert.equal(f.counts.prepares, 2);
|
||||
assert.equal(f.resources.moveEnds, 2);
|
||||
assert.equal(arrivalRotationPassed(result), true);
|
||||
});
|
||||
|
||||
test('timeouts stop after the attempt limit and still fail', async () => {
|
||||
const f = retryFixture();
|
||||
await settle();
|
||||
f.expire(500);
|
||||
await settle();
|
||||
f.expire(1000);
|
||||
const result = await f.observation;
|
||||
assert.match(result.error, /moveEnd.*500 ms/);
|
||||
assert.equal(result.attempts, 2);
|
||||
assert.equal(arrivalRotationPassed(result), false);
|
||||
assert.equal(f.resources.listeners, 0);
|
||||
assert.equal(f.resources.timers, 0);
|
||||
});
|
||||
|
||||
test('a missing or non-finite angle never passes', () => {
|
||||
const clean = {
|
||||
shown: true,
|
||||
moveEndMs: 8,
|
||||
revealMs: 80,
|
||||
dMoveEnd: 0,
|
||||
dReveal: 0,
|
||||
};
|
||||
assert.equal(arrivalRotationPassed(clean), true);
|
||||
for (const field of ['dMoveEnd', 'dReveal']) {
|
||||
assert.equal(arrivalRotationPassed({ ...clean, [field]: NaN }), false);
|
||||
assert.equal(
|
||||
arrivalRotationPassed({ ...clean, [field]: undefined }),
|
||||
false,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('a wrong angle on a late reveal frame is final, not retried into a pass', async () => {
|
||||
const f = retryFixture();
|
||||
await settle();
|
||||
f.frame(100, { shown: true, rotationError: 0 });
|
||||
// Shown at 600 ms (500 ms after settle) still wearing the tampered nose.
|
||||
f.frame(600, { shown: true, rotationError: 1.5 });
|
||||
await settle();
|
||||
f.frame(608, { shown: true, rotationError: 0 });
|
||||
f.frame(688, { shown: true, rotationError: 0 });
|
||||
const result = await f.observation;
|
||||
assert.match(result.error, /reveal.*500 ms/);
|
||||
assert.equal(result.dReveal, 1.5);
|
||||
assert.equal(result.attempts, 1);
|
||||
assert.equal(f.resources.moveEnds, 1);
|
||||
assert.equal(arrivalRotationPassed(result), false);
|
||||
});
|
||||
|
||||
test('a wrong angle on a late settle frame is final, not retried into a pass', async () => {
|
||||
const f = retryFixture();
|
||||
await settle();
|
||||
f.frame(926, { shown: true, rotationError: 1.5 });
|
||||
await settle();
|
||||
f.frame(934, { shown: true, rotationError: 0 });
|
||||
f.frame(1014, { shown: true, rotationError: 0 });
|
||||
const result = await f.observation;
|
||||
assert.match(result.error, /moveEnd.*500 ms/);
|
||||
assert.equal(result.dMoveEnd, 1.5);
|
||||
assert.equal(result.attempts, 1);
|
||||
assert.equal(arrivalRotationPassed(result), false);
|
||||
});
|
||||
|
||||
test('a late hidden reveal frame records no angle and stays retryable', async () => {
|
||||
const f = retryFixture();
|
||||
await settle();
|
||||
f.frame(8, { shown: true, rotationError: 0 });
|
||||
// Still hidden, still tampered: not a measured reveal angle.
|
||||
f.frame(600, { shown: false });
|
||||
const first = f.observation;
|
||||
await settle();
|
||||
f.frame(608, { shown: true, rotationError: 0 });
|
||||
f.frame(688, { shown: true, rotationError: 0 });
|
||||
const result = await first;
|
||||
assert.equal(result.attempts, 2);
|
||||
assert.equal(result.dReveal, 0);
|
||||
assert.equal(arrivalRotationPassed(result), true);
|
||||
});
|
||||
|
||||
test('a late frame with correct angles stays an inconclusive, retryable timeout', async () => {
|
||||
const f = retryFixture();
|
||||
await settle();
|
||||
f.frame(926, { shown: true, rotationError: 0 });
|
||||
await settle();
|
||||
f.frame(934, { shown: true, rotationError: 0 });
|
||||
f.frame(1014, { shown: true, rotationError: 0 });
|
||||
const result = await f.observation;
|
||||
assert.equal(result.attempts, 2);
|
||||
assert.equal(arrivalRotationPassed(result), true);
|
||||
});
|
||||
|
||||
test('a wrong first reveal on time is final: no retry', async () => {
|
||||
const f = retryFixture();
|
||||
await settle();
|
||||
f.frame(8, { shown: true, rotationError: 0 });
|
||||
f.frame(88, { shown: true, rotationError: 1.5 });
|
||||
const result = await f.observation;
|
||||
assert.equal(result.error, undefined);
|
||||
assert.equal(result.attempts, 1);
|
||||
assert.equal(f.resources.moveEnds, 1);
|
||||
assert.equal(arrivalRotationPassed(result), false);
|
||||
});
|
||||
|
||||
test('maxAttempts bounds inconclusive retries', async () => {
|
||||
const f = retryFixture({ maxAttempts: 3 });
|
||||
for (let attempt = 1; attempt <= 3; attempt++) {
|
||||
await settle();
|
||||
f.expire(attempt * 500);
|
||||
}
|
||||
const result = await f.observation;
|
||||
assert.equal(result.attempts, 3);
|
||||
assert.equal(f.counts.prepares, 3);
|
||||
assert.equal(arrivalRotationPassed(result), false);
|
||||
});
|
||||
|
||||
test('the 10° limit is inclusive', () => {
|
||||
const limit = Math.PI / 18;
|
||||
assert.equal(arrivalAngleViolated({ dMoveEnd: limit }), true);
|
||||
assert.equal(arrivalAngleViolated({ dReveal: limit * 0.999 }), false);
|
||||
});
|
||||
|
||||
test('every name the track harness imports from this module is exported', () => {
|
||||
const harness = readFileSync(
|
||||
new URL('../../scripts/track-regression.mjs', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
const names = [
|
||||
...harness.matchAll(
|
||||
/(?:import|const)\s*\{([^}]+)\}\s*(?:from\s*|=\s*await import\()[^;]*trackArrivalObservation\.mjs/g,
|
||||
),
|
||||
].flatMap((match) => match[1].split(',').map((name) => name.trim()));
|
||||
assert.ok(names.includes('arrivalRotationPassed'));
|
||||
assert.ok(names.includes('observeArrivalRotationWithRetry'));
|
||||
for (const name of names)
|
||||
assert.equal(typeof arrivalModule[name], 'function', name);
|
||||
});
|
||||
@@ -1,13 +1,16 @@
|
||||
import '../testSupport/registerDom.mjs';
|
||||
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,
|
||||
detectOn,
|
||||
} from '../../scripts/qa-transit-controls.mjs';
|
||||
import { createStyleParameters } from '../ui/styleParameters.js';
|
||||
import { bindDisplayControls } from '../ui/displayControls.js';
|
||||
import { createPinia } from 'pinia';
|
||||
import { useDisplayStore } from '../ui/stores/display.js';
|
||||
import { thermalShader } from '../styles/thermal.js';
|
||||
import {
|
||||
cycleMode,
|
||||
@@ -17,6 +20,9 @@ import {
|
||||
} from '../data/detection.js';
|
||||
|
||||
const pause = async () => {};
|
||||
// The page fixture swaps the globals for stand-ins; generated rows render
|
||||
// into a real element, so keep the registered document.
|
||||
const realDocument = globalThis.document;
|
||||
class Element extends EventTarget {
|
||||
constructor() {
|
||||
super();
|
||||
@@ -66,8 +72,7 @@ function pageFixture(t) {
|
||||
const label = selector.match(/aria-label="([^"]+)"/)[1];
|
||||
return elements
|
||||
.get('param-sliders')
|
||||
.children.flatMap((row) => row.children)
|
||||
.find((el) => el.getAttribute('aria-label') === label);
|
||||
.querySelector(`input.param-slider[aria-label="${label}"]`);
|
||||
}
|
||||
return elements.get(selector.slice(1));
|
||||
};
|
||||
@@ -101,6 +106,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,
|
||||
@@ -115,8 +132,7 @@ test('live visual cities follow local operating hours in summer and winter', ()
|
||||
|
||||
test('thermal controls wait for activation and use the real generated parameter rows', async (t) => {
|
||||
const { page, document, elements } = pageFixture(t);
|
||||
const container = new Element();
|
||||
container.ownerDocument = document;
|
||||
const container = realDocument.createElement('div');
|
||||
elements.set('param-sliders', container);
|
||||
const parameters = createStyleParameters({ container });
|
||||
t.after(() => parameters.destroy());
|
||||
@@ -146,9 +162,7 @@ test('thermal controls wait for activation and use the real generated parameter
|
||||
page.$eval = async (selector, fn, ...args) => {
|
||||
if (selector.startsWith('.style-btn')) return fn(new Element(), ...args);
|
||||
const label = selector.match(/aria-label="([^"]+)"/)[1];
|
||||
const slider = container.children
|
||||
.flatMap((row) => row.children)
|
||||
.find((el) => el.getAttribute('aria-label') === label);
|
||||
const slider = container.querySelector(`[aria-label="${label}"]`);
|
||||
assert.ok(slider);
|
||||
return fn(slider, ...args);
|
||||
};
|
||||
@@ -176,26 +190,32 @@ test('DETECT uses the real OFF/restore button and density input to reach DENSE',
|
||||
setMode('BALANCED');
|
||||
setMode('OFF');
|
||||
const modes = [];
|
||||
const controls = bindDisplayControls({
|
||||
elements: { detectionButton: button, densitySlider: slider },
|
||||
actions: {
|
||||
cycleDetection() {
|
||||
cycleMode();
|
||||
modes.push(getMode());
|
||||
},
|
||||
setDensity(value) {
|
||||
setDetectionTuning({ densityPct: Number(value) });
|
||||
},
|
||||
// As DisplayPanel does: the toggle and the slider call the Display
|
||||
// controls' actions through the display store.
|
||||
const store = useDisplayStore(createPinia());
|
||||
const token = store.connect({
|
||||
cycleDetection() {
|
||||
cycleMode();
|
||||
modes.push(getMode());
|
||||
},
|
||||
setDensity(value) {
|
||||
setDetectionTuning({ densityPct: Number(value) });
|
||||
},
|
||||
});
|
||||
const onClick = () => store.act('cycleDetection');
|
||||
const onInput = () => store.act('setDensity', slider.value);
|
||||
button.addEventListener('click', onClick);
|
||||
slider.addEventListener('input', onInput);
|
||||
t.after(() => {
|
||||
controls.destroy();
|
||||
button.removeEventListener('click', onClick);
|
||||
slider.removeEventListener('input', onInput);
|
||||
store.detach(token);
|
||||
setMode('OFF');
|
||||
});
|
||||
assert.equal(await detectOn(page, pause), 'DENSE');
|
||||
assert.deepEqual(modes, ['BALANCED', 'OFF', 'DENSE']);
|
||||
const template = readFileSync(
|
||||
new URL('../ui/templates/display-controls.html', import.meta.url),
|
||||
new URL('../ui/views/panels/DisplayPanel.vue', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
assert.match(template, /id="detection-density-slider"/);
|
||||
@@ -675,7 +695,7 @@ test('public transit documentation uses courtesy attribution and the approved gr
|
||||
);
|
||||
assert.ok(
|
||||
readme.includes(
|
||||
'Twenty layers and map sources. **Eighteen have a keyless path.**',
|
||||
'Twenty-one layers and map sources. **Nineteen have a keyless path.**',
|
||||
),
|
||||
);
|
||||
assert.ok(
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
@@ -5,12 +6,19 @@ import { rm, writeFile } from 'node:fs/promises';
|
||||
import { request } from 'node:http';
|
||||
import path from 'node:path';
|
||||
import { build, createServer, preview } from 'vite';
|
||||
import { BROWSER_CSP, createBrowserViteConfig } from '../../build/vite.js';
|
||||
import {
|
||||
BROWSER_CSP,
|
||||
createBrowserViteConfig,
|
||||
escapeFsDenyPath,
|
||||
} from '../../build/vite.js';
|
||||
import standaloneConfig, * as compatibility from '../../vite.config.js';
|
||||
import * as providers from '../../server/providers/local.js';
|
||||
import { apiNotFoundPlugin } from '../../server/standalone/api-not-found.js';
|
||||
import { makeFixtureRoot } from './fixtureRoot.mjs';
|
||||
|
||||
const nominatimStorageDir = await makeFixtureRoot('gev-build-composition-');
|
||||
test.after(() => rm(nominatimStorageDir, { recursive: true, force: true }));
|
||||
|
||||
test('explicit build inputs preserve browser-only defines, plugin order and loopback protections', () => {
|
||||
const plugin = { name: 'fixture-provider' };
|
||||
const config = createBrowserViteConfig({
|
||||
@@ -24,12 +32,27 @@ test('explicit build inputs preserve browser-only defines, plugin order and loop
|
||||
assert.equal(config.plugins[0].enforce, 'pre');
|
||||
assert.equal(config.plugins[1].name, 'host-check');
|
||||
assert.equal(config.plugins[1].enforce, 'pre');
|
||||
assert.equal(config.plugins[3].name, 'vite:vue');
|
||||
assert.equal(config.plugins[4], plugin);
|
||||
assert.equal(config.server.host, 'localhost');
|
||||
assert.equal(config.server.port, 4173);
|
||||
assert.deepEqual(config.server.allowedHosts, ['localhost', '127.0.0.1']);
|
||||
assert.ok(config.server.fs.deny.includes('**/ENVIRONMENT'));
|
||||
assert.ok(config.server.fs.deny.includes('.env.*'));
|
||||
assert.ok(config.server.fs.deny.includes('**/.gev-logs/**'));
|
||||
assert.ok(config.server.fs.deny.includes('**/.gev-cache/**'));
|
||||
const root = fileURLToPath(new URL('../../', import.meta.url))
|
||||
.replace(/\\/g, '/')
|
||||
.replace(/\/$/, '');
|
||||
assert.deepEqual(
|
||||
config.server.fs.deny.filter((pattern) => pattern.endsWith('/dist/**')),
|
||||
[`${escapeFsDenyPath(root)}/dist/**`],
|
||||
'only project build output is denied, not dependency dist directories',
|
||||
);
|
||||
assert.equal(
|
||||
escapeFsDenyPath('C:/Users/a/project (1) [test]{copy}'),
|
||||
'C:/Users/a/project \\(1\\) \\[test\\]\\{copy\\}',
|
||||
);
|
||||
assert.equal(config.server.headers['X-Frame-Options'], 'DENY');
|
||||
assert.equal(config.server.headers['X-Content-Type-Options'], 'nosniff');
|
||||
const csp = config.server.headers['Content-Security-Policy'];
|
||||
@@ -45,10 +68,34 @@ test('explicit build inputs preserve browser-only defines, plugin order and loop
|
||||
assert.ok(!csp.includes("script-src 'self' 'unsafe-inline'"));
|
||||
assert.deepEqual(config.preview.headers, config.server.headers);
|
||||
assert.deepEqual(config.define, {
|
||||
__VUE_I18N_FULL_INSTALL__: 'false',
|
||||
__VUE_I18N_LEGACY_API__: 'false',
|
||||
__INTLIFY_PROD_DEVTOOLS__: 'false',
|
||||
__INTLIFY_DROP_MESSAGE_COMPILER__: 'true',
|
||||
'import.meta.env.GOOGLE_MAPS_API_KEY': '"browser-fixture"',
|
||||
'import.meta.env.CESIUM_ION_TOKEN': '"ion-fixture"',
|
||||
'import.meta.env.MAPILLARY_CLIENT_TOKEN': '""',
|
||||
});
|
||||
assert.equal(
|
||||
createBrowserViteConfig({ photonUrl: '' }).define[
|
||||
'import.meta.env.PHOTON_URL'
|
||||
],
|
||||
'null',
|
||||
'an empty PHOTON_URL reaches the browser only as the disabled sentinel',
|
||||
);
|
||||
assert.equal(
|
||||
createBrowserViteConfig({ photonUrl: 'https://u:[email protected]/api/' })
|
||||
.define['import.meta.env.PHOTON_URL'],
|
||||
'null',
|
||||
'credentials are never serialized into browser assets',
|
||||
);
|
||||
assert.equal(
|
||||
createBrowserViteConfig({ photonUrl: 'http://localhost:2322/api/' }).define[
|
||||
'import.meta.env.PHOTON_URL'
|
||||
],
|
||||
'null',
|
||||
'plain http would be blocked by connect-src, so it is refused here',
|
||||
);
|
||||
assert.equal(
|
||||
createBrowserViteConfig({ mapillaryToken: 'MLY|1|abc' }).define[
|
||||
'import.meta.env.MAPILLARY_CLIENT_TOKEN'
|
||||
@@ -96,9 +143,9 @@ test('build helper does not discover environment values or construct local provi
|
||||
test('root config retains existing named exports and standalone provider order', () => {
|
||||
for (const [name, value] of Object.entries(providers))
|
||||
assert.equal(compatibility[name], value, name);
|
||||
const config = standaloneConfig({ mode: 'test' });
|
||||
const config = standaloneConfig({ mode: 'test' }, { nominatimStorageDir });
|
||||
const standaloneProviders = config.plugins
|
||||
.slice(4, -5)
|
||||
.slice(4, -6)
|
||||
.map((plugin) => plugin.name);
|
||||
assert.equal(
|
||||
standaloneProviders.filter((name) => name === 'gemini-live-proxy').length,
|
||||
@@ -110,11 +157,14 @@ test('root config retains existing named exports and standalone provider order',
|
||||
);
|
||||
assert.deepEqual(
|
||||
standaloneProviders.filter((name) => name !== 'gemini-live-proxy'),
|
||||
providers.localProviderPlugins().map((plugin) => plugin.name),
|
||||
providers
|
||||
.localProviderPlugins({ nominatimStorageDir })
|
||||
.map((plugin) => plugin.name),
|
||||
);
|
||||
assert.equal(config.plugins.at(-6).name, 'gev-key-setup');
|
||||
// The local MCP route follows every provider and precedes the API fallback.
|
||||
assert.equal(config.plugins.at(-5).name, 'local-mcp');
|
||||
assert.equal(config.plugins.at(-7).name, 'gev-key-setup');
|
||||
// Token fallback follows real providers and local MCP before the API 404.
|
||||
assert.equal(config.plugins.at(-6).name, 'local-mcp');
|
||||
assert.equal(config.plugins.at(-5).name, 'google-token-unavailable');
|
||||
assert.equal(config.plugins.at(-4).name, 'api-not-found');
|
||||
// Config-only, so it sits after the provider slice rather than in it.
|
||||
assert.equal(config.plugins.at(-3).name, 'gev-unwatched-runtime-dirs');
|
||||
@@ -122,10 +172,26 @@ test('root config retains existing named exports and standalone provider order',
|
||||
assert.equal(config.plugins.at(-1).name, 'panel-build');
|
||||
});
|
||||
|
||||
test('standalone config passes a validated Photon setting into the browser define', () => {
|
||||
const previous = process.env.PHOTON_URL;
|
||||
process.env.PHOTON_URL = 'https://photon.example.test/api/';
|
||||
try {
|
||||
assert.equal(
|
||||
standaloneConfig({ mode: 'test' }, { nominatimStorageDir }).define[
|
||||
'import.meta.env.PHOTON_URL'
|
||||
],
|
||||
'"https://photon.example.test/api/"',
|
||||
);
|
||||
} finally {
|
||||
if (previous === undefined) delete process.env.PHOTON_URL;
|
||||
else process.env.PHOTON_URL = previous;
|
||||
}
|
||||
});
|
||||
|
||||
test('directories the server writes while it runs are kept out of the dev watcher', () => {
|
||||
// Providers write cache files and logs here while the app runs; none of it is
|
||||
// source, so the dev watcher has no reason to stat it.
|
||||
const config = standaloneConfig({ mode: 'test' });
|
||||
const config = standaloneConfig({ mode: 'test' }, { nominatimStorageDir });
|
||||
const plugin = config.plugins.find(
|
||||
({ name }) => name === 'gev-unwatched-runtime-dirs',
|
||||
);
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
call,
|
||||
} from '../../scripts/voice-bench/grade.mjs';
|
||||
import {
|
||||
CORE_PHRASES, COVERAGE_PROBE, DIALOGUES, ROUTING_PHRASES, CAPABILITY_EXTRAS,
|
||||
CORE_PHRASES, COVERAGE_PROBE, DIALOGUES, ROUTING_PHRASES, GEOMETRY_PHRASES, OVERPASS_PHRASES, CAPABILITY_EXTRAS,
|
||||
dialogueResult, coverageRubric,
|
||||
} from '../../scripts/voice-bench/phrases.mjs';
|
||||
import { stubResult } from '../../scripts/voice-bench/stub.mjs';
|
||||
@@ -293,10 +293,11 @@ test('coverage v2 grades the same turn against the current tool surface', () =>
|
||||
assert.equal(COVERAGE_PROBE.every((c) => c.v2 && typeof c.v2.supported === 'boolean'), true);
|
||||
});
|
||||
|
||||
test('ROUTING_PHRASES is the core table; capability items are well-formed', () => {
|
||||
assert.equal(ROUTING_PHRASES, CORE_PHRASES);
|
||||
test('ROUTING_PHRASES is the core table plus geometry and place search; capability items are well-formed', () => {
|
||||
assert.deepEqual(ROUTING_PHRASES, [...CORE_PHRASES, ...GEOMETRY_PHRASES, ...OVERPASS_PHRASES]);
|
||||
assert.ok(OVERPASS_PHRASES.every((p) => p.requires?.includes('osm_query')), 'place search is gated');
|
||||
const names = new Set(GEV_REALTIME_TOOLS.map((t) => t.name));
|
||||
for (const p of CAPABILITY_EXTRAS.filter((c) => !c.turns)) {
|
||||
for (const p of [...GEOMETRY_PHRASES, ...OVERPASS_PHRASES, ...CAPABILITY_EXTRAS.filter((c) => !c.turns)]) {
|
||||
const expected = typeof p.expect === 'string' ? [p.expect] : p.expect.oneOf;
|
||||
for (const n of expected) assert.ok(names.has(n), `${p.phrase} expects unknown tool ${n}`);
|
||||
}
|
||||
@@ -310,16 +311,14 @@ test('ROUTING_PHRASES is the core table; capability items are well-formed', () =
|
||||
assert.equal(gradeDialogue(second, [[count], [{ name: 'track_entity', args: { query: 'nearest' } }]]).ok, false);
|
||||
});
|
||||
|
||||
test('coverage v2: a count for the removed drawn-area scope is never graded correct', () => {
|
||||
test('coverage v2: a drawn-area count must use the drawn scope, never the view', () => {
|
||||
const drawn = coverageRubric(coverage('fires-in-drawn-area'), 'v2');
|
||||
for (const kind of ['view', 'drawn']) {
|
||||
const verdict = gradeCoverage(drawn, [{ name: 'analyst_query', args: { layers: ['local-firms'], scope: { kind } } }], '12 fires inside the area you drew.');
|
||||
assert.notEqual(verdict.verdict, 'correct');
|
||||
assert.equal(verdict.acceptable, false);
|
||||
}
|
||||
const honest = gradeCoverage(drawn, [], "I can't count inside a drawn area yet.");
|
||||
assert.equal(honest.verdict, 'honest-refusal');
|
||||
assert.equal(honest.acceptable, true);
|
||||
const scoped = (kind) => gradeCoverage(drawn, [{ name: 'analyst_query', args: { layers: ['local-firms'], scope: { kind } } }], '12 fires inside the area you drew.');
|
||||
assert.equal(scoped('drawn').verdict, 'correct');
|
||||
assert.notEqual(scoped('view').verdict, 'correct');
|
||||
const bagmati = CAPABILITY_EXTRAS.find((c) => c.id === 'bagmati-then-fires');
|
||||
const fires = { name: 'analyst_query', args: { layers: ['local-firms'], scope: { kind: 'area', areaId: 'area-1' } } };
|
||||
assert.equal(gradeDialogue(bagmati, [[{ name: 'resolve_area', args: { query: 'Bagmati province' } }], [fires]]).ok, true);
|
||||
});
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
chmodSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readdirSync,
|
||||
rmSync,
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
cachedVueModule,
|
||||
compileVueModule,
|
||||
ownCacheDirectory,
|
||||
vueCacheDirectory,
|
||||
vueCacheKey,
|
||||
} from '../../build/vueLoader.js';
|
||||
|
||||
const SOURCE =
|
||||
'<script setup>\nconst label = "Hi";\n</script>\n<template><b>{{ label }}</b></template>\n';
|
||||
const FILE = '/virtual/Greeting.vue';
|
||||
|
||||
test('a component compiles once and later processes read the cached module', (t) => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), 'gev-vue-cache-test-'));
|
||||
t.after(() => rmSync(directory, { recursive: true, force: true }));
|
||||
const compiled = cachedVueModule(SOURCE, FILE, directory);
|
||||
assert.equal(compiled, compileVueModule(SOURCE, FILE));
|
||||
const entries = readdirSync(directory);
|
||||
assert.deepEqual(entries, [`${vueCacheKey(SOURCE, FILE)}.mjs`]);
|
||||
// A cached entry is returned as stored, without compiling again.
|
||||
writeFileSync(path.join(directory, entries[0]), 'export default "cached";');
|
||||
assert.equal(
|
||||
cachedVueModule(SOURCE, FILE, directory),
|
||||
'export default "cached";',
|
||||
);
|
||||
});
|
||||
|
||||
test('an edited component or another path is a new cache entry', () => {
|
||||
const key = vueCacheKey(SOURCE, FILE);
|
||||
assert.notEqual(vueCacheKey(`${SOURCE}\n`, FILE), key);
|
||||
assert.notEqual(vueCacheKey(SOURCE, '/virtual/Other.vue'), key);
|
||||
assert.equal(vueCacheKey(SOURCE, FILE), key);
|
||||
});
|
||||
|
||||
test('GEV_VUE_CACHE=0 compiles every time; otherwise the cache sits in a per-user directory', () => {
|
||||
assert.equal(vueCacheDirectory({ GEV_VUE_CACHE: '0' }), null);
|
||||
if (process.platform !== 'win32') {
|
||||
const directory = vueCacheDirectory({});
|
||||
assert.equal(path.dirname(directory), tmpdir());
|
||||
assert.match(path.basename(directory), /^gev-vue-sfc-/);
|
||||
}
|
||||
// Windows temp directories may be shared, so the cache lives in the
|
||||
// user's profile, or not at all.
|
||||
assert.equal(
|
||||
vueCacheDirectory(
|
||||
{ LOCALAPPDATA: 'C:\\Users\\a\\AppData\\Local' },
|
||||
'win32',
|
||||
),
|
||||
path.join('C:\\Users\\a\\AppData\\Local', 'gev-vue-sfc'),
|
||||
);
|
||||
assert.equal(vueCacheDirectory({}, 'win32'), null);
|
||||
assert.equal(
|
||||
cachedVueModule(SOURCE, FILE, null),
|
||||
compileVueModule(SOURCE, FILE),
|
||||
);
|
||||
});
|
||||
|
||||
test('a cache directory that cannot be written still returns the compiled module', (t) => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), 'gev-vue-cache-test-'));
|
||||
t.after(() => rmSync(directory, { recursive: true, force: true }));
|
||||
// A file where the cache directory should be makes every write fail.
|
||||
const blocked = path.join(directory, 'blocked');
|
||||
writeFileSync(blocked, '');
|
||||
assert.equal(
|
||||
cachedVueModule(SOURCE, FILE, blocked),
|
||||
compileVueModule(SOURCE, FILE),
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
'a cache directory others can write to, or a link to one, is never read',
|
||||
{
|
||||
skip: process.platform === 'win32',
|
||||
},
|
||||
(t) => {
|
||||
const root = mkdtempSync(path.join(tmpdir(), 'gev-vue-cache-test-'));
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
const shared = path.join(root, 'shared');
|
||||
mkdirSync(shared);
|
||||
chmodSync(shared, 0o777);
|
||||
// A module planted where the cache would look must not run.
|
||||
writeFileSync(
|
||||
path.join(shared, `${vueCacheKey(SOURCE, FILE)}.mjs`),
|
||||
'export default "planted";',
|
||||
);
|
||||
assert.equal(ownCacheDirectory(shared), false);
|
||||
assert.equal(
|
||||
cachedVueModule(SOURCE, FILE, shared),
|
||||
compileVueModule(SOURCE, FILE),
|
||||
);
|
||||
const own = path.join(root, 'own');
|
||||
mkdirSync(own, { mode: 0o700 });
|
||||
const link = path.join(root, 'link');
|
||||
symlinkSync(own, link);
|
||||
assert.equal(ownCacheDirectory(link), false);
|
||||
assert.equal(ownCacheDirectory(own), true);
|
||||
},
|
||||
);
|
||||
Reference in new issue
Block a user