Files
homarr/packages/integrations/src/unifi-os/unifi-sm-api.ts
T
zacharyandClaude Opus 5 ca1cc54623 feat(integrations): add optional UniFi Site Manager client with 5min cache
Task 4 of the UniFi OS integration: an optional cloud client for
Ubiquiti's Site Manager API that enriches the local console with ISP
latency data. Instantiated only when a cloud API key is configured
(Task 5). Every failure path (bad key, non-ok status, parse error,
unmatched gateway MAC) returns null rather than throwing, since the
cloud is a pure enrichment. Metrics are cached 5 minutes, keyed by
gateway MAC, to respect the ~27 min publication lag and avoid rate
limiting; the query window is 3 hours because a 15-minute window
returns an empty array on the real API.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-08 00:21:50 +02:00

137 lines
4.3 KiB
TypeScript

import { createLogger } from "@homarr/core/infrastructure/logs";
import type { UnifiOsFetch } from "./unifi-os-api";
import type { UnifiOsIspMetrics } from "./unifi-os-types";
import {
matchCloudSite,
parseUnifiOsAsync,
unifiSmIspMetricsResponseSchema,
unifiSmSiteSchema,
} from "./unifi-os-types";
import { z } from "zod/v4";
const logger = createLogger({ module: "unifiSmApi" });
const BASE_URL = "https://api.ui.com";
const REQUEST_TIMEOUT_MS = 15_000;
/**
* Les métriques cloud sont agrégées par tranches de 5 min et publiées avec un
* retard mesuré d'environ 27 min. Les rafraîchir plus souvent que le cache
* n'apporterait aucune donnée nouvelle et rapprocherait d'une limitation de débit.
*/
const CACHE_TTL_MS = 5 * 60 * 1000;
/** Une fenêtre de 15 min renvoie un tableau vide sur l'API réelle ; 3 h fonctionne. */
const QUERY_WINDOW_MS = 3 * 60 * 60 * 1000;
const siteListSchema = z.looseObject({ data: z.array(unifiSmSiteSchema) });
interface CacheEntry {
expiresAt: number;
value: UnifiOsIspMetrics | null;
}
/**
* Client de l'API cloud Site Manager. Entièrement optionnel : il n'est instancié
* que lorsqu'une clé Site Manager est configurée.
*
* Toute erreur est absorbée et convertie en `null`. Le cloud est un enrichissement ;
* son indisponibilité ne doit jamais faire tomber le widget.
*/
export class UnifiSmApi {
private static readonly cache = new Map<string, CacheEntry>();
constructor(
private readonly apiKey: string,
private readonly fetchAsync: UnifiOsFetch,
) {}
/** Réservé aux tests : le cache est statique et survivrait d'un cas à l'autre. */
public static clearCache(): void {
UnifiSmApi.cache.clear();
}
public async getIspMetricsAsync(gatewayMac: string | null): Promise<UnifiOsIspMetrics | null> {
if (gatewayMac === null) return null;
const cached = UnifiSmApi.cache.get(gatewayMac);
if (cached !== undefined && cached.expiresAt > Date.now()) {
return cached.value;
}
let value: UnifiOsIspMetrics | null = null;
try {
value = await this.fetchIspMetricsAsync(gatewayMac);
} catch (error) {
logger.warn("Failed to read UniFi Site Manager metrics", { error });
}
UnifiSmApi.cache.set(gatewayMac, { expiresAt: Date.now() + CACHE_TTL_MS, value });
return value;
}
private async fetchIspMetricsAsync(gatewayMac: string): Promise<UnifiOsIspMetrics | null> {
const sitesResponse = await this.fetchAsync(`${BASE_URL}/v1/sites`, {
headers: { "X-API-KEY": this.apiKey, Accept: "application/json" },
timeout: REQUEST_TIMEOUT_MS,
});
if (!sitesResponse.ok) return null;
const sites = await parseUnifiOsAsync(
await sitesResponse.json(),
siteListSchema,
"Invalid Site Manager sites response",
);
const site = matchCloudSite(gatewayMac, sites.data);
if (site === null) return null;
const end = new Date();
const begin = new Date(end.getTime() - QUERY_WINDOW_MS);
const metricsResponse = await this.fetchAsync(`${BASE_URL}/v1/isp-metrics/5m/query`, {
method: "POST",
headers: { "X-API-KEY": this.apiKey, Accept: "application/json", "Content-Type": "application/json" },
timeout: REQUEST_TIMEOUT_MS,
body: JSON.stringify({
sites: [
{
hostId: site.hostId,
siteId: site.siteId,
beginTimestamp: begin.toISOString(),
endTimestamp: end.toISOString(),
},
],
}),
});
if (!metricsResponse.ok) return null;
const parsed = await parseUnifiOsAsync(
await metricsResponse.json(),
unifiSmIspMetricsResponseSchema,
"Invalid Site Manager ISP metrics response",
);
const periods = parsed.data.metrics[0]?.periods ?? [];
const latest = periods.at(-1);
const wan = latest?.data.wan;
if (latest === undefined || wan === undefined) return null;
const externalIp = Object.values(site.statistics?.wans ?? {})
.map((entry) => entry.externalIp)
.find((ip) => ip !== undefined);
return {
name: wan.ispName ?? site.statistics?.ispInfo?.name ?? "",
externalIp: externalIp ?? null,
latencyMs: wan.avgLatency ?? 0,
maxLatencyMs: wan.maxLatency ?? 0,
packetLossPct: wan.packetLoss ?? 0,
uptimePct: wan.uptime ?? site.statistics?.percentages?.wanUptime ?? 0,
measuredAt: new Date(latest.metricTime),
};
}
}