diff --git a/service/CLAUDE.md b/service/CLAUDE.md index 6127aa3..8e03069 100644 --- a/service/CLAUDE.md +++ b/service/CLAUDE.md @@ -27,12 +27,18 @@ 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 - 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 @@ -44,4 +50,5 @@ 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`) - MARINE_COVERAGE_ENABLED - set to `false` to leave the marine subjects unsubscribed diff --git a/service/src/aggregation/coverage-store.ts b/service/src/aggregation/coverage-store.ts index f283192..0ab832b 100644 --- a/service/src/aggregation/coverage-store.ts +++ b/service/src/aggregation/coverage-store.ts @@ -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'; @@ -32,7 +31,6 @@ export class CoverageStore { /** Synced station metadata from main API */ public stationMap = new Map(); /** Rate limiter */ - private rateLimiter = new RateLimiter(); // Metrics public eventsProcessed = 0; @@ -43,6 +41,12 @@ export class CoverageStore { public rejections: Record = {}; /** Events kept, but whose target position was discarded, by reason */ public positionsDiscarded: Record = {}; + /** + * 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 = {}; constructor() { // Initialize sliding windows for each resolution x window combination @@ -76,11 +80,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 @@ -136,8 +137,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); @@ -147,6 +153,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; @@ -221,6 +228,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, @@ -316,63 +330,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 { const stationCounts = new Map(); 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(); - 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); } } } @@ -428,6 +413,7 @@ export class CoverageStore { eventsWithoutPosition: number; rejections: Record; positionsDiscarded: Record; + outOfRange: Record; stationsTracked: number; activeCells: Record; } { @@ -447,6 +433,7 @@ export class CoverageStore { 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, }; @@ -529,6 +516,5 @@ export class CoverageStore { } } for (const sw of this.stationWindows) sw.destroy(); - this.rateLimiter.destroy(); } } diff --git a/service/src/aggregation/station-window.ts b/service/src/aggregation/station-window.ts index 372312a..aeac0d9 100644 --- a/service/src/aggregation/station-window.ts +++ b/service/src/aggregation/station-window.ts @@ -181,6 +181,27 @@ export class StationSlidingWindow { return ids; } + /** Message total and furthest reception per station across all slices, in one pass */ + stationTotals(): Map { + const totals = new Map(); + 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; diff --git a/service/src/api/routes/health.ts b/service/src/api/routes/health.ts index 28bd856..14609c5 100644 --- a/service/src/api/routes/health.ts +++ b/service/src/api/routes/health.ts @@ -37,6 +37,7 @@ healthRoutes.get('/health', (c) => { eventsWithoutPosition: stats.eventsWithoutPosition, rejections: stats.rejections, positionsDiscarded: stats.positionsDiscarded, + outOfRange: stats.outOfRange, stationsTracked: stats.stationsTracked, activeCells: stats.activeCells, cellsInMemory: store.getCellsInMemory(), diff --git a/service/src/compute/signal-analysis.ts b/service/src/compute/signal-analysis.ts index ce0c32c..f00f026 100644 --- a/service/src/compute/signal-analysis.ts +++ b/service/src/compute/signal-analysis.ts @@ -18,7 +18,7 @@ export const MAX_RANGE_KM: Record = { vdl: 400, hfdl: 4000, satcom: 50000, // relayed by satellite - effectively unlimited - ais: 70, + ais: 100, // VHF line of sight; elevated antennas reach 60 nm and more unknown: 1000, }; diff --git a/service/src/config.ts b/service/src/config.ts index 3c49327..eab7427 100644 --- a/service/src/config.ts +++ b/service/src/config.ts @@ -28,6 +28,16 @@ export const config = { // MARINE_COVERAGE_ENABLED=false to leave the marine subjects unsubscribed. marineCoverageEnabled: process.env.MARINE_COVERAGE_ENABLED !== 'false', + // Stations that are not one receiver but a relayed area feed, such as a + // coastal administration's national AIS network (NCT is the Norwegian one). + // Their vessels can be any distance from the station's nominal location, so + // positions are kept without a range limit and give the station no range or + // direction of its own. Comma-separated station idents, case-insensitive. + areaFeedStations: new Set( + (process.env.AREA_FEED_STATIONS ?? 'NCT') + .split(',').map(s => s.trim().toLowerCase()).filter(Boolean), + ), + // WebSocket push intervals (ms) wsCoverageInterval: 5_000, wsStationInterval: 30_000, diff --git a/service/src/validation/rate-limiter.ts b/service/src/validation/rate-limiter.ts deleted file mode 100644 index b78308b..0000000 --- a/service/src/validation/rate-limiter.ts +++ /dev/null @@ -1,54 +0,0 @@ -/** Per-station rate limiter to detect and throttle anomalous message volumes */ - -interface StationRate { - count: number; - windowStart: number; -} - -const WINDOW_MS = 60_000; // 1 minute window -// The busiest production receivers send about 400 messages a minute. -const MAX_PER_MINUTE = 900; - -export class RateLimiter { - private stations = new Map(); - private cleanupTimer: ReturnType; - - constructor() { - // Clean up stale entries every 5 minutes - this.cleanupTimer = setInterval(() => this.cleanup(), 300_000); - } - - /** Returns true if the event should be allowed, false if rate-limited */ - check(stationId: number): boolean { - const now = Date.now(); - const rate = this.stations.get(stationId); - - if (!rate || now - rate.windowStart > WINDOW_MS) { - this.stations.set(stationId, { count: 1, windowStart: now }); - return true; - } - - rate.count++; - return rate.count <= MAX_PER_MINUTE; - } - - /** Get current rate for a station (messages in current window) */ - getRate(stationId: number): number { - const rate = this.stations.get(stationId); - if (!rate || Date.now() - rate.windowStart > WINDOW_MS) return 0; - return rate.count; - } - - private cleanup(): void { - const now = Date.now(); - for (const [id, rate] of this.stations) { - if (now - rate.windowStart > WINDOW_MS * 2) { - this.stations.delete(id); - } - } - } - - destroy(): void { - clearInterval(this.cleanupTimer); - } -} diff --git a/service/test/ingest.test.ts b/service/test/ingest.test.ts index d028e2e..9643722 100644 --- a/service/test/ingest.test.ts +++ b/service/test/ingest.test.ts @@ -182,4 +182,70 @@ describe('ingest', () => { const counts = store.getStationMessageCounts('1h').get(3); expect(counts?.maxDistance).toBeGreaterThan(50); }); + + it('counts each station\'s own messages when stations share a cell', () => { + store = new CoverageStore(); + store.stationMap.set(1, station(1, 50.0, 8.0)); + store.stationMap.set(2, station(2, 50.1, 8.1)); + + // Same target position, so both stations report into the same cells + for (let i = 0; i < 30; i++) store.ingest(event(1, 50.3, 8.3)); + for (let i = 0; i < 5; i++) store.ingest(event(2, 50.3, 8.3)); + // Messages without a position count too + for (let i = 0; i < 4; i++) store.ingest(event(2, null, null)); + + for (const window of ['1m', '1h', '1mo']) { + const counts = store.getStationMessageCounts(window); + expect(counts.get(1)?.messageCount).toBe(30); + expect(counts.get(2)?.messageCount).toBe(9); + } + const total = [...store.getStationMessageCounts('1m').values()].reduce((sum, c) => sum + c.messageCount, 0); + expect(total).toBe(store.eventsProcessed); + expect(store.getStationMessageCounts('1m').get(1)?.maxDistance).toBeGreaterThan(30); + }); + + it('keeps every position of an imported area feed, however far away', () => { + store = new CoverageStore(); + // An ordinary AIS receiver and the Norwegian coastal feed, both placed in Oslo + store.stationMap.set(30, { ...station(30, 59.9, 10.7), ident: 'AIS-OSLO', sourceType: 'aiscatcher' }); + store.stationMap.set(31, { ...station(31, 59.9, 10.7), ident: 'NCT', sourceType: 'aiscatcher' }); + const ais = (stationId: number): CoverageEvent => ({ + // A vessel off Tromso, about 1,150 km away + ...event(stationId, 69.7, 18.9), transportType: 'marine', sourceType: 'ais', source: 'aiscatcher', + frequency: null, signalLevel: null, + }); + + store.ingest(ais(30)); + expect(store.positionsDiscarded.out_of_range).toBe(1); + + store.ingest(ais(31)); + expect(store.positionsDiscarded.out_of_range).toBe(1); + expect(store.eventsWithPosition).toBe(1); + // The feed gets no range of its own from it + expect(store.getStationMessageCounts('1h').get(31)).toEqual({ messageCount: 1, maxDistance: 0 }); + }); + + it('does not limit how much a station may send', () => { + store = new CoverageStore(); + store.stationMap.set(20, station(20, 51.95, 4.05)); + + for (let i = 0; i < 10_000; i++) store.ingest(event(20, null, null)); + + expect(store.eventsRejected).toBe(0); + expect(store.eventsProcessed).toBe(10_000); + }); + + it('reports out-of-range positions by radio family and how far out they were', () => { + store = new CoverageStore(); + store.stationMap.set(22, { ...station(22, 51.95, 4.05), sourceType: 'ais' }); + const marine = { transportType: 'marine' as const, sourceType: 'ais', frequency: null, signalLevel: null }; + + store.ingest({ ...event(22, 51.95, 5.5), ...marine }); // about 100 km: accepted + store.ingest({ ...event(22, 51.95, 6.6), ...marine }); // about 175 km: just outside + store.ingest({ ...event(22, 40.0, -70.0), ...marine }); // across the Atlantic + + expect(store.eventsWithPosition).toBe(1); + expect(store.positionsDiscarded).toEqual({ out_of_range: 2 }); + expect(store.outOfRange).toEqual({ ais: { near: 1, far: 1 } }); + }); });