Flight queue backend: planes hold a queue of upcoming legs, auto-chain on landing (ISS-043 part 1)
CI / build + unit + e2e (pull_request) Failing after 6m37s

- planes.queue TEXT NOT NULL DEFAULT '[]' — ordered JSON array of not-yet-started
  leg ICACs; active leg stays destIcao + departureSimTime. DDL + guarded ALTER
  migration for existing DBs; seed sets queue: [] explicitly.
- deliverPackages() auto-chains on arrival: with a non-empty queue and fuel
  covering the first queued leg (same requiredFuelFor rule as /fly), the plane
  immediately starts that leg from the arrival airport (stays 'flying',
  departureSimTime = arrival instant, queue shortened). Short tank → grounds
  safely with the queue kept intact; empty queue → unchanged grounding. Cargo
  delivery for the reached airport runs first and is unaffected. Ordering kept:
  delivery still runs before tickOnce's pause check, so a chained plane counts
  as still flying — no premature last-plane pause (ISS-041 preserved).
- New endpoints via performAction(): POST /api/planes/{planeId}/queue {destIcao}
  (append; works grounded or flying; 400 bad body/unknown ICAO, 404 unknown
  plane) and POST /api/planes/{planeId}/queue/cancel {index} (remove queued leg
  by index; active in-flight leg never affected; 400 non-integer/out-of-range,
  404 unknown plane). Both return the full state snapshot.
- PlaneState.queue: string[] in /api/state (null/malformed-safe parse helper
  shared with the engine); OpenAPI updated (PlaneState.queue, QueueLegRequest,
  CancelQueuedLegRequest, both paths) and openapi.test.ts expectations extended.
- Tests: auto-chain block in engine.test.ts (chain / short-fuel ground / empty
  queue) + chained-plane-no-pause regression guard; queueLeg/cancelQueuedLeg
  blocks in actions.test.ts; type-compat queue: [] fixtures in deriveEvents,
  right-pane, mapData and seed tests.

v0.25.0 — part 1 (backend) of ISS-043; UI/map rendering lands in a follow-up.
This commit is contained in:
2026-09-20 10:39:00 +00:00
parent e109e003c0
commit 69b708dad3
18 changed files with 486 additions and 35 deletions
+79 -1
View File
@@ -9,7 +9,7 @@ import { loadAirportsGeoJson } from '@/lib/airports';
import { haversineKm } from '@/lib/geo';
import { PLANE_TYPES } from '@/lib/game/catalog';
import { MARKET_TARGET_OPEN_PACKAGES, mulberry32 } from '@/lib/game/seed';
import { arrivalTimeFor, fuelAtWeighted } from './movement';
import { arrivalTimeFor, fuelAtWeighted, requiredFuelFor } from './movement';
import {
clampTimeScale,
deliverPackages,
@@ -235,6 +235,68 @@ describe('deliverPackages (v0.12.0 arrival delivery)', () => {
.set({ status: 'flying', departureSimTime: T0 });
expect(await deliverPackages(inst, T0 + 3_600_000)).toBe(0);
});
// --- Auto-chain on landing (v0.25.0, ISS-043) ---
it('auto-chains to the next queued leg when fuel covers it', async () => {
const { inst, to, km, type } = await setupFlight('chain-ok.db'); // full tank EDDF→LEMD
const fc = await loadAirportsGeoJson();
const nextP = fc.features.find((f) => f.properties.icao === 'EHAM')!.properties;
const nextKm = haversineKm(to.lat, to.lon, nextP.lat, nextP.lon);
// Precondition sanity: a full-tank departure leaves enough for the LEMD→EHAM hop.
const landedFuel = fuelAtWeighted(type.maxFuel, type.burnPerKm, type.emptyWeightKg, type.maxFuel, km, 1);
expect(requiredFuelFor(type.burnPerKm, type.emptyWeightKg, type.maxFuel, nextKm)).toBeLessThanOrEqual(landedFuel);
await inst.db.update(schema.planes)
.set({ queue: JSON.stringify(['EHAM', 'EDDV']) })
.where(eq(schema.planes.id, 'plane-starter'));
const clock = T0 + travelMs(km, type.speedKmh); // exactly at arrival
expect(await deliverPackages(inst, clock)).toBe(1);
const plane = (await inst.db.select().from(schema.planes))[0];
expect(plane.status).toBe('flying'); // chained — still airborne, no ground stop
expect(plane.destIcao).toBe('EHAM'); // first queued leg is now the active one
expect(plane.departureSimTime).toBe(clock); // departed at the arrival instant…
expect(plane.locationIcao).toBe(TO); // …from the airport just landed at
expect(plane.lat).toBe(to.lat);
expect(plane.lon).toBe(to.lon);
expect(JSON.parse(plane.queue)).toEqual(['EDDV']); // first leg consumed, rest kept in order
});
it('grounds when fuel cannot cover the next queued leg, keeping the queue intact', async () => {
const { inst, km, type } = await setupFlight('chain-nofuel.db');
const fc = await loadAirportsGeoJson();
const nextP = fc.features.find((f) => f.properties.icao === 'EHAM')!.properties;
// Depart with exactly the fuel for EDDF→LEMD → lands empty, cannot start LEMD→EHAM.
await inst.db.update(schema.planes)
.set({
fuel: requiredFuelFor(type.burnPerKm, type.emptyWeightKg, type.maxFuel, km),
queue: JSON.stringify(['EHAM']),
})
.where(eq(schema.planes.id, 'plane-starter'));
const clock = T0 + travelMs(km, type.speedKmh); // exactly at arrival
expect(await deliverPackages(inst, clock)).toBe(1);
const plane = (await inst.db.select().from(schema.planes))[0];
expect(plane.status).toBe('available'); // grounded safely…
expect(plane.destIcao).toBeNull();
expect(plane.departureSimTime).toBeNull();
expect(JSON.parse(plane.queue)).toEqual(['EHAM']); // …queue kept for refuel + re-dispatch
});
it('grounds as before when the queue is empty', async () => {
const { inst, km } = await setupFlight('chain-empty.db'); // seeded default queue '[]'
expect(await deliverPackages(inst, T0 + travelMs(km, PLANE_TYPES.atr72.speedKmh))).toBe(1);
const plane = (await inst.db.select().from(schema.planes))[0];
expect(plane.status).toBe('available'); // unchanged landing behavior…
expect(JSON.parse(plane.queue)).toEqual([]); // …and the queue stays empty
});
});
describe('pause on landing when the last plane lands (ISS-041)', () => {
@@ -300,6 +362,22 @@ describe('pause on landing when the last plane lands (ISS-041)', () => {
expect((await inst.db.select().from(schema.planes))[0].status).toBe('available');
});
it('a chained plane does NOT trigger the last-plane pause (ISS-043)', async () => {
const { inst } = await setupLanding('pause-chain.db', 1000); // full tank, arrival exactly T0
// A queued next hop with plenty of fuel → chains on landing instead of grounding.
await inst.db.update(schema.planes)
.set({ queue: JSON.stringify(['EDDV']) })
.where(eq(schema.planes.id, 'plane-starter'));
vi.setSystemTime(T0 + 2_000); // one full clamped tick at scale 1000 → clock T0+2e6 ≥ arrival (T0)
const sim = await tickOnce(inst);
expect(sim.paused).toBe(false); // still flying after the chain — no premature pause…
const plane = (await inst.db.select().from(schema.planes))[0];
expect(plane.status).toBe('flying'); // …the fresh select in tickOnce counts it as airborne
expect(plane.destIcao).toBe('EDDV');
});
it('paused sim with all planes landed → no change', async () => {
const inst = await freshDb('pause-paused.db');
// The fleet is fully grounded (the seeded starter) — a paused tick must not touch the
+57 -19
View File
@@ -5,6 +5,7 @@ import * as schema from '@/lib/db/schema';
import { loadAirportsGeoJson } from '@/lib/airports';
import { haversineKm } from '@/lib/geo';
import { PLANE_TYPES } from '@/lib/game/catalog';
import { parseIcaoQueue } from '@/lib/game/state';
import {
generatePackage,
MARKET_TARGET_OPEN_PACKAGES,
@@ -12,7 +13,7 @@ import {
type Rng,
type SeedAirport,
} from '@/lib/game/seed';
import { arrivalTimeFor, fuelAtWeighted } from './movement';
import { arrivalTimeFor, fuelAtWeighted, requiredFuelFor } from './movement';
// Server-authoritative sim engine (v0.7.0) — tick-on-read: there is NO background
// timer. Every read/action endpoint calls tickNow() first; the clock advances by
@@ -122,12 +123,17 @@ export async function expirePackages(inst: GameDb, clockMs: number): Promise<num
}
// Finalize in-flight planes whose arrival time has passed (v0.12.0 delivery):
// ground the plane at its dest_icao with its remaining fuel, then for every
// package bound to it and destined for that airport — 'loaded' ones still inside
// their deadline are delivered (cash += reward + reputation gain per package),
// 'expired' ones just unbind (no reward). Packages destined elsewhere stay loaded
// on the plane for a later leg. Idempotent — a finalized plane leaves the
// 'flying' state, so it can never be awarded twice. Returns planes landed.
// for every package bound to the plane and destined for its dest_icao — 'loaded'
// ones still inside their deadline are delivered (cash += reward + reputation
// gain per package), 'expired' ones just unbind (no reward). Packages destined
// elsewhere stay loaded on the plane for a later leg. Then (v0.25.0, ISS-043)
// auto-chain: if the queue holds legs and fuel covers the first one, start it
// immediately from the arrival airport; otherwise ground the plane there with
// its remaining fuel (a short tank keeps the queue intact for refuel + re-dispatch).
// Idempotent — a finalized plane either leaves the 'flying' state or starts a NEW
// leg whose own arrival is in the future, so it can never be awarded twice.
// Returns planes landed. NOTE: runs BEFORE tickOnce's pause check on purpose —
// a chained plane counts as still flying there, so chaining never pauses early.
export async function deliverPackages(inst: GameDb, clockMs: number): Promise<number> {
const [planeRows, packageRows] = await Promise.all([
inst.db.select().from(schema.planes),
@@ -149,19 +155,10 @@ export async function deliverPackages(inst: GameDb, clockMs: number): Promise<nu
if (clockMs < arrivalTimeFor(p.departureSimTime, distanceKm, type.speedKmh)) continue;
// Arrived: progress is exactly 1 here, so remaining fuel is the full-leg weighted burn.
await inst.db.update(schema.planes)
.set({
status: 'available',
locationIcao: to.icao,
lat: to.lat,
lon: to.lon,
fuel: fuelAtWeighted(p.fuel, type.burnPerKm, type.emptyWeightKg, type.maxFuel, distanceKm, 1),
departureSimTime: null,
destIcao: null,
})
.where(eq(schema.planes.id, p.id));
const landedFuel = fuelAtWeighted(p.fuel, type.burnPerKm, type.emptyWeightKg, type.maxFuel, distanceKm, 1);
// Deliver every bound package whose destination is the airport just reached.
// Deliver every bound package whose destination is the airport just reached —
// runs whether or not a queued leg chains next (ISS-043).
const onBoard = packageRows.filter((pk) => pk.planeId === p.id && pk.destIcao === to.icao);
for (const pk of onBoard) {
if (pk.status === 'loaded' && clockMs <= pk.deadlineSimTime) {
@@ -178,6 +175,47 @@ export async function deliverPackages(inst: GameDb, clockMs: number): Promise<nu
await inst.db.update(schema.packages).set({ planeId: null }).where(eq(schema.packages.id, pk.id));
}
}
// Auto-chain (ISS-043): with a non-empty queue and enough fuel for the first
// queued leg, start it immediately from `to` — same feasibility rule as flyPlane
// (requiredFuelFor is independent of current load). Otherwise ground here; an
// unknown ICAO in the queue simply cannot chain. The remaining queue is kept
// intact either way so a grounded plane can refuel and re-dispatch.
const queue = parseIcaoQueue(p.queue);
let chainedTo: string | null = null;
if (queue.length > 0) {
const nextDest = queue[0];
const next = byIcao.get(nextDest); // unknown ICAO in the queue → cannot chain
if (next && requiredFuelFor(type.burnPerKm, type.emptyWeightKg, type.maxFuel, haversineKm(to.lat, to.lon, next.lat, next.lon)) <= landedFuel) {
queue.shift();
chainedTo = nextDest;
}
}
await inst.db.update(schema.planes)
.set(
chainedTo
? {
status: 'flying',
locationIcao: to.icao,
lat: to.lat,
lon: to.lon,
fuel: landedFuel,
destIcao: chainedTo,
departureSimTime: clockMs, // the arrival instant — position is exactly `to`
queue: JSON.stringify(queue),
}
: {
status: 'available',
locationIcao: to.icao,
lat: to.lat,
lon: to.lon,
fuel: landedFuel,
departureSimTime: null,
destIcao: null,
queue: JSON.stringify(queue),
},
)
.where(eq(schema.planes.id, p.id));
n++;
}
return n;