Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(flight-live): leave a through flight's first sector aircraft to that sector

Maurice40dea84085d5
diff --git a/server/src/nest/flight-live/flight-live-poll.service.ts b/server/src/nest/flight-live/flight-live-poll.service.ts
index 60ffbabdf..81988d22c 100644
--- a/server/src/nest/flight-live/flight-live-poll.service.ts
+++ b/server/src/nest/flight-live/flight-live-poll.service.ts
@@ -19,6 +19,7 @@ import {
toLiveLeg,
watchWindow,
type LiveState,
+ type SiblingSector,
} from './flight-live.derive';
import { FlightLiveFeedService, type FeedLookup } from './flight-live.feeds';
import { FlightLiveService, legKey, type TripLeg } from './flight-live.service';
@@ -96,6 +97,23 @@ function utcDate(now: number, days: number): string {
return new Date(now + days * DAY_MS).toISOString().slice(0, 10);
}
+/** The other sectors in their window that fly under the same callsign as the flight `key`. */
+function siblingSectors(
+ key: string,
+ groups: ReadonlyMap<string, TripLeg[]>,
+ stored: ReadonlyMap<string, LiveState>,
+): SiblingSector[] {
+ const route = groups.get(key)?.[0];
+ if (!route) return [];
+ const siblings: SiblingSector[] = [];
+ for (const [other, legs] of groups) {
+ const sector = legs[0];
+ if (other === key || !sector || sector.callsign !== route.callsign) continue;
+ siblings.push({ route: sector, landed: stored.get(other)?.phase === 'landed' });
+ }
+ return siblings;
+}
+
/**
* The poll behind live flight status, one tick a minute (FlightLiveJob).
*
@@ -176,7 +194,11 @@ export class FlightLivePollService {
(a.state?.next_poll_at ?? 0) - (b.state?.next_poll_at ?? 0),
);
- const queue = due.slice(0, MAX_REQUESTS_PER_TICK).map(({ key, state }) => ({ legs: groups.get(key) ?? [], state }));
+ const queue = due.slice(0, MAX_REQUESTS_PER_TICK).map(({ key, state }) => ({
+ legs: groups.get(key) ?? [],
+ state,
+ siblings: siblingSectors(key, groups, stored),
+ }));
const result: PollResult = { asked: 0, changed: 0, skipped: null };
await this.pollEach(queue, clock, result);
return result;
@@ -214,7 +236,7 @@ export class FlightLivePollService {
* @txIndependent one write per flight (pollDue).
*/
private async pollEach(
- queue: ReadonlyArray<{ legs: TripLeg[]; state: LiveState | null }>,
+ queue: ReadonlyArray<{ legs: TripLeg[]; state: LiveState | null; siblings: SiblingSector[] }>,
clock: () => number,
result: PollResult,
): Promise<void> {
@@ -231,7 +253,8 @@ export class FlightLivePollService {
if (!answer.ok && (answer as Extract<FeedLookup, { ok: false }>).reason === 'budget') return;
result.asked++;
const at = clock();
- let next = answer.ok ? advance(prev, pickAircraft(answer.aircraft, route), route, at, answer.source) : failed(prev);
+ const picked = answer.ok ? pickAircraft(answer.aircraft, route, { now: at, siblings: head.siblings }) : null;
+ let next = answer.ok ? advance(prev, picked, route, at, answer.source) : failed(prev);
next = closeIfOver({ ...next, next_poll_at: nextPollAt(next, route, at) }, route, at);
const notices = this.dueNotices(prev, next, head.legs, at);
next = { ...next, ...notices.flags };
diff --git a/server/src/nest/flight-live/flight-live.derive.ts b/server/src/nest/flight-live/flight-live.derive.ts
index 7dedc1cc6..a663f7626 100644
--- a/server/src/nest/flight-live/flight-live.derive.ts
+++ b/server/src/nest/flight-live/flight-live.derive.ts
@@ -117,23 +117,73 @@ export function inWatchWindow(leg: Schedule, now: number): boolean {
return span !== null && now >= span.start && now <= span.end;
}
+/** Another sector the same callsign flies in its watch window right now, and whether it is down already. */
+export interface SiblingSector {
+ route: Route;
+ landed: boolean;
+}
+
+function detourKm(lat: number, lng: number, route: Route): number {
+ const total = kmTo(route.origin.lat, route.origin.lng, route.destination);
+ return kmTo(lat, lng, route.origin) + kmTo(lat, lng, route.destination) - total;
+}
+
+/**
+ * How far a position is from where the sector's aircraft should be at `now`,
+ * in km: at the origin before the scheduled departure, at the destination
+ * after the scheduled arrival, on the route in between.
+ */
+function sectorFitKm(lat: number, lng: number, route: Route, now: number): number {
+ if (route.scheduled_departure !== null && now < route.scheduled_departure) return kmTo(lat, lng, route.origin);
+ if (route.scheduled_arrival !== null && now > route.scheduled_arrival) return kmTo(lat, lng, route.destination);
+ return detourKm(lat, lng, route);
+}
+
+function departsEarlier(a: Route, b: Route): boolean {
+ return (a.scheduled_departure ?? Number.POSITIVE_INFINITY) < (b.scheduled_departure ?? Number.POSITIVE_INFINITY);
+}
+
+/**
+ * Whether a sibling sector of the same flight number claims this position: it
+ * fits that sector better, or as well and that sector flies first and has not
+ * landed yet. A through flight (BWI-MDW-DEN as one number) is in the second
+ * sector's window during the whole first one, and the aircraft flying to MDW
+ * must not read as the MDW-DEN sector having departed.
+ */
+function claimedBySibling(
+ lat: number,
+ lng: number,
+ route: Route,
+ now: number,
+ siblings: readonly SiblingSector[],
+): boolean {
+ const own = sectorFitKm(lat, lng, route, now);
+ return siblings.some((sibling) => {
+ if (sibling.landed) return false;
+ const fit = sectorFitKm(lat, lng, sibling.route, now);
+ return fit < own || (fit === own && departsEarlier(sibling.route, route));
+ });
+}
+
/**
* The aircraft that flies this leg among those the feed answered for the
* callsign: the one with a position nearest the great circle between the two
* airports (least detour over the direct distance). A callsign is reused by
- * the next leg of a rotation, so two can be in the air at once.
+ * the next leg of a rotation, so two can be in the air at once. An aircraft a
+ * sibling sector of the same flight number claims at `now` is left to it.
*/
-export function pickAircraft(aircraft: readonly FeedAircraft[], route: Route): FeedAircraft | null {
- const total = kmTo(route.origin.lat, route.origin.lng, route.destination);
+export function pickAircraft(
+ aircraft: readonly FeedAircraft[],
+ route: Route,
+ sectors: { now: number; siblings: readonly SiblingSector[] } = { now: 0, siblings: [] },
+): FeedAircraft | null {
let best: FeedAircraft | null = null;
let bestScore = Number.POSITIVE_INFINITY;
for (const ac of aircraft) {
const lat = finite(ac.lat);
const lng = finite(ac.lon);
- const score =
- lat === null || lng === null
- ? Number.MAX_VALUE
- : kmTo(lat, lng, route.origin) + kmTo(lat, lng, route.destination) - total;
+ if (lat !== null && lng !== null && claimedBySibling(lat, lng, route, sectors.now, sectors.siblings)) continue;
+ const score = lat === null || lng === null ? Number.MAX_VALUE : detourKm(lat, lng, route);
if (best === null || score < bestScore) {
best = ac;
bestScore = score;
diff --git a/server/tests/unit/nest/flight-live/flight-live-poll.service.test.ts b/server/tests/unit/nest/flight-live/flight-live-poll.service.test.ts
index 41f84bee4..25688b443 100644
--- a/server/tests/unit/nest/flight-live/flight-live-poll.service.test.ts
+++ b/server/tests/unit/nest/flight-live/flight-live-poll.service.test.ts
@@ -347,10 +347,53 @@ describe('FlightLivePollService: closing and sectors', () => {
expect(await poll.poll(at(DEP + 5 * MIN))).toMatchObject({ asked: 2 });
const rows = await findRows(orm, FlightLiveStates, { callsign: 'DLH100' });
// Seen climbing out of Frankfurt: wheels-up for the first sector, nothing claimed for the second.
- expect(rows.map((r) => [r.origin, r.destination, r.departed_at]).sort()).toEqual([
- ['BER', 'FRA', null],
- ['FRA', 'BER', '2026-07-01 10:05:00'],
+ expect(rows.map((r) => [r.origin, r.destination, r.phase, r.departed_at]).sort()).toEqual([
+ ['BER', 'FRA', 'scheduled', null],
+ ['FRA', 'BER', 'airborne', '2026-07-01 10:05:00'],
]);
+ expect(events()).toEqual(['flight_departed']);
+ feed.lookup.mockReset();
+ });
+
+ it('FLPOLL-013: the second sector of a through flight departs only when its own aircraft leaves', async () => {
+ const { user } = await makeUser(orm);
+ const trip = await makeTrip(orm, user.id, { title: 'Onwards' });
+ const day = await makeDay(orm, trip.id, { day_number: 1, date: '2026-07-01' });
+ const legs = [
+ { from: 'FRA', to: 'BER', flight_number: 'LH 100', dep_day_id: day.id, dep_time: '12:00', arr_time: '13:10' },
+ { from: 'BER', to: 'VIE', flight_number: 'LH 100', dep_day_id: day.id, dep_time: '13:55', arr_time: '15:05' },
+ ];
+ const flight = await makeReservation(orm, trip.id, {
+ title: 'Through flight',
+ type: 'flight',
+ metadata: JSON.stringify({ legs }),
+ });
+ const fra = { name: 'Frankfurt (FRA)', code: 'FRA', lat: 50.0333, lng: 8.5706, timezone: 'Europe/Berlin' };
+ const ber = { name: 'Berlin (BER)', code: 'BER', lat: 52.3667, lng: 13.5033, timezone: 'Europe/Berlin' };
+ const vie = { name: 'Vienna (VIE)', code: 'VIE', lat: 48.1103, lng: 16.5697, timezone: 'Europe/Vienna' };
+ await makeReservationEndpoint(orm, flight.id, { role: 'from', sequence: 0, ...fra, local_date: '2026-07-01' });
+ await makeReservationEndpoint(orm, flight.id, { role: 'stop', sequence: 1, ...ber, local_date: '2026-07-01' });
+ await makeReservationEndpoint(orm, flight.id, { role: 'to', sequence: 2, ...vie, local_date: '2026-07-01' });
+ const sector = (origin: string) => findRow(orm, FlightLiveStates, { callsign: 'DLH100', origin });
+
+ // Cruising towards Berlin on the first sector: the Vienna sector stays on the ground.
+ feed.lookup.mockResolvedValue(seen(aircraft({ alt_baro: 30000, lat: 51.2, lon: 11, gs: 450 })));
+ await poll.poll(at(DEP + 30 * MIN));
+ expect(await sector('BER')).toMatchObject({ phase: 'scheduled', departed_notified: 0 });
+ expect(events()).toEqual(['flight_departed']);
+
+ // Down in Berlin: the first sector lands, the second still waits for its own departure.
+ feed.lookup.mockResolvedValue(seen(aircraft({ alt_baro: 'ground', lat: 52.37, lon: 13.5, gs: 15 })));
+ await poll.poll(at(ARR + 2 * MIN));
+ expect(await sector('FRA')).toMatchObject({ phase: 'landed' });
+ expect(await sector('BER')).toMatchObject({ departed_notified: 0, departed_at: null });
+
+ // Climbing out of Berlin towards Vienna: now the second sector has departed, told once.
+ notifications.send.mockClear();
+ feed.lookup.mockResolvedValue(seen(aircraft({ alt_baro: 5000, lat: 52.3, lon: 13.6, gs: 230 })));
+ await poll.poll(at(DEP + 120 * MIN));
+ expect(await sector('BER')).toMatchObject({ phase: 'airborne', departed_at: '2026-07-01 12:00:00' });
+ expect(events()).toEqual(['flight_departed']);
feed.lookup.mockReset();
});
});
diff --git a/server/tests/unit/nest/flight-live/flight-live.derive.test.ts b/server/tests/unit/nest/flight-live/flight-live.derive.test.ts
index cf15e0267..4313d3860 100644
--- a/server/tests/unit/nest/flight-live/flight-live.derive.test.ts
+++ b/server/tests/unit/nest/flight-live/flight-live.derive.test.ts
@@ -17,6 +17,7 @@ import {
watchWindow,
type FeedAircraft,
type LiveState,
+ type SiblingSector,
} from '../../../../src/nest/flight-live/flight-live.derive';
import type { ScheduledLeg } from '../../../../src/nest/flight-live/flight-live.schedule';
import { flightLiveLegSchema } from '@trek/shared';
@@ -87,6 +88,56 @@ describe('pickAircraft and observe', () => {
expect(pickAircraft([], LEG)).toBeNull();
});
+ it('FLDER-020: on a through flight the aircraft of the first sector is not taken for the second', () => {
+ const at = (iso: string) => Date.parse(iso);
+ const bwi = { code: 'BWI', name: 'Baltimore', lat: 39.1754, lng: -76.6683, timezone: 'America/New_York' };
+ const mdw = { code: 'MDW', name: 'Chicago Midway', lat: 41.7868, lng: -87.7522, timezone: 'America/Chicago' };
+ const den = { code: 'DEN', name: 'Denver', lat: 39.8561, lng: -104.6737, timezone: 'America/Denver' };
+ const sector = { ...LEG, callsign: 'SWA1234', flight_number: 'WN 1234', service_date: '2026-07-01' };
+ const first: ScheduledLeg = {
+ ...sector,
+ origin: bwi,
+ destination: mdw,
+ scheduled_departure: at('2026-07-01T12:00:00Z'),
+ scheduled_arrival: at('2026-07-01T14:00:00Z'),
+ };
+ const second: ScheduledLeg = {
+ ...sector,
+ leg_index: 1,
+ origin: mdw,
+ destination: den,
+ scheduled_departure: at('2026-07-01T14:45:00Z'),
+ scheduled_arrival: at('2026-07-01T17:15:00Z'),
+ };
+ const flying = [{ route: first, landed: false }];
+ const landed = [{ route: first, landed: true }];
+ const pick = (aircraft: FeedAircraft, leg: ScheduledLeg, now: number, siblings: SiblingSector[]) =>
+ pickAircraft([aircraft], leg, { now, siblings })?.hex ?? null;
+ const swa = (overrides: Partial<FeedAircraft>) => ac({ hex: 'swa', flight: 'SWA1234', ...overrides });
+
+ // At the gate in Baltimore and climbing out of it: the first sector's, not the second's.
+ const atGate = swa({ lat: 39.18, lon: -76.67 });
+ const climbing = swa({ alt_baro: 8000, lat: 39.3, lon: -77.01 });
+ const takeoff = at('2026-07-01T12:10:00Z');
+ expect(pick(atGate, second, at('2026-07-01T11:45:00Z'), flying)).toBeNull();
+ expect(pick(climbing, second, takeoff, flying)).toBeNull();
+ expect(pick(climbing, first, takeoff, [{ route: second, landed: false }])).toBe('swa');
+ const empty = emptyState('SWA1234', '2026-07-01', 'MDW', 'DEN');
+ const picked = pickAircraft([climbing], second, { now: takeoff, siblings: flying });
+ const quiet = advance(empty, picked, second, takeoff, 'adsb.lol');
+ expect(quiet).toMatchObject({ phase: 'scheduled', departed_at: null, first_seen_at: null });
+
+ // Late on final into Midway, close to the second sector's departure: still the first sector's while it flies.
+ const onFinal = swa({ alt_baro: 2500, lat: 41.78, lon: -87.6 });
+ const nearDeparture = at('2026-07-01T14:40:00Z');
+ expect(pick(onFinal, second, nearDeparture, flying)).toBeNull();
+
+ // Once the first sector is down the aircraft at Midway is the second one's, and so is its climb towards Denver.
+ expect(pick(swa({ lat: 41.787, lon: -87.75 }), second, nearDeparture, landed)).toBe('swa');
+ const westbound = swa({ alt_baro: 6000, lat: 41.77, lon: -88.1 });
+ expect(pick(westbound, second, at('2026-07-01T14:52:00Z'), flying)).toBe('swa');
+ });
+
it('FLDER-003: reads a report at its own time, on the ground at zero feet, the geometric height as a fallback', () => {
const now = DEP;
expect(observe(ac(), now)).toEqual({