World airport dataset + distance cap on generated jobs (ISS-079, v0.44.0)
CI / build + unit + e2e (pull_request) Successful in 11m2s
CI / build + unit + e2e (pull_request) Successful in 11m2s
This commit is contained in:
+22
-13
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { parseCsv, filterEuAirports, toGeoJson, airportsHandler } from './airports';
|
||||
import { assertUniqueIcaos, filterWorldAirports, parseCsv, toGeoJson, airportsHandler } from './airports';
|
||||
|
||||
const HEADER =
|
||||
'"id","ident","type","name","latitude_deg","longitude_deg","elevation_ft","continent","iso_country","iso_region","municipality","scheduled_service","icao_code","iata_code","gps_code","local_code","home_link","wikipedia_link","keywords"';
|
||||
@@ -53,25 +53,34 @@ describe('parseCsv', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('filterEuAirports', () => {
|
||||
it('keeps EU fixed-wing airports and seaplane bases, drops the rest', () => {
|
||||
describe('filterWorldAirports (v0.44.0 — world dataset, no continent check)', () => {
|
||||
it('keeps fixed-wing airports and seaplane bases from every continent, drops the rest by type', () => {
|
||||
const rows = parseCsv(
|
||||
[
|
||||
HEADER,
|
||||
row({ ident: 'EU-SMALL', type: 'small_airport' }),
|
||||
row({ ident: 'EU-MED', type: 'medium_airport' }),
|
||||
row({ ident: 'EU-LRG', type: 'large_airport' }),
|
||||
row({ ident: 'NA-LRG', continent: 'NA', type: 'large_airport' }),
|
||||
row({ ident: 'AS-LRG', continent: 'AS', type: 'large_airport' }),
|
||||
row({ ident: 'EU-SEA', type: 'seaplane_base' }),
|
||||
row({ ident: 'EU-LEGACY', type: 'airport' }),
|
||||
row({ ident: 'EU-Helio', type: 'heliport' }),
|
||||
row({ ident: 'EU-CLOSED', type: 'closed' }),
|
||||
row({ ident: 'EU-BALLOON', type: 'balloonport' }),
|
||||
row({ ident: 'NA-SMALL', continent: 'NA' }),
|
||||
row({ ident: 'AS-LRG', continent: 'AS', type: 'large_airport' }),
|
||||
row({ ident: 'NA-Helio', continent: 'NA', type: 'heliport' }),
|
||||
row({ ident: 'AS-CLOSED', continent: 'AS', type: 'closed' }),
|
||||
].join('\n'),
|
||||
);
|
||||
const kept = filterEuAirports(rows).map((r) => r.ident);
|
||||
expect(kept.sort()).toEqual(['EU-LEGACY', 'EU-LRG', 'EU-MED', 'EU-SEA', 'EU-SMALL']);
|
||||
const kept = filterWorldAirports(rows).map((r) => r.ident);
|
||||
expect(kept.sort()).toEqual(['AS-LRG', 'EU-LEGACY', 'EU-SEA', 'EU-SMALL', 'NA-LRG']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('assertUniqueIcaos (v0.44.0 load-time guard)', () => {
|
||||
it('passes a collection with unique ICACOs and throws on the first duplicate', () => {
|
||||
const ok = toGeoJson(parseCsv([HEADER, row({ ident: 'AAAA', icao_code: 'AAAA' }), row({ ident: 'BBBB', icao_code: 'BBBB' })].join('\n')));
|
||||
expect(() => assertUniqueIcaos(ok)).not.toThrow();
|
||||
|
||||
// icao_code empty → the effective key is the ident fallback (toGeoJson), so a duplicate
|
||||
// ident must trip the guard too.
|
||||
const dup = toGeoJson(parseCsv([HEADER, row({ ident: 'CCCC', icao_code: '' }), row({ ident: 'CCCC', icao_code: '', latitude_deg: '51.0' })].join('\n')));
|
||||
expect(() => assertUniqueIcaos(dup)).toThrow(/duplicate ICAO.*CCCC/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -102,7 +111,7 @@ describe('toGeoJson', () => {
|
||||
});
|
||||
|
||||
describe('/api/airports handler', () => {
|
||||
it('returns a valid GeoJSON FeatureCollection of EU airports', async () => {
|
||||
it('returns a valid GeoJSON FeatureCollection of world airports', async () => {
|
||||
const res = await airportsHandler();
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get('content-type')).toContain('application/json');
|
||||
|
||||
+20
-5
@@ -52,11 +52,13 @@ export function parseCsv(text: string): CsvRow[] {
|
||||
// The 2026 schema splits "airport" into small/medium/large_airport (older dumps used a
|
||||
// single "airport" type + category column) — both spellings are accepted. Heliports are
|
||||
// excluded — no fixed-wing transport ops; other types (closed, balloonport, ...) are
|
||||
// irrelevant to an airline-ops game.
|
||||
// irrelevant to an airline-ops game. The committed dataset is pre-curated to large_airport
|
||||
// only (scripts/build-world-airports.mjs); this check stays as a cheap guard against an
|
||||
// uncurated dump being swapped in.
|
||||
const INCLUDED_TYPES = new Set(['airport', 'small_airport', 'medium_airport', 'large_airport', 'seaplane_base']);
|
||||
|
||||
export function filterEuAirports(rows: CsvRow[]): CsvRow[] {
|
||||
return rows.filter((r) => r.continent === 'EU' && INCLUDED_TYPES.has(r.type));
|
||||
export function filterWorldAirports(rows: CsvRow[]): CsvRow[] {
|
||||
return rows.filter((r) => INCLUDED_TYPES.has(r.type));
|
||||
}
|
||||
|
||||
export interface AirportProperties {
|
||||
@@ -93,13 +95,26 @@ export function toGeoJson(rows: CsvRow[]): GeoJsonFeatureCollection {
|
||||
return { type: 'FeatureCollection', features };
|
||||
}
|
||||
|
||||
// Three consumers key features by ICAO with silent-overwrite semantics (the map's airport
|
||||
// index, the route/queue GeoJSON builders and the sim's airport lookups) — a duplicate would
|
||||
// corrupt state without any error, so fail loud at load instead.
|
||||
export function assertUniqueIcaos(fc: GeoJsonFeatureCollection): void {
|
||||
const seen = new Set<string>();
|
||||
for (const f of fc.features) {
|
||||
if (seen.has(f.properties.icao)) throw new Error(`duplicate ICAO in airport dataset: ${f.properties.icao}`);
|
||||
seen.add(f.properties.icao);
|
||||
}
|
||||
}
|
||||
|
||||
let cached: GeoJsonFeatureCollection | null = null;
|
||||
|
||||
export async function loadAirportsGeoJson(): Promise<GeoJsonFeatureCollection> {
|
||||
if (cached) return cached;
|
||||
const file = path.join(process.cwd(), 'data', 'airports_eu.csv');
|
||||
const file = path.join(process.cwd(), 'data', 'airports_world.csv');
|
||||
const text = await fs.readFile(file, 'utf8');
|
||||
cached = toGeoJson(filterEuAirports(parseCsv(text)));
|
||||
const fc = toGeoJson(filterWorldAirports(parseCsv(text)));
|
||||
assertUniqueIcaos(fc);
|
||||
cached = fc;
|
||||
return cached;
|
||||
}
|
||||
|
||||
|
||||
@@ -11,12 +11,15 @@ import {
|
||||
PACKAGE_COUNT_MIN,
|
||||
generatePackage,
|
||||
HUB_ICAO,
|
||||
MAX_JOB_LEG_KM,
|
||||
pickDestWithinCap,
|
||||
mulberry32,
|
||||
REWARD_PER_KG,
|
||||
REWARD_PER_KM,
|
||||
rewardFor,
|
||||
STARTING_CASH,
|
||||
STARTING_REPUTATION,
|
||||
type Rng,
|
||||
type SeedAirport,
|
||||
} from './seed';
|
||||
|
||||
@@ -336,3 +339,94 @@ describe('generatePackage (shared seed/spawn builder)', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('distance cap (v0.44.0, ISS-079)', () => {
|
||||
// A and B are ~90 km apart; C is ~19000 km from both — every pair touching C exceeds the cap.
|
||||
const FAR: SeedAirport[] = [
|
||||
{ icao: 'AAAA', name: 'Close One', lat: 50, lon: 8 },
|
||||
{ icao: 'BBBB', name: 'Close Two', lat: 50.5, lon: 9 },
|
||||
{ icao: 'CCCC', name: 'Far Away', lat: -35, lon: 175 },
|
||||
];
|
||||
|
||||
// Scripted RNG: each value v yields index floor(v * FAR.length) — 0.x → AAAAA/BBBBB range.
|
||||
const scripted = (values: number[]): { rng: Rng; draws: () => number } => {
|
||||
let i = 0;
|
||||
return { rng: () => values[Math.min(i++, values.length - 1)], draws: () => i };
|
||||
};
|
||||
|
||||
it('re-picks an over-cap pair until the leg fits (both endpoints unforced)', () => {
|
||||
// Attempt 1: C→A (over cap) → rejected; attempt 2: A→B (~90 km) → accepted. Exactly 4 endpoint draws.
|
||||
const { rng, draws } = scripted([0.9, 0.1, 0.1, 0.4]);
|
||||
const c = generatePackage({ id: 'c-cap', airports: FAR, rng, nowMs: NOW, special: null });
|
||||
expect(c.originIcao).toBe('AAAA');
|
||||
expect(c.destIcao).toBe('BBBB');
|
||||
// 4 endpoint draws (origin + dest per attempt — the accepted pair stops the loop) + 4 fixed draws.
|
||||
expect(draws()).toBe(8);
|
||||
});
|
||||
|
||||
it('falls back to a within-cap pick of the last origin when attempts exhaust', () => {
|
||||
// 24 over-cap C→A attempts, then A→C (still over cap) ends the bounded loop; the fallback keeps
|
||||
// origin A and draws one index from its within-cap neighbours [B] → A→B. 25×2 + 1 = 51 draws.
|
||||
const values: number[] = [];
|
||||
for (let i = 0; i < 24; i++) values.push(0.9, 0.1); // C→A ×24
|
||||
values.push(0.1, 0.9); // A→C — attempt 25, still over cap
|
||||
values.push(0.5); // fallback draw → candidates[0] = B
|
||||
const { rng, draws } = scripted(values);
|
||||
const c = generatePackage({ id: 'c-cap-fb', airports: FAR, rng, nowMs: NOW, special: null });
|
||||
expect(c.originIcao).toBe('AAAA');
|
||||
expect(c.destIcao).toBe('BBBB');
|
||||
// 51 endpoint draws (25 attempts × 2 + the fallback draw) + 4 fixed draws.
|
||||
expect(draws()).toBe(55);
|
||||
});
|
||||
|
||||
it('keeps the last over-cap pair when the origin has no within-cap neighbour (no throw mid-tick)', () => {
|
||||
// All 25 attempts C→A; the fallback finds no airport within cap of C → -1, pair kept. No extra draw.
|
||||
const values: number[] = [];
|
||||
for (let i = 0; i < 25; i++) values.push(0.9, 0.1); // C→A ×25
|
||||
const { rng, draws } = scripted(values);
|
||||
const c = generatePackage({ id: 'c-cap-keep', airports: FAR, rng, nowMs: NOW, special: null });
|
||||
expect(c.originIcao).toBe('CCCC');
|
||||
expect(c.destIcao).toBe('AAAA');
|
||||
// 50 endpoint draws (25 attempts × 2) + no fallback draw when there are no candidates + 4 fixed.
|
||||
expect(draws()).toBe(54);
|
||||
});
|
||||
|
||||
it('leaves forced endpoints uncapped and consumes no extra draws (the UNNT→LPPD backstop relies on this)', () => {
|
||||
const c = generatePackage({ id: 'c-cap-forced', airports: FAR, rng: mulberry32(42), nowMs: NOW, originIcao: 'CCCC', destIcao: 'AAAA' });
|
||||
expect(c.originIcao).toBe('CCCC'); // ~19000 km — forced pairs skip the cap entirely
|
||||
expect(c.destIcao).toBe('AAAA');
|
||||
|
||||
const countDraws = (origin?: string, dest?: string): number => {
|
||||
let n = 0;
|
||||
generatePackage({ id: 'c-cap-n', airports: FAR, rng: () => { n += 1; return mulberry32(42)(); }, nowMs: NOW, originIcao: origin, destIcao: dest, special: null });
|
||||
return n;
|
||||
};
|
||||
expect(countDraws('CCCC')).toBe(5); // forced origin + random (uncapped) dest → 1 endpoint draw + 4 fixed
|
||||
expect(countDraws('CCCC', 'AAAA')).toBe(4); // both forced → no endpoint draws at all
|
||||
});
|
||||
|
||||
it('pickDestWithinCap picks uniformly from within-cap neighbours, excludes the origin, and returns -1 without a draw when none fit', () => {
|
||||
const near: SeedAirport[] = [FAR[0], FAR[1]]; // A + B only — both within cap of each other
|
||||
let calls = 0;
|
||||
const countingRng: Rng = () => { calls += 1; return 0.9; };
|
||||
expect(pickDestWithinCap(near, 0, countingRng)).toBe(1); // A's only neighbour is B
|
||||
expect(calls).toBe(1);
|
||||
|
||||
let farCalls = 0;
|
||||
const farRng: Rng = () => { farCalls += 1; return 0.9; };
|
||||
expect(pickDestWithinCap(FAR, 2, farRng)).toBe(-1); // C has no neighbour within the cap
|
||||
expect(farCalls).toBe(0); // -1 path consumes no draw
|
||||
});
|
||||
|
||||
it('every generated leg on the real dataset stays under the cap', async () => {
|
||||
const { loadAirportsGeoJson } = await import('@/lib/airports');
|
||||
const fc = await loadAirportsGeoJson();
|
||||
const airports: SeedAirport[] = fc.features.map((f) => ({ icao: f.properties.icao, name: f.properties.name, lat: f.properties.lat, lon: f.properties.lon }));
|
||||
for (let seed = 1; seed <= 50; seed++) {
|
||||
const c = generatePackage({ id: `c-real-${seed}`, airports, rng: mulberry32(seed), nowMs: NOW });
|
||||
const o = airports.find((a) => a.icao === c.originIcao)!;
|
||||
const d = airports.find((a) => a.icao === c.destIcao)!;
|
||||
expect(haversineKm(o.lat, o.lon, d.lat, d.lon)).toBeLessThanOrEqual(MAX_JOB_LEG_KM);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -101,6 +101,16 @@ export const JOB_BONUS_PER_REP = 0.01;
|
||||
// ponytail: balance-tunable — max job reward bonus (up to ×2 at rep ≥ 110).
|
||||
export const MAX_JOB_BONUS = 1.0;
|
||||
|
||||
// v0.44.0 (ISS-079): generated jobs are capped at this great-circle distance so every spawned
|
||||
// leg is flyable by at least one catalog plane even in worst-case headwind — the b777's full-tank
|
||||
// range is ~13045 km nominal and ~10871 km with the +20% wind factor (maxRangeKm ÷ 1.2), so 9000
|
||||
// leaves margin below it while still spanning most of a continent. ponytail: balance-tunable —
|
||||
// must stay ≤ maxRangeKm(b777) / 1.2 or some generated legs are permanently unflyable.
|
||||
export const MAX_JOB_LEG_KM = 9000;
|
||||
|
||||
// Bounded rejection attempts in generatePackage before the within-cap fallback kicks in.
|
||||
const LEG_CAP_MAX_ATTEMPTS = 25;
|
||||
|
||||
// Package deadlines: now + a plausible game-time window of 6–72 hours.
|
||||
const DEADLINE_MIN_HOURS = 6;
|
||||
const DEADLINE_MAX_HOURS = 72;
|
||||
@@ -171,6 +181,27 @@ export function generatePackage(input: {
|
||||
} else {
|
||||
di = Math.floor(rng() * airports.length);
|
||||
if (di === oi) di = (di + 1) % airports.length;
|
||||
// v0.44.0 (ISS-079): cap on generated legs — when BOTH endpoints are unforced, rejection-sample
|
||||
// the pair until it fits MAX_JOB_LEG_KM so spawned jobs stay flyable by at least one catalog plane.
|
||||
// Forced paths keep their pre-v0.44.0 draw behavior exactly (the engine's coverage spawn caps its
|
||||
// random dest itself via pickDestWithinCap). Under-cap pairs take just the two draws above, so the
|
||||
// RNG stream is byte-identical to before for them.
|
||||
if (input.originIcao === undefined) {
|
||||
let km = haversineKm(airports[oi].lat, airports[oi].lon, airports[di].lat, airports[di].lon);
|
||||
for (let attempt = 1; km > MAX_JOB_LEG_KM && attempt < LEG_CAP_MAX_ATTEMPTS; attempt++) {
|
||||
oi = Math.floor(rng() * airports.length);
|
||||
di = Math.floor(rng() * airports.length);
|
||||
if (di === oi) di = (di + 1) % airports.length;
|
||||
km = haversineKm(airports[oi].lat, airports[oi].lon, airports[di].lat, airports[di].lon);
|
||||
}
|
||||
if (km > MAX_JOB_LEG_KM) {
|
||||
// Exhausted: keep the last origin and pick uniformly from its within-cap neighbours. If none
|
||||
// exist (impossible in the curated dataset — every airport has a neighbour well inside the cap),
|
||||
// keep the over-cap pair rather than throw mid-tick.
|
||||
const fallback = pickDestWithinCap(airports, oi, rng);
|
||||
if (fallback >= 0) di = fallback;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (oi === di) throw new Error('origin and destination must differ'); // both forced identical
|
||||
const origin = airports[oi];
|
||||
@@ -213,6 +244,19 @@ export function generatePackage(input: {
|
||||
};
|
||||
}
|
||||
|
||||
// v0.44.0 (ISS-079): uniform random index of an airport within MAX_JOB_LEG_KM of airports[originIdx]
|
||||
// (excluding the origin itself) — one RNG draw, -1 when no neighbour fits. Shared by generatePackage's
|
||||
// exhaustion fallback and the engine's coverage spawn so both cap identically without duplicating the scan.
|
||||
export function pickDestWithinCap(airports: SeedAirport[], originIdx: number, rng: Rng): number {
|
||||
const candidates: number[] = [];
|
||||
for (let j = 0; j < airports.length; j++) {
|
||||
if (j === originIdx) continue;
|
||||
if (haversineKm(airports[originIdx].lat, airports[originIdx].lon, airports[j].lat, airports[j].lon) <= MAX_JOB_LEG_KM) candidates.push(j);
|
||||
}
|
||||
if (candidates.length === 0) return -1;
|
||||
return candidates[Math.floor(rng() * candidates.length)];
|
||||
}
|
||||
|
||||
function pickHub(airports: SeedAirport[]): SeedAirport {
|
||||
return airports.find((a) => a.icao === HUB_ICAO) ?? airports[0];
|
||||
}
|
||||
|
||||
+4
-4
@@ -8,7 +8,7 @@ export const openApiSpec = {
|
||||
info: {
|
||||
title: 'Flight Ops API',
|
||||
description:
|
||||
'JSON API for Flight Ops — EU airport data for the map, the live game-state snapshot, player actions (load / fly / abandon / buy / sell), and app metadata. Every action endpoint ticks the sim clock first and returns the full state snapshot on success.',
|
||||
'JSON API for Flight Ops — world airport data for the map, the live game-state snapshot, player actions (load / fly / abandon / buy / sell), and app metadata. Every action endpoint ticks the sim clock first and returns the full state snapshot on success.',
|
||||
// Sourced from package.json so it stays in sync with every version bump.
|
||||
version: pkg.version,
|
||||
},
|
||||
@@ -17,13 +17,13 @@ export const openApiSpec = {
|
||||
paths: {
|
||||
'/api/airports': {
|
||||
get: {
|
||||
summary: 'List EU airports',
|
||||
summary: 'List world airports',
|
||||
description:
|
||||
'All fixed-wing EU airports (large, medium and seaplane bases) as a GeoJSON FeatureCollection.',
|
||||
'The curated world airport dataset — one marker per metro area (large airports only, close clusters merged to the biggest; see scripts/build-world-airports.mjs) — as a GeoJSON FeatureCollection.',
|
||||
operationId: 'listAirports',
|
||||
responses: {
|
||||
200: {
|
||||
description: 'GeoJSON FeatureCollection of EU airports',
|
||||
description: 'GeoJSON FeatureCollection of world airports',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: { $ref: '#/components/schemas/AirportFeatureCollection' },
|
||||
|
||||
+15
-2
@@ -12,6 +12,7 @@ import {
|
||||
generatePackage,
|
||||
MARKET_TARGET_OPEN_PACKAGES,
|
||||
mulberry32,
|
||||
pickDestWithinCap,
|
||||
type Rng,
|
||||
type SeedAirport,
|
||||
} from '@/lib/game/seed';
|
||||
@@ -371,9 +372,21 @@ export async function spawnCoveragePackages(
|
||||
|
||||
let n = 0;
|
||||
for (const icao of missing) {
|
||||
if (!airports.some((a) => a.icao === icao)) continue; // defensive — the dataset is the source of all ICACs
|
||||
const oi = airports.findIndex((a) => a.icao === icao);
|
||||
if (oi < 0) continue; // defensive — the dataset is the source of all ICACs
|
||||
// v0.44.0 (ISS-079): cap the random dest at MAX_JOB_LEG_KM like generatePackage's unforced pairs —
|
||||
// one draw in the same stream position as the old uncapped pick, so downstream draws are unchanged.
|
||||
const di = pickDestWithinCap(airports, oi, rand);
|
||||
await inst.db.insert(schema.packages).values(
|
||||
generatePackage({ id: randomUUID(), airports, rng: rand, nowMs: clockMs, originIcao: icao, reputation: account.reputation }),
|
||||
generatePackage({
|
||||
id: randomUUID(),
|
||||
airports,
|
||||
rng: rand,
|
||||
nowMs: clockMs,
|
||||
originIcao: icao,
|
||||
...(di >= 0 ? { destIcao: airports[di].icao } : {}), // di < 0 (no within-cap neighbour) → old uncapped behavior
|
||||
reputation: account.reputation,
|
||||
}),
|
||||
);
|
||||
n++;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user