mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-23 13:23:04 +00:00
feat(airtrail): use the AirTrail /api/v1 routes, and keep the legacy routes
AirTrail 3.13 adds /api/v1 and marks the /api/flight/* routes as deprecated. TREK now asks the public discovery document GET /api/v1 and uses v1 when the instance has it. It uses the legacy routes for an older instance. The client methods keep their signatures, and the sync hash stays the same, so a linked flight does not sync again when an instance changes to v1. The probe cache holds only a clear answer: 200 with the discovery document gives v1, and 404 gives legacy. The cache is per AirTrail URL, for 10 minutes. A timeout, a 5xx or a network error fails that call only. A 401, a 403 or a page that is not the discovery document uses legacy for that call only. A 404 for one flight makes the client ask the probe again before it reports the flight as deleted. A missing scope gives AirtrailScopeError, which names the scope. It does not unlink a flight. The API key hint and the help step list the scopes for read and for write-back, in all languages. Each new request goes through safeFetch, with the SSRF guard, the timeout and the size cap. The flight list reads pages of 100 and fails above 50 pages. A failed list unlinks nothing. airtrail-v1.ts translates between the v1 shapes and the legacy shapes. A write-back looks up the airport, airline and aircraft ids, and changes each local time to a UTC instant in the zone of its own airport. It writes each instant in the +00:00 form of the legacy save, because AirTrail stores the string as it gets it and the sync hash reads that string. The tests cover both APIs over HTTP, the probe cache rules, the sync hash on a switch and on a save, the page limit, the scope error, and the UTC conversion across midnight, the date line and daylight-saving changes.
This commit is contained in:
@@ -61,7 +61,9 @@ export class AirtrailSyncService {
|
||||
try {
|
||||
flights = await this.client.listFlights(creds);
|
||||
} catch (err) {
|
||||
// A failed list detaches nothing. Without a full list, no flight is known to be deleted in AirTrail.
|
||||
if (err instanceof AirtrailAuthError) logError(`AirTrail sync: invalid API key for user ${uid}`);
|
||||
else logError(`AirTrail sync for user ${uid}: ${err instanceof Error ? err.message : err}`);
|
||||
return 0;
|
||||
}
|
||||
const byId = new Map(flights.map((f) => [String(f.id), f]));
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
import { wallClockInstant } from '../common/timezoneService';
|
||||
import type { AirtrailAirport, AirtrailFlightRaw, AirtrailSavePayload } from './airtrail.client';
|
||||
|
||||
/**
|
||||
* The translation between AirTrail's `/api/v1` and the shapes the rest of TREK
|
||||
* uses (AirtrailFlightRaw, AirtrailSavePayload), which are the shapes of the
|
||||
* legacy `/api/flight/*` routes. The callers use one shape for each API that an
|
||||
* instance speaks. This file is the only place that knows the difference.
|
||||
*
|
||||
* The contract comes from AirTrail 3.13.0 to 3.14.0 (`src/lib/api/v1/schemas.ts`,
|
||||
* `src/lib/api/v1/dto.ts`). The v1 contract is the same in these versions.
|
||||
*
|
||||
* The functions are pure, so the unit test gives them fixture objects.
|
||||
*/
|
||||
|
||||
/** An airport as v1 returns it, on a flight and from `GET /api/v1/airports`. */
|
||||
export interface AirtrailV1Airport {
|
||||
id: number;
|
||||
icao: string | null;
|
||||
iata: string | null;
|
||||
name: string | null;
|
||||
latitude: number | null;
|
||||
longitude: number | null;
|
||||
timezone: string | null;
|
||||
country: string | null;
|
||||
}
|
||||
|
||||
/** An airline or aircraft as v1 returns it. Aircraft have no IATA code. */
|
||||
export interface AirtrailV1Entity {
|
||||
id: number;
|
||||
name: string | null;
|
||||
icao: string | null;
|
||||
iata?: string | null;
|
||||
}
|
||||
|
||||
interface AirtrailV1Passenger {
|
||||
id: number;
|
||||
user: { id: string } | null;
|
||||
guestName: string | null;
|
||||
seat: string | null;
|
||||
seatNumber: string | null;
|
||||
seatClass: string | null;
|
||||
flightReason: string | null;
|
||||
}
|
||||
|
||||
/** A flight as `GET /api/v1/flights` and `GET /api/v1/flights/{id}` return it. */
|
||||
export interface AirtrailV1Flight {
|
||||
id: number;
|
||||
from: AirtrailV1Airport | null;
|
||||
to: AirtrailV1Airport | null;
|
||||
airline: AirtrailV1Entity | null;
|
||||
aircraft: AirtrailV1Entity | null;
|
||||
passengers: AirtrailV1Passenger[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/** What a v1 write needs that a code-based payload does not carry. */
|
||||
export interface AirtrailV1References {
|
||||
from: AirtrailV1Airport;
|
||||
to: AirtrailV1Airport;
|
||||
airlineId: number | null;
|
||||
aircraftId: number | null;
|
||||
/** The key owner's AirTrail user id, for a `<USER_ID>` passenger. */
|
||||
selfUserId: string | null;
|
||||
}
|
||||
|
||||
/** A payload that cannot become a valid v1 body. The message is for the log. */
|
||||
export class AirtrailV1InputError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'AirtrailV1InputError';
|
||||
}
|
||||
}
|
||||
|
||||
/** The placeholder the legacy save resolved to the key owner. */
|
||||
export const AIRTRAIL_SELF_USER_PLACEHOLDER = '<USER_ID>';
|
||||
|
||||
function toAirport(a: AirtrailV1Airport | null): AirtrailAirport | null {
|
||||
if (!a) return null;
|
||||
return {
|
||||
id: a.id,
|
||||
icao: a.icao,
|
||||
iata: a.iata,
|
||||
name: a.name,
|
||||
lat: a.latitude,
|
||||
lon: a.longitude,
|
||||
tz: a.timezone,
|
||||
country: a.country,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A v1 flight in the legacy shape. Airports rename their coordinate and zone
|
||||
* keys, and a passenger names its user as an object instead of a `userId`.
|
||||
* Every other key passes through, so `buildSavePayload` still carries the
|
||||
* AirTrail-owned fields (terminal, gate, takeoff and landing times) it does not
|
||||
* model.
|
||||
*/
|
||||
export function fromAirtrailV1Flight(f: AirtrailV1Flight): AirtrailFlightRaw {
|
||||
return {
|
||||
...(f as unknown as AirtrailFlightRaw),
|
||||
from: toAirport(f.from),
|
||||
to: toAirport(f.to),
|
||||
passengers: (f.passengers ?? []).map((p) => ({
|
||||
userId: p.user?.id ?? null,
|
||||
guestName: p.guestName,
|
||||
seat: p.seat,
|
||||
seatNumber: p.seatNumber,
|
||||
seatClass: p.seatClass,
|
||||
flightReason: p.flightReason,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The entry of a search result whose code is `code`: an ICAO match first, then
|
||||
* an IATA match, as the legacy save looked up an airport. With `icaoOnly`, an
|
||||
* IATA match does not count, as the legacy save looked up an airline and an
|
||||
* aircraft.
|
||||
*/
|
||||
export function pickAirtrailByCode<T extends { icao?: string | null; iata?: string | null }>(
|
||||
rows: T[],
|
||||
code: string,
|
||||
icaoOnly: boolean,
|
||||
): T | null {
|
||||
const wanted = code.trim().toUpperCase();
|
||||
const icao = rows.find((r) => r.icao?.toUpperCase() === wanted);
|
||||
if (icao || icaoOnly) return icao ?? null;
|
||||
return rows.find((r) => r.iata?.toUpperCase() === wanted) ?? null;
|
||||
}
|
||||
|
||||
const DATE = /^\d{4}-\d{2}-\d{2}/;
|
||||
const FULL_ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
|
||||
|
||||
function datePart(value: unknown): string | null {
|
||||
return typeof value === 'string' && DATE.test(value) ? value.slice(0, 10) : null;
|
||||
}
|
||||
|
||||
function text(value: unknown): string | null {
|
||||
return typeof value === 'string' ? value : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A local date and `HH:MM` at an airport, as an ISO instant. Null when there is no time.
|
||||
*
|
||||
* AirTrail stores the string as it gets it, and the sync hash reads that string.
|
||||
* The instant ends in `+00:00`, as the legacy save wrote it, so that a save
|
||||
* that changes no time keeps the hash.
|
||||
*/
|
||||
function localInstant(date: string | null, time: unknown, zone: string | null, field: string): string | null {
|
||||
if (!date || typeof time !== 'string' || !time) return null;
|
||||
const ms = wallClockInstant(date, time, zone || 'UTC');
|
||||
if (ms === null) throw new AirtrailV1InputError(`Invalid ${field} time "${time}" on ${date}`);
|
||||
return new Date(ms).toISOString().replace(/Z$/, '+00:00');
|
||||
}
|
||||
|
||||
/**
|
||||
* A takeoff or landing time. The payload carries it as AirTrail returned it (an
|
||||
* ISO instant) unless a caller set the date and `HH:MM` form; the instant then
|
||||
* passes through unchanged.
|
||||
*/
|
||||
function carriedInstant(p: Record<string, unknown>, key: string, zone: string | null): string | null {
|
||||
if (`${key}Time` in p) return localInstant(datePart(p[key]), p[`${key}Time`], zone, key);
|
||||
const value = p[key];
|
||||
return typeof value === 'string' && FULL_ISO.test(value) ? value : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A legacy save payload as a v1 flight body (`POST /api/v1/flights`,
|
||||
* `PUT /api/v1/flights/{id}`), with the rules the legacy save applied:
|
||||
* - Departure and its scheduled time are the local wall clock at the origin,
|
||||
* arrival and its scheduled time at the destination. A date without a time
|
||||
* gives no instant. An arrival time without an arrival date takes the
|
||||
* departure date.
|
||||
* - `date` is the departure date, else the scheduled departure date.
|
||||
* - A precision other than `day` keeps only the departure, at 10:00 UTC.
|
||||
* - A flight-level reason fills each passenger that has none.
|
||||
*
|
||||
* v1 does not derive `duration`, so it is the departure-to-arrival time when
|
||||
* both are known, else the duration AirTrail had.
|
||||
*
|
||||
* v1 replaces every field a PUT omits with its default, so the body names each
|
||||
* field except `track`. Without a track, AirTrail keeps the stored track. A
|
||||
* track in the body needs the `tracks.write` scope.
|
||||
*/
|
||||
export function toAirtrailV1FlightInput(
|
||||
payload: AirtrailSavePayload,
|
||||
refs: AirtrailV1References,
|
||||
): Record<string, unknown> {
|
||||
const p = payload as unknown as Record<string, unknown>;
|
||||
const fromTz = refs.from.timezone;
|
||||
const toTz = refs.to.timezone;
|
||||
|
||||
const depDate = datePart(p.departure);
|
||||
const date = depDate ?? datePart(p.departureScheduled);
|
||||
if (!date) throw new AirtrailV1InputError('A departure date is required');
|
||||
|
||||
const datePrecision = text(p.datePrecision) ?? 'day';
|
||||
const passengers = (payload.passengers ?? payload.seats ?? []).map((s) => {
|
||||
const userId = s.userId === AIRTRAIL_SELF_USER_PLACEHOLDER ? refs.selfUserId : s.userId;
|
||||
if (s.userId === AIRTRAIL_SELF_USER_PLACEHOLDER && !userId)
|
||||
throw new AirtrailV1InputError('The AirTrail user of this API key is unknown');
|
||||
return {
|
||||
userId: userId ?? null,
|
||||
guestName: s.guestName ?? null,
|
||||
seat: s.seat ?? null,
|
||||
seatNumber: s.seatNumber ?? null,
|
||||
seatClass: s.seatClass ?? null,
|
||||
flightReason: s.flightReason ?? payload.flightReason ?? null,
|
||||
};
|
||||
});
|
||||
|
||||
let times: Record<string, string | null>;
|
||||
if (datePrecision !== 'day') {
|
||||
times = {
|
||||
departure: `${date}T10:00:00.000+00:00`,
|
||||
arrival: null,
|
||||
departureScheduled: null,
|
||||
arrivalScheduled: null,
|
||||
takeoffScheduled: null,
|
||||
takeoffActual: null,
|
||||
landingScheduled: null,
|
||||
landingActual: null,
|
||||
};
|
||||
} else {
|
||||
const arrivalDate = datePart(p.arrival) ?? (p.arrivalTime ? depDate : null);
|
||||
times = {
|
||||
departure: localInstant(depDate, p.departureTime, fromTz, 'departure'),
|
||||
arrival: localInstant(arrivalDate, p.arrivalTime, toTz, 'arrival'),
|
||||
departureScheduled: localInstant(
|
||||
datePart(p.departureScheduled),
|
||||
p.departureScheduledTime,
|
||||
fromTz,
|
||||
'scheduled departure',
|
||||
),
|
||||
arrivalScheduled: localInstant(datePart(p.arrivalScheduled), p.arrivalScheduledTime, toTz, 'scheduled arrival'),
|
||||
takeoffScheduled: carriedInstant(p, 'takeoffScheduled', fromTz),
|
||||
takeoffActual: carriedInstant(p, 'takeoffActual', fromTz),
|
||||
landingScheduled: carriedInstant(p, 'landingScheduled', toTz),
|
||||
landingActual: carriedInstant(p, 'landingActual', toTz),
|
||||
};
|
||||
}
|
||||
|
||||
const known =
|
||||
times.departure && times.arrival ? (Date.parse(times.arrival) - Date.parse(times.departure)) / 1000 : null;
|
||||
const duration =
|
||||
known !== null && known >= 0 ? Math.round(known) : typeof p.duration === 'number' ? p.duration : null;
|
||||
|
||||
return {
|
||||
date,
|
||||
datePrecision,
|
||||
...times,
|
||||
duration,
|
||||
departureTerminal: text(p.departureTerminal),
|
||||
departureGate: text(p.departureGate),
|
||||
arrivalTerminal: text(p.arrivalTerminal),
|
||||
arrivalGate: text(p.arrivalGate),
|
||||
flightNumber: text(p.flightNumber),
|
||||
aircraftReg: text(p.aircraftReg),
|
||||
note: text(p.note),
|
||||
fromId: refs.from.id,
|
||||
toId: refs.to.id,
|
||||
airlineId: refs.airlineId,
|
||||
aircraftId: refs.aircraftId,
|
||||
passengers,
|
||||
};
|
||||
}
|
||||
@@ -1,30 +1,66 @@
|
||||
import { safeFetch } from '../../utils/ssrfGuard';
|
||||
import {
|
||||
AirtrailV1InputError,
|
||||
fromAirtrailV1Flight,
|
||||
pickAirtrailByCode,
|
||||
AIRTRAIL_SELF_USER_PLACEHOLDER,
|
||||
toAirtrailV1FlightInput,
|
||||
type AirtrailV1Airport,
|
||||
type AirtrailV1Entity,
|
||||
type AirtrailV1Flight,
|
||||
} from './airtrail-v1';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* Thin HTTP client for the AirTrail REST API (github.com/johanohly/AirTrail).
|
||||
* This is the ONLY place that talks to a user's AirTrail instance.
|
||||
*
|
||||
* Verified against AirTrail source:
|
||||
* - Auth: `Authorization: Bearer <key>`; a key maps to exactly one user.
|
||||
* - GET /api/flight/list — defaults to scope=mine. We NEVER send a scope
|
||||
* param so the key only ever returns its owner's own flights (isolation
|
||||
* holds even if an admin key is pasted).
|
||||
* - GET /api/flight/get/{id}
|
||||
* - POST /api/flight/save — `id` present => update, else create. The
|
||||
* passenger list is required (>=1). An entry with userId '<USER_ID>' is
|
||||
* attributed to the key owner server-side, so we never need the caller's
|
||||
* AirTrail user id.
|
||||
* - AirTrail 3.12.0 renamed that list from `seats` to `passengers` and moved
|
||||
* flightReason from the flight onto each passenger, with no alias on either
|
||||
* side (verified against running 3.11.1 and 3.12.0 instances: each returns
|
||||
* its own key and null for the other). TREK reads and writes both shapes so
|
||||
* one build works against either version.
|
||||
* AirTrail 3.13.0 and later serve the versioned API under `/api/v1`. They mark
|
||||
* the `/api/flight/*` routes as deprecated, and the next major release removes
|
||||
* them. Older instances have only `/api/flight/*`. The client asks the public
|
||||
* discovery document `GET /api/v1` which API an instance has, and keeps the
|
||||
* answer for FLAVOR_TTL_MS (see `apiFlavor`). A 404 from a flight route cannot
|
||||
* tell the difference, because v1 also answers 404 for a flight that does not exist.
|
||||
*
|
||||
* Both APIs, verified against AirTrail source:
|
||||
* - Auth: `Authorization: Bearer <key>`; a key maps to exactly one user. A key
|
||||
* made before 3.13.0 holds every scope. A newer key needs `flight.read.own`,
|
||||
* and for the write-back also `flight.update.own`,
|
||||
* `flight.passengers.manage.own` (a PUT that changes a passenger, for example
|
||||
* the seat), `reference_data.read` (code lookups) and `profile.read`
|
||||
* (`GET /api/v1/me`, for a flight with no passenger). A save with no id also
|
||||
* needs `flight.create.own`. A missing scope raises AirtrailScopeError, which
|
||||
* names it.
|
||||
* - The flight list defaults to scope=mine. We NEVER send a scope param so the
|
||||
* key only ever returns its owner's own flights (isolation holds even if an
|
||||
* admin key is pasted). v1 gives the list in pages, and the client reads every page.
|
||||
* - Legacy: GET /api/flight/list, GET /api/flight/get/{id}, and
|
||||
* POST /api/flight/save (`id` present => update, else create), with airports,
|
||||
* airline and aircraft as codes and times as a local date plus `HH:MM`. An
|
||||
* entry with userId '<USER_ID>' is attributed to the key owner server-side.
|
||||
* - v1: GET /api/v1/flights, GET /api/v1/flights/{id}, POST /api/v1/flights,
|
||||
* PUT /api/v1/flights/{id}, with numeric ids and ISO instants. airtrail-v1.ts
|
||||
* translates both ways, so callers use the legacy shapes for either API.
|
||||
* - The passenger list is required (>=1). AirTrail 3.12.0 renamed it from
|
||||
* `seats` to `passengers` and moved flightReason from the flight onto each
|
||||
* passenger, with no alias on either side (verified against running 3.11.1
|
||||
* and 3.12.0 instances: each returns its own key and null for the other).
|
||||
* TREK reads and writes both shapes so one build works against either version.
|
||||
* - There is no webhook and no updated_at on a flight, so change detection is
|
||||
* snapshot-hash based (see airtrailSync).
|
||||
*/
|
||||
|
||||
const TIMEOUT_MS = 12000;
|
||||
/** How long the client keeps the answer of the discovery probe. After this time, it sees an AirTrail upgrade. */
|
||||
const FLAVOR_TTL_MS = 10 * 60_000;
|
||||
/** The largest page `GET /api/v1/flights` gives. */
|
||||
const V1_PAGE_LIMIT = 100;
|
||||
/**
|
||||
* The most list pages read in one call (5000 flights). Past it the list fails
|
||||
* instead of answering a part, because the sync detaches every linked flight
|
||||
* that is missing from the list.
|
||||
*/
|
||||
const V1_MAX_PAGES = 50;
|
||||
|
||||
export interface AirtrailCreds {
|
||||
/** Instance origin without a trailing /api. */
|
||||
@@ -40,6 +76,24 @@ export class AirtrailAuthError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A v1 key that is valid but does not have a scope that the request needs. It is
|
||||
* not an AirtrailAuthError, because the key still works for its other scopes.
|
||||
* A caller must not detach linked flights for this error.
|
||||
*/
|
||||
export class AirtrailScopeError extends Error {
|
||||
readonly scope: string | null;
|
||||
constructor(scope: string | null) {
|
||||
super(
|
||||
scope
|
||||
? `The AirTrail API key lacks the scope ${scope}. Add it to the key in AirTrail, or create a new key.`
|
||||
: 'The AirTrail API key lacks a scope that this request needs.',
|
||||
);
|
||||
this.name = 'AirtrailScopeError';
|
||||
this.scope = scope;
|
||||
}
|
||||
}
|
||||
|
||||
export class AirtrailRequestError extends Error {
|
||||
status?: number;
|
||||
constructor(message: string, status?: number) {
|
||||
@@ -179,6 +233,25 @@ async function parseJson<T>(resp: Response): Promise<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/** The error of a v1 error body (`{error:{code,message,details}}`), when the response holds one. */
|
||||
async function airtrailV1Error(resp: Response): Promise<{ code: string | null; message: string } | null> {
|
||||
try {
|
||||
const body = JSON.parse(await resp.text()) as { error?: { code?: unknown; message?: unknown; details?: unknown } };
|
||||
const message = typeof body?.error?.message === 'string' ? body.error.message : null;
|
||||
if (!message) return null;
|
||||
const code = typeof body.error?.code === 'string' ? body.error.code : null;
|
||||
const details = body.error?.details;
|
||||
return { code, message: details === undefined ? message : `${message}: ${JSON.stringify(details)}` };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The scope name in AirTrail's `insufficient_scope` message ("The credential requires flight.read.own"). */
|
||||
function scopeIn(message: string): string | null {
|
||||
return /\b[a-z_]+(?:\.[a-z_]+)+\b/.exec(message)?.[0] ?? null;
|
||||
}
|
||||
|
||||
async function request(creds: AirtrailCreds, path: string, init: RequestInit): Promise<Response> {
|
||||
const url = apiBase(creds.baseUrl) + path;
|
||||
let resp: Response;
|
||||
@@ -200,11 +273,21 @@ async function request(creds: AirtrailCreds, path: string, init: RequestInit): P
|
||||
throw new AirtrailRequestError(err instanceof Error ? err.message : 'Could not reach AirTrail');
|
||||
}
|
||||
if (resp.status === 401 || resp.status === 403) {
|
||||
throw new AirtrailAuthError();
|
||||
// v1 gives the cause, for example the scope that the key does not have. The legacy API does not.
|
||||
const reason = await airtrailV1Error(resp);
|
||||
if (reason?.code === 'insufficient_scope') throw new AirtrailScopeError(scopeIn(reason.message));
|
||||
throw reason ? new AirtrailAuthError(`AirTrail refused the request: ${reason.message}`) : new AirtrailAuthError();
|
||||
}
|
||||
return resp;
|
||||
}
|
||||
|
||||
async function airtrailV1Failure(resp: Response, action: string): Promise<AirtrailRequestError> {
|
||||
const reason = await airtrailV1Error(resp);
|
||||
return new AirtrailRequestError(reason?.message ?? `AirTrail ${action} failed (HTTP ${resp.status})`, resp.status);
|
||||
}
|
||||
|
||||
type ApiFlavor = 'v1' | 'legacy';
|
||||
|
||||
/**
|
||||
* The AirTrail HTTP surface, as a provider.
|
||||
*
|
||||
@@ -215,7 +298,11 @@ async function request(creds: AirtrailCreds, path: string, init: RequestInit): P
|
||||
*/
|
||||
@Injectable()
|
||||
export class AirtrailClient {
|
||||
/** The API each instance speaks, by API base URL, with the time it was asked. */
|
||||
private readonly flavors = new Map<string, { flavor: ApiFlavor; at: number }>();
|
||||
|
||||
async listFlights(creds: AirtrailCreds): Promise<AirtrailFlightRaw[]> {
|
||||
if ((await this.apiFlavor(creds)) === 'v1') return this.listFlightsV1(creds);
|
||||
const resp = await request(creds, '/flight/list', { method: 'GET' });
|
||||
if (!resp.ok) throw new AirtrailRequestError(`AirTrail list failed (HTTP ${resp.status})`, resp.status);
|
||||
const data = await parseJson<{ flights?: AirtrailFlightRaw[] }>(resp);
|
||||
@@ -223,14 +310,31 @@ export class AirtrailClient {
|
||||
}
|
||||
|
||||
async getFlight(creds: AirtrailCreds, id: number): Promise<AirtrailFlightRaw | null> {
|
||||
const resp = await request(creds, `/flight/get/${id}`, { method: 'GET' });
|
||||
const flavor = await this.apiFlavor(creds);
|
||||
const flight = await this.getFlightAs(creds, id, flavor);
|
||||
if (flight) return flight;
|
||||
// A 404 from a stale answer (AirTrail was upgraded or downgraded) looks like a deleted
|
||||
// flight, and a caller detaches a deleted flight. Ask the probe again before null.
|
||||
this.flavors.delete(apiBase(creds.baseUrl));
|
||||
const fresh = await this.apiFlavor(creds);
|
||||
return fresh === flavor ? null : this.getFlightAs(creds, id, fresh);
|
||||
}
|
||||
|
||||
private async getFlightAs(creds: AirtrailCreds, id: number, flavor: ApiFlavor): Promise<AirtrailFlightRaw | null> {
|
||||
const v1 = flavor === 'v1';
|
||||
const resp = await request(creds, v1 ? `/v1/flights/${id}` : `/flight/get/${id}`, { method: 'GET' });
|
||||
if (resp.status === 404) return null;
|
||||
if (!resp.ok) throw new AirtrailRequestError(`AirTrail get failed (HTTP ${resp.status})`, resp.status);
|
||||
if (v1) {
|
||||
const data = await parseJson<{ data?: AirtrailV1Flight }>(resp);
|
||||
return data.data ? fromAirtrailV1Flight(data.data) : null;
|
||||
}
|
||||
const data = await parseJson<{ flight?: AirtrailFlightRaw }>(resp);
|
||||
return data.flight ?? null;
|
||||
}
|
||||
|
||||
async saveFlight(creds: AirtrailCreds, payload: AirtrailSavePayload): Promise<{ id?: number }> {
|
||||
if ((await this.apiFlavor(creds)) === 'v1') return this.saveFlightV1(creds, payload);
|
||||
const resp = await request(creds, '/flight/save', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -250,4 +354,148 @@ export class AirtrailClient {
|
||||
const data = await parseJson<{ id?: number }>(resp);
|
||||
return { id: data.id };
|
||||
}
|
||||
|
||||
/**
|
||||
* Which API the instance speaks. `GET /api/v1` is public and answers a
|
||||
* discovery document with `api.version` on 3.13.0 and later. An older
|
||||
* instance answers 404. The client keeps only these two answers. For each
|
||||
* other answer, the client asks again on the next call:
|
||||
* - A 5xx, a timeout or a network error fails this call.
|
||||
* - A page that is not the discovery document (for example a login page in
|
||||
* front of AirTrail) sends this call to the legacy route. The error of
|
||||
* that route explains a wrong URL.
|
||||
*/
|
||||
private async apiFlavor(creds: AirtrailCreds): Promise<ApiFlavor> {
|
||||
const base = apiBase(creds.baseUrl);
|
||||
const known = this.flavors.get(base);
|
||||
if (known && Date.now() - known.at < FLAVOR_TTL_MS) return known.flavor;
|
||||
|
||||
let resp: Response;
|
||||
try {
|
||||
resp = await request(creds, '/v1', { method: 'GET' });
|
||||
} catch (err) {
|
||||
// `GET /api/v1` is public in AirTrail, so a 401 or 403 comes from a proxy in front of it.
|
||||
// It says nothing about the key. Use the legacy route for this call, and do not keep the answer.
|
||||
if (err instanceof AirtrailAuthError || err instanceof AirtrailScopeError) return 'legacy';
|
||||
throw err;
|
||||
}
|
||||
let flavor: ApiFlavor;
|
||||
let keep = true;
|
||||
if (resp.status === 404) {
|
||||
flavor = 'legacy';
|
||||
} else if (resp.ok) {
|
||||
let version: unknown;
|
||||
try {
|
||||
version = (JSON.parse(await resp.text()) as { api?: { version?: unknown } })?.api?.version;
|
||||
} catch {
|
||||
version = undefined;
|
||||
}
|
||||
flavor = version === 'v1' ? 'v1' : 'legacy';
|
||||
keep = flavor === 'v1';
|
||||
} else {
|
||||
throw new AirtrailRequestError(`AirTrail did not answer (HTTP ${resp.status})`, resp.status);
|
||||
}
|
||||
if (keep) {
|
||||
if (this.flavors.size >= 1000) this.flavors.clear();
|
||||
this.flavors.set(base, { flavor, at: Date.now() });
|
||||
}
|
||||
return flavor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every page of `GET /api/v1/flights`, one after the other, because each
|
||||
* request needs the cursor of the page before it.
|
||||
*/
|
||||
private async listFlightsV1(
|
||||
creds: AirtrailCreds,
|
||||
cursor: string | null = null,
|
||||
flights: AirtrailFlightRaw[] = [],
|
||||
seen: Set<string> = new Set(),
|
||||
): Promise<AirtrailFlightRaw[]> {
|
||||
const query = new URLSearchParams({ limit: String(V1_PAGE_LIMIT) });
|
||||
if (cursor) query.set('cursor', cursor);
|
||||
const resp = await request(creds, `/v1/flights?${query}`, { method: 'GET' });
|
||||
if (!resp.ok) throw new AirtrailRequestError(`AirTrail list failed (HTTP ${resp.status})`, resp.status);
|
||||
const body = await parseJson<{ data?: AirtrailV1Flight[]; page?: { nextCursor?: string | null } }>(resp);
|
||||
for (const f of body.data ?? []) flights.push(fromAirtrailV1Flight(f));
|
||||
const next = body.page?.nextCursor ?? null;
|
||||
if (!next) return flights;
|
||||
// A cursor that came before makes an endless loop. AirTrail does not send one, but a caching proxy can.
|
||||
if (seen.has(next)) throw new AirtrailRequestError('AirTrail repeated a page cursor');
|
||||
seen.add(next);
|
||||
if (seen.size >= V1_MAX_PAGES)
|
||||
throw new AirtrailRequestError(`AirTrail has more than ${V1_MAX_PAGES * V1_PAGE_LIMIT} flights`);
|
||||
return this.listFlightsV1(creds, next, flights, seen);
|
||||
}
|
||||
|
||||
private async saveFlightV1(creds: AirtrailCreds, payload: AirtrailSavePayload): Promise<{ id?: number }> {
|
||||
const [from, to, airline, aircraft] = await Promise.all([
|
||||
this.findByCode<AirtrailV1Airport>(creds, 'airports', payload.from, false, 'departure airport'),
|
||||
this.findByCode<AirtrailV1Airport>(creds, 'airports', payload.to, false, 'arrival airport'),
|
||||
payload.airline ? this.findByCode<AirtrailV1Entity>(creds, 'airlines', payload.airline, true, 'airline') : null,
|
||||
payload.aircraft
|
||||
? this.findByCode<AirtrailV1Entity>(creds, 'aircraft', payload.aircraft, true, 'aircraft')
|
||||
: null,
|
||||
]);
|
||||
const people = payload.passengers ?? payload.seats ?? [];
|
||||
const selfUserId = people.some((s) => s.userId === AIRTRAIL_SELF_USER_PLACEHOLDER)
|
||||
? await this.selfUserId(creds)
|
||||
: null;
|
||||
|
||||
let body: Record<string, unknown>;
|
||||
try {
|
||||
body = toAirtrailV1FlightInput(payload, {
|
||||
from,
|
||||
to,
|
||||
airlineId: airline?.id ?? null,
|
||||
aircraftId: aircraft?.id ?? null,
|
||||
selfUserId,
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof AirtrailV1InputError) throw new AirtrailRequestError(err.message, 400);
|
||||
throw err;
|
||||
}
|
||||
|
||||
const update = payload.id !== undefined && payload.id !== null;
|
||||
const resp = await request(creds, update ? `/v1/flights/${payload.id}` : '/v1/flights', {
|
||||
method: update ? 'PUT' : 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!resp.ok) throw await airtrailV1Failure(resp, 'save');
|
||||
// The legacy save answers an id only for a new flight. This method does the same.
|
||||
if (update) return {};
|
||||
const data = await parseJson<{ data?: { id?: number } }>(resp);
|
||||
return { id: data.data?.id };
|
||||
}
|
||||
|
||||
/**
|
||||
* The row whose code is `code`, from a v1 reference search. The search also
|
||||
* matches names, so `pickAirtrailByCode` compares the code again.
|
||||
*/
|
||||
private async findByCode<T extends { id: number; icao?: string | null; iata?: string | null }>(
|
||||
creds: AirtrailCreds,
|
||||
kind: 'airports' | 'airlines' | 'aircraft',
|
||||
code: string,
|
||||
icaoOnly: boolean,
|
||||
label: string,
|
||||
): Promise<T> {
|
||||
const resp = await request(creds, `/v1/${kind}?${new URLSearchParams({ query: code.trim() })}`, {
|
||||
method: 'GET',
|
||||
});
|
||||
if (!resp.ok) throw await airtrailV1Failure(resp, `${label} lookup`);
|
||||
const body = await parseJson<{ data?: T[] }>(resp);
|
||||
const row = pickAirtrailByCode(body.data ?? [], code, icaoOnly);
|
||||
if (!row) throw new AirtrailRequestError(`Invalid ${label}: ${code}`, 400);
|
||||
return row;
|
||||
}
|
||||
|
||||
/** The AirTrail user id of the key owner, which v1 needs where the legacy save took '<USER_ID>'. */
|
||||
private async selfUserId(creds: AirtrailCreds): Promise<string> {
|
||||
const resp = await request(creds, '/v1/me', { method: 'GET' });
|
||||
if (!resp.ok) throw await airtrailV1Failure(resp, 'profile read');
|
||||
const body = await parseJson<{ data?: { id?: unknown } }>(resp);
|
||||
if (typeof body.data?.id !== 'string') throw new AirtrailRequestError('AirTrail did not name the key owner');
|
||||
return body.data.id;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,803 @@
|
||||
import { buildSavePayload } from '../../../../src/nest/integrations/airtrail-sync.helpers';
|
||||
import {
|
||||
fromAirtrailV1Flight,
|
||||
toAirtrailV1FlightInput,
|
||||
type AirtrailV1Airport,
|
||||
} from '../../../../src/nest/integrations/airtrail-v1';
|
||||
import {
|
||||
AirtrailAuthError,
|
||||
AirtrailClient,
|
||||
AirtrailRequestError,
|
||||
AirtrailScopeError,
|
||||
type AirtrailCreds,
|
||||
type AirtrailSavePayload,
|
||||
} from '../../../../src/nest/integrations/airtrail.client';
|
||||
import { canonicalHash } from '../../../../src/nest/integrations/airtrail.mapper';
|
||||
import { safeFetch } from '../../../../src/utils/ssrfGuard';
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
|
||||
vi.mock('../../../../src/utils/ssrfGuard', () => ({
|
||||
checkSsrf: vi.fn(async () => ({ allowed: true, isPrivate: false })),
|
||||
safeFetch: vi.fn(),
|
||||
}));
|
||||
|
||||
const fetchMock = vi.mocked(safeFetch);
|
||||
const creds: AirtrailCreds = { baseUrl: 'https://at.example', apiKey: 'k', allowInsecureTls: false };
|
||||
|
||||
type Route = (url: URL, init: RequestInit) => Response | undefined;
|
||||
let routes: Route[];
|
||||
let calls: { method: string; url: URL; body: unknown }[];
|
||||
|
||||
const json = (body: unknown, status = 200) =>
|
||||
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
|
||||
|
||||
function on(method: string, path: string, answer: (url: URL, body: unknown) => Response) {
|
||||
routes.push((url, init) =>
|
||||
(init.method ?? 'GET') === method && url.pathname === path
|
||||
? answer(url, init.body ? JSON.parse(String(init.body)) : undefined)
|
||||
: undefined,
|
||||
);
|
||||
}
|
||||
|
||||
function present<T>(value: T | null | undefined): T {
|
||||
if (value === null || value === undefined) throw new Error('expected a value');
|
||||
return value;
|
||||
}
|
||||
|
||||
const DISCOVERY = { api: { version: 'v1', minimumSupportedVersion: 'v1' }, instance: { version: '3.14.0' } };
|
||||
|
||||
const LAX: AirtrailV1Airport = {
|
||||
id: 11,
|
||||
icao: 'KLAX',
|
||||
iata: 'LAX',
|
||||
name: 'Los Angeles International Airport',
|
||||
latitude: 33.94,
|
||||
longitude: -118.41,
|
||||
timezone: 'America/Los_Angeles',
|
||||
country: 'US',
|
||||
};
|
||||
const MEL: AirtrailV1Airport = {
|
||||
id: 22,
|
||||
icao: 'YMML',
|
||||
iata: 'MEL',
|
||||
name: 'Melbourne Airport',
|
||||
latitude: -37.67,
|
||||
longitude: 144.84,
|
||||
timezone: 'Australia/Melbourne',
|
||||
country: 'AU',
|
||||
};
|
||||
const QANTAS = { id: 7, name: 'Qantas', icao: 'QFA', iata: 'QF', iconPath: null };
|
||||
|
||||
function v1Flight(id: number, overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id,
|
||||
date: '2026-10-04',
|
||||
datePrecision: 'day',
|
||||
departure: '2026-10-05T05:00:00.000+00:00',
|
||||
arrival: '2026-10-05T20:30:00.000+00:00',
|
||||
departureScheduled: '2026-10-05T05:00:00.000+00:00',
|
||||
arrivalScheduled: '2026-10-05T20:30:00.000+00:00',
|
||||
takeoffScheduled: null,
|
||||
takeoffActual: '2026-10-05T05:21:00.000+00:00',
|
||||
landingScheduled: null,
|
||||
landingActual: null,
|
||||
duration: 55800,
|
||||
departureTerminal: 'B',
|
||||
departureGate: '148',
|
||||
arrivalTerminal: null,
|
||||
arrivalGate: null,
|
||||
flightNumber: 'QF94',
|
||||
aircraftReg: null,
|
||||
note: null,
|
||||
from: LAX,
|
||||
to: MEL,
|
||||
airline: QANTAS,
|
||||
aircraft: null,
|
||||
passengers: [
|
||||
{
|
||||
id: 5,
|
||||
user: { id: 'u-self', username: 'aaron', displayName: 'Aaron' },
|
||||
guestName: null,
|
||||
seat: 'aisle',
|
||||
seatNumber: '4D',
|
||||
seatClass: 'business',
|
||||
flightReason: 'business',
|
||||
},
|
||||
],
|
||||
track: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function v1Instance() {
|
||||
on('GET', '/api/v1', () => json(DISCOVERY));
|
||||
on('GET', '/api/v1/airports', (url) => {
|
||||
const q = url.searchParams.get('query')?.toUpperCase();
|
||||
return json({ data: [LAX, MEL].filter((a) => a.iata === q || a.icao === q), page: { nextCursor: null } });
|
||||
});
|
||||
on('GET', '/api/v1/airlines', (url) => {
|
||||
const q = url.searchParams.get('query')?.toUpperCase();
|
||||
return json({ data: [QANTAS].filter((a) => a.iata === q || a.icao === q), page: { nextCursor: null } });
|
||||
});
|
||||
on('GET', '/api/v1/me', () => json({ data: { id: 'u-self', username: 'aaron' } }));
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
routes = [];
|
||||
calls = [];
|
||||
fetchMock.mockReset();
|
||||
fetchMock.mockImplementation(async (input, init = {}) => {
|
||||
const url = new URL(String(input));
|
||||
calls.push({ method: init.method ?? 'GET', url, body: init.body ? JSON.parse(String(init.body)) : undefined });
|
||||
for (const route of routes) {
|
||||
const answer = route(url, init);
|
||||
if (answer) return answer;
|
||||
}
|
||||
return new Response('<html>not found</html>', { status: 404 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('AirtrailClient picks the API the instance speaks', () => {
|
||||
it('reads every v1 page into the legacy shape, with no scope parameter', async () => {
|
||||
v1Instance();
|
||||
on('GET', '/api/v1/flights', (url) =>
|
||||
url.searchParams.get('cursor') === 'c2'
|
||||
? json({ data: [v1Flight(2)], page: { nextCursor: null } })
|
||||
: json({ data: [v1Flight(1)], page: { nextCursor: 'c2' } }),
|
||||
);
|
||||
|
||||
const flights = await new AirtrailClient().listFlights(creds);
|
||||
|
||||
expect(flights.map((f) => f.id)).toEqual([1, 2]);
|
||||
expect(flights[0].from).toMatchObject({ iata: 'LAX', lat: 33.94, lon: -118.41, tz: 'America/Los_Angeles' });
|
||||
expect(flights[0].passengers?.[0]).toMatchObject({ userId: 'u-self', seatNumber: '4D', flightReason: 'business' });
|
||||
const lists = calls.filter((c) => c.url.pathname === '/api/v1/flights');
|
||||
expect(lists).toHaveLength(2);
|
||||
expect(lists.every((c) => c.url.searchParams.get('limit') === '100' && !c.url.searchParams.has('scope'))).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it('uses the legacy routes when the instance has no /api/v1', async () => {
|
||||
on('GET', '/api/flight/list', () => json({ success: true, flights: [{ id: 9 }] }));
|
||||
|
||||
const flights = await new AirtrailClient().listFlights(creds);
|
||||
|
||||
expect(flights).toEqual([{ id: 9 }]);
|
||||
expect(calls.map((c) => c.url.pathname)).toEqual(['/api/v1', '/api/flight/list']);
|
||||
});
|
||||
|
||||
it('asks once and keeps the answer for the next call', async () => {
|
||||
v1Instance();
|
||||
on('GET', '/api/v1/flights/3', () => json({ data: v1Flight(3) }));
|
||||
const client = new AirtrailClient();
|
||||
|
||||
await client.getFlight(creds, 3);
|
||||
await client.getFlight(creds, 3);
|
||||
|
||||
expect(calls.filter((c) => c.url.pathname === '/api/v1')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('does not keep an answer that is not the discovery document, such as a login page', async () => {
|
||||
on('GET', '/api/v1', () => new Response('<html>sign in</html>', { status: 200 }));
|
||||
on('GET', '/api/flight/get/3', () => json({ success: true, flight: { id: 3 } }));
|
||||
const client = new AirtrailClient();
|
||||
|
||||
expect(await client.getFlight(creds, 3)).toEqual({ id: 3 });
|
||||
await client.getFlight(creds, 3);
|
||||
|
||||
expect(calls.filter((c) => c.url.pathname === '/api/v1')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('gives a v1 flight the same sync hash as the legacy route gave it, so a switch re-syncs nothing', async () => {
|
||||
v1Instance();
|
||||
on('GET', '/api/v1/flights/1', () => json({ data: v1Flight(1) }));
|
||||
const fromV1 = present(await new AirtrailClient().getFlight(creds, 1));
|
||||
const airport = (a: AirtrailV1Airport) => ({
|
||||
id: a.id,
|
||||
icao: a.icao,
|
||||
iata: a.iata,
|
||||
name: a.name,
|
||||
lat: a.latitude,
|
||||
lon: a.longitude,
|
||||
tz: a.timezone,
|
||||
country: a.country,
|
||||
});
|
||||
const { passengers, ...rest } = v1Flight(1);
|
||||
const legacy = {
|
||||
...rest,
|
||||
from: airport(LAX),
|
||||
to: airport(MEL),
|
||||
passengers: passengers.map(({ user, ...p }) => ({ ...p, flightId: 1, userId: user.id, user })),
|
||||
};
|
||||
|
||||
expect(canonicalHash(fromV1)).toBe(canonicalHash(legacy as never));
|
||||
});
|
||||
|
||||
it('answers null for a v1 flight that does not exist', async () => {
|
||||
v1Instance();
|
||||
on('GET', '/api/v1/flights/404', () => json({ error: { code: 'not_found', message: 'Flight not found' } }, 404));
|
||||
|
||||
expect(await new AirtrailClient().getFlight(creds, 404)).toBeNull();
|
||||
});
|
||||
|
||||
it('names the missing scope when v1 refuses the key, and does not call the key invalid', async () => {
|
||||
on('GET', '/api/v1', () => json(DISCOVERY));
|
||||
on('GET', '/api/v1/flights', () =>
|
||||
json({ error: { code: 'insufficient_scope', message: 'The credential requires flight.read.own' } }, 403),
|
||||
);
|
||||
|
||||
const err = await new AirtrailClient().listFlights(creds).catch((e: unknown) => e);
|
||||
|
||||
expect(err).toBeInstanceOf(AirtrailScopeError);
|
||||
expect(err).not.toBeInstanceOf(AirtrailAuthError);
|
||||
expect((err as AirtrailScopeError).scope).toBe('flight.read.own');
|
||||
expect((err as Error).message).toContain('lacks the scope flight.read.own');
|
||||
});
|
||||
|
||||
it('gives the auth error when v1 refuses the key for a reason other than a scope', async () => {
|
||||
on('GET', '/api/v1', () => json(DISCOVERY));
|
||||
on('GET', '/api/v1/flights', () => json({ error: { code: 'unauthorized', message: 'Invalid API key' } }, 401));
|
||||
|
||||
const err = await new AirtrailClient().listFlights(creds).catch((e: unknown) => e);
|
||||
|
||||
expect(err).toBeInstanceOf(AirtrailAuthError);
|
||||
});
|
||||
|
||||
it('stops at the hard page limit, and fails so that it does not give a part of the list', async () => {
|
||||
v1Instance();
|
||||
on('GET', '/api/v1/flights', (url) => {
|
||||
const n = Number(url.searchParams.get('cursor') ?? '0');
|
||||
return json({ data: [v1Flight(n + 1)], page: { nextCursor: String(n + 1) } });
|
||||
});
|
||||
|
||||
const err = await new AirtrailClient().listFlights(creds).catch((e: unknown) => e);
|
||||
|
||||
expect(err).toBeInstanceOf(AirtrailRequestError);
|
||||
expect((err as Error).message).toBe('AirTrail has more than 5000 flights');
|
||||
expect(calls.filter((c) => c.url.pathname === '/api/v1/flights')).toHaveLength(50);
|
||||
});
|
||||
|
||||
it('sends every v1 request through the guarded fetch, with the timeout signal', async () => {
|
||||
v1Instance();
|
||||
on('GET', '/api/v1/flights', () => json({ data: [v1Flight(1)], page: { nextCursor: null } }));
|
||||
on('PUT', '/api/v1/flights/1', () => json({ data: v1Flight(1) }));
|
||||
const client = new AirtrailClient();
|
||||
|
||||
await client.listFlights(creds);
|
||||
await client.saveFlight(creds, {
|
||||
id: 1,
|
||||
from: 'LAX',
|
||||
to: 'MEL',
|
||||
departure: '2026-10-04',
|
||||
seats: [],
|
||||
passengers: [{ userId: '<USER_ID>', guestName: null, seat: null, seatNumber: null, seatClass: null }],
|
||||
});
|
||||
|
||||
const paths = calls.map((c) => c.url.pathname);
|
||||
expect(paths).toEqual(
|
||||
expect.arrayContaining(['/api/v1', '/api/v1/flights', '/api/v1/airports', '/api/v1/me', '/api/v1/flights/1']),
|
||||
);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(calls.length);
|
||||
// The timeout signal on each request, and no override of the default response size cap.
|
||||
for (const [, init, options] of fetchMock.mock.calls) {
|
||||
expect(init?.signal).toBeInstanceOf(AbortSignal);
|
||||
expect(options).not.toHaveProperty('maxBytes');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('AirtrailClient keeps only a clear answer of the discovery probe', () => {
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it('keeps a 404 as the legacy API', async () => {
|
||||
on('GET', '/api/flight/get/3', () => json({ success: true, flight: { id: 3 } }));
|
||||
const client = new AirtrailClient();
|
||||
|
||||
await client.getFlight(creds, 3);
|
||||
await client.getFlight(creds, 3);
|
||||
|
||||
expect(calls.filter((c) => c.url.pathname === '/api/v1')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('fails the call on a 5xx and asks again on the next call', async () => {
|
||||
let down = true;
|
||||
on('GET', '/api/v1', () => (down ? json({ message: 'bad gateway' }, 502) : json(DISCOVERY)));
|
||||
on('GET', '/api/v1/flights/3', () => json({ data: v1Flight(3) }));
|
||||
const client = new AirtrailClient();
|
||||
|
||||
const err = await client.getFlight(creds, 3).catch((e: unknown) => e);
|
||||
down = false;
|
||||
const flight = await client.getFlight(creds, 3);
|
||||
|
||||
expect((err as AirtrailRequestError).status).toBe(502);
|
||||
expect(flight?.id).toBe(3);
|
||||
expect(calls.filter((c) => c.url.pathname === '/api/flight/get/3')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('fails the call on a timeout or a network error and asks again on the next call', async () => {
|
||||
v1Instance();
|
||||
on('GET', '/api/v1/flights/3', () => json({ data: v1Flight(3) }));
|
||||
const client = new AirtrailClient();
|
||||
fetchMock.mockRejectedValueOnce(new DOMException('The operation was aborted due to timeout', 'TimeoutError'));
|
||||
fetchMock.mockRejectedValueOnce(new Error('connect ECONNREFUSED'));
|
||||
|
||||
const timeout = await client.getFlight(creds, 3).catch((e: unknown) => e);
|
||||
const refused = await client.getFlight(creds, 3).catch((e: unknown) => e);
|
||||
const flight = await client.getFlight(creds, 3);
|
||||
|
||||
expect(timeout).toBeInstanceOf(AirtrailRequestError);
|
||||
expect(refused).toBeInstanceOf(AirtrailRequestError);
|
||||
expect(flight?.id).toBe(3);
|
||||
expect(fetchMock.mock.calls.filter(([u]) => new URL(String(u)).pathname === '/api/v1')).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('asks the probe again on a 404 for a flight, so a stale answer does not look like a deleted flight', async () => {
|
||||
let upgraded = false;
|
||||
on('GET', '/api/v1', () => (upgraded ? json(DISCOVERY) : json({}, 404)));
|
||||
on('GET', '/api/v1/flights/3', () => json({ data: v1Flight(3) }));
|
||||
on('GET', '/api/flight/get/3', () => (upgraded ? json({}, 404) : json({ success: true, flight: { id: 3 } })));
|
||||
const client = new AirtrailClient();
|
||||
|
||||
await client.getFlight(creds, 3);
|
||||
upgraded = true; // the next major AirTrail has no /api/flight/* routes
|
||||
const flight = await client.getFlight(creds, 3);
|
||||
|
||||
expect(flight?.id).toBe(3);
|
||||
expect(calls.map((c) => c.url.pathname)).toEqual([
|
||||
'/api/v1',
|
||||
'/api/flight/get/3',
|
||||
'/api/flight/get/3',
|
||||
'/api/v1',
|
||||
'/api/v1/flights/3',
|
||||
]);
|
||||
});
|
||||
|
||||
it('answers null after the probe gives the same API again, because the flight is deleted', async () => {
|
||||
v1Instance();
|
||||
const client = new AirtrailClient();
|
||||
|
||||
expect(await client.getFlight(creds, 404)).toBeNull();
|
||||
// The probe again, but no second read: the probe gave the same API.
|
||||
expect(calls.map((c) => c.url.pathname)).toEqual(['/api/v1', '/api/v1/flights/404', '/api/v1']);
|
||||
});
|
||||
|
||||
it('uses the legacy route, and does not call the key invalid, when a proxy refuses the probe', async () => {
|
||||
on('GET', '/api/v1', () => new Response('Unauthorized', { status: 401 }));
|
||||
on('GET', '/api/flight/get/3', () => json({ success: true, flight: { id: 3 } }));
|
||||
const client = new AirtrailClient();
|
||||
|
||||
expect(await client.getFlight(creds, 3)).toEqual({ id: 3 });
|
||||
await client.getFlight(creds, 3);
|
||||
|
||||
expect(calls.filter((c) => c.url.pathname === '/api/v1')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('keeps the answer for each AirTrail URL apart', async () => {
|
||||
on('GET', '/api/v1', (url) => (url.hostname === 'new.example' ? json(DISCOVERY) : json({}, 404)));
|
||||
on('GET', '/api/v1/flights/3', () => json({ data: v1Flight(3) }));
|
||||
on('GET', '/api/flight/get/3', () => json({ success: true, flight: { id: 3 } }));
|
||||
const client = new AirtrailClient();
|
||||
const old = { ...creds, baseUrl: 'https://old.example' };
|
||||
const fresh = { ...creds, baseUrl: 'https://new.example/' };
|
||||
|
||||
await client.getFlight(creds, 3);
|
||||
await client.getFlight(old, 3);
|
||||
await client.getFlight(fresh, 3);
|
||||
await client.getFlight({ ...fresh, baseUrl: 'https://new.example/api' }, 3);
|
||||
|
||||
const got = calls.filter((c) => c.url.pathname !== '/api/v1').map((c) => `${c.url.hostname}${c.url.pathname}`);
|
||||
expect(got).toEqual([
|
||||
'at.example/api/flight/get/3',
|
||||
'old.example/api/flight/get/3',
|
||||
'new.example/api/v1/flights/3',
|
||||
'new.example/api/v1/flights/3',
|
||||
]);
|
||||
// One probe for each instance. A trailing slash or /api names the same instance.
|
||||
expect(calls.filter((c) => c.url.pathname === '/api/v1').map((c) => c.url.hostname)).toEqual([
|
||||
'at.example',
|
||||
'old.example',
|
||||
'new.example',
|
||||
]);
|
||||
});
|
||||
|
||||
it('asks again after ten minutes, and the flight keeps its sync hash when the instance moved to v1', async () => {
|
||||
vi.useFakeTimers({ toFake: ['Date'] });
|
||||
let upgraded = false;
|
||||
on('GET', '/api/v1', () => (upgraded ? json(DISCOVERY) : json({}, 404)));
|
||||
on('GET', '/api/v1/flights/1', () => json({ data: v1Flight(1) }));
|
||||
const { passengers, ...rest } = v1Flight(1);
|
||||
const legacyFlight = {
|
||||
...rest,
|
||||
from: {
|
||||
id: 11,
|
||||
icao: 'KLAX',
|
||||
iata: 'LAX',
|
||||
name: LAX.name,
|
||||
lat: 33.94,
|
||||
lon: -118.41,
|
||||
tz: LAX.timezone,
|
||||
country: 'US',
|
||||
},
|
||||
to: {
|
||||
id: 22,
|
||||
icao: 'YMML',
|
||||
iata: 'MEL',
|
||||
name: MEL.name,
|
||||
lat: -37.67,
|
||||
lon: 144.84,
|
||||
tz: MEL.timezone,
|
||||
country: 'AU',
|
||||
},
|
||||
passengers: passengers.map(({ user, ...p }) => ({ ...p, flightId: 1, userId: user.id, user })),
|
||||
};
|
||||
on('GET', '/api/flight/get/1', () => json({ success: true, flight: legacyFlight }));
|
||||
const client = new AirtrailClient();
|
||||
|
||||
const before = present(await client.getFlight(creds, 1));
|
||||
upgraded = true;
|
||||
vi.advanceTimersByTime(9 * 60_000);
|
||||
await client.getFlight(creds, 1);
|
||||
vi.advanceTimersByTime(2 * 60_000);
|
||||
const after = present(await client.getFlight(creds, 1));
|
||||
|
||||
expect(calls.map((c) => c.url.pathname)).toEqual([
|
||||
'/api/v1',
|
||||
'/api/flight/get/1',
|
||||
'/api/flight/get/1',
|
||||
'/api/v1',
|
||||
'/api/v1/flights/1',
|
||||
]);
|
||||
expect(canonicalHash(after)).toBe(canonicalHash(before));
|
||||
});
|
||||
});
|
||||
|
||||
/** An instance with no /api/v1: the probe gets the default 404 route. */
|
||||
describe('AirtrailClient on the legacy routes', () => {
|
||||
const payload: AirtrailSavePayload = {
|
||||
id: 41,
|
||||
from: 'KLAX',
|
||||
to: 'YMML',
|
||||
departure: '2026-10-04',
|
||||
departureTime: '22:00',
|
||||
airline: 'QFA',
|
||||
seats: [{ userId: '<USER_ID>', guestName: null, seat: null, seatNumber: '3A', seatClass: null }],
|
||||
passengers: [{ userId: '<USER_ID>', guestName: null, seat: null, seatNumber: '3A', seatClass: null }],
|
||||
};
|
||||
|
||||
it('reads one flight, and answers null for a flight that does not exist', async () => {
|
||||
on('GET', '/api/flight/get/3', () => json({ success: true, flight: { id: 3, flightNumber: 'QF94' } }));
|
||||
const client = new AirtrailClient();
|
||||
|
||||
expect(await client.getFlight(creds, 3)).toEqual({ id: 3, flightNumber: 'QF94' });
|
||||
expect(await client.getFlight(creds, 4)).toBeNull();
|
||||
});
|
||||
|
||||
it('lists the flights with no scope parameter', async () => {
|
||||
on('GET', '/api/flight/list', () => json({ success: true, flights: [{ id: 1 }, { id: 2 }] }));
|
||||
|
||||
expect(await new AirtrailClient().listFlights(creds)).toEqual([{ id: 1 }, { id: 2 }]);
|
||||
const list = present(calls.find((c) => c.url.pathname === '/api/flight/list'));
|
||||
expect(list.url.search).toBe('');
|
||||
});
|
||||
|
||||
it('sends the save payload unchanged, with codes and local times, and answers the id', async () => {
|
||||
on('POST', '/api/flight/save', () => json({ success: true, id: 41 }));
|
||||
|
||||
expect(await new AirtrailClient().saveFlight(creds, payload)).toEqual({ id: 41 });
|
||||
const save = present(calls.find((c) => c.method === 'POST'));
|
||||
expect(save.body).toEqual(payload);
|
||||
// The legacy save needs no lookup and no profile read.
|
||||
expect(calls.map((c) => c.url.pathname)).toEqual(['/api/v1', '/api/flight/save']);
|
||||
});
|
||||
|
||||
it('passes the save error message through', async () => {
|
||||
on('POST', '/api/flight/save', () => json({ success: false, message: 'Invalid airline' }, 400));
|
||||
|
||||
const err = await new AirtrailClient().saveFlight(creds, payload).catch((e: unknown) => e);
|
||||
|
||||
expect(err).toBeInstanceOf(AirtrailRequestError);
|
||||
expect((err as AirtrailRequestError).status).toBe(400);
|
||||
expect((err as Error).message).toBe('Invalid airline');
|
||||
});
|
||||
|
||||
it('gives a refused key the auth error with the generic message', async () => {
|
||||
on('GET', '/api/flight/list', () => new Response('Unauthorized', { status: 401 }));
|
||||
|
||||
const err = await new AirtrailClient().listFlights(creds).catch((e: unknown) => e);
|
||||
|
||||
expect(err).toBeInstanceOf(AirtrailAuthError);
|
||||
expect((err as Error).message).toBe('AirTrail rejected the API key');
|
||||
});
|
||||
|
||||
it('explains a page that is not JSON, such as a wrong URL', async () => {
|
||||
on('GET', '/api/flight/list', () => new Response('<html>app</html>', { status: 200 }));
|
||||
|
||||
const err = await new AirtrailClient().listFlights(creds).catch((e: unknown) => e);
|
||||
|
||||
expect((err as Error).message).toContain('AirTrail returned a non-JSON response');
|
||||
});
|
||||
});
|
||||
|
||||
describe('AirtrailClient writes a flight through v1', () => {
|
||||
it('turns the write-back payload into a PUT with ids, UTC instants and the AirTrail-owned fields', async () => {
|
||||
v1Instance();
|
||||
on('PUT', '/api/v1/flights/41', () => json({ data: v1Flight(41) }));
|
||||
on('GET', '/api/v1/flights/41', () => json({ data: v1Flight(41) }));
|
||||
const existing = present(await new AirtrailClient().getFlight(creds, 41));
|
||||
const reservation = {
|
||||
id: 1,
|
||||
external_id: '41',
|
||||
notes: 'Window if free',
|
||||
reservation_time: '2026-10-04T22:00',
|
||||
reservation_end_time: '2026-10-06T07:30',
|
||||
endpoints: [
|
||||
{ role: 'from', code: 'LAX' },
|
||||
{ role: 'to', code: 'MEL' },
|
||||
],
|
||||
metadata: JSON.stringify({ seat: '3A', airline_code: 'QFA', flight_number: 'QF94' }),
|
||||
};
|
||||
const payload = present(buildSavePayload(reservation, existing));
|
||||
|
||||
expect(await new AirtrailClient().saveFlight(creds, payload)).toEqual({});
|
||||
|
||||
const put = present(calls.find((c) => c.method === 'PUT'));
|
||||
expect(put.url.pathname).toBe('/api/v1/flights/41');
|
||||
expect(put.body).toMatchObject({
|
||||
date: '2026-10-04',
|
||||
fromId: 11,
|
||||
toId: 22,
|
||||
airlineId: 7,
|
||||
aircraftId: null,
|
||||
// 22:00 in Los Angeles (UTC-7) and 07:30 in Melbourne (UTC+11).
|
||||
departure: '2026-10-05T05:00:00.000+00:00',
|
||||
departureScheduled: '2026-10-05T05:00:00.000+00:00',
|
||||
arrival: '2026-10-05T20:30:00.000+00:00',
|
||||
arrivalScheduled: '2026-10-05T20:30:00.000+00:00',
|
||||
duration: 55800,
|
||||
takeoffActual: '2026-10-05T05:21:00.000+00:00',
|
||||
departureTerminal: 'B',
|
||||
departureGate: '148',
|
||||
flightNumber: 'QF94',
|
||||
note: 'Window if free',
|
||||
passengers: [
|
||||
{
|
||||
userId: 'u-self',
|
||||
guestName: null,
|
||||
seat: 'aisle',
|
||||
seatNumber: '3A',
|
||||
seatClass: 'business',
|
||||
flightReason: 'business',
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(put.body).not.toHaveProperty('track');
|
||||
// The owner is named on the flight already, so the profile is not read.
|
||||
expect(calls.some((c) => c.url.pathname === '/api/v1/me')).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps the sync hash when a save changes no time, because AirTrail stores the time string as it gets it', async () => {
|
||||
v1Instance();
|
||||
on('GET', '/api/v1/flights/41', () => json({ data: v1Flight(41) }));
|
||||
on('PUT', '/api/v1/flights/41', () => json({ data: v1Flight(41) }));
|
||||
const existing = present(await new AirtrailClient().getFlight(creds, 41));
|
||||
const reservation = {
|
||||
id: 1,
|
||||
external_id: '41',
|
||||
reservation_time: '2026-10-04T22:00',
|
||||
reservation_end_time: '2026-10-06T07:30',
|
||||
endpoints: [
|
||||
{ role: 'from', code: 'LAX' },
|
||||
{ role: 'to', code: 'MEL' },
|
||||
],
|
||||
metadata: JSON.stringify({ seat: '4D', airline_code: 'QFA', flight_number: 'QF94' }),
|
||||
};
|
||||
|
||||
await new AirtrailClient().saveFlight(creds, present(buildSavePayload(reservation, existing)));
|
||||
|
||||
const body = present(calls.find((c) => c.method === 'PUT')).body as Record<string, unknown>;
|
||||
const times = ['departure', 'arrival', 'departureScheduled', 'arrivalScheduled'];
|
||||
const stored = fromAirtrailV1Flight(v1Flight(41, Object.fromEntries(times.map((k) => [k, body[k]]))) as never);
|
||||
expect(times.map((k) => body[k])).toEqual(times.map((k) => (existing as unknown as Record<string, unknown>)[k]));
|
||||
expect(canonicalHash(stored)).toBe(canonicalHash(existing));
|
||||
});
|
||||
|
||||
it('creates a flight for the key owner with POST and answers its id', async () => {
|
||||
v1Instance();
|
||||
on('POST', '/api/v1/flights', () => json({ data: { id: 77 } }, 201));
|
||||
|
||||
const out = await new AirtrailClient().saveFlight(creds, {
|
||||
from: 'KLAX',
|
||||
to: 'MEL',
|
||||
departure: '2026-10-04',
|
||||
departureTime: '22:00',
|
||||
seats: [],
|
||||
passengers: [{ userId: '<USER_ID>', guestName: null, seat: null, seatNumber: null, seatClass: null }],
|
||||
});
|
||||
|
||||
expect(out).toEqual({ id: 77 });
|
||||
const post = present(calls.find((c) => c.method === 'POST'));
|
||||
expect(post.body).toMatchObject({ fromId: 11, toId: 22, passengers: [{ userId: 'u-self' }] });
|
||||
});
|
||||
|
||||
it('refuses an airline code that only an IATA code matches, as the legacy save did', async () => {
|
||||
v1Instance();
|
||||
|
||||
const err = await new AirtrailClient()
|
||||
.saveFlight(creds, {
|
||||
from: 'LAX',
|
||||
to: 'MEL',
|
||||
departure: '2026-10-04',
|
||||
airline: 'QF',
|
||||
seats: [],
|
||||
passengers: [{ userId: 'u-self', guestName: null, seat: null, seatNumber: null, seatClass: null }],
|
||||
})
|
||||
.catch((e: unknown) => e);
|
||||
|
||||
expect(err).toBeInstanceOf(AirtrailRequestError);
|
||||
expect((err as AirtrailRequestError).status).toBe(400);
|
||||
expect((err as Error).message).toBe('Invalid airline: QF');
|
||||
expect(calls.some((c) => c.method === 'POST' || c.method === 'PUT')).toBe(false);
|
||||
});
|
||||
|
||||
it('passes the v1 validation message through', async () => {
|
||||
v1Instance();
|
||||
on('POST', '/api/v1/flights', () =>
|
||||
json(
|
||||
{
|
||||
error: {
|
||||
code: 'validation_failed',
|
||||
message: 'Request validation failed',
|
||||
details: [{ path: ['flightNumber'] }],
|
||||
},
|
||||
},
|
||||
422,
|
||||
),
|
||||
);
|
||||
|
||||
const err = await new AirtrailClient()
|
||||
.saveFlight(creds, {
|
||||
from: 'LAX',
|
||||
to: 'MEL',
|
||||
departure: '2026-10-04',
|
||||
seats: [],
|
||||
passengers: [{ userId: 'u-self', guestName: null, seat: null, seatNumber: null, seatClass: null }],
|
||||
})
|
||||
.catch((e: unknown) => e);
|
||||
|
||||
expect((err as AirtrailRequestError).status).toBe(422);
|
||||
expect((err as Error).message).toContain('Request validation failed');
|
||||
expect((err as Error).message).toContain('flightNumber');
|
||||
});
|
||||
});
|
||||
|
||||
describe('toAirtrailV1FlightInput keeps the rules of the legacy save', () => {
|
||||
const refs = { from: LAX, to: MEL, airlineId: null, aircraftId: null, selfUserId: 'u-self' };
|
||||
const base = {
|
||||
from: 'LAX',
|
||||
to: 'MEL',
|
||||
departure: '2026-10-04',
|
||||
seats: [],
|
||||
passengers: [{ userId: 'u-self', guestName: null, seat: null, seatNumber: null, seatClass: null }],
|
||||
};
|
||||
|
||||
it('gives no instant for a date without a time, and keeps the date', () => {
|
||||
const body = toAirtrailV1FlightInput(
|
||||
{ ...base, departureTime: null, arrival: '2026-10-06', arrivalTime: null },
|
||||
refs,
|
||||
);
|
||||
expect(body).toMatchObject({ date: '2026-10-04', departure: null, arrival: null, duration: null });
|
||||
});
|
||||
|
||||
it('puts an arrival time without an arrival date on the departure date', () => {
|
||||
const body = toAirtrailV1FlightInput({ ...base, departureTime: '06:00', arrivalTime: '23:00' }, refs);
|
||||
expect(body.arrival).toBe('2026-10-04T12:00:00.000+00:00');
|
||||
});
|
||||
|
||||
it('keeps only the departure for a flight known to the month, at 10:00 UTC', () => {
|
||||
const body = toAirtrailV1FlightInput({ ...base, datePrecision: 'month', departureTime: '22:00' }, refs);
|
||||
expect(body).toMatchObject({ datePrecision: 'month', departure: '2026-10-04T10:00:00.000+00:00', arrival: null });
|
||||
});
|
||||
|
||||
it('gives each passenger without a reason the flight-level reason', () => {
|
||||
const body = toAirtrailV1FlightInput({ ...base, flightReason: 'leisure' }, refs);
|
||||
expect(body.passengers).toEqual([expect.objectContaining({ flightReason: 'leisure' })]);
|
||||
});
|
||||
|
||||
it('refuses a time the clock cannot show', () => {
|
||||
expect(() => toAirtrailV1FlightInput({ ...base, departureTime: '25:00' }, refs)).toThrow('Invalid departure time');
|
||||
});
|
||||
});
|
||||
|
||||
describe('toAirtrailV1FlightInput converts the local wall clock to UTC', () => {
|
||||
const SYD: AirtrailV1Airport = { ...MEL, id: 33, icao: 'YSSY', iata: 'SYD', timezone: 'Australia/Sydney' };
|
||||
const LHR: AirtrailV1Airport = { ...LAX, id: 44, icao: 'EGLL', iata: 'LHR', timezone: 'Europe/London' };
|
||||
const NOZONE: AirtrailV1Airport = { ...LAX, id: 55, timezone: null };
|
||||
const refs = (from: AirtrailV1Airport, to: AirtrailV1Airport) => ({
|
||||
from,
|
||||
to,
|
||||
airlineId: null,
|
||||
aircraftId: null,
|
||||
selfUserId: 'u-self',
|
||||
});
|
||||
const flight = (fields: Partial<AirtrailSavePayload> & { departure: string }): AirtrailSavePayload => ({
|
||||
from: 'X',
|
||||
to: 'Y',
|
||||
seats: [],
|
||||
passengers: [{ userId: 'u-self', guestName: null, seat: null, seatNumber: null, seatClass: null }],
|
||||
...fields,
|
||||
});
|
||||
|
||||
it('moves a late-evening departure west of UTC onto the next UTC day, and keeps the local date', () => {
|
||||
const body = toAirtrailV1FlightInput(flight({ departure: '2026-10-04', departureTime: '23:30' }), refs(LAX, MEL));
|
||||
expect(body).toMatchObject({ date: '2026-10-04', departure: '2026-10-05T06:30:00.000+00:00' });
|
||||
});
|
||||
|
||||
it('moves an early-morning departure east of UTC onto the previous UTC day, and keeps the local date', () => {
|
||||
const body = toAirtrailV1FlightInput(flight({ departure: '2026-10-06', departureTime: '00:30' }), refs(MEL, LAX));
|
||||
expect(body).toMatchObject({ date: '2026-10-06', departure: '2026-10-05T13:30:00.000+00:00' });
|
||||
});
|
||||
|
||||
it('puts each end in the zone of its own airport, across the date line', () => {
|
||||
// QF94: Oct 4 22:00 in Los Angeles (PDT, UTC-7), lands Oct 6 07:30 in Melbourne (AEDT, UTC+11).
|
||||
const body = toAirtrailV1FlightInput(
|
||||
flight({ departure: '2026-10-04', departureTime: '22:00', arrival: '2026-10-06', arrivalTime: '07:30' }),
|
||||
refs(LAX, MEL),
|
||||
);
|
||||
expect(body).toMatchObject({
|
||||
departure: '2026-10-05T05:00:00.000+00:00',
|
||||
arrival: '2026-10-05T20:30:00.000+00:00',
|
||||
duration: 15.5 * 3600,
|
||||
});
|
||||
});
|
||||
|
||||
it('follows a daylight-saving change at the airport', () => {
|
||||
// Sydney moves to UTC+11 on 2026-10-04. Los Angeles moves back to UTC-8 on 2026-11-01.
|
||||
const before = toAirtrailV1FlightInput(flight({ departure: '2026-10-03', departureTime: '10:00' }), refs(SYD, LHR));
|
||||
const after = toAirtrailV1FlightInput(flight({ departure: '2026-10-05', departureTime: '10:00' }), refs(SYD, LHR));
|
||||
const pdt = toAirtrailV1FlightInput(flight({ departure: '2026-10-31', departureTime: '22:00' }), refs(LAX, LHR));
|
||||
const pst = toAirtrailV1FlightInput(flight({ departure: '2026-11-02', departureTime: '22:00' }), refs(LAX, LHR));
|
||||
expect(before.departure).toBe('2026-10-03T00:00:00.000+00:00');
|
||||
expect(after.departure).toBe('2026-10-04T23:00:00.000+00:00');
|
||||
expect(pdt.departure).toBe('2026-11-01T05:00:00.000+00:00');
|
||||
expect(pst.departure).toBe('2026-11-03T06:00:00.000+00:00');
|
||||
});
|
||||
|
||||
it('converts the scheduled times in the same zones as the actual times', () => {
|
||||
const body = toAirtrailV1FlightInput(
|
||||
flight({
|
||||
departure: '2026-10-04',
|
||||
departureScheduled: '2026-10-04',
|
||||
departureScheduledTime: '23:45',
|
||||
arrivalScheduled: '2026-10-05',
|
||||
arrivalScheduledTime: '06:10',
|
||||
}),
|
||||
refs(LAX, LHR),
|
||||
);
|
||||
expect(body).toMatchObject({
|
||||
departureScheduled: '2026-10-05T06:45:00.000+00:00',
|
||||
arrivalScheduled: '2026-10-05T05:10:00.000+00:00',
|
||||
});
|
||||
});
|
||||
|
||||
it('reads the time as UTC at an airport with no zone', () => {
|
||||
const body = toAirtrailV1FlightInput(
|
||||
flight({ departure: '2026-10-04', departureTime: '23:30' }),
|
||||
refs(NOZONE, MEL),
|
||||
);
|
||||
expect(body.departure).toBe('2026-10-04T23:30:00.000+00:00');
|
||||
});
|
||||
|
||||
it('keeps the stored duration for an arrival before the departure', () => {
|
||||
const body = toAirtrailV1FlightInput(
|
||||
// `duration` is not a payload field; it passes through from the AirTrail flight.
|
||||
{
|
||||
...flight({ departure: '2026-10-05', departureTime: '10:00', arrival: '2026-10-05', arrivalTime: '09:00' }),
|
||||
duration: 600,
|
||||
} as AirtrailSavePayload,
|
||||
refs(LHR, LHR),
|
||||
);
|
||||
expect(body.duration).toBe(600);
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,11 @@ import type { ReservationsRepository } from '../../../../src/db/repositories/Res
|
||||
import type { AddonsService } from '../../../../src/nest/addons/addons.service';
|
||||
import { AirtrailLinkService } from '../../../../src/nest/integrations/airtrail-link.service';
|
||||
import { AirtrailSyncService } from '../../../../src/nest/integrations/airtrail-sync.service';
|
||||
import { AirtrailAuthError } from '../../../../src/nest/integrations/airtrail.client';
|
||||
import {
|
||||
AirtrailAuthError,
|
||||
AirtrailRequestError,
|
||||
AirtrailScopeError,
|
||||
} from '../../../../src/nest/integrations/airtrail.client';
|
||||
import type { AirtrailClient } from '../../../../src/nest/integrations/airtrail.client';
|
||||
import type { AirtrailService } from '../../../../src/nest/integrations/airtrail.service';
|
||||
import type { RealtimeService } from '../../../../src/nest/realtime/realtime.service';
|
||||
@@ -184,6 +188,14 @@ describe('pushReservationToAirtrail write gate (#1240)', () => {
|
||||
expect(detachSpy).toHaveBeenCalledWith(5);
|
||||
});
|
||||
|
||||
it('keeps the link when the key only lacks a scope, because the key still works', async () => {
|
||||
isAirtrailWriteEnabled.mockReturnValue(true);
|
||||
getFlight.mockRejectedValue(new AirtrailScopeError('flight.read.own'));
|
||||
await svc.link.pushReservationToAirtrail(5, 9);
|
||||
expect(saveFlight).not.toHaveBeenCalled();
|
||||
expect(detachSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('detaches when the flight is gone from AirTrail — the same as a remote delete', async () => {
|
||||
isAirtrailWriteEnabled.mockReturnValue(true);
|
||||
getFlight.mockResolvedValue(null);
|
||||
@@ -234,6 +246,19 @@ describe('inbound sync multi-leg guard (#1535)', () => {
|
||||
expect(changed).toBe(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['the page limit', new AirtrailRequestError('AirTrail has more than 5000 flights')],
|
||||
['a missing scope', new AirtrailScopeError('flight.read.own')],
|
||||
['a 5xx', new AirtrailRequestError('AirTrail list failed (HTTP 502)', 502)],
|
||||
])('detaches nothing when the list fails on %s', async (_, error) => {
|
||||
withLinkedRow(2);
|
||||
listFlights.mockRejectedValue(error);
|
||||
const { changed } = await svc.sync.runAirtrailSyncForUser(7);
|
||||
expect(updateReservation).not.toHaveBeenCalled();
|
||||
expect(detachSpy).not.toHaveBeenCalled();
|
||||
expect(changed).toBe(0);
|
||||
});
|
||||
|
||||
it('leaves a disconnected owner alone rather than detaching their rows', async () => {
|
||||
withLinkedRow(2);
|
||||
getAirtrailCredentials.mockReturnValue(null);
|
||||
|
||||
Reference in New Issue
Block a user