File size: 10,662 Bytes
9d2d895 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 | import { getRpcBaseUrl } from '@/services/rpc-client';
import type { AisDensityZone as ProtoDensityZone, AisDisruption as ProtoDisruption, GetVesselSnapshotResponse, SnapshotCandidateReport as ProtoCandidateReport } from '@/generated/client/worldmonitor/maritime/v1/service_client';
import { createCircuitBreaker } from '@/utils';
import type { AisDisruptionEvent, AisDensityZone, AisDisruptionType } from '@/types';
import { dataFreshness } from '../data-freshness';
import { isFeatureAvailable } from '../runtime-config';
import { startSmartPollLoop, type SmartPollLoopHandle } from '../runtime';
import { MaritimeServiceClient } from '@/services/generated-rpc-clients';
const client = new MaritimeServiceClient(getRpcBaseUrl(), { fetch: (...args) => globalThis.fetch(...args) });
const snapshotBreaker = createCircuitBreaker<GetVesselSnapshotResponse>({ name: 'Maritime Snapshot', cacheTtlMs: 10 * 60 * 1000, persistCache: true });
const emptySnapshotFallback: GetVesselSnapshotResponse = { snapshot: undefined, fetchedAt: 0, dataAvailable: false };
const DISRUPTION_TYPE_REVERSE: Record<string, AisDisruptionType> = {
AIS_DISRUPTION_TYPE_GAP_SPIKE: 'gap_spike',
AIS_DISRUPTION_TYPE_CHOKEPOINT_CONGESTION: 'chokepoint_congestion',
};
const SEVERITY_REVERSE: Record<string, 'low' | 'elevated' | 'high'> = {
AIS_DISRUPTION_SEVERITY_LOW: 'low',
AIS_DISRUPTION_SEVERITY_ELEVATED: 'elevated',
AIS_DISRUPTION_SEVERITY_HIGH: 'high',
};
/**
* Convert a proto disruption to the app shape. Returns null when either enum
* is UNSPECIFIED / unknown — the legacy silent fallbacks mislabeled unknown
* values as `gap_spike` / `low`, which would have polluted the dashboard the
* first time the proto adds a new enum value the client doesn't know about.
* Filtering at the mapping boundary is safer than shipping wrong data.
*/
function toDisruptionEvent(proto: ProtoDisruption): AisDisruptionEvent | null {
const type = DISRUPTION_TYPE_REVERSE[proto.type];
const severity = SEVERITY_REVERSE[proto.severity];
if (!type || !severity) return null;
return {
id: proto.id,
name: proto.name,
type,
lat: proto.location?.latitude ?? 0,
lon: proto.location?.longitude ?? 0,
severity,
changePct: proto.changePct,
windowHours: proto.windowHours,
darkShips: proto.darkShips,
vesselCount: proto.vesselCount,
region: proto.region,
description: proto.description,
};
}
function toDensityZone(proto: ProtoDensityZone): AisDensityZone {
return {
id: proto.id,
name: proto.name,
lat: proto.location?.latitude ?? 0,
lon: proto.location?.longitude ?? 0,
intensity: proto.intensity,
deltaPct: proto.deltaPct,
shipsPerDay: proto.shipsPerDay,
note: proto.note,
};
}
function toLegacyCandidateReport(proto: ProtoCandidateReport): SnapshotCandidateReport {
return {
mmsi: proto.mmsi,
name: proto.name,
lat: proto.lat,
lon: proto.lon,
shipType: proto.shipType || undefined,
heading: proto.heading || undefined,
speed: proto.speed || undefined,
course: proto.course || undefined,
timestamp: proto.timestamp,
};
}
// ---- Feature Gating ----
const isClientRuntime = typeof window !== 'undefined';
const aisConfigured = isClientRuntime && import.meta.env.VITE_ENABLE_AIS !== 'false';
export function isAisConfigured(): boolean {
return aisConfigured && isFeatureAvailable('aisRelay');
}
// ---- AisPositionData (exported for military-vessels.ts) ----
export interface AisPositionData {
mmsi: string;
name: string;
lat: number;
lon: number;
shipType?: number;
heading?: number;
speed?: number;
course?: number;
}
// ---- Internal Interfaces ----
interface SnapshotStatus {
connected: boolean;
vessels: number;
messages: number;
}
interface SnapshotCandidateReport extends AisPositionData {
timestamp: number;
}
// ---- Callback System ----
type AisCallback = (data: AisPositionData) => void;
const positionCallbacks = new Set<AisCallback>();
const lastCallbackTimestampByMmsi = new Map<string, number>();
// ---- Polling State ----
let pollLoop: SmartPollLoopHandle | null = null;
let inFlight = false;
let isPolling = false;
let lastPollAt = 0;
let lastSequence = 0;
let latestDisruptions: AisDisruptionEvent[] = [];
let latestDensity: AisDensityZone[] = [];
let latestStatus: SnapshotStatus = {
connected: false,
vessels: 0,
messages: 0,
};
// ---- Constants ----
const SNAPSHOT_POLL_INTERVAL_MS = 5 * 60 * 1000;
const SNAPSHOT_STALE_MS = 6 * 60 * 1000;
const CALLBACK_RETENTION_MS = 2 * 60 * 60 * 1000; // 2 hours
const MAX_CALLBACK_TRACKED_VESSELS = 20000;
// ---- Internal Helpers ----
function shouldIncludeCandidates(): boolean {
return positionCallbacks.size > 0;
}
interface ParsedSnapshot {
sequence: number;
status: SnapshotStatus;
disruptions: AisDisruptionEvent[];
density: AisDensityZone[];
candidateReports: SnapshotCandidateReport[];
}
async function fetchSnapshotPayload(includeCandidates: boolean, signal?: AbortSignal): Promise<ParsedSnapshot | null> {
const response = await snapshotBreaker.execute(
async () => client.getVesselSnapshot(
{ neLat: 0, neLon: 0, swLat: 0, swLon: 0, includeCandidates, includeTankers: false },
{ signal },
),
emptySnapshotFallback,
);
const snapshot = response.snapshot;
if (!snapshot) return null;
return {
sequence: snapshot.sequence,
status: {
connected: snapshot.status?.connected ?? false,
vessels: snapshot.status?.vessels ?? 0,
messages: snapshot.status?.messages ?? 0,
},
disruptions: snapshot.disruptions
.map(toDisruptionEvent)
.filter((e): e is AisDisruptionEvent => e !== null),
density: snapshot.densityZones.map(toDensityZone),
candidateReports: snapshot.candidateReports.map(toLegacyCandidateReport),
};
}
// ---- Callback Emission ----
function pruneCallbackTimestampIndex(now: number): void {
if (lastCallbackTimestampByMmsi.size <= MAX_CALLBACK_TRACKED_VESSELS) {
return;
}
const threshold = now - CALLBACK_RETENTION_MS;
for (const [mmsi, ts] of lastCallbackTimestampByMmsi) {
if (ts < threshold) {
lastCallbackTimestampByMmsi.delete(mmsi);
}
}
if (lastCallbackTimestampByMmsi.size <= MAX_CALLBACK_TRACKED_VESSELS) {
return;
}
const oldest = Array.from(lastCallbackTimestampByMmsi.entries())
.sort((a, b) => a[1] - b[1]);
const toDelete = lastCallbackTimestampByMmsi.size - MAX_CALLBACK_TRACKED_VESSELS;
for (let i = 0; i < toDelete; i++) {
const entry = oldest[i];
if (!entry) break;
lastCallbackTimestampByMmsi.delete(entry[0]);
}
}
function emitCandidateReports(reports: SnapshotCandidateReport[]): void {
if (positionCallbacks.size === 0 || reports.length === 0) return;
const now = Date.now();
for (const report of reports) {
if (!report?.mmsi || !Number.isFinite(report.lat) || !Number.isFinite(report.lon)) continue;
const reportTs = Number.isFinite(report.timestamp) ? Number(report.timestamp) : now;
const lastTs = lastCallbackTimestampByMmsi.get(report.mmsi) || 0;
if (reportTs <= lastTs) continue;
lastCallbackTimestampByMmsi.set(report.mmsi, reportTs);
const callbackData: AisPositionData = {
mmsi: report.mmsi,
name: report.name || '',
lat: report.lat,
lon: report.lon,
shipType: report.shipType,
heading: report.heading,
speed: report.speed,
course: report.course,
};
for (const callback of positionCallbacks) {
try {
callback(callbackData);
} catch {
// Ignore callback errors
}
}
}
pruneCallbackTimestampIndex(now);
}
// ---- Polling ----
async function pollSnapshot(force = false, signal?: AbortSignal): Promise<void> {
if (!isAisConfigured()) return;
if (inFlight && !force) return;
if (signal?.aborted) return;
inFlight = true;
try {
const includeCandidates = shouldIncludeCandidates();
const snapshot = await fetchSnapshotPayload(includeCandidates, signal);
if (!snapshot) throw new Error('Invalid snapshot payload');
latestDisruptions = snapshot.disruptions;
latestDensity = snapshot.density;
latestStatus = snapshot.status;
lastPollAt = Date.now();
if (includeCandidates) {
if (snapshot.sequence > lastSequence) {
emitCandidateReports(snapshot.candidateReports);
lastSequence = snapshot.sequence;
} else if (lastSequence === 0) {
emitCandidateReports(snapshot.candidateReports);
lastSequence = snapshot.sequence;
}
} else {
lastSequence = snapshot.sequence;
}
const itemCount = latestDisruptions.length + latestDensity.length;
if (itemCount > 0 || latestStatus.vessels > 0) {
dataFreshness.recordUpdate('ais', itemCount > 0 ? itemCount : latestStatus.vessels);
}
} catch {
latestStatus.connected = false;
} finally {
inFlight = false;
}
}
function startPolling(): void {
if (isPolling || !isAisConfigured()) return;
isPolling = true;
void pollSnapshot(true);
pollLoop?.stop();
pollLoop = startSmartPollLoop(({ signal }) => pollSnapshot(false, signal), {
intervalMs: SNAPSHOT_POLL_INTERVAL_MS,
// AIS relay traffic is high-cost; pause entirely in hidden tabs.
pauseWhenHidden: true,
refreshOnVisible: true,
runImmediately: false,
});
}
// ---- Exported Functions ----
export function registerAisCallback(callback: AisCallback): void {
positionCallbacks.add(callback);
startPolling();
}
export function unregisterAisCallback(callback: AisCallback): void {
positionCallbacks.delete(callback);
if (positionCallbacks.size === 0) {
lastCallbackTimestampByMmsi.clear();
}
}
export function initAisStream(): void {
startPolling();
}
export function disconnectAisStream(): void {
pollLoop?.stop();
pollLoop = null;
isPolling = false;
inFlight = false;
latestStatus.connected = false;
}
export function getAisStatus(): { connected: boolean; vessels: number; messages: number } {
const isFresh = Date.now() - lastPollAt <= SNAPSHOT_STALE_MS;
return {
connected: latestStatus.connected && isFresh,
vessels: latestStatus.vessels,
messages: latestStatus.messages,
};
}
export async function fetchAisSignals(): Promise<{ disruptions: AisDisruptionEvent[]; density: AisDensityZone[] }> {
if (!aisConfigured) {
return { disruptions: [], density: [] };
}
startPolling();
const shouldRefresh = Date.now() - lastPollAt > SNAPSHOT_STALE_MS;
if (shouldRefresh) {
await pollSnapshot(true);
}
return {
disruptions: latestDisruptions,
density: latestDensity,
};
}
|