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
Binary file added docs/screenshots/10-marine-coverage.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
8 changes: 7 additions & 1 deletion service/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@ Airframes coverage aggregation service. Subscribes to NATS processed messages ac
- `npm test` - Run unit and API smoke tests (Vitest, in `test/`)

## Architecture
- NATS subscriber for all processed message subjects (aircraft, marine, reports, flights)
- NATS subscriber for aircraft message and report subjects, and for marine AIS
- Marine events carry no `station` object: `ais_message.created` has the station
UUID and `voyage-position.created` the vessel position, joined on the voyage id
in src/nats/marine-correlator.ts (one reception per AIS message). `/api/v1/health`
reports the join under `marine`.
- Flight events (`v1.aircraft.flight.*`) name no station, so they are not subscribed
- Server-side validation pipeline (coordinates, signal, range plausibility, station trust)
- In-memory sliding window aggregation at H3 resolutions 2-7
- 9 time windows: 1m, 5m, 30m, 1h, 6h, 12h, 24h, 1w, 1mo
Expand Down Expand Up @@ -39,3 +44,4 @@ Airframes coverage aggregation service. Subscribes to NATS processed messages ac
- MAIN_API_URL - Main Airframes API (for station sync)
- PORT - HTTP port (default 3002)
- DATABASE_URL - PostgreSQL connection string
- MARINE_COVERAGE_ENABLED - set to `false` to leave the marine subjects unsubscribed
8 changes: 8 additions & 0 deletions service/src/api/routes/health.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ healthRoutes.get('/health', (c) => {
parsed: nats.messagesParsed,
parseErrors: nats.parseErrors,
},
marine: {
paired: nats.marine.paired,
fromLastPosition: nats.marine.fromLastPosition,
withoutPosition: nats.marine.withoutPosition,
unknownStation: nats.marineUnknownStation,
pending: nats.marine.pendingSize,
trackedVoyages: nats.marine.trackedVoyages,
},
coverage: {
eventsProcessed: stats.eventsProcessed,
eventsRejected: stats.eventsRejected,
Expand Down
4 changes: 4 additions & 0 deletions service/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ export const config = {
// Set this to the production API to match stations by ident and backfill coords.
stationEnrichUrl: process.env.STATION_ENRICH_URL || '',

// Marine (AIS) coverage. About 600 events a second in production; set
// MARINE_COVERAGE_ENABLED=false to leave the marine subjects unsubscribed.
marineCoverageEnabled: process.env.MARINE_COVERAGE_ENABLED !== 'false',

// WebSocket push intervals (ms)
wsCoverageInterval: 5_000,
wsStationInterval: 30_000,
Expand Down
135 changes: 135 additions & 0 deletions service/src/nats/marine-correlator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import { readPosition } from './parsers/aircraft.js';

/**
* Marine events do not carry a `station` object the way aircraft events do.
* For every AIS sentence the aggregation server publishes
*
* v1.marine.ais_message.created { source, ais_message: { marine_voyage_id, station_id (station UUID), ... } }
* v1.marine.voyage-position.created { source, voyage_position: { marine_voyage_id, latitude, longitude, ... } }
*
* in that order, the second only when the sentence held a position. The
* receiving station is in the first and the vessel position in the second, so
* the two are joined here on the voyage id. Each AIS message yields exactly
* one reception.
*/
export interface MarineReception {
stationUuid: string;
lat: number | null;
lon: number | null;
source: string;
}

interface Pending {
stationUuid: string;
source: string;
at: number;
}

interface LastPosition {
lat: number;
lon: number;
at: number;
}

/** How long an AIS message waits for its position event */
export const PAIR_WINDOW_MS = 5_000;
/** How long a vessel's last position stands in for a message without one (static data, etc.) */
export const LAST_POSITION_TTL_MS = 120_000;
/** Upper bound on messages waiting for a position; beyond it the oldest are released early */
export const MAX_PENDING = 50_000;

export class MarineCorrelator {
private pending = new Map<string, Pending[]>();
private pendingCount = 0;
private lastPosition = new Map<string, LastPosition>();
private lastPrune = 0;

public paired = 0;
public fromLastPosition = 0;
public withoutPosition = 0;

constructor(private readonly emit: (reception: MarineReception) => void) {}

onAisMessage(data: any, now: number = Date.now()): void {
const message = data?.ais_message;
const voyageId = toKey(message?.marine_voyage_id);
const stationUuid = message?.station_id;
if (voyageId === null || typeof stationUuid !== 'string' || stationUuid === '') return;

const entry: Pending = { stationUuid, source: data?.source?.name ?? 'aiscatcher', at: now };
const list = this.pending.get(voyageId);
if (list) list.push(entry);
else this.pending.set(voyageId, [entry]);
this.pendingCount++;

if (this.pendingCount > MAX_PENDING) this.flush(now, true);
}

onVoyagePosition(data: any, now: number = Date.now()): void {
const row = data?.voyage_position;
const voyageId = toKey(row?.marine_voyage_id);
if (voyageId === null) return;
const position = readPosition(row);
if (!position) return;

this.lastPosition.set(voyageId, { lat: position.lat, lon: position.lon, at: now });

const list = this.pending.get(voyageId);
if (!list) return;
this.pending.delete(voyageId);
this.pendingCount -= list.length;
for (const entry of list) {
this.paired++;
this.emit({ stationUuid: entry.stationUuid, lat: position.lat, lon: position.lon, source: entry.source });
}
}

/**
* Release messages whose position event did not arrive. They take the
* vessel's last known position when it is recent, and otherwise count as a
* reception without a position. Call about once a second.
*/
flush(now: number = Date.now(), force = false): void {
for (const [voyageId, list] of this.pending) {
let keep = 0;
for (const entry of list) {
if (!force && now - entry.at < PAIR_WINDOW_MS) {
list[keep++] = entry;
continue;
}
const last = this.lastPosition.get(voyageId);
if (last && now - last.at <= LAST_POSITION_TTL_MS) {
this.fromLastPosition++;
this.emit({ stationUuid: entry.stationUuid, lat: last.lat, lon: last.lon, source: entry.source });
} else {
this.withoutPosition++;
this.emit({ stationUuid: entry.stationUuid, lat: null, lon: null, source: entry.source });
}
this.pendingCount--;
}
if (keep === 0) this.pending.delete(voyageId);
else list.length = keep;
}

if (now - this.lastPrune >= 30_000) {
this.lastPrune = now;
for (const [voyageId, last] of this.lastPosition) {
if (now - last.at > LAST_POSITION_TTL_MS) this.lastPosition.delete(voyageId);
}
}
}

get pendingSize(): number {
return this.pendingCount;
}

get trackedVoyages(): number {
return this.lastPosition.size;
}
}

function toKey(value: unknown): string | null {
if (typeof value === 'number' && Number.isFinite(value)) return String(value);
if (typeof value === 'string' && value !== '') return value;
return null;
}
32 changes: 0 additions & 32 deletions service/src/nats/parsers/aircraft.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,35 +78,3 @@ export function parseAircraftMessageCreated(data: AircraftMessagePayload): Cover
if (data.station && data.messageReport?.id != null) return null;
return parseAircraftMessage(data);
}

/**
* Parse an aircraft flight update NATS event.
* Flight updates often have richer position data than messages.
*/
export function parseAircraftFlight(data: AircraftMessagePayload): CoverageEvent | null {
const station = data.station;

const stationId = toStationId(station?.id);
if (stationId === null || !station?.uuid) return null;

const position = readPosition(data.flight);
if (!position) return null;

return {
stationId,
stationUuid: station.uuid,
targetLat: position.lat,
targetLon: position.lon,
targetAlt: position.alt,
transportType: 'aircraft',
sourceType: station.source_type ?? data.source?.name ?? 'unknown',
source: data.source?.name ?? 'unknown',
frequency: null,
signalLevel: null,
errorCount: null,
timestamp: new Date(),
hasTargetPosition: true,
_natsStationLat: station.latitude ?? station.fuzzed_latitude,
_natsStationLon: station.longitude ?? station.fuzzed_longitude,
};
}
111 changes: 0 additions & 111 deletions service/src/nats/parsers/marine.ts

This file was deleted.

Loading