mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 01:28:55 +00:00
feat(flight-live): follow booked flights live from keyless ADS-B feeds
A new flight-live domain polls the open feeds adsb.lol and adsb.fi (no key, no cost; adsb.fi only on self-hosted installs, its terms are non-commercial) for every booked flight leg in its watch window, derives phase, take-off, landing, delay and an arrival estimate, and pushes changes as flight:live. GET /api/trips/:tripId/flights/live, the MCP tool get_trip_flight_status, notifications for take-off, landing and delays, and the admin switch flight_live_enabled (FLIGHT_LIVE_ENABLED wins) come with it.
This commit is contained in:
@@ -234,6 +234,13 @@ describe('derivePlugins', () => {
|
||||
});
|
||||
|
||||
describe('deriveIntegrations', () => {
|
||||
it('reads FLIGHT_LIVE_ENABLED as the setting spells it, unset or unparseable as no word at all', () => {
|
||||
expect(deriveIntegrations({}).flightLiveEnabled).toBeUndefined();
|
||||
expect(deriveIntegrations({ FLIGHT_LIVE_ENABLED: 'off' }).flightLiveEnabled).toBe('false');
|
||||
expect(deriveIntegrations({ FLIGHT_LIVE_ENABLED: ' YES ' }).flightLiveEnabled).toBe('true');
|
||||
expect(deriveIntegrations({ FLIGHT_LIVE_ENABLED: 'maybe' }).flightLiveEnabled).toBeUndefined();
|
||||
});
|
||||
|
||||
it('pins unsplash trim, nominatim trim + default, overpass timeout', () => {
|
||||
expect(deriveIntegrations({ UNSPLASH_ACCESS_KEY: ' key ' }).unsplashAccessKey).toBe('key');
|
||||
expect(deriveIntegrations({}).nominatimUrl).toBe('https://nominatim.openstreetmap.org');
|
||||
|
||||
@@ -63,8 +63,8 @@ describe('ALL_ENTITIES', () => {
|
||||
* `entity-schema-parity.test.ts` can't see — it iterates the metadata map,
|
||||
* which de-duplicates by class name).
|
||||
*/
|
||||
it('ENT-003: exactly 167 entities, every class name unique', () => {
|
||||
expect(ALL_ENTITIES.length).toBe(167);
|
||||
it('ENT-003: exactly 168 entities, every class name unique', () => {
|
||||
expect(ALL_ENTITIES.length).toBe(168);
|
||||
const names = ALL_ENTITIES.map((s) => s.meta.className);
|
||||
expect(new Set(names).size).toBe(names.length);
|
||||
});
|
||||
|
||||
@@ -61,7 +61,9 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
// (an attached file is only ever written whole, by the turn it was attached in).
|
||||
// + storage_reclaim_marks: category, key, first_seen_at, size (a mark is only ever written whole, by the reclaim pass).
|
||||
// + storage_release_queue: category, key, due_at (a queued release is only ever written whole, by the release queue).
|
||||
const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 611;
|
||||
// + flight_live_states: callsign, service_date, origin, destination (a flight's state is always found and
|
||||
// written by its key).
|
||||
const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 615;
|
||||
|
||||
describe('entity class fields never carry a NaN initialiser (task-4-review-shape.md, Important 1)', () => {
|
||||
it('CLASSFIELD-001: new X() has no own property whose value is NaN, across all 133 entities', () => {
|
||||
|
||||
@@ -107,6 +107,7 @@ const UNNUMBERED = [
|
||||
'Migration20200101046370_a_deleted_chat_message_keeps_no_text',
|
||||
'Migration20200101046380_ireland_gained_its_counties',
|
||||
'Migration20200101046390_a_trip_can_keep_its_costs_as_totals_only',
|
||||
'Migration20200101046400_a_booked_flight_shows_where_it_is',
|
||||
];
|
||||
// The last step the positional runner ever had; planLegacyBaseline refuses a
|
||||
// schema_version past it.
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
/**
|
||||
* FlightLiveStatesRepository: the stored state of a flight per callsign and
|
||||
* day, and the reads of flight bookings, endpoints, days and travellers the
|
||||
* live flight status builds its legs from. FLREPO-001 to FLREPO-007.
|
||||
*/
|
||||
import { FlightLiveStates } from '../../../../src/db/entities/FlightLiveStates.entity';
|
||||
import type {
|
||||
FlightLiveStatesRepository,
|
||||
FlightLiveStateWrite,
|
||||
} from '../../../../src/db/repositories/FlightLiveStates.repository';
|
||||
import type { DbTimestamp } from '../../../../src/db/types';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import {
|
||||
addReservationTraveler,
|
||||
makeReservation,
|
||||
makeReservationEndpoint,
|
||||
} from '../../../helpers/factories/reservations';
|
||||
import { findRows } from '../../../helpers/factories/rows';
|
||||
import { addTripMember, makeDay, makeTrip } from '../../../helpers/factories/trips';
|
||||
import { makeUser } from '../../../helpers/factories/users';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
let repo: FlightLiveStatesRepository;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
repo = t.repo(FlightLiveStates);
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
t.clear();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
function state(overrides: Partial<FlightLiveStateWrite> = {}): FlightLiveStateWrite {
|
||||
return {
|
||||
callsign: 'DLH716',
|
||||
service_date: '2026-07-01',
|
||||
origin: 'FRA',
|
||||
destination: 'HND',
|
||||
phase: 'airborne',
|
||||
departed_at: '2026-07-01 11:52:00' as DbTimestamp,
|
||||
landed_at: null,
|
||||
lat: 55.1,
|
||||
lng: 60.2,
|
||||
altitude_ft: 36000,
|
||||
ground_speed_kt: 480,
|
||||
track_deg: 51,
|
||||
vertical_rate_fpm: 0,
|
||||
on_ground: 0,
|
||||
registration: 'D-AIXA',
|
||||
aircraft_type: 'A359',
|
||||
source: 'adsb.lol',
|
||||
first_seen_at: '2026-07-01 11:40:00' as DbTimestamp,
|
||||
last_seen_at: '2026-07-01 14:00:00' as DbTimestamp,
|
||||
fetched_at: '2026-07-01 14:00:01' as DbTimestamp,
|
||||
next_poll_at: '2026-07-01 14:03:01' as DbTimestamp,
|
||||
fail_count: 0,
|
||||
departed_notified: 1,
|
||||
landed_notified: 0,
|
||||
delay_notified: 0,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('FlightLiveStatesRepository: states', () => {
|
||||
it('FLREPO-001: writes a whole state and replaces it under the same key', async () => {
|
||||
await repo.saveState(state());
|
||||
await repo.saveState(state({ phase: 'landed', landed_at: '2026-07-01 23:10:00' as DbTimestamp, lat: 35.5 }));
|
||||
await repo.saveState(state({ service_date: '2026-07-02', phase: 'scheduled' }));
|
||||
await repo.saveState(state({ callsign: 'BAW12' }));
|
||||
|
||||
const rows = await repo.findForCallsigns(['DLH716']);
|
||||
expect(rows.map((r) => [r.service_date, r.phase, r.landed_at, r.lat]).sort()).toEqual([
|
||||
['2026-07-01', 'landed', '2026-07-01 23:10:00', 35.5],
|
||||
['2026-07-02', 'scheduled', null, 55.1],
|
||||
]);
|
||||
expect(rows.find((r) => r.service_date === '2026-07-01')).toMatchObject({
|
||||
registration: 'D-AIXA',
|
||||
departed_notified: 1,
|
||||
next_poll_at: '2026-07-01 14:03:01',
|
||||
});
|
||||
expect(await repo.findForCallsigns([])).toEqual([]);
|
||||
});
|
||||
|
||||
it('FLREPO-001b: two sectors of one flight number on one day are two states', async () => {
|
||||
await repo.saveState(state({ callsign: 'DLH754', origin: 'FRA', destination: 'BOM' }));
|
||||
await repo.saveState(state({ callsign: 'DLH754', origin: 'BOM', destination: 'SIN', phase: 'scheduled' }));
|
||||
const rows = await repo.findForCallsigns(['DLH754']);
|
||||
expect(rows.map((r) => [r.origin, r.destination, r.phase]).sort()).toEqual([
|
||||
['BOM', 'SIN', 'scheduled'],
|
||||
['FRA', 'BOM', 'airborne'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('FLREPO-002: drops the states of flights that departed before a day', async () => {
|
||||
await repo.saveState(state({ service_date: '2026-05-30' }));
|
||||
await repo.saveState(state({ service_date: '2026-06-01' }));
|
||||
expect(await repo.deleteBefore('2026-06-01')).toBe(1);
|
||||
expect((await findRows(t, FlightLiveStates)).map((r) => r.service_date)).toEqual(['2026-06-01']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('FlightLiveStatesRepository: bookings', () => {
|
||||
it('FLREPO-003: the flight bookings of one trip with the trip title, nothing of other types or trips', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const trip = await makeTrip(t, user.id, { title: 'Japan' });
|
||||
const other = await makeTrip(t, user.id);
|
||||
const flight = await makeReservation(t, trip.id, {
|
||||
title: 'FRA to HND',
|
||||
type: 'flight',
|
||||
metadata: '{"flight_number":"LH 716"}',
|
||||
reservation_time: '2026-07-01T13:40',
|
||||
});
|
||||
await makeReservation(t, trip.id, { title: 'Hotel', type: 'hotel' });
|
||||
await makeReservation(t, other.id, { title: 'Elsewhere', type: 'flight' });
|
||||
|
||||
expect(await repo.listFlightBookingsForTrip(trip.id)).toEqual([
|
||||
{
|
||||
id: flight.id,
|
||||
trip_id: trip.id,
|
||||
trip_title: 'Japan',
|
||||
metadata: '{"flight_number":"LH 716"}',
|
||||
day_id: null,
|
||||
end_day_id: null,
|
||||
reservation_time: '2026-07-01T13:40',
|
||||
reservation_end_time: null,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('FLREPO-004: the poll candidates skip archived trips and trips whose dates lie outside the span', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const current = await makeTrip(t, user.id, { start_date: '2026-06-28', end_date: '2026-07-05' });
|
||||
const undated = await makeTrip(t, user.id);
|
||||
const past = await makeTrip(t, user.id, { start_date: '2026-05-01', end_date: '2026-05-03' });
|
||||
const future = await makeTrip(t, user.id, { start_date: '2026-09-01', end_date: '2026-09-03' });
|
||||
const archived = await makeTrip(t, user.id, { start_date: '2026-06-28', end_date: '2026-07-05', is_archived: 1 });
|
||||
await [current, undated, past, future, archived].reduce(async (previous, trip) => {
|
||||
await previous;
|
||||
await makeReservation(t, trip.id, { title: 'Flight', type: 'flight' });
|
||||
}, Promise.resolve());
|
||||
const rows = await repo.listFlightBookingsBetween('2026-06-29', '2026-07-03');
|
||||
expect(rows.map((r) => r.trip_id).sort((a, b) => a - b)).toEqual([current.id, undated.id].sort((a, b) => a - b));
|
||||
});
|
||||
|
||||
it('FLREPO-005: the endpoints of the bookings in their order, and none for no bookings', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const trip = await makeTrip(t, user.id);
|
||||
const flight = await makeReservation(t, trip.id, { title: 'Flight', type: 'flight' });
|
||||
await makeReservationEndpoint(t, flight.id, { role: 'to', sequence: 1, code: 'HND', name: 'Haneda (HND)' });
|
||||
await makeReservationEndpoint(t, flight.id, {
|
||||
role: 'from',
|
||||
sequence: 0,
|
||||
code: 'FRA',
|
||||
name: 'Frankfurt (FRA)',
|
||||
timezone: 'Europe/Berlin',
|
||||
local_date: '2026-07-01',
|
||||
local_time: '13:40',
|
||||
});
|
||||
const endpoints = await repo.listEndpoints([flight.id]);
|
||||
expect(endpoints.map((e) => [e.sequence, e.code])).toEqual([
|
||||
[0, 'FRA'],
|
||||
[1, 'HND'],
|
||||
]);
|
||||
expect(endpoints[0]).toMatchObject({
|
||||
reservation_id: flight.id,
|
||||
role: 'from',
|
||||
timezone: 'Europe/Berlin',
|
||||
local_date: '2026-07-01',
|
||||
local_time: '13:40',
|
||||
});
|
||||
expect(await repo.listEndpoints([])).toEqual([]);
|
||||
});
|
||||
|
||||
it('FLREPO-006: the dates of trip days, leaving out a day without one', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const trip = await makeTrip(t, user.id);
|
||||
const dated = await makeDay(t, trip.id, { day_number: 1, date: '2026-07-01' });
|
||||
const undated = await makeDay(t, trip.id, { day_number: 2, date: null });
|
||||
expect(await repo.listDayDates([dated.id, undated.id])).toEqual([{ id: dated.id, date: '2026-07-01' }]);
|
||||
expect(await repo.listDayDates([])).toEqual([]);
|
||||
});
|
||||
|
||||
it('FLREPO-007: the travellers put on a booking who still belong to the trip, never a removed member', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const { user: friend } = await makeUser(t);
|
||||
const { user: removed } = await makeUser(t);
|
||||
const trip = await makeTrip(t, user.id);
|
||||
await addTripMember(t, trip.id, friend.id);
|
||||
const flight = await makeReservation(t, trip.id, { title: 'Flight', type: 'flight' });
|
||||
expect(await repo.listTravelerIds(flight.id)).toEqual([]);
|
||||
await addReservationTraveler(t, flight.id, friend.id);
|
||||
await addReservationTraveler(t, flight.id, user.id);
|
||||
// On the traveller list from before, but no longer on the trip.
|
||||
await addReservationTraveler(t, flight.id, removed.id);
|
||||
expect(await repo.listTravelerIds(flight.id)).toEqual([user.id, friend.id].sort((a, b) => a - b));
|
||||
});
|
||||
});
|
||||
@@ -50,6 +50,7 @@ describe('the derived key lists', () => {
|
||||
'webauthn_rp_id',
|
||||
'webauthn_origins',
|
||||
'places_provider',
|
||||
'flight_live_enabled',
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -133,6 +134,7 @@ describe('reading', () => {
|
||||
oidc_client_secret: ['OIDC_CLIENT_SECRET', 'oidc-env-secret'],
|
||||
oidc_display_name: ['OIDC_DISPLAY_NAME', 'Company SSO'],
|
||||
oidc_discovery_url: ['OIDC_DISCOVERY_URL', 'https://idp.env.example/.well-known/openid-configuration'],
|
||||
flight_live_enabled: ['FLIGHT_LIVE_ENABLED', 'false'],
|
||||
};
|
||||
const withEnv = (Object.entries(APP_SETTINGS) as Array<[string, AppSettingDef]>)
|
||||
.filter(([, def]) => def.env)
|
||||
|
||||
@@ -1063,6 +1063,23 @@ describe('deleteAccount', () => {
|
||||
});
|
||||
|
||||
describe('updateAppSettings', () => {
|
||||
it('AUTH-DB-070b: FLIGHT_LIVE_ENABLED holds the switch: the form shows it as env_override_*, a save skips it', async () => {
|
||||
const { user } = createAdmin(testDb);
|
||||
vi.stubEnv('FLIGHT_LIVE_ENABLED', 'false');
|
||||
try {
|
||||
await appSetting('flight_live_enabled', 'true');
|
||||
const read = await asLegacyResult(svc.getAppSettings(user.id));
|
||||
expect(read.data).toMatchObject({ flight_live_enabled: 'false', env_override_flight_live_enabled: 'false' });
|
||||
|
||||
await deleteRows(orm, AppSettings, { key: 'flight_live_enabled' });
|
||||
const saved = await asLegacyResult(svc.updateAppSettings(user.id, { flight_live_enabled: 'true' }));
|
||||
expect(saved).toMatchObject({ success: true, managedKeys: ['flight_live_enabled'] });
|
||||
expect(await findRow(orm, AppSettings, { key: 'flight_live_enabled' })).toBeNull();
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
}
|
||||
});
|
||||
|
||||
it('AUTH-DB-071: 403 for non-admin', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
expect((await asLegacyResult(svc.updateAppSettings(user.id, {}))).status).toBe(403);
|
||||
|
||||
@@ -0,0 +1,383 @@
|
||||
/**
|
||||
* FlightLivePollService: the minute tick behind live flight status. The poll
|
||||
* comes out of FlightLiveModule over the migrated snapshot; the feed and the
|
||||
* notifications are stubs, broadcasts land on the FakeRealtimeService.
|
||||
*/
|
||||
import { AppSettings } from '../../../../src/db/entities/AppSettings.entity';
|
||||
import { FlightLiveStates } from '../../../../src/db/entities/FlightLiveStates.entity';
|
||||
import { FlightLivePollService } from '../../../../src/nest/flight-live/flight-live-poll.service';
|
||||
import type { FeedAircraft } from '../../../../src/nest/flight-live/flight-live.derive';
|
||||
import { FlightLiveFeedService, type FeedLookup } from '../../../../src/nest/flight-live/flight-live.feeds';
|
||||
import { FlightLiveJob } from '../../../../src/nest/flight-live/flight-live.job';
|
||||
import { FlightLiveModule } from '../../../../src/nest/flight-live/flight-live.module';
|
||||
import { FlightLiveService } from '../../../../src/nest/flight-live/flight-live.service';
|
||||
import { NotificationsService } from '../../../../src/nest/notifications/notifications.service';
|
||||
import { CronRegistrarService } from '../../../../src/nest/scheduling/cron-registrar.service';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import {
|
||||
addReservationTraveler,
|
||||
makeReservation,
|
||||
makeReservationEndpoint,
|
||||
} from '../../../helpers/factories/reservations';
|
||||
import { findRow, findRows, insertRow } from '../../../helpers/factories/rows';
|
||||
import { makeDay, makeTrip } from '../../../helpers/factories/trips';
|
||||
import { makeUser } from '../../../helpers/factories/users';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createTestModule, type TestModule } from '../../../helpers/test-module';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { flightLiveLegSchema } from '@trek/shared';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
let t: TestModule;
|
||||
let poll: FlightLivePollService;
|
||||
let orm: MikroORM;
|
||||
|
||||
const feed = {
|
||||
lookup: vi.fn<(callsign: string, clock?: () => number) => Promise<FeedLookup>>(),
|
||||
attribution: vi.fn(() => 'Live positions: adsb.lol (ODbL)'),
|
||||
sources: vi.fn(() => ['adsb.lol']),
|
||||
canAsk: vi.fn(() => true),
|
||||
waitMs: vi.fn(() => 0),
|
||||
};
|
||||
const notifications = { send: vi.fn(async () => ({ attempted: 1, delivered: 1 })) };
|
||||
|
||||
const MIN = 60_000;
|
||||
/** LH 100 leaves Frankfurt at 12:00 local (10:00 UTC) on 1 July 2026 and lands in Berlin at 13:10. */
|
||||
const DEP = Date.parse('2026-07-01T10:00:00Z');
|
||||
const ARR = Date.parse('2026-07-01T11:10:00Z');
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestModule({
|
||||
db,
|
||||
imports: [FlightLiveModule],
|
||||
overrides: [
|
||||
{ provide: FlightLiveFeedService, useValue: feed },
|
||||
{ provide: NotificationsService, useValue: notifications },
|
||||
],
|
||||
});
|
||||
poll = t.get(FlightLivePollService);
|
||||
poll.sleep = async () => undefined;
|
||||
orm = t.get(MikroORM);
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(db);
|
||||
vi.clearAllMocks();
|
||||
t.realtime.broadcastMock.mockClear();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
db.close();
|
||||
});
|
||||
|
||||
async function seedFlight(title = 'Berlin') {
|
||||
const { user } = await makeUser(orm);
|
||||
const trip = await makeTrip(orm, user.id, { title });
|
||||
const flight = await makeReservation(orm, trip.id, {
|
||||
title: 'FRA to BER',
|
||||
type: 'flight',
|
||||
metadata: JSON.stringify({ flight_number: 'LH 100' }),
|
||||
});
|
||||
const end = { lat: 52.3667, lng: 13.5033, timezone: 'Europe/Berlin', local_date: '2026-07-01' };
|
||||
await makeReservationEndpoint(orm, flight.id, {
|
||||
role: 'from',
|
||||
sequence: 0,
|
||||
name: 'Frankfurt (FRA)',
|
||||
code: 'FRA',
|
||||
lat: 50.0333,
|
||||
lng: 8.5706,
|
||||
timezone: 'Europe/Berlin',
|
||||
local_date: '2026-07-01',
|
||||
local_time: '12:00',
|
||||
});
|
||||
await makeReservationEndpoint(orm, flight.id, {
|
||||
role: 'to',
|
||||
sequence: 1,
|
||||
name: 'Berlin (BER)',
|
||||
code: 'BER',
|
||||
local_time: '13:10',
|
||||
...end,
|
||||
});
|
||||
return { user, trip, flight };
|
||||
}
|
||||
|
||||
function aircraft(overrides: Partial<FeedAircraft> = {}): FeedAircraft {
|
||||
return {
|
||||
hex: '3c6444',
|
||||
flight: 'DLH100',
|
||||
registration: 'D-AINA',
|
||||
type: 'A20N',
|
||||
alt_baro: 4000,
|
||||
alt_geom: null,
|
||||
gs: 220,
|
||||
track: 60,
|
||||
baro_rate: 2000,
|
||||
geom_rate: null,
|
||||
lat: 50.1,
|
||||
lon: 8.7,
|
||||
seen: 0,
|
||||
seen_pos: 0,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const seen = (...list: FeedAircraft[]): FeedLookup => ({ ok: true, source: 'adsb.lol', now: 0, aircraft: list });
|
||||
const at = (ms: number) => () => ms;
|
||||
const events = () => notifications.send.mock.calls.map((call) => (call as unknown as [{ event: string }])[0].event);
|
||||
|
||||
describe('FlightLivePollService.poll', () => {
|
||||
it('FLPOLL-001: switched off, it asks nothing', async () => {
|
||||
await seedFlight();
|
||||
await insertRow(orm, AppSettings, { key: 'flight_live_enabled', value: 'false' });
|
||||
expect(await poll.poll(at(DEP))).toEqual({ asked: 0, changed: 0, skipped: 'disabled' });
|
||||
expect(feed.lookup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FLPOLL-002: outside its window a flight is not asked about', async () => {
|
||||
await seedFlight();
|
||||
expect(await poll.poll(at(DEP - 4 * 60 * MIN))).toEqual({ asked: 0, changed: 0, skipped: null });
|
||||
expect(feed.lookup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FLPOLL-003: wheels-up is stored, sent to the trip and told to the whole trip without travellers', async () => {
|
||||
const { trip, flight } = await seedFlight();
|
||||
feed.lookup.mockResolvedValueOnce(seen(aircraft()));
|
||||
const now = DEP + 5 * MIN;
|
||||
expect(await poll.poll(at(now))).toEqual({ asked: 1, changed: 1, skipped: null });
|
||||
expect(feed.lookup).toHaveBeenCalledWith('DLH100', expect.any(Function));
|
||||
|
||||
const row = await findRow(orm, FlightLiveStates, { callsign: 'DLH100', service_date: '2026-07-01' });
|
||||
expect(row).toMatchObject({
|
||||
phase: 'airborne',
|
||||
departed_at: '2026-07-01 10:05:00',
|
||||
departed_notified: 1,
|
||||
delay_notified: 0,
|
||||
source: 'adsb.lol',
|
||||
next_poll_at: '2026-07-01 10:08:00',
|
||||
});
|
||||
|
||||
expect(t.realtime.broadcastMock).toHaveBeenCalledTimes(1);
|
||||
const [tripId, event, payload] = t.realtime.broadcastMock.mock.calls[0];
|
||||
expect([tripId, event]).toEqual([trip.id, 'flight:live']);
|
||||
const legs = (payload as { flights: unknown[] }).flights;
|
||||
expect(legs).toHaveLength(1);
|
||||
expect(flightLiveLegSchema.parse(legs[0])).toMatchObject({ reservation_id: flight.id, phase: 'airborne' });
|
||||
|
||||
expect(notifications.send).toHaveBeenCalledTimes(1);
|
||||
expect(notifications.send).toHaveBeenCalledWith({
|
||||
event: 'flight_departed',
|
||||
actorId: null,
|
||||
scope: 'trip',
|
||||
targetId: trip.id,
|
||||
params: { flight: 'LH 100', from: 'FRA', to: 'BER', trip: 'Berlin', tripId: String(trip.id), delay: '5' },
|
||||
});
|
||||
});
|
||||
|
||||
it('FLPOLL-004: a late departure is told once, to the travellers of each booking, next to wheels-up', async () => {
|
||||
const { user, flight } = await seedFlight();
|
||||
const second = await seedFlight('Berlin too');
|
||||
await addReservationTraveler(orm, flight.id, user.id);
|
||||
feed.lookup.mockResolvedValueOnce(seen(aircraft()));
|
||||
await poll.poll(at(DEP + 25 * MIN));
|
||||
|
||||
expect(events().sort()).toEqual(['flight_delayed', 'flight_delayed', 'flight_departed', 'flight_departed']);
|
||||
expect(notifications.send).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ event: 'flight_delayed', scope: 'user', targetId: user.id }),
|
||||
);
|
||||
expect(notifications.send).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ event: 'flight_delayed', scope: 'trip', targetId: second.trip.id }),
|
||||
);
|
||||
expect(t.realtime.broadcastMock).toHaveBeenCalledTimes(2);
|
||||
|
||||
notifications.send.mockClear();
|
||||
feed.lookup.mockResolvedValueOnce(seen(aircraft({ alt_baro: 30000, lat: 51.2, lon: 11, gs: 450 })));
|
||||
expect(await poll.poll(at(DEP + 30 * MIN))).toMatchObject({ asked: 1 });
|
||||
expect(notifications.send).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FLPOLL-005: landed is told once and the flight is asked about no more', async () => {
|
||||
const { trip } = await seedFlight();
|
||||
feed.lookup.mockResolvedValueOnce(seen(aircraft()));
|
||||
await poll.poll(at(DEP + 2 * MIN));
|
||||
feed.lookup.mockResolvedValueOnce(seen(aircraft({ alt_baro: 'ground', lat: 52.37, lon: 13.5, gs: 15 })));
|
||||
await poll.poll(at(ARR));
|
||||
expect(events()).toEqual(['flight_departed', 'flight_landed']);
|
||||
expect(await findRow(orm, FlightLiveStates, { callsign: 'DLH100' })).toMatchObject({
|
||||
phase: 'landed',
|
||||
landed_at: '2026-07-01 11:10:00',
|
||||
landed_notified: 1,
|
||||
next_poll_at: null,
|
||||
});
|
||||
feed.lookup.mockClear();
|
||||
expect(await poll.poll(at(ARR + 10 * MIN))).toMatchObject({ asked: 0 });
|
||||
expect(feed.lookup).not.toHaveBeenCalled();
|
||||
expect(t.realtime.broadcastMock.mock.calls.every((call) => call[0] === trip.id)).toBe(true);
|
||||
});
|
||||
|
||||
it('FLPOLL-006: first seen on the ground at the destination is a landing without a departure notice', async () => {
|
||||
await seedFlight();
|
||||
feed.lookup.mockResolvedValueOnce(seen(aircraft({ alt_baro: 'ground', lat: 52.37, lon: 13.5 })));
|
||||
await poll.poll(at(ARR));
|
||||
expect(events()).toEqual(['flight_landed']);
|
||||
expect(await findRow(orm, FlightLiveStates, { callsign: 'DLH100' })).toMatchObject({
|
||||
phase: 'landed',
|
||||
departed_notified: 1,
|
||||
landed_notified: 1,
|
||||
delay_notified: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('FLPOLL-007: a failed ask counts and backs off, nothing is broadcast', async () => {
|
||||
await seedFlight();
|
||||
feed.lookup.mockResolvedValue({ ok: false, reason: 'unavailable' });
|
||||
await poll.poll(at(DEP - 30 * MIN));
|
||||
await poll.poll(at(DEP - 28 * MIN));
|
||||
await poll.poll(at(DEP - 26 * MIN));
|
||||
expect(await findRow(orm, FlightLiveStates, { callsign: 'DLH100' })).toMatchObject({
|
||||
phase: 'scheduled',
|
||||
fail_count: 3,
|
||||
next_poll_at: '2026-07-01 09:49:00',
|
||||
});
|
||||
expect(t.realtime.broadcastMock).not.toHaveBeenCalled();
|
||||
feed.lookup.mockReset();
|
||||
});
|
||||
|
||||
it('FLPOLL-008: an empty budget ends the tick before anything is stored', async () => {
|
||||
await seedFlight();
|
||||
feed.lookup.mockResolvedValueOnce({ ok: false, reason: 'budget' });
|
||||
expect(await poll.poll(at(DEP))).toEqual({ asked: 0, changed: 0, skipped: null });
|
||||
expect(await findRows(orm, FlightLiveStates)).toEqual([]);
|
||||
feed.canAsk.mockReturnValueOnce(false);
|
||||
expect(await poll.poll(at(DEP))).toEqual({ asked: 0, changed: 0, skipped: null });
|
||||
expect(feed.lookup).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FLPOLL-009: a flight not due waits, unless a client asked for it; the feed spacing is waited out', async () => {
|
||||
const { trip } = await seedFlight();
|
||||
feed.lookup.mockResolvedValue(seen(aircraft({ alt_baro: 'ground', lat: 50.035, lon: 8.56, gs: 5 })));
|
||||
await poll.poll(at(DEP - 60 * MIN));
|
||||
expect(feed.lookup).toHaveBeenCalledTimes(1);
|
||||
await poll.poll(at(DEP - 58 * MIN));
|
||||
expect(feed.lookup).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Asked for seven minutes before its next poll: the cadence holds.
|
||||
const live = t.get(FlightLiveService);
|
||||
await live.tripFlights(trip.id, DEP - 57 * MIN);
|
||||
await poll.poll(at(DEP - 57 * MIN));
|
||||
expect(feed.lookup).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Asked within two minutes of it: brought forward.
|
||||
await live.tripFlights(trip.id, DEP - 51.5 * MIN);
|
||||
const sleep = vi.fn(async () => undefined);
|
||||
poll.sleep = sleep;
|
||||
feed.waitMs.mockReturnValueOnce(400);
|
||||
await poll.poll(at(DEP - 51.5 * MIN));
|
||||
expect(feed.lookup).toHaveBeenCalledTimes(2);
|
||||
expect(sleep).toHaveBeenCalledWith(400);
|
||||
poll.sleep = async () => undefined;
|
||||
feed.lookup.mockReset();
|
||||
});
|
||||
|
||||
it('FLPOLL-010: a tick while one runs returns at once, and old states go once a day', async () => {
|
||||
const old = { callsign: 'BAW1', service_date: '2026-01-01', origin: 'LHR', destination: 'JFK' };
|
||||
await insertRow(orm, FlightLiveStates, old);
|
||||
// An earlier case already purged today; the guard is per day, so forget it.
|
||||
(poll as unknown as { lastPurgeDay: string | null }).lastPurgeDay = null;
|
||||
let release: () => void = () => undefined;
|
||||
feed.lookup.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
release = () => resolve({ ok: false, reason: 'budget' });
|
||||
}),
|
||||
);
|
||||
await seedFlight();
|
||||
const first = poll.poll(at(DEP + 10 * MIN));
|
||||
await vi.waitFor(() => expect(feed.lookup).toHaveBeenCalled());
|
||||
expect(await poll.poll(at(DEP + 10 * MIN))).toEqual({ asked: 0, changed: 0, skipped: 'running' });
|
||||
release();
|
||||
await first;
|
||||
expect(await findRows(orm, FlightLiveStates, { callsign: 'BAW1' })).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('FlightLivePollService: closing and sectors', () => {
|
||||
it('FLPOLL-011: a flight still in the air when its window ends is closed as unknown and asked about no more', async () => {
|
||||
const { trip } = await seedFlight();
|
||||
feed.lookup.mockResolvedValueOnce(seen(aircraft({ alt_baro: 30000, lat: 51.2, lon: 11, gs: 450 })));
|
||||
await poll.poll(at(DEP + 20 * MIN));
|
||||
t.realtime.broadcastMock.mockClear();
|
||||
feed.lookup.mockClear();
|
||||
|
||||
await poll.poll(at(ARR + 121 * MIN));
|
||||
expect(feed.lookup).not.toHaveBeenCalled();
|
||||
expect(await findRow(orm, FlightLiveStates, { callsign: 'DLH100' })).toMatchObject({
|
||||
phase: 'unknown',
|
||||
next_poll_at: null,
|
||||
});
|
||||
expect(t.realtime.broadcastMock).toHaveBeenCalledTimes(1);
|
||||
const [tripId, , payload] = t.realtime.broadcastMock.mock.calls[0];
|
||||
expect(tripId).toBe(trip.id);
|
||||
expect((payload as { flights: Array<{ phase: string }> }).flights[0].phase).toBe('unknown');
|
||||
|
||||
t.realtime.broadcastMock.mockClear();
|
||||
await poll.poll(at(ARR + 125 * MIN));
|
||||
expect(t.realtime.broadcastMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FLPOLL-012: two sectors of one through flight keep a state each', async () => {
|
||||
const { user } = await makeUser(orm);
|
||||
const trip = await makeTrip(orm, user.id, { title: 'There and back' });
|
||||
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' },
|
||||
{ from: 'BER', to: 'FRA', flight_number: 'LH 100', dep_day_id: day.id, dep_time: '15:00' },
|
||||
];
|
||||
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' };
|
||||
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, ...fra, local_date: '2026-07-01' });
|
||||
feed.lookup.mockResolvedValue(seen(aircraft()));
|
||||
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'],
|
||||
]);
|
||||
feed.lookup.mockReset();
|
||||
});
|
||||
});
|
||||
|
||||
describe('FlightLiveJob', () => {
|
||||
it('FLJOB-001: registers nothing under test and runs one poll per tick, a failure logged not thrown', async () => {
|
||||
const job = t.get(FlightLiveJob);
|
||||
const registrar = t.get(CronRegistrarService);
|
||||
const register = vi.spyOn(registrar, 'register');
|
||||
job.onApplicationBootstrap();
|
||||
expect(register).not.toHaveBeenCalled();
|
||||
|
||||
const run = vi.spyOn(poll, 'poll').mockResolvedValueOnce({ asked: 2, changed: 1, skipped: null });
|
||||
await job.tick();
|
||||
run.mockRejectedValueOnce(new Error('boom'));
|
||||
await expect(job.tick()).resolves.toBeUndefined();
|
||||
expect(run).toHaveBeenCalledTimes(2);
|
||||
run.mockRestore();
|
||||
});
|
||||
|
||||
it('FLJOB-002: registers the minute tick where crons run', () => {
|
||||
const job = t.get(FlightLiveJob);
|
||||
const registrar = t.get(CronRegistrarService);
|
||||
vi.spyOn(registrar, 'isEnabled').mockReturnValueOnce(true);
|
||||
const register = vi.spyOn(registrar, 'register').mockReturnValueOnce(true);
|
||||
job.onApplicationBootstrap();
|
||||
expect(register).toHaveBeenCalledWith('flight-live', '* * * * *', expect.any(Function));
|
||||
register.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* From a booked flight number to the callsign an aircraft transmits: the
|
||||
* spellings a traveller types, the ICAO form taken as it is, an airline code
|
||||
* borrowed from the airline field, and what cannot be told.
|
||||
*/
|
||||
import { airlineTable, toCallsign } from '../../../../src/nest/flight-live/flight-live.callsign';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const TABLE = new Map([
|
||||
['LH', 'DLH'],
|
||||
['U2', 'EZY'],
|
||||
['4U', 'GWI'],
|
||||
]);
|
||||
|
||||
describe('toCallsign', () => {
|
||||
it('FLCS-001: "LH 716", "LH0716", "lh716" and "LH-716" all fly as DLH716', () => {
|
||||
for (const booked of ['LH 716', 'LH0716', 'lh716', 'LH-716', ' LH 0716 ']) {
|
||||
expect(toCallsign(booked, null, TABLE)).toBe('DLH716');
|
||||
}
|
||||
});
|
||||
|
||||
it('FLCS-002: codes with a digit map like any other, and a letter suffix stays', () => {
|
||||
expect(toCallsign('U2 1234', null, TABLE)).toBe('EZY1234');
|
||||
expect(toCallsign('4U9520', null, TABLE)).toBe('GWI9520');
|
||||
expect(toCallsign('LH 7A', null, TABLE)).toBe('DLH7A');
|
||||
});
|
||||
|
||||
it('FLCS-003: a number already in ICAO form is taken as it is, its zeros trimmed', () => {
|
||||
expect(toCallsign('DLH716', null, TABLE)).toBe('DLH716');
|
||||
expect(toCallsign('BAW0012', null, TABLE)).toBe('BAW12');
|
||||
expect(toCallsign('EZY0', null, TABLE)).toBe('EZY0');
|
||||
});
|
||||
|
||||
it('FLCS-004: a bare number borrows the airline code, never an airline name', () => {
|
||||
expect(toCallsign('716', 'LH', TABLE)).toBe('DLH716');
|
||||
expect(toCallsign('0716', 'dlh', TABLE)).toBe('DLH716');
|
||||
expect(toCallsign('716', 'Lufthansa', TABLE)).toBeNull();
|
||||
expect(toCallsign('716', 'XX', TABLE)).toBeNull();
|
||||
expect(toCallsign('716', null, TABLE)).toBeNull();
|
||||
});
|
||||
|
||||
it('FLCS-005: an unknown code, an empty or odd number and no number at all answer null', () => {
|
||||
expect(toCallsign('XX 716', null, TABLE)).toBeNull();
|
||||
expect(toCallsign('', null, TABLE)).toBeNull();
|
||||
expect(toCallsign(' ', null, TABLE)).toBeNull();
|
||||
expect(toCallsign('LH 12345', null, TABLE)).toBeNull();
|
||||
expect(toCallsign('Lufthansa', null, TABLE)).toBeNull();
|
||||
expect(toCallsign(null, 'LH', TABLE)).toBeNull();
|
||||
expect(toCallsign(undefined, 'LH', TABLE)).toBeNull();
|
||||
});
|
||||
|
||||
it('FLCS-006: the bundled table maps the big carriers, once read and then kept', () => {
|
||||
const table = airlineTable();
|
||||
expect(table.get('LH')).toBe('DLH');
|
||||
expect(table.get('BA')).toBe('BAW');
|
||||
expect(table.get('U2')).toBe('EZY');
|
||||
expect(airlineTable()).toBe(table);
|
||||
expect(toCallsign('LH 400')).toBe('DLH400');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* GET /api/trips/:tripId/flights/live and its MCP twin get_trip_flight_status
|
||||
* over a stub service: the route's guards and contract, the tool's scope and
|
||||
* input, and parity: both ask the same service method for the same trip
|
||||
* after the same access check, and answer the same body.
|
||||
*/
|
||||
import type { McpContext, McpTextResult, ToolOptions } from '../../../../src/nest-mcp';
|
||||
import { getEntry, type ClassRef } from '../../../../src/nest-mcp/metadata';
|
||||
import { JwtAuthGuard } from '../../../../src/nest/auth-core/jwt-auth.guard';
|
||||
import { RESPONSE_CONTRACT_KEY } from '../../../../src/nest/common/response-contract';
|
||||
import { FlightLiveController } from '../../../../src/nest/flight-live/flight-live.controller';
|
||||
import { FlightLiveMcp } from '../../../../src/nest/flight-live/flight-live.mcp';
|
||||
import type { FlightLiveService } from '../../../../src/nest/flight-live/flight-live.service';
|
||||
import { TripAccessGuard } from '../../../../src/nest/permissions/trip-access.guard';
|
||||
import type { TripAccessService } from '../../../../src/nest/trip-membership/trip-access.service';
|
||||
import { RequestMethod } from '@nestjs/common';
|
||||
import { GUARDS_METADATA, METHOD_METADATA, PATH_METADATA } from '@nestjs/common/constants';
|
||||
import { tripFlightLiveResponseSchema, type TripFlightLiveResponse } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { z } from 'zod';
|
||||
|
||||
const ANSWER: TripFlightLiveResponse = {
|
||||
enabled: true,
|
||||
attribution: 'Live positions: adsb.lol (ODbL)',
|
||||
flights: [
|
||||
{
|
||||
reservation_id: 10,
|
||||
leg_index: 0,
|
||||
callsign: 'DLH100',
|
||||
flight_number: 'LH 100',
|
||||
service_date: '2026-07-01',
|
||||
origin: { code: 'FRA', name: 'Frankfurt', lat: 50.03, lng: 8.57, timezone: 'Europe/Berlin' },
|
||||
destination: { code: 'BER', name: 'Berlin', lat: 52.36, lng: 13.5, timezone: 'Europe/Berlin' },
|
||||
phase: 'scheduled',
|
||||
scheduled_departure: '2026-07-01T10:00:00.000Z',
|
||||
scheduled_arrival: '2026-07-01T11:10:00.000Z',
|
||||
departed_at: null,
|
||||
landed_at: null,
|
||||
estimated_arrival: null,
|
||||
departure_delay_min: null,
|
||||
arrival_delay_min: null,
|
||||
progress: 0,
|
||||
distance_total_km: 431,
|
||||
distance_remaining_km: 431,
|
||||
position: null,
|
||||
aircraft: null,
|
||||
last_seen_at: null,
|
||||
fetched_at: null,
|
||||
stale: false,
|
||||
source: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
function service() {
|
||||
return { tripFlights: vi.fn<FlightLiveService['tripFlights']>().mockResolvedValue(ANSWER) };
|
||||
}
|
||||
|
||||
describe('FlightLiveController', () => {
|
||||
it('FLCTL-001: GET api/trips/:tripId/flights/live sits behind the session and the trip, on the response contract', () => {
|
||||
expect(Reflect.getMetadata(PATH_METADATA, FlightLiveController)).toBe('api/trips/:tripId/flights');
|
||||
expect(Reflect.getMetadata(GUARDS_METADATA, FlightLiveController)).toEqual([JwtAuthGuard, TripAccessGuard]);
|
||||
const handler = FlightLiveController.prototype.list;
|
||||
expect(Reflect.getMetadata(METHOD_METADATA, handler)).toBe(RequestMethod.GET);
|
||||
expect(Reflect.getMetadata(PATH_METADATA, handler)).toBe('live');
|
||||
expect(Reflect.getMetadata(RESPONSE_CONTRACT_KEY, handler)).toBe(tripFlightLiveResponseSchema);
|
||||
});
|
||||
|
||||
it('FLCTL-002: asks the service for the trip the guard resolved and answers what it said', async () => {
|
||||
const live = service();
|
||||
const controller = new FlightLiveController(live as unknown as FlightLiveService);
|
||||
await expect(controller.list({ id: 3, user_id: 1, currency: null })).resolves.toBe(ANSWER);
|
||||
expect(live.tripFlights).toHaveBeenCalledWith(3);
|
||||
});
|
||||
});
|
||||
|
||||
const ctx = { userId: 7, scopes: null, isStaticToken: false } as McpContext;
|
||||
|
||||
function toolOptions(): ToolOptions {
|
||||
const entry = getEntry(FlightLiveMcp as unknown as ClassRef, 'getTripFlightStatus');
|
||||
if (!entry || entry.kind !== 'tool') throw new Error('get_trip_flight_status is not registered');
|
||||
return entry.options;
|
||||
}
|
||||
|
||||
function makeMcp(accessible: boolean) {
|
||||
const live = service();
|
||||
const trip = accessible ? { id: 3, user_id: 1, currency: null } : undefined;
|
||||
const access = { findAccessible: vi.fn().mockResolvedValue(trip) };
|
||||
const mcp = new FlightLiveMcp(live as unknown as FlightLiveService, access as unknown as TripAccessService);
|
||||
return { mcp, live, access };
|
||||
}
|
||||
|
||||
describe('FlightLiveMcp', () => {
|
||||
it('FLMCP-001: get_trip_flight_status is read only, in the bookings scope like reading them', () => {
|
||||
const options = toolOptions();
|
||||
expect(options.name).toBe('get_trip_flight_status');
|
||||
expect(options.annotations?.readOnlyHint).toBe(true);
|
||||
expect(options.access).toEqual({ group: 'reservations', mode: 'read' });
|
||||
const input = z.object(options.inputSchema as z.ZodRawShape);
|
||||
expect(input.safeParse({ tripId: 3 }).success).toBe(true);
|
||||
expect(input.safeParse({ tripId: 0 }).success).toBe(false);
|
||||
expect(input.safeParse({}).success).toBe(false);
|
||||
});
|
||||
|
||||
it('FLMCP-002: parity: the same service method for the same trip answers the same body as the route', async () => {
|
||||
const { mcp, live, access } = makeMcp(true);
|
||||
const result = (await mcp.getTripFlightStatus({ tripId: 3 }, ctx)) as McpTextResult;
|
||||
expect(access.findAccessible).toHaveBeenCalledWith(3, 7);
|
||||
expect(live.tripFlights).toHaveBeenCalledWith(3);
|
||||
expect(result.isError).toBeUndefined();
|
||||
const restBody = await new FlightLiveController(live as unknown as FlightLiveService).list({
|
||||
id: 3,
|
||||
user_id: 1,
|
||||
currency: null,
|
||||
});
|
||||
expect(JSON.parse(result.content[0].text)).toEqual(restBody);
|
||||
});
|
||||
|
||||
it('FLMCP-003: a trip the caller cannot see is refused before anything is read', async () => {
|
||||
const { mcp, live } = makeMcp(false);
|
||||
const result = (await mcp.getTripFlightStatus({ tripId: 9 }, ctx)) as McpTextResult;
|
||||
expect(result).toEqual({ content: [{ type: 'text', text: 'Trip not found or access denied.' }], isError: true });
|
||||
expect(live.tripFlights).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FLMCP-004: an answer off the contract is not passed on', async () => {
|
||||
const { mcp, live } = makeMcp(true);
|
||||
live.tripFlights.mockResolvedValueOnce({ enabled: 'yes' } as unknown as TripFlightLiveResponse);
|
||||
await expect(mcp.getTripFlightStatus({ tripId: 3 }, ctx)).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,339 @@
|
||||
/**
|
||||
* What positions say about a booked flight, without the airline: the phase,
|
||||
* wheels-up and touchdown, the delays and the arrival estimate, the watch
|
||||
* window and how often the feed is asked. Every clock is passed in.
|
||||
*/
|
||||
import {
|
||||
advance,
|
||||
closeIfOver,
|
||||
departureDelay,
|
||||
emptyState,
|
||||
failed,
|
||||
inWatchWindow,
|
||||
nextPollAt,
|
||||
observe,
|
||||
pickAircraft,
|
||||
toLiveLeg,
|
||||
watchWindow,
|
||||
type FeedAircraft,
|
||||
type LiveState,
|
||||
} from '../../../../src/nest/flight-live/flight-live.derive';
|
||||
import type { ScheduledLeg } from '../../../../src/nest/flight-live/flight-live.schedule';
|
||||
import { flightLiveLegSchema } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const MIN = 60_000;
|
||||
const DEP = Date.parse('2026-07-01T10:00:00Z');
|
||||
const ARR = Date.parse('2026-07-01T11:10:00Z');
|
||||
|
||||
const LEG: ScheduledLeg = {
|
||||
reservation_id: 10,
|
||||
trip_id: 3,
|
||||
leg_index: 0,
|
||||
callsign: 'DLH100',
|
||||
flight_number: 'LH 100',
|
||||
service_date: '2026-07-01',
|
||||
origin: { code: 'FRA', name: 'Frankfurt', lat: 50.0333, lng: 8.5706, timezone: 'Europe/Berlin' },
|
||||
destination: { code: 'TXL', name: 'Berlin', lat: 52.3667, lng: 13.5033, timezone: 'Europe/Berlin' },
|
||||
scheduled_departure: DEP,
|
||||
scheduled_arrival: ARR,
|
||||
};
|
||||
|
||||
function ac(overrides: Partial<FeedAircraft> = {}): FeedAircraft {
|
||||
return {
|
||||
hex: '3c6444',
|
||||
flight: 'DLH100',
|
||||
registration: 'D-AINA',
|
||||
type: 'A20N',
|
||||
alt_baro: 'ground',
|
||||
alt_geom: null,
|
||||
gs: 12,
|
||||
track: 90,
|
||||
baro_rate: null,
|
||||
geom_rate: null,
|
||||
lat: 50.035,
|
||||
lon: 8.56,
|
||||
seen: 1,
|
||||
seen_pos: 2,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const start = emptyState('DLH100', '2026-07-01', 'FRA', 'TXL');
|
||||
|
||||
describe('the watch window', () => {
|
||||
it('FLDER-001: runs from three hours before departure to two after arrival, or 16 h of flight without one', () => {
|
||||
expect(watchWindow(LEG)).toEqual({ start: DEP - 180 * MIN, end: ARR + 120 * MIN });
|
||||
expect(watchWindow({ scheduled_departure: DEP, scheduled_arrival: null })).toEqual({
|
||||
start: DEP - 180 * MIN,
|
||||
end: DEP + 18 * 60 * MIN,
|
||||
});
|
||||
expect(watchWindow({ scheduled_departure: null, scheduled_arrival: ARR })).toBeNull();
|
||||
expect(inWatchWindow(LEG, DEP - 181 * MIN)).toBe(false);
|
||||
expect(inWatchWindow(LEG, DEP - 179 * MIN)).toBe(true);
|
||||
expect(inWatchWindow(LEG, ARR + 121 * MIN)).toBe(false);
|
||||
expect(inWatchWindow({ scheduled_departure: null, scheduled_arrival: null }, DEP)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('pickAircraft and observe', () => {
|
||||
it('FLDER-002: picks the aircraft nearest the route, one without a position last', () => {
|
||||
const near = ac({ hex: 'near', lat: 51.2, lon: 11 });
|
||||
const far = ac({ hex: 'far', lat: 40, lon: -3 });
|
||||
const blind = ac({ hex: 'blind', lat: null, lon: null });
|
||||
expect(pickAircraft([blind, far, near], LEG)?.hex).toBe('near');
|
||||
expect(pickAircraft([blind], LEG)?.hex).toBe('blind');
|
||||
expect(pickAircraft([], LEG)).toBeNull();
|
||||
});
|
||||
|
||||
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({
|
||||
position: {
|
||||
lat: 50.035,
|
||||
lng: 8.56,
|
||||
altitude_ft: 0,
|
||||
ground_speed_kt: 12,
|
||||
track_deg: 90,
|
||||
vertical_rate_fpm: null,
|
||||
on_ground: true,
|
||||
},
|
||||
positionAt: now - 2000,
|
||||
heardAt: now - 1000,
|
||||
});
|
||||
const air = observe(ac({ alt_baro: null, alt_geom: 3200, geom_rate: 1500, seen_pos: null, seen: null }), now);
|
||||
expect(air?.position.altitude_ft).toBe(3200);
|
||||
expect(air?.position.vertical_rate_fpm).toBe(1500);
|
||||
expect(air?.positionAt).toBe(now);
|
||||
expect(observe(ac({ lat: null }), now)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('advance', () => {
|
||||
it('FLDER-004: on the ground at the origin is taxiing, first and last heard set', () => {
|
||||
const next = advance(start, ac(), LEG, DEP - 10 * MIN, 'adsb.lol');
|
||||
expect(next).toMatchObject({
|
||||
phase: 'taxiing',
|
||||
departed_at: null,
|
||||
first_seen_at: DEP - 10 * MIN - 1000,
|
||||
last_seen_at: DEP - 10 * MIN - 1000,
|
||||
registration: 'D-AINA',
|
||||
aircraft_type: 'A20N',
|
||||
source: 'adsb.lol',
|
||||
fetched_at: DEP - 10 * MIN,
|
||||
fail_count: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('FLDER-005: the first airborne report low near the origin is wheels-up; a later one keeps it', () => {
|
||||
const now = DEP + 12 * MIN;
|
||||
const climbing = advance(start, ac({ alt_baro: 4000, lat: 50.1, lon: 8.7, gs: 220 }), LEG, now, 'adsb.lol');
|
||||
expect(climbing.phase).toBe('airborne');
|
||||
expect(climbing.departed_at).toBe(now - 2000);
|
||||
const high = ac({ alt_baro: 36000, lat: 51.2, lon: 11, gs: 450 });
|
||||
const cruising = advance(climbing, high, LEG, now + 10 * MIN, 'adsb.fi');
|
||||
expect(cruising.departed_at).toBe(now - 2000);
|
||||
expect(cruising.source).toBe('adsb.fi');
|
||||
});
|
||||
|
||||
it('FLDER-006: first seen high or far from the origin leaves wheels-up unknown', () => {
|
||||
const high = advance(start, ac({ alt_baro: 30000, lat: 50.1, lon: 8.7 }), LEG, DEP + 30 * MIN, 'adsb.lol');
|
||||
expect(high).toMatchObject({ phase: 'airborne', departed_at: null });
|
||||
const far = advance(start, ac({ alt_baro: 8000, lat: 51.5, lon: 12 }), LEG, DEP + 30 * MIN, 'adsb.lol');
|
||||
expect(far.departed_at).toBeNull();
|
||||
});
|
||||
|
||||
it('FLDER-007: back on the ground near the destination after flying is landed, once', () => {
|
||||
const flying = advance(start, ac({ alt_baro: 5000, lat: 50.1, lon: 8.7 }), LEG, DEP + 10 * MIN, 'adsb.lol');
|
||||
const down = advance(flying, ac({ lat: 52.37, lon: 13.5 }), LEG, ARR, 'adsb.lol');
|
||||
expect(down.phase).toBe('landed');
|
||||
expect(down.landed_at).toBe(ARR - 2000);
|
||||
const later = advance(down, ac({ lat: 52.37, lon: 13.5 }), LEG, ARR + 10 * MIN, 'adsb.lol');
|
||||
expect(later.landed_at).toBe(ARR - 2000);
|
||||
expect(later.position).toEqual(down.position);
|
||||
});
|
||||
|
||||
it('FLDER-008: on the ground somewhere else after flying is a landing too, a diversion', () => {
|
||||
const flying = { ...start, phase: 'airborne' as const };
|
||||
expect(advance(flying, ac({ lat: 48.35, lon: 11.79 }), LEG, ARR, 'adsb.lol').phase).toBe('landed');
|
||||
expect(advance(start, ac({ lat: 48.35, lon: 11.79 }), LEG, ARR, 'adsb.lol').phase).toBe('taxiing');
|
||||
});
|
||||
|
||||
it('FLDER-008b: first seen down at the destination is landed after the departure time, not before', () => {
|
||||
const atBerlin = ac({ lat: 52.37, lon: 13.5 });
|
||||
expect(advance(start, atBerlin, LEG, ARR, 'adsb.lol')).toMatchObject({ phase: 'landed', landed_at: ARR - 2000 });
|
||||
expect(advance(start, atBerlin, LEG, DEP - 30 * MIN, 'adsb.lol').phase).toBe('taxiing');
|
||||
});
|
||||
|
||||
it('FLDER-009: lost low near the destination and silent ten minutes is landed at its last report', () => {
|
||||
const lastSeen = ARR - 15 * MIN;
|
||||
const position = {
|
||||
lat: 52.3,
|
||||
lng: 13.4,
|
||||
altitude_ft: 2500,
|
||||
ground_speed_kt: 160,
|
||||
track_deg: 80,
|
||||
vertical_rate_fpm: -700,
|
||||
on_ground: false,
|
||||
};
|
||||
const flying: LiveState = { ...start, phase: 'airborne', first_seen_at: DEP, last_seen_at: lastSeen, position };
|
||||
expect(advance(flying, null, LEG, lastSeen + 5 * MIN, 'adsb.lol').phase).toBe('airborne');
|
||||
const down = advance(flying, null, LEG, lastSeen + 10 * MIN, 'adsb.lol');
|
||||
expect(down).toMatchObject({ phase: 'landed', landed_at: lastSeen });
|
||||
const high = { ...flying, position: { ...position, altitude_ft: 20000 } };
|
||||
expect(advance(high, null, LEG, lastSeen + 30 * MIN, 'adsb.lol').phase).toBe('airborne');
|
||||
});
|
||||
|
||||
it('FLDER-010: never heard two hours after departure is unknown; earlier it stays scheduled', () => {
|
||||
expect(advance(start, null, LEG, DEP + 119 * MIN, 'adsb.lol').phase).toBe('scheduled');
|
||||
expect(advance(start, null, LEG, DEP + 120 * MIN, 'adsb.lol').phase).toBe('unknown');
|
||||
const seen = { ...start, first_seen_at: DEP - 30 * MIN, phase: 'taxiing' as const };
|
||||
expect(advance(seen, null, LEG, DEP + 180 * MIN, 'adsb.lol').phase).toBe('taxiing');
|
||||
});
|
||||
|
||||
it('FLDER-011: a failure counts and keeps the state', () => {
|
||||
const once = failed({ ...start, phase: 'taxiing' });
|
||||
expect(once).toMatchObject({ phase: 'taxiing', fail_count: 1 });
|
||||
expect(failed(once).fail_count).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('nextPollAt', () => {
|
||||
it('FLDER-012: every 10 minutes until 40 before departure, then every 2 until airborne', () => {
|
||||
expect(nextPollAt(start, LEG, DEP - 170 * MIN)).toBe(DEP - 160 * MIN);
|
||||
expect(nextPollAt(start, LEG, DEP - 45 * MIN)).toBe(DEP - 40 * MIN);
|
||||
expect(nextPollAt(start, LEG, DEP - 41 * MIN)).toBe(DEP - 39 * MIN);
|
||||
expect(nextPollAt({ ...start, phase: 'taxiing' }, LEG, DEP + 5 * MIN)).toBe(DEP + 7 * MIN);
|
||||
});
|
||||
|
||||
it('FLDER-013: airborne every 3 minutes, every 6 when more than two hours from both airports', () => {
|
||||
const position = {
|
||||
lat: 51.2,
|
||||
lng: 11,
|
||||
altitude_ft: 36000,
|
||||
ground_speed_kt: 450,
|
||||
track_deg: 60,
|
||||
vertical_rate_fpm: 0,
|
||||
on_ground: false,
|
||||
};
|
||||
const flying: LiveState = { ...start, phase: 'airborne', position };
|
||||
expect(nextPollAt(flying, LEG, DEP + 30 * MIN)).toBe(DEP + 33 * MIN);
|
||||
const longHaul = { ...LEG, destination: { ...LEG.destination, lat: 35.55, lng: 139.78 }, scheduled_arrival: null };
|
||||
const midway = { ...flying, position: { ...position, lat: 60, lng: 70 } };
|
||||
expect(nextPollAt(midway, longHaul, DEP + 300 * MIN)).toBe(DEP + 306 * MIN);
|
||||
expect(nextPollAt({ ...flying, position: null }, LEG, DEP + 30 * MIN)).toBe(DEP + 33 * MIN);
|
||||
});
|
||||
|
||||
it('FLDER-014: unknown or failing every 15 minutes; landed or past the window stops', () => {
|
||||
expect(nextPollAt({ ...start, phase: 'unknown' }, LEG, DEP + 130 * MIN)).toBe(DEP + 145 * MIN);
|
||||
expect(nextPollAt({ ...start, fail_count: 3 }, LEG, DEP)).toBe(DEP + 15 * MIN);
|
||||
expect(nextPollAt({ ...start, phase: 'landed' }, LEG, ARR)).toBeNull();
|
||||
expect(nextPollAt(start, LEG, ARR + 121 * MIN)).toBeNull();
|
||||
expect(nextPollAt(start, { ...LEG, scheduled_departure: null }, DEP)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('toLiveLeg and departureDelay', () => {
|
||||
it('FLDER-015: without a state the schedule answers: scheduled, unknown late in the window, scheduled after it', () => {
|
||||
const before = toLiveLeg(LEG, null, DEP - 24 * 60 * MIN);
|
||||
expect(flightLiveLegSchema.parse(before)).toEqual(before);
|
||||
expect(before).toMatchObject({
|
||||
phase: 'scheduled',
|
||||
scheduled_departure: '2026-07-01T10:00:00.000Z',
|
||||
scheduled_arrival: '2026-07-01T11:10:00.000Z',
|
||||
progress: 0,
|
||||
distance_remaining_km: before.distance_total_km,
|
||||
position: null,
|
||||
aircraft: null,
|
||||
source: null,
|
||||
stale: false,
|
||||
});
|
||||
expect(before.distance_total_km).toBeGreaterThan(400);
|
||||
expect(toLiveLeg(LEG, null, DEP + 130 * MIN).phase).toBe('unknown');
|
||||
// Past its window the client tells a past flight from its times; nothing claims a landing nobody saw.
|
||||
const after = toLiveLeg(LEG, null, ARR + 3 * 60 * MIN);
|
||||
expect(after).toMatchObject({ phase: 'scheduled', progress: 0, landed_at: null });
|
||||
expect(after.distance_remaining_km).toBe(after.distance_total_km);
|
||||
});
|
||||
|
||||
it('FLDER-016: airborne answers its estimate from ground speed with the approach buffer and the delays', () => {
|
||||
const now = DEP + 40 * MIN;
|
||||
const position = {
|
||||
lat: 52.3667,
|
||||
lng: 10.5,
|
||||
altitude_ft: 36000,
|
||||
ground_speed_kt: 405,
|
||||
track_deg: 90,
|
||||
vertical_rate_fpm: 0,
|
||||
on_ground: false,
|
||||
};
|
||||
const state: LiveState = {
|
||||
...start,
|
||||
phase: 'airborne',
|
||||
departed_at: DEP + 20 * MIN,
|
||||
first_seen_at: DEP,
|
||||
last_seen_at: now,
|
||||
fetched_at: now,
|
||||
registration: 'D-AINA',
|
||||
source: 'adsb.lol',
|
||||
position,
|
||||
};
|
||||
const live = toLiveLeg(LEG, state, now);
|
||||
expect(flightLiveLegSchema.parse(live)).toEqual(live);
|
||||
expect(live.departure_delay_min).toBe(20);
|
||||
expect(live.departed_at).toBe('2026-07-01T10:20:00.000Z');
|
||||
expect(live.aircraft).toEqual({ registration: 'D-AINA', type: null });
|
||||
expect(live.progress).toBeGreaterThan(0.3);
|
||||
expect(live.progress).toBeLessThan(1);
|
||||
// About 204 km left at 750 km/h is 16 minutes, plus 8 for the approach.
|
||||
const eta = Date.parse(live.estimated_arrival ?? '');
|
||||
expect(Math.round((eta - now) / MIN)).toBe(24);
|
||||
expect(live.arrival_delay_min).toBe(Math.round((eta - ARR) / MIN));
|
||||
expect(live.stale).toBe(false);
|
||||
expect(toLiveLeg(LEG, state, now + 11 * MIN).stale).toBe(true);
|
||||
const slow = { ...state, position: { ...position, ground_speed_kt: 120 } };
|
||||
expect(toLiveLeg(LEG, slow, now).estimated_arrival).toBeNull();
|
||||
});
|
||||
|
||||
it('FLDER-017: landed answers its touchdown and the arrival delay from it', () => {
|
||||
const state: LiveState = { ...start, phase: 'landed', landed_at: ARR + 25 * MIN, fetched_at: ARR + 30 * MIN };
|
||||
const live = toLiveLeg(LEG, state, ARR + 30 * MIN);
|
||||
expect(live).toMatchObject({
|
||||
phase: 'landed',
|
||||
landed_at: '2026-07-01T11:35:00.000Z',
|
||||
arrival_delay_min: 25,
|
||||
distance_remaining_km: 0,
|
||||
progress: 1,
|
||||
estimated_arrival: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('FLDER-018: the departure delay comes from wheels-up, or from a recent report still at the gate past the time', () => {
|
||||
expect(departureDelay(LEG, { ...start, departed_at: DEP + 17 * MIN }, DEP + 30 * MIN)).toBe(17);
|
||||
const atGate = { ...start, phase: 'taxiing' as const, last_seen_at: DEP + 16 * MIN };
|
||||
expect(departureDelay(LEG, atGate, DEP + 17 * MIN)).toBe(16);
|
||||
// Gone quiet on the ground: the last report says nothing about now.
|
||||
expect(departureDelay(LEG, atGate, DEP + 26 * MIN)).toBeNull();
|
||||
// Heard before the scheduled time: not late yet, however late it is now.
|
||||
expect(departureDelay(LEG, { ...atGate, last_seen_at: DEP - 5 * MIN }, DEP + 2 * MIN)).toBeNull();
|
||||
expect(departureDelay(LEG, { ...start, phase: 'taxiing' }, DEP + 16 * MIN)).toBeNull();
|
||||
expect(departureDelay(LEG, start, DEP + 60 * MIN)).toBeNull();
|
||||
expect(departureDelay({ ...LEG, scheduled_departure: null }, { ...start, departed_at: DEP }, DEP)).toBeNull();
|
||||
});
|
||||
|
||||
it('FLDER-019: after its window nothing is shown taxiing or in the air, and the state closes as unknown', () => {
|
||||
const after = ARR + 121 * MIN;
|
||||
const flying: LiveState = { ...start, phase: 'airborne', last_seen_at: ARR - 30 * MIN, next_poll_at: ARR };
|
||||
expect(toLiveLeg(LEG, flying, after)).toMatchObject({ phase: 'unknown', stale: false });
|
||||
expect(toLiveLeg(LEG, { ...flying, phase: 'taxiing' }, after).phase).toBe('unknown');
|
||||
expect(toLiveLeg(LEG, flying, ARR).phase).toBe('airborne');
|
||||
|
||||
expect(closeIfOver(flying, LEG, after)).toMatchObject({ phase: 'unknown', next_poll_at: null });
|
||||
expect(closeIfOver(flying, LEG, ARR)).toBe(flying);
|
||||
const landed: LiveState = { ...start, phase: 'landed', landed_at: ARR };
|
||||
expect(closeIfOver(landed, LEG, after)).toBe(landed);
|
||||
expect(closeIfOver(start, LEG, after)).toBe(start);
|
||||
expect(closeIfOver(flying, { scheduled_departure: null, scheduled_arrival: null }, after)).toBe(flying);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,213 @@
|
||||
/**
|
||||
* The two keyless ADS-B feeds and the budget that spaces them: what goes out
|
||||
* (the callsign, nothing else), what an answer has to look like, and how a
|
||||
* bad, oversized, slow or refusing source is handled. fetch is stubbed.
|
||||
*/
|
||||
import { AppConfigModule } from '../../../../src/nest/app-config/app-config.module';
|
||||
import { BUDGET_PER_HOUR, FeedBudget } from '../../../../src/nest/flight-live/flight-live.budget';
|
||||
import { FlightLiveFeedService } from '../../../../src/nest/flight-live/flight-live.feeds';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { createTestModule, type TestModule } from '../../../helpers/test-module';
|
||||
|
||||
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('../../../../src/nest/audit/audit-log.logger', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../../../src/nest/audit/audit-log.logger')>()),
|
||||
logWarn: vi.fn(),
|
||||
}));
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
let t: TestModule;
|
||||
let feeds: FlightLiveFeedService;
|
||||
let clock = 1_000_000;
|
||||
const now = () => clock;
|
||||
|
||||
const AIRCRAFT = {
|
||||
hex: '3c6444',
|
||||
flight: 'DLH716 ',
|
||||
r: 'D-AIXA',
|
||||
t: 'A359',
|
||||
alt_baro: 36000,
|
||||
alt_geom: 36500,
|
||||
gs: 480.2,
|
||||
track: 51.3,
|
||||
baro_rate: 0,
|
||||
geom_rate: 64,
|
||||
lat: 55.1,
|
||||
lon: 60.2,
|
||||
seen: 0.4,
|
||||
seen_pos: 1.1,
|
||||
category: 'A5',
|
||||
squawk: '1000',
|
||||
};
|
||||
|
||||
function answer(body: unknown, status = 200) {
|
||||
return new Response(typeof body === 'string' ? body : JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
clock += 60 * 60 * 1000;
|
||||
t = await createTestModule({ db, imports: [AppConfigModule], providers: [FlightLiveFeedService] });
|
||||
feeds = t.get(FlightLiveFeedService);
|
||||
feeds.sleep = async () => undefined;
|
||||
});
|
||||
afterEach(async () => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.unstubAllEnvs();
|
||||
vi.restoreAllMocks();
|
||||
await t.close();
|
||||
});
|
||||
afterAll(() => db.close());
|
||||
|
||||
describe('FeedBudget', () => {
|
||||
it('FLFEED-001: one request a second and 200 an hour, a paused source for a quarter of an hour', () => {
|
||||
const budget = new FeedBudget();
|
||||
expect(budget.tryTake(0)).toBe(true);
|
||||
expect(budget.tryTake(500)).toBe(false);
|
||||
expect(budget.waitMs(500)).toBe(500);
|
||||
expect(budget.tryTake(1000)).toBe(true);
|
||||
for (let i = 2; i < BUDGET_PER_HOUR; i++) expect(budget.tryTake(i * 1000)).toBe(true);
|
||||
expect(budget.exhausted(BUDGET_PER_HOUR * 1000)).toBe(true);
|
||||
expect(budget.tryTake(BUDGET_PER_HOUR * 1000)).toBe(false);
|
||||
expect(budget.tryTake(60 * 60 * 1000 + 500)).toBe(true);
|
||||
expect(new FeedBudget().waitMs(0)).toBe(0);
|
||||
|
||||
budget.pause('adsb.lol', 0);
|
||||
expect(budget.isPaused('adsb.lol', 14 * 60 * 1000)).toBe(true);
|
||||
expect(budget.isPaused('adsb.lol', 15 * 60 * 1000)).toBe(false);
|
||||
expect(budget.isPaused('adsb.fi', 0)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('FlightLiveFeedService', () => {
|
||||
it('FLFEED-002: asks adsb.lol for the callsign alone and reads the aircraft it answers', async () => {
|
||||
const fetcher = vi.fn(async () => answer({ ac: [AIRCRAFT], now: 1_700_000_000_000, total: 1 }));
|
||||
vi.stubGlobal('fetch', fetcher);
|
||||
const result = await feeds.lookup('DLH716', now);
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
const [url, init] = fetcher.mock.calls[0] as unknown as [string, RequestInit];
|
||||
expect(url).toBe('https://api.adsb.lol/v2/callsign/DLH716');
|
||||
expect(init.signal).toBeInstanceOf(AbortSignal);
|
||||
expect(init).not.toHaveProperty('body');
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
source: 'adsb.lol',
|
||||
now: 1_700_000_000_000,
|
||||
aircraft: [
|
||||
{
|
||||
hex: '3c6444',
|
||||
flight: 'DLH716',
|
||||
registration: 'D-AIXA',
|
||||
type: 'A359',
|
||||
alt_baro: 36000,
|
||||
alt_geom: 36500,
|
||||
gs: 480.2,
|
||||
track: 51.3,
|
||||
baro_rate: 0,
|
||||
geom_rate: 64,
|
||||
lat: 55.1,
|
||||
lon: 60.2,
|
||||
seen: 0.4,
|
||||
seen_pos: 1.1,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(feeds.attribution()).toBe('Live positions: adsb.lol (ODbL)');
|
||||
});
|
||||
|
||||
it('FLFEED-003: keeps only the aircraft flying the callsign, and an answer without any is empty', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(answer({ ac: [AIRCRAFT, { ...AIRCRAFT, hex: 'x', flight: 'DLH7160' }], now: 1 }))
|
||||
.mockResolvedValueOnce(answer({ now: 2 })),
|
||||
);
|
||||
const first = await feeds.lookup('DLH716', now);
|
||||
expect(first).toMatchObject({ ok: true, aircraft: [expect.objectContaining({ hex: '3c6444' })] });
|
||||
expect((first as { aircraft: unknown[] }).aircraft).toHaveLength(1);
|
||||
clock += 2000;
|
||||
expect(await feeds.lookup('DLH716', now)).toEqual({ ok: true, source: 'adsb.lol', now: 2, aircraft: [] });
|
||||
});
|
||||
|
||||
it('FLFEED-004: falls back to adsb.fi on a self-hosted install when adsb.lol fails', async () => {
|
||||
const fetcher = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(answer('not json at all'))
|
||||
.mockResolvedValueOnce(answer({ ac: [AIRCRAFT], now: 5 }));
|
||||
vi.stubGlobal('fetch', fetcher);
|
||||
let calls = 0;
|
||||
const result = await feeds.lookup('DLH716', () => clock + 1000 * calls++);
|
||||
expect(result).toMatchObject({ ok: true, source: 'adsb.fi' });
|
||||
expect(fetcher.mock.calls[1]?.[0]).toBe('https://opendata.adsb.fi/api/v2/callsign/DLH716');
|
||||
});
|
||||
|
||||
it('FLFEED-005: a managed install never asks adsb.fi', async () => {
|
||||
vi.stubEnv('TREK_MANAGED', 'true');
|
||||
const fetcher = vi.fn(async () => answer({ unexpected: true }));
|
||||
vi.stubGlobal('fetch', fetcher);
|
||||
let calls = 0;
|
||||
expect(await feeds.lookup('DLH716', () => clock + 1000 * calls++)).toEqual({ ok: false, reason: 'unavailable' });
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
expect(feeds.sources()).toEqual(['adsb.lol']);
|
||||
});
|
||||
|
||||
it('FLFEED-006: an oversized body, a timeout and a bad shape are failures, never data', async () => {
|
||||
vi.stubEnv('TREK_MANAGED', 'true');
|
||||
const huge = 'x'.repeat(300 * 1024);
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(answer(huge))
|
||||
.mockRejectedValueOnce(new DOMException('The operation timed out.', 'TimeoutError'))
|
||||
.mockResolvedValueOnce(answer({ ac: [{ hex: 1 }], now: 1 })),
|
||||
);
|
||||
const failure = { ok: false, reason: 'unavailable' };
|
||||
clock += 2000;
|
||||
expect(await feeds.lookup('DLH716', now)).toEqual(failure);
|
||||
clock += 2000;
|
||||
expect(await feeds.lookup('DLH716', now)).toEqual(failure);
|
||||
clock += 2000;
|
||||
expect(await feeds.lookup('DLH716', now)).toEqual(failure);
|
||||
// Three failures in a row pause adsb.lol: nothing is asked and nothing is spent.
|
||||
clock += 2000;
|
||||
expect(await feeds.lookup('DLH716', now)).toEqual({ ok: false, reason: 'budget' });
|
||||
});
|
||||
|
||||
it('FLFEED-007: a 429 pauses the source at once and its body is let go', async () => {
|
||||
vi.stubEnv('TREK_MANAGED', 'true');
|
||||
const cancel = vi.fn(async () => undefined);
|
||||
const limited = { ok: false, status: 429, body: { cancel } } as unknown as Response;
|
||||
const fetcher = vi.fn(async () => limited);
|
||||
vi.stubGlobal('fetch', fetcher);
|
||||
expect(await feeds.lookup('DLH716', now)).toEqual({ ok: false, reason: 'unavailable' });
|
||||
expect(cancel).toHaveBeenCalled();
|
||||
clock += 5 * 60 * 1000;
|
||||
expect(await feeds.lookup('DLH716', now)).toEqual({ ok: false, reason: 'budget' });
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
clock += 11 * 60 * 1000;
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async () => answer({ ac: [], now: 9 })),
|
||||
);
|
||||
expect(await feeds.lookup('DLH716', now)).toMatchObject({ ok: true, source: 'adsb.lol' });
|
||||
});
|
||||
|
||||
it('FLFEED-008: the spacing between requests is held, and a malformed callsign never leaves', async () => {
|
||||
const fetcher = vi.fn(async () => answer({ ac: [], now: 1 }));
|
||||
vi.stubGlobal('fetch', fetcher);
|
||||
expect(feeds.canAsk(clock)).toBe(true);
|
||||
await feeds.lookup('DLH716', now);
|
||||
expect(feeds.canAsk(clock)).toBe(false);
|
||||
expect(feeds.waitMs(clock)).toBe(1000);
|
||||
expect(await feeds.lookup('DLH716', now)).toEqual({ ok: false, reason: 'budget' });
|
||||
clock += 1000;
|
||||
expect(await feeds.lookup('DLH716/../x', now)).toEqual({ ok: false, reason: 'unavailable' });
|
||||
expect(await feeds.lookup('dlh716', now)).toEqual({ ok: false, reason: 'unavailable' });
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,247 @@
|
||||
/**
|
||||
* The legs of a flight booking with their schedule in UTC, read the way the
|
||||
* client's flightLegs.ts reads them: a single leg from the endpoints and the
|
||||
* flat metadata, a chain from `metadata.legs` with the days it names, and
|
||||
* the local clocks turned into instants with each airport's own zone.
|
||||
*/
|
||||
import {
|
||||
legsOfBooking,
|
||||
localToUtc,
|
||||
type AirportFacts,
|
||||
type FlightBookingRow,
|
||||
type FlightEndpointRow,
|
||||
} from '../../../../src/nest/flight-live/flight-live.schedule';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const AIRLINES = new Map([
|
||||
['LH', 'DLH'],
|
||||
['NH', 'ANA'],
|
||||
]);
|
||||
|
||||
const AIRPORTS: Record<string, AirportFacts> = {
|
||||
FRA: { name: 'Frankfurt am Main Airport', city: 'Frankfurt', lat: 50.0333, lng: 8.5706, tz: 'Europe/Berlin' },
|
||||
MUC: { name: 'Munich Airport', city: 'Munich', lat: 48.3538, lng: 11.7861, tz: 'Europe/Berlin' },
|
||||
HND: { name: 'Tokyo Haneda Airport', city: 'Tokyo', lat: 35.5523, lng: 139.7798, tz: 'Asia/Tokyo' },
|
||||
JFK: {
|
||||
name: 'John F Kennedy International Airport',
|
||||
city: 'New York',
|
||||
lat: 40.6398,
|
||||
lng: -73.7789,
|
||||
tz: 'America/New_York',
|
||||
},
|
||||
};
|
||||
const lookup = (code: string) => AIRPORTS[code] ?? null;
|
||||
|
||||
function booking(overrides: Partial<FlightBookingRow> = {}): FlightBookingRow {
|
||||
return {
|
||||
id: 10,
|
||||
trip_id: 3,
|
||||
metadata: {},
|
||||
day_id: null,
|
||||
end_day_id: null,
|
||||
reservation_time: null,
|
||||
reservation_end_time: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function endpoint(overrides: Partial<FlightEndpointRow>): FlightEndpointRow {
|
||||
return {
|
||||
reservation_id: 10,
|
||||
role: 'from',
|
||||
sequence: 0,
|
||||
name: 'Frankfurt (FRA)',
|
||||
code: 'FRA',
|
||||
lat: 50.0333,
|
||||
lng: 8.5706,
|
||||
timezone: 'Europe/Berlin',
|
||||
local_date: null,
|
||||
local_time: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const NO_DAYS = new Map<number, string>();
|
||||
|
||||
describe('localToUtc', () => {
|
||||
it('FLSCH-001: reads a local clock in its zone, summer time included, and needs all three parts', () => {
|
||||
expect(localToUtc('2026-07-01', '10:30', 'Europe/Berlin')).toBe(Date.parse('2026-07-01T08:30:00Z'));
|
||||
expect(localToUtc('2026-01-15', '10:30', 'Europe/Berlin')).toBe(Date.parse('2026-01-15T09:30:00Z'));
|
||||
expect(localToUtc('2026-07-01', '10:30', 'Asia/Tokyo')).toBe(Date.parse('2026-07-01T01:30:00Z'));
|
||||
expect(localToUtc(null, '10:30', 'Europe/Berlin')).toBeNull();
|
||||
expect(localToUtc('2026-07-01', null, 'Europe/Berlin')).toBeNull();
|
||||
expect(localToUtc('2026-07-01', '10:30', null)).toBeNull();
|
||||
expect(localToUtc('2026-07-01', '10:30', 'Not/AZone')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('legsOfBooking', () => {
|
||||
it('FLSCH-002: a single leg from its endpoints, with each end in its own zone', () => {
|
||||
const legs = legsOfBooking(
|
||||
booking({ metadata: { flight_number: 'LH 716', airline: 'Lufthansa' } }),
|
||||
[
|
||||
endpoint({ local_date: '2026-07-01', local_time: '13:40' }),
|
||||
endpoint({
|
||||
role: 'to',
|
||||
sequence: 1,
|
||||
name: 'Tokyo Haneda (HND)',
|
||||
code: 'HND',
|
||||
lat: 35.5523,
|
||||
lng: 139.7798,
|
||||
timezone: 'Asia/Tokyo',
|
||||
local_date: '2026-07-02',
|
||||
local_time: '08:15',
|
||||
}),
|
||||
],
|
||||
NO_DAYS,
|
||||
lookup,
|
||||
AIRLINES,
|
||||
);
|
||||
expect(legs).toEqual([
|
||||
{
|
||||
reservation_id: 10,
|
||||
trip_id: 3,
|
||||
leg_index: 0,
|
||||
callsign: 'DLH716',
|
||||
flight_number: 'LH 716',
|
||||
service_date: '2026-07-01',
|
||||
origin: { code: 'FRA', name: 'Frankfurt', lat: 50.0333, lng: 8.5706, timezone: 'Europe/Berlin' },
|
||||
destination: { code: 'HND', name: 'Tokyo Haneda', lat: 35.5523, lng: 139.7798, timezone: 'Asia/Tokyo' },
|
||||
scheduled_departure: Date.parse('2026-07-01T11:40:00Z'),
|
||||
scheduled_arrival: Date.parse('2026-07-01T23:15:00Z'),
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('FLSCH-003: a chain of legs takes its days and times from metadata.legs and its airports from the dataset', () => {
|
||||
const days = new Map([
|
||||
[1, '2026-07-01'],
|
||||
[2, '2026-07-02'],
|
||||
]);
|
||||
const legs = legsOfBooking(
|
||||
booking({
|
||||
metadata: {
|
||||
legs: [
|
||||
{
|
||||
from: 'MUC',
|
||||
to: 'FRA',
|
||||
flight_number: 'LH 101',
|
||||
dep_day_id: 1,
|
||||
dep_time: '07:00',
|
||||
arr_day_id: 1,
|
||||
arr_time: '08:00',
|
||||
},
|
||||
{
|
||||
from: 'FRA',
|
||||
to: 'HND',
|
||||
airline: 'NH',
|
||||
flight_number: '204',
|
||||
dep_day_id: 1,
|
||||
dep_time: '21:00',
|
||||
arr_time: '16:00',
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
[],
|
||||
days,
|
||||
lookup,
|
||||
AIRLINES,
|
||||
);
|
||||
expect(legs.map((l) => [l.leg_index, l.callsign, l.service_date, l.origin.code, l.destination.code])).toEqual([
|
||||
[0, 'DLH101', '2026-07-01', 'MUC', 'FRA'],
|
||||
[1, 'ANA204', '2026-07-01', 'FRA', 'HND'],
|
||||
]);
|
||||
expect(legs[0].origin).toEqual({
|
||||
code: 'MUC',
|
||||
name: 'Munich Airport',
|
||||
lat: 48.3538,
|
||||
lng: 11.7861,
|
||||
timezone: 'Europe/Berlin',
|
||||
});
|
||||
expect(legs[0].scheduled_departure).toBe(Date.parse('2026-07-01T05:00:00Z'));
|
||||
expect(legs[0].scheduled_arrival).toBe(Date.parse('2026-07-01T06:00:00Z'));
|
||||
// No arrival day: 16:00 Tokyo on the departure day is before 21:00 Frankfurt, so it lands the next day.
|
||||
expect(legs[1].scheduled_departure).toBe(Date.parse('2026-07-01T19:00:00Z'));
|
||||
expect(legs[1].scheduled_arrival).toBe(Date.parse('2026-07-02T07:00:00Z'));
|
||||
});
|
||||
|
||||
it('FLSCH-004: a leg without a mappable number, a known airport or a departure day is left out', () => {
|
||||
const days = new Map([[1, '2026-07-01']]);
|
||||
const legs = legsOfBooking(
|
||||
booking({
|
||||
metadata: {
|
||||
legs: [
|
||||
{ from: 'FRA', to: 'HND', flight_number: 'Lufthansa', dep_day_id: 1 },
|
||||
{ from: 'FRA', to: 'XYZ', flight_number: 'LH 1', dep_day_id: 1 },
|
||||
{ from: 'FRA', to: 'HND', flight_number: 'LH 2', dep_day_id: 99 },
|
||||
{ from: 'FRA', to: 'HND', flight_number: 'LH 3', dep_day_id: 1 },
|
||||
'not a leg',
|
||||
],
|
||||
},
|
||||
}),
|
||||
[],
|
||||
days,
|
||||
lookup,
|
||||
AIRLINES,
|
||||
);
|
||||
expect(legs.map((l) => [l.leg_index, l.callsign, l.scheduled_departure, l.scheduled_arrival])).toEqual([
|
||||
[3, 'DLH3', null, null],
|
||||
]);
|
||||
});
|
||||
|
||||
it('FLSCH-005: the flat metadata and the booking times stand in for missing endpoints', () => {
|
||||
const legs = legsOfBooking(
|
||||
booking({
|
||||
metadata: { departure_airport: 'JFK', arrival_airport: 'FRA', flight_number: 'LH0401' },
|
||||
reservation_time: '2026-03-10T17:30',
|
||||
reservation_end_time: '2026-03-11T07:45',
|
||||
}),
|
||||
[],
|
||||
NO_DAYS,
|
||||
lookup,
|
||||
AIRLINES,
|
||||
);
|
||||
expect(legs).toHaveLength(1);
|
||||
expect(legs[0].callsign).toBe('DLH401');
|
||||
expect(legs[0].service_date).toBe('2026-03-10');
|
||||
expect(legs[0].origin.name).toBe('John F Kennedy International Airport');
|
||||
expect(legs[0].scheduled_departure).toBe(Date.parse('2026-03-10T21:30:00Z'));
|
||||
expect(legs[0].scheduled_arrival).toBe(Date.parse('2026-03-11T06:45:00Z'));
|
||||
});
|
||||
|
||||
it('FLSCH-006: a booking day stands in for an endpoint without a date, and an arrival before departure on its own date is dropped', () => {
|
||||
const days = new Map([
|
||||
[5, '2026-07-01'],
|
||||
[6, '2026-07-01'],
|
||||
]);
|
||||
const legs = legsOfBooking(
|
||||
booking({ metadata: { flight_number: 'LH 716' }, day_id: 5, end_day_id: 6 }),
|
||||
[
|
||||
endpoint({ local_time: '13:40:00' }),
|
||||
endpoint({
|
||||
role: 'to',
|
||||
sequence: 1,
|
||||
code: 'HND',
|
||||
name: 'Haneda',
|
||||
lat: 35.55,
|
||||
lng: 139.78,
|
||||
timezone: null,
|
||||
local_time: '08:15',
|
||||
}),
|
||||
],
|
||||
days,
|
||||
lookup,
|
||||
AIRLINES,
|
||||
);
|
||||
expect(legs[0].service_date).toBe('2026-07-01');
|
||||
expect(legs[0].destination.timezone).toBe('Asia/Tokyo');
|
||||
expect(legs[0].scheduled_departure).toBe(Date.parse('2026-07-01T11:40:00Z'));
|
||||
expect(legs[0].scheduled_arrival).toBeNull();
|
||||
});
|
||||
|
||||
it('FLSCH-007: a booking with no airports at all has no legs', () => {
|
||||
expect(legsOfBooking(booking({ metadata: { flight_number: 'LH 1' } }), [], NO_DAYS, lookup, AIRLINES)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,223 @@
|
||||
/**
|
||||
* FlightLiveService: the trip read the REST route and the MCP tool share.
|
||||
* The service comes out of FlightLiveModule over the migrated snapshot, with
|
||||
* the real airports, settings and repository; only the feed is a stub, and
|
||||
* the read must never ask it.
|
||||
*/
|
||||
import { AppSettings } from '../../../../src/db/entities/AppSettings.entity';
|
||||
import { FlightLiveStates } from '../../../../src/db/entities/FlightLiveStates.entity';
|
||||
import type { FlightLiveStateRow } from '../../../../src/db/repositories/FlightLiveStates.repository';
|
||||
import { FlightLiveFeedService } from '../../../../src/nest/flight-live/flight-live.feeds';
|
||||
import { FlightLiveModule } from '../../../../src/nest/flight-live/flight-live.module';
|
||||
import { FlightLiveService, rowToState, stateKey } from '../../../../src/nest/flight-live/flight-live.service';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { makeReservation, makeReservationEndpoint } from '../../../helpers/factories/reservations';
|
||||
import { deleteRows, insertRow } from '../../../helpers/factories/rows';
|
||||
import { makeTrip } from '../../../helpers/factories/trips';
|
||||
import { makeUser } from '../../../helpers/factories/users';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createTestModule, type TestModule } from '../../../helpers/test-module';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { tripFlightLiveResponseSchema } from '@trek/shared';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
let t: TestModule;
|
||||
let service: FlightLiveService;
|
||||
let orm: MikroORM;
|
||||
const feed = {
|
||||
lookup: vi.fn(),
|
||||
attribution: vi.fn(() => 'Live positions: adsb.lol (ODbL)'),
|
||||
sources: vi.fn(() => ['adsb.lol']),
|
||||
canAsk: vi.fn(() => true),
|
||||
waitMs: vi.fn(() => 0),
|
||||
};
|
||||
|
||||
const MIN = 60_000;
|
||||
/** 12:00 in Frankfurt on 1 July 2026; the flight lands in Berlin at 13:10. */
|
||||
const DEP = Date.parse('2026-07-01T10:00:00Z');
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestModule({
|
||||
db,
|
||||
imports: [FlightLiveModule],
|
||||
overrides: [{ provide: FlightLiveFeedService, useValue: feed }],
|
||||
});
|
||||
service = t.get(FlightLiveService);
|
||||
orm = t.get(MikroORM);
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(db);
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
db.close();
|
||||
});
|
||||
|
||||
/** A trip with one flight LH 100 from Frankfurt to Berlin on 1 July 2026. */
|
||||
async function seedFlight(flightNumber = 'LH 100') {
|
||||
const { user } = await makeUser(orm);
|
||||
const trip = await makeTrip(orm, user.id, { title: 'Berlin' });
|
||||
const flight = await makeReservation(orm, trip.id, {
|
||||
title: 'FRA to BER',
|
||||
type: 'flight',
|
||||
metadata: JSON.stringify({ flight_number: flightNumber, airline: 'Lufthansa' }),
|
||||
});
|
||||
await makeReservationEndpoint(orm, flight.id, {
|
||||
role: 'from',
|
||||
sequence: 0,
|
||||
name: 'Frankfurt (FRA)',
|
||||
code: 'FRA',
|
||||
lat: 50.0333,
|
||||
lng: 8.5706,
|
||||
timezone: 'Europe/Berlin',
|
||||
local_date: '2026-07-01',
|
||||
local_time: '12:00',
|
||||
});
|
||||
await makeReservationEndpoint(orm, flight.id, {
|
||||
role: 'to',
|
||||
sequence: 1,
|
||||
name: 'Berlin Brandenburg (BER)',
|
||||
code: 'BER',
|
||||
lat: 52.3667,
|
||||
lng: 13.5033,
|
||||
timezone: 'Europe/Berlin',
|
||||
local_date: '2026-07-01',
|
||||
local_time: '13:10',
|
||||
});
|
||||
return { user, trip, flight };
|
||||
}
|
||||
|
||||
function storedRow(overrides: Partial<FlightLiveStateRow> = {}): FlightLiveStateRow {
|
||||
return {
|
||||
callsign: 'DLH100',
|
||||
service_date: '2026-07-01',
|
||||
origin: 'FRA',
|
||||
destination: 'BER',
|
||||
phase: 'airborne',
|
||||
departed_at: '2026-07-01 10:12:00',
|
||||
landed_at: null,
|
||||
lat: 51.2,
|
||||
lng: 11,
|
||||
altitude_ft: 36000,
|
||||
ground_speed_kt: 420,
|
||||
track_deg: 60,
|
||||
vertical_rate_fpm: 0,
|
||||
on_ground: 0,
|
||||
registration: 'D-AINA',
|
||||
aircraft_type: 'A20N',
|
||||
source: 'adsb.fi',
|
||||
first_seen_at: '2026-07-01 09:50:00',
|
||||
last_seen_at: '2026-07-01 10:30:00',
|
||||
fetched_at: '2026-07-01 10:30:00',
|
||||
next_poll_at: '2026-07-01 10:33:00',
|
||||
fail_count: 0,
|
||||
departed_notified: 1,
|
||||
landed_notified: 0,
|
||||
delay_notified: 0,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('FlightLiveService.tripFlights', () => {
|
||||
it('FLSVC-001: switched off, it answers nothing and reads no booking', async () => {
|
||||
const { trip } = await seedFlight();
|
||||
await insertRow(orm, AppSettings, { key: 'flight_live_enabled', value: 'false' });
|
||||
expect(await service.isEnabled()).toBe(false);
|
||||
expect(await service.tripFlights(trip.id, DEP)).toEqual({ enabled: false, attribution: null, flights: [] });
|
||||
});
|
||||
|
||||
it('FLSVC-002: a flight days ahead comes back with its schedule in UTC, and nothing is put up for a poll', async () => {
|
||||
const { trip, flight } = await seedFlight();
|
||||
const answer = await service.tripFlights(trip.id, DEP - 3 * 24 * 60 * MIN);
|
||||
expect(tripFlightLiveResponseSchema.parse(answer)).toEqual(answer);
|
||||
expect(answer).toMatchObject({ enabled: true, attribution: 'Live positions: adsb.lol (ODbL)' });
|
||||
expect(answer.flights).toHaveLength(1);
|
||||
expect(answer.flights[0]).toMatchObject({
|
||||
reservation_id: flight.id,
|
||||
leg_index: 0,
|
||||
callsign: 'DLH100',
|
||||
flight_number: 'LH 100',
|
||||
service_date: '2026-07-01',
|
||||
origin: { code: 'FRA', name: 'Frankfurt', timezone: 'Europe/Berlin' },
|
||||
destination: { code: 'BER', name: 'Berlin Brandenburg', timezone: 'Europe/Berlin' },
|
||||
phase: 'scheduled',
|
||||
scheduled_departure: '2026-07-01T10:00:00.000Z',
|
||||
scheduled_arrival: '2026-07-01T11:10:00.000Z',
|
||||
source: null,
|
||||
});
|
||||
expect(service.takeRefreshRequests(DEP)).toEqual(new Set());
|
||||
expect(feed.lookup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FLSVC-003: an in-window flight without a fresh answer is put up for the next tick, once a minute', async () => {
|
||||
const { trip } = await seedFlight();
|
||||
const key = stateKey('DLH100', '2026-07-01', 'FRA', 'BER');
|
||||
await service.tripFlights(trip.id, DEP - 30 * MIN);
|
||||
await service.tripFlights(trip.id, DEP - 29.5 * MIN);
|
||||
expect(service.takeRefreshRequests(DEP - 29.4 * MIN)).toEqual(new Set([key]));
|
||||
// Within the minute of the first ask: nothing new to hand over.
|
||||
await service.tripFlights(trip.id, DEP - 29.2 * MIN);
|
||||
expect(service.takeRefreshRequests(DEP - 29.1 * MIN)).toEqual(new Set());
|
||||
await service.tripFlights(trip.id, DEP - 28.5 * MIN);
|
||||
expect(service.takeRefreshRequests(DEP - 28.5 * MIN)).toEqual(new Set([key]));
|
||||
expect(feed.lookup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FLSVC-004: a stored state answers on top of the schedule, with the credit of its source', async () => {
|
||||
const { trip } = await seedFlight();
|
||||
await insertRow(orm, FlightLiveStates, storedRow());
|
||||
const now = Date.parse('2026-07-01T10:31:00Z');
|
||||
const answer = await service.tripFlights(trip.id, now);
|
||||
expect(answer.attribution).toBe('Live positions: adsb.fi');
|
||||
expect(answer.flights[0]).toMatchObject({
|
||||
phase: 'airborne',
|
||||
departed_at: '2026-07-01T10:12:00.000Z',
|
||||
departure_delay_min: 12,
|
||||
aircraft: { registration: 'D-AINA', type: 'A20N' },
|
||||
last_seen_at: '2026-07-01T10:30:00.000Z',
|
||||
source: 'adsb.fi',
|
||||
stale: false,
|
||||
});
|
||||
// Fetched a minute ago: fresh enough, nothing to refresh.
|
||||
expect(service.takeRefreshRequests(now)).toEqual(new Set());
|
||||
});
|
||||
|
||||
it('FLSVC-004b: a flight the poll backs off from, or has given up on, is not put up by a client', async () => {
|
||||
const { trip } = await seedFlight();
|
||||
const now = Date.parse('2026-07-01T10:31:00Z');
|
||||
await insertRow(orm, FlightLiveStates, storedRow({ phase: 'unknown', fetched_at: '2026-07-01 10:20:00' }));
|
||||
await service.tripFlights(trip.id, now);
|
||||
expect(service.takeRefreshRequests(now)).toEqual(new Set());
|
||||
await deleteRows(orm, FlightLiveStates);
|
||||
await insertRow(orm, FlightLiveStates, storedRow({ fail_count: 3, fetched_at: '2026-07-01 10:20:00' }));
|
||||
await service.tripFlights(trip.id, now + 2 * MIN);
|
||||
expect(service.takeRefreshRequests(now + 2 * MIN)).toEqual(new Set());
|
||||
});
|
||||
|
||||
it('FLSVC-005: a flight number that maps to no callsign is not listed', async () => {
|
||||
const { trip } = await seedFlight('Lufthansa');
|
||||
expect((await service.tripFlights(trip.id, DEP)).flights).toEqual([]);
|
||||
const { user } = await makeUser(orm);
|
||||
const empty = await makeTrip(orm, user.id);
|
||||
expect(await service.tripFlights(empty.id, DEP)).toMatchObject({ enabled: true, flights: [] });
|
||||
});
|
||||
});
|
||||
|
||||
describe('rowToState', () => {
|
||||
it('FLSVC-006: reads the stored text back as instants, and an unknown phase or source falls back', () => {
|
||||
const state = rowToState(storedRow());
|
||||
expect(state).toMatchObject({
|
||||
phase: 'airborne',
|
||||
departed_at: Date.parse('2026-07-01T10:12:00Z'),
|
||||
source: 'adsb.fi',
|
||||
departed_notified: true,
|
||||
landed_notified: false,
|
||||
position: { lat: 51.2, lng: 11, on_ground: false },
|
||||
});
|
||||
const odd = rowToState(storedRow({ phase: 'cruising', source: 'radar', lat: null, on_ground: 1 }));
|
||||
expect(odd).toMatchObject({ phase: 'scheduled', source: null, position: null });
|
||||
});
|
||||
});
|
||||
@@ -15,12 +15,14 @@ import {
|
||||
MANAGED_LOCKED_SETTING_KEYS,
|
||||
MANAGED_LOCKED_PROFILE_KEYS,
|
||||
MANAGED_CUSTOMER_KEYS,
|
||||
envLockedKeys,
|
||||
isManagedLockedKey,
|
||||
splitManagedKeys,
|
||||
withEnvLocks,
|
||||
} from '../../../src/nest/common/managed';
|
||||
import { DEFAULTABLE_USER_SETTING_KEYS } from '../../../src/nest/settings/settings.service';
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { afterEach, describe, it, expect, vi } from 'vitest';
|
||||
|
||||
const SOURCE_KEYS: string[] = [...ADMIN_FORM_SETTING_KEYS, ...DEFAULTABLE_USER_SETTING_KEYS];
|
||||
const locked = new Set<string>(MANAGED_LOCKED_SETTING_KEYS);
|
||||
@@ -129,3 +131,28 @@ describe('splitManagedKeys', () => {
|
||||
expect(blocked).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('env-held admin switches', () => {
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
it('MANAGED-ENV-001: unset, the form answers the stored value and a save writes it', () => {
|
||||
vi.stubEnv('FLIGHT_LIVE_ENABLED', '');
|
||||
expect(withEnvLocks({ flight_live_enabled: 'true', require_mfa: 'false' })).toEqual({
|
||||
flight_live_enabled: 'true',
|
||||
require_mfa: 'false',
|
||||
});
|
||||
expect(envLockedKeys({ flight_live_enabled: 'false' })).toEqual([]);
|
||||
});
|
||||
|
||||
it('MANAGED-ENV-002: set, the form shows the variable and env_override_flight_live_enabled, and a save skips it', () => {
|
||||
vi.stubEnv('FLIGHT_LIVE_ENABLED', 'off');
|
||||
expect(withEnvLocks({ flight_live_enabled: 'true', require_mfa: 'false' })).toEqual({
|
||||
flight_live_enabled: 'false',
|
||||
env_override_flight_live_enabled: 'false',
|
||||
require_mfa: 'false',
|
||||
});
|
||||
expect(withEnvLocks({})).toEqual({ flight_live_enabled: 'false', env_override_flight_live_enabled: 'false' });
|
||||
expect(envLockedKeys({ flight_live_enabled: 'true', require_mfa: 'true' })).toEqual(['flight_live_enabled']);
|
||||
expect(envLockedKeys({ require_mfa: 'true' })).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -156,14 +156,15 @@ describe('getPreferencesMatrix', () => {
|
||||
expect(event_types).not.toContain('version_available');
|
||||
// +1 for plugin_notification: users can mute host-mediated plugin notifications.
|
||||
// +1 for wanderer_source_hint: the hints of the user's own wanderer watch (WAN-02).
|
||||
expect(event_types.length).toBe(13);
|
||||
// +3 for flight_departed, flight_delayed and flight_landed (live flight status, on by default).
|
||||
expect(event_types.length).toBe(16);
|
||||
});
|
||||
|
||||
it('NPREF-005 — user scope excludes version_available for everyone including admins', async () => {
|
||||
const { user } = createAdmin(testDb);
|
||||
const { event_types } = await getPreferencesMatrix(user.id, 'admin', 'user');
|
||||
expect(event_types).not.toContain('version_available');
|
||||
expect(event_types.length).toBe(13);
|
||||
expect(event_types.length).toBe(16);
|
||||
});
|
||||
|
||||
it('NPREF-005b — admin scope returns the admin-scoped events', async () => {
|
||||
@@ -481,4 +482,13 @@ describe('listed events follow the features that are on', () => {
|
||||
Object.assign(features, all);
|
||||
}
|
||||
});
|
||||
|
||||
it('NPREF-LIST-002: the flight events are listed only while live flight status is on', async () => {
|
||||
const flights = ['flight_departed', 'flight_delayed', 'flight_landed'];
|
||||
const { user } = createUser(testDb);
|
||||
expect((await svc.getPreferencesMatrix(user.id, 'user')).event_types).toEqual(expect.arrayContaining(flights));
|
||||
setAppSetting(testDb, 'flight_live_enabled', 'false');
|
||||
const { event_types } = await svc.getPreferencesMatrix(user.id, 'user');
|
||||
for (const hidden of flights) expect(event_types).not.toContain(hidden);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -608,6 +608,30 @@ describe('send() — in-app notification content', () => {
|
||||
);
|
||||
expect(notifs.every((n) => n.title_key === 'notif.wanderer_source_hint.title')).toBe(true);
|
||||
});
|
||||
|
||||
it('NOTIF-FLT-001 the three live flight notices lead to their trip, and nowhere without one', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
setNotificationChannels(testDb, 'none');
|
||||
const params = { flight: 'LH 716', from: 'FRA', to: 'HND', trip: 'Japan', delay: '25' };
|
||||
const events = ['flight_departed', 'flight_delayed', 'flight_landed'] as const;
|
||||
await events.reduce(async (previous, event) => {
|
||||
await previous;
|
||||
await send({ event, actorId: null, scope: 'user', targetId: user.id, params: { ...params, tripId: '7' } });
|
||||
await send({ event, actorId: null, scope: 'user', targetId: user.id, params });
|
||||
}, Promise.resolve());
|
||||
|
||||
const notifs = await getInAppNotifications(user.id);
|
||||
expect(notifs.map((n) => [n.title_key, n.text_key, n.navigate_target])).toEqual(
|
||||
expect.arrayContaining([
|
||||
['notif.flight_departed.title', 'notif.flight_departed.text', '/trips/7'],
|
||||
['notif.flight_delayed.title', 'notif.flight_delayed.text', '/trips/7'],
|
||||
['notif.flight_landed.title', 'notif.flight_landed.text', '/trips/7'],
|
||||
['notif.flight_departed.title', 'notif.flight_departed.text', null],
|
||||
['notif.flight_delayed.title', 'notif.flight_delayed.text', null],
|
||||
['notif.flight_landed.title', 'notif.flight_landed.text', null],
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
Reference in New Issue
Block a user