Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions service/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,15 @@ Airframes coverage aggregation service. Subscribes to NATS processed messages ac
- Imported area feeds (station idents in `AREA_FEED_STATIONS`, default `NCT`) are
treated like satellite relays: every position is kept, with no range limit and
no range or direction for the station
- A station whose location nobody entered only has a GeoIP guess (the provider's
city, often hundreds of km off). Such a station is placed at the centre of the
positions it hears (median of the last 200) once those form one group no wider
than the radio's range and the centre is further from the registered spot than
the group is wide (at least 100 km): src/compute/heard-location.ts and
`placeByHeard` in the store. Owner-entered locations (`userLatitude` in the main
API) are never moved. Station responses carry `locationSource` (`registered` or
`heard`), health reports `stationsPlacedByHeard`, and the estimates are saved
with the snapshots. Nothing is written back to the main API.
- Hono REST API on port 3002
- Prometheus metrics at `GET /metrics` (root of the same port, prom-client). The
port is public, so the route needs `MONITORING_TOKEN` as `Authorization: Bearer`
Expand Down
107 changes: 105 additions & 2 deletions service/src/aggregation/coverage-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,17 @@ import { validateCoordinate } from '../validation/coordinate-validator.js';
import { validateSignal, isPlausibleRange } from '../validation/signal-validator.js';
import { checkStationTrust } from '../validation/station-trust.js';
import { sourceFamily } from '../compute/source-family.js';
import { HeardLocationEstimator, type HeardLocation } from '../compute/heard-location.js';
import { config } from '../config.js';
import { WINDOW_CONFIGS, H3_RESOLUTION_CONFIGS } from '../types/coverage.js';
import type { CellAggregation, CellResponse, StationCoverage, WindowConfig } from '../types/coverage.js';
import type { CoverageEvent, StationMeta, TransportType } from '../types/events.js';

/** A heard centre this close to the registered location does not move the station */
const HEARD_MIN_OFFSET_KM = 100;
/** A station already placed by what it hears moves again only for a shift this large */
const HEARD_MOVE_KM = 25;

/** Grid used for coverage area figures */
const AREA_RESOLUTION = 3;

Expand Down Expand Up @@ -56,6 +62,13 @@ export class CoverageStore {
*/
private outOfRangeByStation = new Map<number, { near: number; far: number; maxDistanceKm: number }>();

/** Where stations without an owner-entered location appear to be, from what they hear */
private heard = new HeardLocationEstimator();
/** Stations whose restored estimate has been applied since start */
private heardApplied = new Set<number>();
/** How many times a station was moved to, or back from, where it is heard */
public stationsRelocated = 0;

constructor() {
// Initialize sliding windows for each resolution x window combination
// Windows a resolution is not kept for stay empty; they only keep indexing consistent.
Expand Down Expand Up @@ -91,11 +104,15 @@ export class CoverageStore {
// There is deliberately no per-station rate limit: a receiver near a busy
// port or airport is legitimately far busier than the rest.

// 2b. A station without an owner-entered location is placed where it is heard
this.placeByHeard(event);

// 3. Determine station coordinates
// Prefer authoritative (synced from main API), fall back to NATS payload
// when the synced station has no coordinates (common when GeoIP isn't populated)
let stationLat = trust.stationLat;
let stationLon = trust.stationLon;
const located = this.stationMap.get(event.stationId);
let stationLat = located?.latitude ?? trust.stationLat;
let stationLon = located?.longitude ?? trust.stationLon;

const stationHasCoords = Number.isFinite(stationLat) && Number.isFinite(stationLon)
&& !(Math.abs(stationLat) < 0.01 && Math.abs(stationLon) < 0.01);
Expand Down Expand Up @@ -234,6 +251,92 @@ export class CoverageStore {
this.rejections[reason] = (this.rejections[reason] ?? 0) + 1;
}

/**
* Feed the station's heard-location estimate with this event's position and
* move the station when the estimate says the registered spot is wrong.
*
* Applies only to stations whose location nobody entered (a GeoIP guess, often
* the internet provider's city), that hear their targets directly, and that
* are not area feeds. The station moves to the centre of what it hears when
* the heard positions form one group no wider than the radio's range and that
* centre is further from the registered spot than the group is wide (and at
* least 100 km): a real antenna in the right place sits inside its own group.
*/
private placeByHeard(event: CoverageEvent): void {
const meta = this.stationMap.get(event.stationId);
if (!meta || meta.ownerLocated !== false) return;
if (sourceFamily(event.sourceType) === 'satcom') return;
if (config.areaFeedStations.has(meta.ident.toLowerCase())) return;

let recomputed = false;
if (event.hasTargetPosition && event.targetLat !== null && event.targetLon !== null
&& validateCoordinate(event.targetLat, event.targetLon).valid) {
recomputed = this.heard.add(event.stationId, event.targetLat, event.targetLon);
}

// An estimate restored after a restart is applied on the station's first
// event. The saved sectors were measured from it, so they are kept.
const restored = !this.heardApplied.has(event.stationId);
if (!recomputed && !restored) return;
this.heardApplied.add(event.stationId);

const estimate = this.heard.get(event.stationId);
if (!estimate) return;

const regLat = meta.registeredLatitude ?? meta.latitude;
const regLon = meta.registeredLongitude ?? meta.longitude;
const registered = Number.isFinite(regLat) && Number.isFinite(regLon)
&& !(Math.abs(regLat) < 0.01 && Math.abs(regLon) < 0.01);

const oneAntenna = estimate.spreadKm <= maxRangeKm(event.sourceType);
const offsetKm = registered
? haversineDistance(regLat, regLon, estimate.latitude, estimate.longitude)
: Infinity;
const useHeard = oneAntenna && offsetKm > Math.max(HEARD_MIN_OFFSET_KM, estimate.spreadKm);

if (useHeard) {
// Small drifts of the centre are not worth throwing the sectors away for
if (meta.locationSource === 'heard'
&& haversineDistance(meta.latitude, meta.longitude, estimate.latitude, estimate.longitude) < HEARD_MOVE_KM) return;
meta.latitude = estimate.latitude;
meta.longitude = estimate.longitude;
meta.locationSource = 'heard';
} else {
if (meta.locationSource !== 'heard') return;
meta.latitude = regLat;
meta.longitude = regLon;
meta.locationSource = 'registered';
}

if (recomputed) {
for (const sw of new Set(this.stationWindows)) sw.clearSectors(event.stationId);
this.outOfRangeByStation.delete(event.stationId);
this.stationsRelocated++;
}
}

/** Heard-location estimates, for saving across restarts */
getHeardLocations(): Array<HeardLocation & { stationId: number }> {
return [...this.heard.entries()].map(([stationId, location]) => ({ stationId, ...location }));
}

loadHeardLocations(saved: any[]): void {
for (const s of saved) {
if (!Number.isFinite(s?.stationId) || !Number.isFinite(s.latitude) || !Number.isFinite(s.longitude)
|| !Number.isFinite(s.spreadKm)) continue;
this.heard.restore(s.stationId, {
latitude: s.latitude, longitude: s.longitude, spreadKm: s.spreadKm, samples: s.samples ?? 0,
});
}
}

/** Stations currently shown where they are heard, not where they are registered */
getStationsPlacedByHeard(): number {
let n = 0;
for (const meta of this.stationMap.values()) if (meta.locationSource === 'heard') n++;
return n;
}

private discardPosition(reason: string): void {
this.positionsDiscarded[reason] = (this.positionsDiscarded[reason] ?? 0) + 1;
}
Expand Down
17 changes: 17 additions & 0 deletions service/src/aggregation/station-window.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,23 @@ export class StationSlidingWindow {
return ids;
}

/**
* Forget a station's range and direction, keeping its message counts. Used
* when the station turns out to be somewhere else: distances and bearings
* measured from the old spot mean nothing.
*/
clearSectors(stationId: number): void {
const prefix = `${stationId}:`;
for (const slice of this.slices) {
for (const [key, data] of slice) {
if (!key.startsWith(prefix)) continue;
data.sectorMaxDist.fill(0);
data.sectorMsgCount.fill(0);
data.sectorLevelSum.fill(0);
}
}
}

/** Message total and furthest reception per station across all slices, in one pass */
stationTotals(): Map<number, { totalMessages: number; maxDistance: number }> {
const totals = new Map<number, { totalMessages: number; maxDistance: number }>();
Expand Down
1 change: 1 addition & 0 deletions service/src/api/routes/coverage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ coverageRoutes.get('/stations/:id', (c) => {
stationId,
ident: station.ident,
position: { lat: station.latitude, lon: station.longitude },
locationSource: station.locationSource ?? 'registered',
sourceType: station.sourceType,
window: windowName,
messageCount: windowData.messageCount,
Expand Down
1 change: 1 addition & 0 deletions service/src/api/routes/health.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ healthRoutes.get('/health', (c) => {
positionsDiscarded: stats.positionsDiscarded,
outOfRange: stats.outOfRange,
outOfRangeStations: store.getOutOfRangeStations(),
stationsPlacedByHeard: store.getStationsPlacedByHeard(),
stationsTracked: stats.stationsTracked,
activeCells: stats.activeCells,
cellsInMemory: store.getCellsInMemory(),
Expand Down
1 change: 1 addition & 0 deletions service/src/api/routes/stations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ stationRoutes.get('/', (c) => {
ident: meta.ident,
latitude: meta.latitude,
longitude: meta.longitude,
locationSource: meta.locationSource ?? 'registered',
sourceType: meta.sourceType,
messageCount: counts.messageCount,
messagesWithPosition: cov?.messagesWithPosition ?? 0,
Expand Down
102 changes: 102 additions & 0 deletions service/src/compute/heard-location.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import { haversineDistance } from './distance.js';

/** Where a station appears to be, judged from the positions it hears */
export interface HeardLocation {
latitude: number;
longitude: number;
/** 90% of the sampled positions lie within this distance of the centre */
spreadKm: number;
samples: number;
}

/** Positions kept per station: recent ones, so a moved antenna is followed */
const SAMPLE_CAPACITY = 200;
/** Fewer positions than this say nothing reliable */
const MIN_SAMPLES = 30;
/** Recompute the centre every this many new positions */
const RECOMPUTE_EVERY = 25;

interface Samples {
/** lat, lon pairs in a ring */
points: Float64Array;
count: number;
next: number;
sinceCompute: number;
}

function median(values: number[]): number {
values.sort((a, b) => a - b);
const mid = values.length >> 1;
return values.length % 2 ? values[mid] : (values[mid - 1] + values[mid]) / 2;
}

/**
* Estimates a receiver's location as the centre of the positions it hears.
*
* A station without an owner-entered location only has the GeoIP guess for its
* internet address, which is the provider's city and can be hundreds of
* kilometres from the antenna. What a VHF receiver hears, though, lies in a
* tight group around it. The centre is the median latitude and longitude (so a
* few bogus positions do not move it), and the spread tells a single antenna
* from a relay of a wide area.
*/
export class HeardLocationEstimator {
private samples = new Map<number, Samples>();
private estimates = new Map<number, HeardLocation>();

/** Add a heard position. Returns true when the station's estimate was recomputed. */
add(stationId: number, latitude: number, longitude: number): boolean {
let s = this.samples.get(stationId);
if (!s) {
s = { points: new Float64Array(SAMPLE_CAPACITY * 2), count: 0, next: 0, sinceCompute: 0 };
this.samples.set(stationId, s);
}
s.points[s.next * 2] = latitude;
s.points[s.next * 2 + 1] = longitude;
s.next = (s.next + 1) % SAMPLE_CAPACITY;
if (s.count < SAMPLE_CAPACITY) s.count++;
s.sinceCompute++;

if (s.count < MIN_SAMPLES) return false;
if (s.sinceCompute < RECOMPUTE_EVERY && this.estimates.has(stationId)) return false;
s.sinceCompute = 0;
this.estimates.set(stationId, this.compute(s));
return true;
}

private compute(s: Samples): HeardLocation {
const lats: number[] = [];
const lons: number[] = [];
// Longitudes are taken relative to the first sample so a cluster across the
// antimeridian does not average out to the other side of the world.
const ref = s.points[1];
for (let i = 0; i < s.count; i++) {
lats.push(s.points[i * 2]);
lons.push(((s.points[i * 2 + 1] - ref + 540) % 360) - 180);
}
const latitude = median(lats.slice());
const longitude = ((median(lons.slice()) + ref + 540) % 360) - 180;

const distances: number[] = [];
for (let i = 0; i < s.count; i++) {
distances.push(haversineDistance(latitude, longitude, s.points[i * 2], s.points[i * 2 + 1]));
}
distances.sort((a, b) => a - b);
const spreadKm = distances[Math.min(distances.length - 1, Math.floor(distances.length * 0.9))];

return { latitude, longitude, spreadKm, samples: s.count };
}

get(stationId: number): HeardLocation | undefined {
return this.estimates.get(stationId);
}

/** Restore an estimate saved before a restart */
restore(stationId: number, location: HeardLocation): void {
this.estimates.set(stationId, location);
}

entries(): IterableIterator<[number, HeardLocation]> {
return this.estimates.entries();
}
}
2 changes: 1 addition & 1 deletion service/src/compute/signal-analysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export const MAX_RANGE_KM: Record<SourceFamily, number> = {
vdl: 400,
hfdl: 4000,
satcom: 50000, // relayed by satellite - effectively unlimited
ais: 100, // VHF line of sight; elevated antennas reach 60 nm and more
ais: 250, // 300 km with the 20% margin in isPlausibleRange; good coastal antennas were seen at 140-240 km
unknown: 1000,
};

Expand Down
26 changes: 25 additions & 1 deletion service/src/data/persistence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,19 @@ export class Persistence {
}
}

// Where GeoIP-located stations are heard, so they are not shown in the
// wrong place again for the first minutes after every restart
const heard = this.store.getHeardLocations();
if (heard.length > 0) {
await db.query(`DELETE FROM coverage_snapshots WHERE snapshot_type = 'heard_locations'`);
await db.query(
`INSERT INTO coverage_snapshots (snapshot_type, window_name, resolution, data)
VALUES ('heard_locations', 'all', 0, $1)`,
[JSON.stringify(heard)]
);
saved++;
}

jobStatus.snapshotLastSuccess = Date.now() / 1000;
jobStatus.snapshotDurationSeconds = (Date.now() - startedAt) / 1000;

Expand Down Expand Up @@ -144,7 +157,18 @@ export class Persistence {
}
}

console.log(`[Persistence] Loaded ${h3Loaded} H3 cells, ${stationsLoaded} station coverages`);
const heardResult = await db.query(
`SELECT data FROM coverage_snapshots
WHERE snapshot_type = 'heard_locations'
ORDER BY created_at DESC LIMIT 1`
);
const heard = heardResult.rows[0]?.data;
if (Array.isArray(heard)) this.store.loadHeardLocations(heard);

console.log(
`[Persistence] Loaded ${h3Loaded} H3 cells, ${stationsLoaded} station coverages, ` +
`${Array.isArray(heard) ? heard.length : 0} heard locations`
);
} catch (err) {
console.error('[Persistence] Load failed:', err instanceof Error ? err.message : err);
}
Expand Down
16 changes: 14 additions & 2 deletions service/src/sync/station-sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,12 +102,24 @@ export class StationSync {
}
}

// Only an owner-entered location is taken as the antenna's position. Anything
// else is a GeoIP guess, which the coverage store may replace with the centre
// of what the station hears; that placement survives the sync.
const ownerLocated = Number.isFinite(parseFloat(s.userLatitude))
&& Number.isFinite(parseFloat(s.userLongitude));
const prev = this.stationMap.get(id);
const keepHeard = !ownerLocated && prev?.locationSource === 'heard';

this.stationMap.set(id, {
id,
uuid: s.uuid ?? '',
ident: s.ident ?? '',
latitude: lat,
longitude: lon,
latitude: keepHeard ? prev.latitude : lat,
longitude: keepHeard ? prev.longitude : lon,
registeredLatitude: lat,
registeredLongitude: lon,
ownerLocated,
locationSource: keepHeard ? 'heard' : 'registered',
sourceType: s.sourceType ?? '',
status: s.status ?? 'unknown',
flagged: s.flagged ?? false,
Expand Down
Loading