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

With two booked sectors under one flight number, the second is in its watch
window for the whole first one, and the aircraft flying the first sector was
read as the second having departed, with its departure notice hours early.
An aircraft that fits a sibling sector better is now left to it.
This commit is contained in:
Maurice
2026-11-16 10:45:22 +01:00
parent 89f7908359
commit 40dea84085
4 changed files with 180 additions and 13 deletions
@@ -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 };
@@ -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;