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
2 changes: 2 additions & 0 deletions .github/workflows/service.yml
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ jobs:
with:
context: service
push: true
build-args: |
GIT_SHA=${{ github.sha }}
# The sha tag gives production an immutable reference to pin.
tags: |
ghcr.io/airframesio/coverage-service:latest
Expand Down
17 changes: 16 additions & 1 deletion service/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,28 @@ Airframes coverage aggregation service. Subscribes to NATS processed messages ac
- Stations flagged by the main API are accepted (the flag marks the busiest
stations); blocked stations are rejected. `/api/v1/health` reports rejections
and discarded positions by reason, and `cellsInMemory`.
- No per-station rate limit (busy receivers are legitimate). `/api/v1/health` reports
`outOfRange` positions by radio family (`near` = within twice the range limit,
`far` = beyond it)
- 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
- 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`
or `X-Monitoring-Token` and answers 401 when the variable is unset. Every value
is read at scrape time from the counters `/api/v1/health` reports
(src/metrics/metrics.ts). Names follow the Airframes metrics contract, prefix
`coverage_`; keep labels to small fixed sets (no station ids or idents).
- Station metadata synced from main API (authoritative coordinates)

## Key Directories
- src/nats/ - NATS subscription and message parsers
- src/validation/ - Coordinate, signal, trust, and rate validation
- src/validation/ - Coordinate, signal and trust validation
- src/compute/ - Distance, bearing, H3 indexing, signal analysis
- src/aggregation/ - Sliding windows and coverage store
- src/api/ - Hono HTTP routes
- src/metrics/ - Prometheus registry and job status for `/metrics`
- src/sync/ - Station metadata sync from main API

## Environment Variables
Expand All @@ -44,4 +57,6 @@ 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
- AREA_FEED_STATIONS - comma-separated idents of stations that relay an area feed (default `NCT`)
- MONITORING_TOKEN - token Prometheus sends to scrape `/metrics`; unset means the route always answers 401
- MARINE_COVERAGE_ENABLED - set to `false` to leave the marine subjects unsubscribed
4 changes: 4 additions & 0 deletions service/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ WORKDIR /app
ENV NODE_ENV=production
ENV PORT=3002

# Commit the image was built from, reported as coverage_build_info{commit}
ARG GIT_SHA=unknown
ENV GIT_SHA=$GIT_SHA

RUN addgroup --system --gid 1001 appgroup && \
adduser --system --uid 1001 appuser

Expand Down
39 changes: 39 additions & 0 deletions service/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions service/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"hono": "^4.13.18",
"ioredis": "^6.0.0",
"pg": "^8.23.1",
"prom-client": "^15.1.3",
"ws": "^8.23.0",
"zod": "^4.6.7"
},
Expand Down
114 changes: 53 additions & 61 deletions service/src/aggregation/coverage-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,10 @@ import { StationSlidingWindow } from './station-window.js';
import { cellArea } from 'h3-js';
import { indexPoint, shouldMaintainResolution } from '../compute/h3-indexer.js';
import { haversineDistance, bearing, bearingToSector } from '../compute/distance.js';
import { computeConfidence } from '../compute/signal-analysis.js';
import { computeConfidence, maxRangeKm } from '../compute/signal-analysis.js';
import { validateCoordinate } from '../validation/coordinate-validator.js';
import { validateSignal, isPlausibleRange } from '../validation/signal-validator.js';
import { checkStationTrust } from '../validation/station-trust.js';
import { RateLimiter } from '../validation/rate-limiter.js';
import { sourceFamily } from '../compute/source-family.js';
import { config } from '../config.js';
import { WINDOW_CONFIGS, H3_RESOLUTION_CONFIGS } from '../types/coverage.js';
Expand All @@ -32,17 +31,24 @@ export class CoverageStore {
/** Synced station metadata from main API */
public stationMap = new Map<number, StationMeta>();
/** Rate limiter */
private rateLimiter = new RateLimiter();

// Metrics
public eventsProcessed = 0;
/** Accepted events by radio family. Sums to eventsProcessed. */
public processedBySource: Record<string, number> = {};
public eventsRejected = 0;
public eventsWithPosition = 0;
public eventsWithoutPosition = 0;
/** Why events were rejected, by reason. Sums to eventsRejected. */
public rejections: Record<string, number> = {};
/** Events kept, but whose target position was discarded, by reason */
public positionsDiscarded: Record<string, number> = {};
/**
* Out-of-range positions by radio family: how many were within twice the
* limit (the limit may be too tight) and how many beyond it (a stale target
* position or a wrongly located station).
*/
public outOfRange: Record<string, { near: number; far: number }> = {};

constructor() {
// Initialize sliding windows for each resolution x window combination
Expand Down Expand Up @@ -76,11 +82,8 @@ export class CoverageStore {
return;
}

// 2. Rate limiting
if (!this.rateLimiter.check(event.stationId)) {
this.reject('rate_limited');
return;
}
// There is deliberately no per-station rate limit: a receiver near a busy
// port or airport is legitimately far busier than the rest.

// 3. Determine station coordinates
// Prefer authoritative (synced from main API), fall back to NATS payload
Expand Down Expand Up @@ -136,8 +139,13 @@ export class CoverageStore {

// Distance and bearing only mean something when we know where the station
// is, and when the station hears the target directly. A satellite relay
// says nothing about the receiver's own range or direction.
directional = stationLocated && sourceFamily(event.sourceType) !== 'satcom';
// says nothing about the receiver's own range or direction, and neither
// does an imported area feed (see config.areaFeedStations): its positions
// are kept wherever they are, with no range limit.
const ident = this.stationMap.get(event.stationId)?.ident.toLowerCase() ?? '';
directional = stationLocated
&& sourceFamily(event.sourceType) !== 'satcom'
&& !config.areaFeedStations.has(ident);
if (directional) {
distance = haversineDistance(stationLat, stationLon, event.targetLat, event.targetLon);
brng = bearing(stationLat, stationLon, event.targetLat, event.targetLon);
Expand All @@ -147,6 +155,7 @@ export class CoverageStore {
// the event as proof the station is receiving and drop the position.
if (!isPlausibleRange(event.sourceType, distance)) {
this.discardPosition('out_of_range');
this.countOutOfRange(event.sourceType, distance);
hasValidTarget = false;
directional = false;
distance = 0;
Expand All @@ -160,6 +169,8 @@ export class CoverageStore {
else this.eventsWithoutPosition++;

this.eventsProcessed++;
const family = sourceFamily(event.sourceType);
this.processedBySource[family] = (this.processedBySource[family] ?? 0) + 1;

// 5. Index into H3 cells
// If we have a target position, index at the target (aircraft/vessel) location.
Expand Down Expand Up @@ -221,6 +232,13 @@ export class CoverageStore {
this.positionsDiscarded[reason] = (this.positionsDiscarded[reason] ?? 0) + 1;
}

private countOutOfRange(sourceType: string, distanceKm: number): void {
const family = sourceFamily(sourceType);
const entry = (this.outOfRange[family] ??= { near: 0, far: 0 });
if (distanceKm <= maxRangeKm(sourceType) * 2) entry.near++;
else entry.far++;
}

private updateStationCoverage(
event: CoverageEvent,
distance: number,
Expand Down Expand Up @@ -316,63 +334,34 @@ export class CoverageStore {
}

/**
* Get per-station message counts derived from the H3 sliding windows.
* Unlike StationCoverage (which accumulates forever), this properly
* reflects only messages within the selected time window.
* Per-station message counts within a time window, from the per-station
* sliding windows, which count every accepted event exactly once.
*
* These must not be derived from the H3 cells: a cell's count is the total
* of every station that reported into it, so crediting it to each of those
* stations multiplies the figure wherever stations share a cell, and events
* without a position are in no cell at all.
*/
getStationMessageCounts(windowName: string): Map<number, { messageCount: number; maxDistance: number }> {
const stationCounts = new Map<number, { messageCount: number; maxDistance: number }>();
const wi = WINDOW_CONFIGS.findIndex(c => c.name === windowName);
if (wi === -1) return stationCounts;

const ri = H3_RESOLUTION_CONFIGS.findIndex(c => c.resolution === 3);

// Scan the requested window AND all shorter windows.
// A station visible in a shorter window must appear in all longer windows.
// Use the requested window's counts as the primary, but ensure stations
// from shorter windows are included.
const windowsToCheck = ri !== -1
? Array.from({ length: wi + 1 }, (_, i) => i)
: [];

for (const checkWi of windowsToCheck) {
if (ri === -1) continue;
const aggregated = this.aggregated(ri, checkWi);

// Sum this window's cells per station on their own. Windows overlap, so
// totals from different windows must never be added together.
const windowCounts = new Map<number, number>();
for (const [, cell] of aggregated) {
for (const stationId of cellStationIds(cell)) {
windowCounts.set(stationId, (windowCounts.get(stationId) ?? 0) + cell.messageCount);
const existing = stationCounts.get(stationId);
if (existing) {
existing.maxDistance = Math.max(existing.maxDistance, cell.maxDistance);
} else {
stationCounts.set(stationId, { messageCount: 0, maxDistance: cell.maxDistance });
}
}
}

for (const [stationId, count] of windowCounts) {
const existing = stationCounts.get(stationId)!;
// The requested window is authoritative. A station seen only in shorter
// windows keeps the largest single-window count.
existing.messageCount = checkWi === wi ? count : Math.max(existing.messageCount, count);
}
// The requested window is authoritative. Slices of different windows do not
// rotate together, so a station can be in a shorter window and just have left
// this one; it is then listed with its largest single-window count. Windows
// overlap, so their counts are never added together.
for (const [stationId, totals] of this.stationWindows[wi].stationTotals()) {
stationCounts.set(stationId, { messageCount: totals.totalMessages, maxDistance: totals.maxDistance });
}

// Also check station sliding windows (for persistence-loaded data)
for (let swi = 0; swi <= wi && swi < this.stationWindows.length; swi++) {
const sw = this.stationWindows[swi];
for (const stationId of sw.activeStationIds()) {
if (stationCounts.has(stationId)) continue;
const cov = sw.getStationCoverage(stationId);
if (cov && cov.totalMessages > 0) {
stationCounts.set(stationId, {
messageCount: cov.totalMessages,
maxDistance: cov.maxDistance,
});
for (let swi = 0; swi < wi; swi++) {
for (const [stationId, totals] of this.stationWindows[swi].stationTotals()) {
const existing = stationCounts.get(stationId);
if (!existing) {
stationCounts.set(stationId, { messageCount: totals.totalMessages, maxDistance: totals.maxDistance });
} else if (existing.messageCount < totals.totalMessages) {
existing.messageCount = totals.totalMessages;
existing.maxDistance = Math.max(existing.maxDistance, totals.maxDistance);
}
}
}
Expand Down Expand Up @@ -423,11 +412,13 @@ export class CoverageStore {
/** Get summary metrics */
getStats(): {
eventsProcessed: number;
processedBySource: Record<string, number>;
eventsRejected: number;
eventsWithPosition: number;
eventsWithoutPosition: number;
rejections: Record<string, number>;
positionsDiscarded: Record<string, number>;
outOfRange: Record<string, { near: number; far: number }>;
stationsTracked: number;
activeCells: Record<number, number>;
} {
Expand All @@ -442,11 +433,13 @@ export class CoverageStore {

return {
eventsProcessed: this.eventsProcessed,
processedBySource: { ...this.processedBySource },
eventsRejected: this.eventsRejected,
eventsWithPosition: this.eventsWithPosition,
eventsWithoutPosition: this.eventsWithoutPosition,
rejections: { ...this.rejections },
positionsDiscarded: { ...this.positionsDiscarded },
outOfRange: structuredClone(this.outOfRange),
stationsTracked: this.stationWindows.length > 3 ? this.stationWindows[3].activeStationIds().size : 0,
activeCells,
};
Expand Down Expand Up @@ -529,6 +522,5 @@ export class CoverageStore {
}
}
for (const sw of this.stationWindows) sw.destroy();
this.rateLimiter.destroy();
}
}
21 changes: 21 additions & 0 deletions service/src/aggregation/station-window.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,27 @@ export class StationSlidingWindow {
return ids;
}

/** 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 }>();
for (const slice of this.slices) {
for (const [key, data] of slice) {
if (data.totalMessages === 0) continue;
const stationId = parseInt(key, 10);
let entry = totals.get(stationId);
if (!entry) {
entry = { totalMessages: 0, maxDistance: 0 };
totals.set(stationId, entry);
}
entry.totalMessages += data.totalMessages;
for (let i = 0; i < 36; i++) {
if (data.sectorMaxDist[i] > entry.maxDistance) entry.maxDistance = data.sectorMaxDist[i];
}
}
}
return totals;
}

/** Events recorded across all slices of this window */
totalMessages(): number {
let total = 0;
Expand Down
Loading