diff --git a/.github/workflows/service.yml b/.github/workflows/service.yml index 75f6958..0317cb1 100644 --- a/.github/workflows/service.yml +++ b/.github/workflows/service.yml @@ -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 diff --git a/service/CLAUDE.md b/service/CLAUDE.md index 6127aa3..9c9385e 100644 --- a/service/CLAUDE.md +++ b/service/CLAUDE.md @@ -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 @@ -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 diff --git a/service/Dockerfile b/service/Dockerfile index 24db178..9f0339f 100644 --- a/service/Dockerfile +++ b/service/Dockerfile @@ -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 diff --git a/service/package-lock.json b/service/package-lock.json index 09d4df7..e0f2728 100644 --- a/service/package-lock.json +++ b/service/package-lock.json @@ -15,6 +15,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" }, @@ -620,6 +621,15 @@ "node": ">= 18.0.0" } }, + "node_modules/@opentelemetry/api": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.10.0.tgz", + "integrity": "sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + } + }, "node_modules/@oxc-project/types": { "version": "0.156.0", "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", @@ -1386,6 +1396,12 @@ "node": ">=12" } }, + "node_modules/bintrees": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/bintrees/-/bintrees-1.0.2.tgz", + "integrity": "sha512-VOMgTMwjAaUG580SXn3LacVgjurrbMme7ZZNYGSSV7mmtY6QQRh0Eg3pwIcntQ77DErK1L0NxkbetjcoXzVwKw==", + "license": "MIT" + }, "node_modules/chai": { "version": "6.3.0", "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", @@ -2093,6 +2109,20 @@ "node": ">=0.10.0" } }, + "node_modules/prom-client": { + "version": "15.1.3", + "resolved": "https://registry.npmjs.org/prom-client/-/prom-client-15.1.3.tgz", + "integrity": "sha512-6ZiOBfCywsD4k1BN9IX0uZhF+tJkV8q8llP64G5Hajs4JOeVLPCwpPVcpXy3BwYiUGgyJzsJJQeOIv7+hDSq8g==", + "deprecated": "prom-client has been replaced by @prometheus-io/client", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api": "^1.4.0", + "tdigest": "^0.1.1" + }, + "engines": { + "node": "^16 || ^18 || >=20" + } + }, "node_modules/redis-errors": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/redis-errors/-/redis-errors-1.2.0.tgz", @@ -2171,6 +2201,15 @@ "dev": true, "license": "MIT" }, + "node_modules/tdigest": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/tdigest/-/tdigest-0.1.3.tgz", + "integrity": "sha512-zbRt+lT+/H4fRItHshczHErVCQnitJk8MfMT24MqFJf3YL7SJJPqGIGeuOdvxXxM/AHFzKBl7WoyaYwqO9s3Kw==", + "license": "MIT", + "dependencies": { + "bintrees": "1.0.2" + } + }, "node_modules/tinybench": { "version": "6.2.3", "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.3.tgz", diff --git a/service/package.json b/service/package.json index 0674c47..6851147 100644 --- a/service/package.json +++ b/service/package.json @@ -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" }, diff --git a/service/src/aggregation/coverage-store.ts b/service/src/aggregation/coverage-store.ts index f283192..303bbcc 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,10 +31,11 @@ export class CoverageStore { /** Synced station metadata from main API */ public stationMap = new Map(); /** Rate limiter */ - private rateLimiter = new RateLimiter(); // Metrics public eventsProcessed = 0; + /** Accepted events by radio family. Sums to eventsProcessed. */ + public processedBySource: Record = {}; public eventsRejected = 0; public eventsWithPosition = 0; public eventsWithoutPosition = 0; @@ -43,6 +43,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 +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 @@ -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); @@ -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; @@ -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. @@ -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, @@ -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 { 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); } } } @@ -423,11 +412,13 @@ export class CoverageStore { /** Get summary metrics */ getStats(): { eventsProcessed: number; + processedBySource: Record; eventsRejected: number; eventsWithPosition: number; eventsWithoutPosition: number; rejections: Record; positionsDiscarded: Record; + outOfRange: Record; stationsTracked: number; activeCells: Record; } { @@ -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, }; @@ -529,6 +522,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..14dcf3c 100644 --- a/service/src/api/routes/health.ts +++ b/service/src/api/routes/health.ts @@ -32,11 +32,13 @@ healthRoutes.get('/health', (c) => { }, coverage: { eventsProcessed: stats.eventsProcessed, + processedBySource: stats.processedBySource, eventsRejected: stats.eventsRejected, eventsWithPosition: stats.eventsWithPosition, 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/api/routes/metrics.ts b/service/src/api/routes/metrics.ts new file mode 100644 index 0000000..3505a24 --- /dev/null +++ b/service/src/api/routes/metrics.ts @@ -0,0 +1,38 @@ +import { timingSafeEqual } from 'node:crypto'; +import { Hono } from 'hono'; +import type { Registry } from 'prom-client'; + +/** + * GET /metrics, Prometheus text format. This port is public, so the route is + * gated behind MONITORING_TOKEN exactly like the api-server's metrics guard: + * the token comes in `X-Monitoring-Token` or `Authorization: Bearer `, + * is compared in constant time, and the route fails closed (401) when + * MONITORING_TOKEN is not configured. + */ +export function metricsRoutes(registry: Registry): Hono { + const routes = new Hono(); + + routes.get('/metrics', async (c) => { + const expected = process.env.MONITORING_TOKEN; + if (!expected) { + return c.json({ statusCode: 401, message: 'metrics endpoint not configured' }, 401); + } + + const auth = c.req.header('authorization') ?? ''; + const provided = c.req.header('x-monitoring-token') + ?? (auth.startsWith('Bearer ') ? auth.slice(7) : ''); + + const a = Buffer.from(provided); + const b = Buffer.from(expected); + if (a.length !== b.length || !timingSafeEqual(a, b)) { + return c.json({ statusCode: 401, message: 'Unauthorized' }, 401); + } + + return c.body(await registry.metrics(), 200, { + 'Content-Type': registry.contentType, + 'Cache-Control': 'no-store', + }); + }); + + return routes; +} diff --git a/service/src/api/server.ts b/service/src/api/server.ts index d283e5b..d55788b 100644 --- a/service/src/api/server.ts +++ b/service/src/api/server.ts @@ -3,6 +3,8 @@ import { cors } from 'hono/cors'; import { coverageRoutes } from './routes/coverage.js'; import { stationRoutes } from './routes/stations.js'; import { healthRoutes } from './routes/health.js'; +import { metricsRoutes } from './routes/metrics.js'; +import { createMetricsRegistry } from '../metrics/metrics.js'; import type { CoverageStore } from '../aggregation/coverage-store.js'; import type { NatsSubscriber } from '../nats/subscriber.js'; @@ -35,5 +37,8 @@ export function createApiServer(store: CoverageStore, nats: NatsSubscriber): Hon app.route('/api/v1/stations', stationRoutes); app.route('/api/v1', healthRoutes); + // Prometheus scrape endpoint at the root, gated by MONITORING_TOKEN + app.route('/', metricsRoutes(createMetricsRegistry(store, nats))); + return app; } 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/data/persistence.ts b/service/src/data/persistence.ts index f77f918..0b1fbe1 100644 --- a/service/src/data/persistence.ts +++ b/service/src/data/persistence.ts @@ -2,6 +2,7 @@ import { getPool } from './database.js'; import type { CoverageStore } from '../aggregation/coverage-store.js'; import { WINDOW_CONFIGS } from '../types/coverage.js'; import { shouldMaintainResolution } from '../compute/h3-indexer.js'; +import { jobStatus } from '../metrics/job-status.js'; // Only persist windows >= 1h (short windows rebuild fast from live traffic) const PERSIST_WINDOW_NAMES = ['1h', '6h', '12h', '24h', '1w', '1mo']; @@ -38,6 +39,7 @@ export class Persistence { async save(): Promise { const db = getPool(); let saved = 0; + const startedAt = Date.now(); try { for (const windowName of PERSIST_WINDOW_NAMES) { @@ -94,6 +96,9 @@ export class Persistence { } } + jobStatus.snapshotLastSuccess = Date.now() / 1000; + jobStatus.snapshotDurationSeconds = (Date.now() - startedAt) / 1000; + if (saved > 0) { console.log(`[Persistence] Saved ${saved} snapshots`); } diff --git a/service/src/metrics/job-status.ts b/service/src/metrics/job-status.ts new file mode 100644 index 0000000..51c2ee5 --- /dev/null +++ b/service/src/metrics/job-status.ts @@ -0,0 +1,10 @@ +/** + * Last outcome of the periodic jobs, written by the jobs themselves and read + * by GET /metrics. Timestamps are Unix seconds; 0 means "not yet succeeded + * since this process started". + */ +export const jobStatus = { + stationSyncLastSuccess: 0, + snapshotLastSuccess: 0, + snapshotDurationSeconds: 0, +}; diff --git a/service/src/metrics/metrics.ts b/service/src/metrics/metrics.ts new file mode 100644 index 0000000..655e0ba --- /dev/null +++ b/service/src/metrics/metrics.ts @@ -0,0 +1,129 @@ +import { readFileSync } from 'node:fs'; +import { Counter, Gauge, Registry, collectDefaultMetrics } from 'prom-client'; +import type { CoverageStore } from '../aggregation/coverage-store.js'; +import type { NatsSubscriber } from '../nats/subscriber.js'; +import { jobStatus } from './job-status.js'; + +/** + * Prometheus metrics for GET /metrics. Names follow the Airframes metrics + * contract (prefix `coverage_`). Nothing is counted twice: every value is read + * at scrape time from the counters `/api/v1/health` already reports, so the + * two can never disagree and the ingest hot path does no extra work. + * + * Labels are small fixed sets only (radio family, rejection reason, outcome). + * No station ids or idents. + */ +export function createMetricsRegistry(store: CoverageStore, nats: NatsSubscriber): Registry { + const registry = new Registry(); + collectDefaultMetrics({ register: registry }); + + // getStats() walks the hour window to count active cells, and several + // collectors read it, so each scrape computes it once. + let scrapeStats: ReturnType | null = null; + const stats = () => (scrapeStats ??= store.getStats()); + const collectAll = registry.metrics.bind(registry); + registry.metrics = () => { + scrapeStats = null; + return collectAll(); + }; + + const gauge = (name: string, help: string, read: () => number) => + new Gauge({ name, help, registers: [registry], collect() { this.set(read()); } }); + + const counter = (name: string, help: string, read: () => number) => + new Counter({ name, help, registers: [registry], collect() { this.reset(); this.inc(read()); } }); + + /** A counter with one label, mirrored from a `{ labelValue: count }` record */ + const labelledCounter = (name: string, help: string, label: string, read: () => Record) => + new Counter({ + name, help, labelNames: [label], registers: [registry], + collect() { + this.reset(); + for (const [value, count] of Object.entries(read())) this.inc({ [label]: value }, count); + }, + }); + + new Gauge({ + name: 'coverage_build_info', + help: 'Build of the running coverage service (value is always 1)', + labelNames: ['version', 'commit'], + registers: [registry], + }).set({ version: readVersion(), commit: process.env.GIT_SHA || 'unknown' }, 1); + + // NATS + gauge('coverage_nats_connected', '1 when the NATS connection is open', () => (nats.isConnected() ? 1 : 0)); + counter('coverage_nats_messages_received_total', 'Messages received on the processed and marine subjects', () => nats.messagesReceived); + counter('coverage_nats_messages_parsed_total', 'Messages turned into a coverage event', () => nats.messagesParsed); + counter('coverage_nats_parse_errors_total', 'Messages that could not be parsed', () => nats.parseErrors); + counter('coverage_nats_raw_positions_found_total', 'Positions recovered from raw decoder output', () => nats.rawPositionsFound); + + // Events + labelledCounter('coverage_events_processed_total', 'Events accepted into coverage, by radio family', 'source', () => stats().processedBySource); + labelledCounter('coverage_events_rejected_total', 'Events rejected, by reason', 'reason', () => stats().rejections); + counter('coverage_events_with_position_total', 'Accepted events with a usable target position', () => store.eventsWithPosition); + counter('coverage_events_without_position_total', 'Accepted events without a usable target position', () => store.eventsWithoutPosition); + labelledCounter('coverage_positions_discarded_total', 'Events kept whose target position was discarded, by reason', 'reason', () => stats().positionsDiscarded); + new Counter({ + name: 'coverage_positions_out_of_range_total', + help: 'Positions discarded as out of range, by radio family (near = within twice the range limit, far = beyond it)', + labelNames: ['source', 'band'], + registers: [registry], + collect() { + this.reset(); + for (const [source, { near, far }] of Object.entries(stats().outOfRange)) { + this.inc({ source, band: 'near' }, near); + this.inc({ source, band: 'far' }, far); + } + }, + }); + + // Store size + gauge('coverage_stations_tracked', 'Stations heard in the last hour', () => stats().stationsTracked); + new Gauge({ + name: 'coverage_active_cells', + help: 'H3 cells with traffic in the last hour, by H3 resolution', + labelNames: ['resolution'], + registers: [registry], + collect() { + this.reset(); + for (const [resolution, cells] of Object.entries(stats().activeCells)) { + this.set({ resolution }, cells); + } + }, + }); + gauge('coverage_cells_in_memory', 'H3 cells held in memory across all windows and resolutions', () => store.getCellsInMemory()); + + // Marine (AIS) join + new Counter({ + name: 'coverage_marine_events_total', + help: 'AIS receptions by how their position was resolved', + labelNames: ['outcome'], + registers: [registry], + collect() { + this.reset(); + this.inc({ outcome: 'paired' }, nats.marine.paired); + this.inc({ outcome: 'from_last_position' }, nats.marine.fromLastPosition); + this.inc({ outcome: 'without_position' }, nats.marine.withoutPosition); + this.inc({ outcome: 'unknown_station' }, nats.marineUnknownStation); + }, + }); + gauge('coverage_marine_pending', 'AIS messages waiting for their position event', () => nats.marine.pendingSize); + gauge('coverage_marine_tracked_voyages', 'Voyages with a recent last position', () => nats.marine.trackedVoyages); + + // Periodic jobs + gauge('coverage_station_sync_last_success_timestamp_seconds', 'Unix time of the last successful station sync from the main API (0 = none yet)', () => jobStatus.stationSyncLastSuccess); + gauge('coverage_snapshot_last_success_timestamp_seconds', 'Unix time of the last successful snapshot save to PostgreSQL (0 = none yet)', () => jobStatus.snapshotLastSuccess); + gauge('coverage_snapshot_duration_seconds', 'How long the last successful snapshot save took', () => jobStatus.snapshotDurationSeconds); + + return registry; +} + +function readVersion(): string { + try { + // src/metrics and dist/metrics are both two levels below package.json + const pkg = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')); + return typeof pkg.version === 'string' ? pkg.version : 'unknown'; + } catch { + return 'unknown'; + } +} diff --git a/service/src/sync/station-sync.ts b/service/src/sync/station-sync.ts index dcbdf87..6a7785e 100644 --- a/service/src/sync/station-sync.ts +++ b/service/src/sync/station-sync.ts @@ -1,6 +1,7 @@ import { config } from '../config.js'; import type { StationMeta } from '../types/events.js'; import { toStationId } from '../nats/parsers/station-id.js'; +import { jobStatus } from '../metrics/job-status.js'; /** * Periodically syncs station metadata from the main API. @@ -117,6 +118,8 @@ export class StationSync { updated++; } + jobStatus.stationSyncLastSuccess = Date.now() / 1000; + const withCoords = [...this.stationMap.values()].filter( s => s.latitude !== 0 || s.longitude !== 0 ).length; 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 } }); + }); }); diff --git a/service/test/metrics.test.ts b/service/test/metrics.test.ts new file mode 100644 index 0000000..2e84d6e --- /dev/null +++ b/service/test/metrics.test.ts @@ -0,0 +1,152 @@ +import { afterAll, afterEach, describe, expect, it } from 'vitest'; +import { CoverageStore } from '../src/aggregation/coverage-store.js'; +import { createApiServer } from '../src/api/server.js'; +import { NatsSubscriber } from '../src/nats/subscriber.js'; +import { jobStatus } from '../src/metrics/job-status.js'; +import type { CoverageEvent, StationMeta } from '../src/types/events.js'; + +const TOKEN = 'test-monitoring-token'; + +const store = new CoverageStore(); +const nats = new NatsSubscriber((event) => store.ingest(event), store.stationMap); +const app = createApiServer(store, nats); + +function station(id: number, overrides: Partial = {}): StationMeta { + return { + id, uuid: `uuid-${id}`, ident: `TEST-${id}`, latitude: 47.45, longitude: -122.31, + sourceType: 'vdl', status: 'active', flagged: false, blocked: false, + trustScore: 0.5, lastSyncedAt: new Date(), ...overrides, + }; +} + +function event(stationId: number, overrides: Partial = {}): CoverageEvent { + return { + stationId, stationUuid: `uuid-${stationId}`, + targetLat: 47.6, targetLon: -122.3, targetAlt: null, + transportType: 'aircraft', sourceType: 'vdl', source: 'dumpvdl2', + frequency: null, signalLevel: null, errorCount: null, + timestamp: new Date(), hasTargetPosition: true, ...overrides, + }; +} + +async function scrape(): Promise { + process.env.MONITORING_TOKEN = TOKEN; + const res = await app.request('/metrics', { headers: { Authorization: `Bearer ${TOKEN}` } }); + expect(res.status).toBe(200); + return res.text(); +} + +/** Value of one sample line, matched on its exact name and label set */ +function sample(text: string, series: string): number | undefined { + const line = text.split('\n').find(l => l.startsWith(`${series} `)); + return line === undefined ? undefined : Number(line.slice(series.length + 1)); +} + +afterEach(() => { delete process.env.MONITORING_TOKEN; }); +afterAll(() => store.destroy()); + +describe('GET /metrics access', () => { + it('fails closed when MONITORING_TOKEN is not configured', async () => { + const res = await app.request('/metrics', { headers: { Authorization: 'Bearer anything' } }); + expect(res.status).toBe(401); + expect(await res.text()).not.toContain('coverage_'); + }); + + it('rejects a missing or wrong token', async () => { + process.env.MONITORING_TOKEN = TOKEN; + expect((await app.request('/metrics')).status).toBe(401); + expect((await app.request('/metrics', { headers: { Authorization: 'Bearer wrong' } })).status).toBe(401); + expect((await app.request('/metrics', { headers: { 'X-Monitoring-Token': `${TOKEN}x` } })).status).toBe(401); + // The token must be sent as a header, not in the URL + expect((await app.request(`/metrics?token=${TOKEN}`)).status).toBe(401); + }); + + it('accepts the token as a bearer token or X-Monitoring-Token', async () => { + process.env.MONITORING_TOKEN = TOKEN; + const bearer = await app.request('/metrics', { headers: { Authorization: `Bearer ${TOKEN}` } }); + expect(bearer.status).toBe(200); + expect(bearer.headers.get('content-type')).toContain('text/plain; version=0.0.4'); + const header = await app.request('/metrics', { headers: { 'X-Monitoring-Token': TOKEN } }); + expect(header.status).toBe(200); + }); + + it('leaves the public API open', async () => { + expect((await app.request('/api/v1/health')).status).toBe(200); + }); +}); + +describe('GET /metrics content', () => { + it('mirrors the health counters', async () => { + store.stationMap.set(1, station(1)); + store.stationMap.set(2, station(2, { blocked: true })); + store.ingest(event(1)); + store.ingest(event(1)); + store.ingest(event(1, { sourceType: 'hfdl', hasTargetPosition: false, targetLat: null, targetLon: null })); + store.ingest(event(2)); // blocked + store.ingest(event(999)); // unknown station + nats.messagesReceived = 7; + nats.messagesParsed = 5; + nats.parseErrors = 1; + nats.marine.paired = 4; + nats.marineUnknownStation = 2; + + const text = await scrape(); + const health = await (await app.request('/api/v1/health')).json(); + + expect(sample(text, 'coverage_events_processed_total{source="vdl"}')).toBe(2); + expect(sample(text, 'coverage_events_processed_total{source="hfdl"}')).toBe(1); + expect(health.coverage.eventsProcessed).toBe(3); + expect(sample(text, 'coverage_events_rejected_total{reason="station_blocked"}')).toBe(1); + expect(sample(text, 'coverage_events_rejected_total{reason="unknown_station"}')).toBe(1); + expect(sample(text, 'coverage_events_with_position_total')).toBe(health.coverage.eventsWithPosition); + expect(sample(text, 'coverage_events_without_position_total')).toBe(1); + expect(sample(text, 'coverage_stations_tracked')).toBe(health.coverage.stationsTracked); + expect(sample(text, 'coverage_cells_in_memory')).toBe(health.coverage.cellsInMemory); + expect(sample(text, 'coverage_active_cells{resolution="4"}')).toBe(health.coverage.activeCells[4]); + + expect(sample(text, 'coverage_nats_connected')).toBe(0); + expect(sample(text, 'coverage_nats_messages_received_total')).toBe(7); + expect(sample(text, 'coverage_nats_messages_parsed_total')).toBe(5); + expect(sample(text, 'coverage_nats_parse_errors_total')).toBe(1); + expect(sample(text, 'coverage_marine_events_total{outcome="paired"}')).toBe(4); + expect(sample(text, 'coverage_marine_events_total{outcome="unknown_station"}')).toBe(2); + expect(sample(text, 'coverage_marine_pending')).toBe(0); + }); + + it('counts out-of-range positions by radio family', async () => { + // Tokyo is far beyond VDL range from Seattle + store.ingest(event(1, { targetLat: 35.68, targetLon: 139.69 })); + const text = await scrape(); + expect(sample(text, 'coverage_positions_discarded_total{reason="out_of_range"}')).toBe(1); + expect(sample(text, 'coverage_positions_out_of_range_total{source="vdl",band="far"}')).toBe(1); + }); + + it('does not double count across scrapes', async () => { + const first = sample(await scrape(), 'coverage_events_processed_total{source="vdl"}'); + const second = sample(await scrape(), 'coverage_events_processed_total{source="vdl"}'); + expect(second).toBe(first); + }); + + it('reports job timestamps, build info and process metrics', async () => { + let text = await scrape(); + expect(sample(text, 'coverage_station_sync_last_success_timestamp_seconds')).toBe(0); + + jobStatus.stationSyncLastSuccess = 1_795_000_000; + jobStatus.snapshotLastSuccess = 1_795_000_060; + jobStatus.snapshotDurationSeconds = 0.25; + text = await scrape(); + expect(sample(text, 'coverage_station_sync_last_success_timestamp_seconds')).toBe(1_795_000_000); + expect(sample(text, 'coverage_snapshot_last_success_timestamp_seconds')).toBe(1_795_000_060); + expect(sample(text, 'coverage_snapshot_duration_seconds')).toBe(0.25); + + expect(text).toMatch(/^coverage_build_info\{version="\d+\.\d+\.\d+",commit="unknown"\} 1$/m); + expect(text).toMatch(/^process_resident_memory_bytes \d+/m); + expect(text).toMatch(/^process_cpu_seconds_total /m); + expect(text).toMatch(/^process_start_time_seconds \d+/m); + }); + + it('exposes no per-station labels', async () => { + const text = await scrape(); + expect(text).not.toMatch(/station_id|ident=|uuid/); + }); +});