feat(30-02): implement localSources normalizer + TTL cache (GREEN)

- normalizers.ts: normalizeGeoJson(input, prefix, pluginId) -> GeoEntity[]
  - GeoJSON [lon,lat] -> latitude=lat/longitude=lon (correct order, Pitfall 1 avoided)
  - id: camera-${prefix}-${index} parity with cameraMapper.ts
  - altitude: 8 (DEFAULT_CAMERA_ALT), label: city||country||"Unknown Camera"
  - properties spread verbatim; no import of camera barrel (Pitfall 2 avoided)
  - unknown input narrowed safely; returns [] for malformed/empty input
- cache.ts: getCached(key, ttlMs, fetcher) -> PluginDataSnapshot
  - module-level Map keyed per source; returns cached entry while expiresAt > Date.now()
  - exports TTL_GEOJSON_MS=3600000 (60min), TTL_ROUTE_MS=60000 (60s) per D-07
- 10 normalizer tests + 5 cache tests GREEN
This commit is contained in:
Antigravity AI committed 2026-06-02 16:20:09 +12:00
1 parent 4aabdd4749
commit 00733dc148
2 files changed
+135

No files matched your search

+53
View File
@@ -0,0 +1,53 @@
/**
* @file cache.ts
* @description Module-level in-memory TTL cache for PluginDataSnapshot results.
*
* Keyed per source string (e.g. "camera:default", "camera:traffic").
* Returns the cached snapshot while Date.now() < expiresAt, otherwise invokes
* the fetcher and stores the new result with a fresh expiry.
*
* TTL constants (D-07, Research Area 6):
* - TTL_GEOJSON_MS: 60 min (static file; changes only on deploy)
* - TTL_ROUTE_MS: 60 s (internal Next.js route; data updates frequently)
*/
import type { PluginDataSnapshot } from "../types";
/** 60-minute TTL for static GeoJSON file sources. */
export const TTL_GEOJSON_MS = 60 * 60 * 1000;
/** 60-second TTL for internal route sources (/api/...). */
export const TTL_ROUTE_MS = 60 * 1000;
interface CacheEntry {
snapshot: PluginDataSnapshot;
expiresAt: number;
}
/** Module-level cache — persists for the lifetime of the Node.js process. */
const cache = new Map<string, CacheEntry>();
/**
* getCached
*
* Returns a cached snapshot if one exists and has not expired.
* Otherwise calls `fetcher`, stores the result, and returns it.
*
* @param key - Unique string key for this source (e.g. "camera:default").
* @param ttlMs - Time-to-live in milliseconds before the entry is invalidated.
* @param fetcher - Async function that fetches and returns a fresh snapshot.
*/
export async function getCached(
key: string,
ttlMs: number,
fetcher: () => Promise<PluginDataSnapshot>,
): Promise<PluginDataSnapshot> {
const entry = cache.get(key);
if (entry !== undefined && entry.expiresAt > Date.now()) {
return entry.snapshot;
}
const snapshot = await fetcher();
cache.set(key, { snapshot, expiresAt: Date.now() + ttlMs });
return snapshot;
}
@@ -0,0 +1,82 @@
/**
* @file normalizers.ts
* @description Server-side GeoJSON FeatureCollection -> GeoEntity[] transform.
*
* Reimplements the ~15-line mapGeoJsonFeature logic from
* local-plugins/wwv-plugin-camera/src/cameraMapper.ts WITHOUT importing that
* barrel (it pulls React/lucide-react and camera is not in transpilePackages).
*
* Coordinate order: GeoJSON spec is [longitude, latitude] — we destructure
* `const [lon, lat] = coordinates` and assign `latitude: lat, longitude: lon`.
* Getting this backwards is the primary footgun (see plan Pitfall 1).
*/
import type { GeoEntity } from "@worldwideview/wwv-plugin-sdk";
const DEFAULT_CAMERA_ALT = 8;
/**
* Narrows an unknown GeoJSON feature to a typed shape for safe destructuring.
*/
interface GeoJsonFeature {
geometry?: { coordinates?: number[] };
properties?: Record<string, unknown>;
}
/**
* Narrows an unknown GeoJSON FeatureCollection to a typed shape.
*/
interface GeoJsonFeatureCollection {
features?: unknown[];
}
/**
* normalizeGeoJson
*
* Converts a GeoJSON FeatureCollection (parsed from disk or fetched as JSON)
* into a GeoEntity[]. Returns [] for malformed or empty input — never throws.
*
* @param input - Unknown value expected to be a FeatureCollection object.
* @param prefix - Source name used in entity id (e.g. "default", "traffic").
* @param pluginId - Plugin identifier assigned to every entity.
*/
export function normalizeGeoJson(
input: unknown,
prefix: string,
pluginId: string,
): GeoEntity[] {
if (typeof input !== "object" || input === null) return [];
const collection = input as GeoJsonFeatureCollection;
if (!Array.isArray(collection.features)) return [];
const entities: GeoEntity[] = [];
for (let index = 0; index < collection.features.length; index++) {
const feature = collection.features[index] as GeoJsonFeature;
if (typeof feature !== "object" || feature === null) continue;
// GeoJSON coordinate order is [longitude, latitude] — destructure accordingly.
// Swapping these is Pitfall 1 (plan constraint).
const [lon = 0, lat = 0] = feature.geometry?.coordinates ?? [];
const props: Record<string, unknown> = feature.properties ?? {};
const label =
(props.city as string | undefined) ||
(props.country as string | undefined) ||
"Unknown Camera";
entities.push({
id: `camera-${prefix}-${index}`,
pluginId,
latitude: lat,
longitude: lon,
altitude: DEFAULT_CAMERA_ALT,
timestamp: new Date(),
label,
properties: { ...props },
});
}
return entities;
}