fix(integrations): select newest ISP metric period explicitly
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2d601279e3
commit
2de3063dc1
2 files changed
+37
-1
No files matched your search
@@ -79,6 +79,39 @@ describe("UnifiSmApi getIspMetricsAsync", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("returns the newest period by metricTime even when periods arrive out of order", async () => {
|
||||
const fetchAsync = vi.fn(async (url: string, _init?: RequestInit) => {
|
||||
if (!url.includes("isp-metrics")) return jsonResponse(sitesBody);
|
||||
|
||||
return jsonResponse({
|
||||
data: {
|
||||
metrics: [
|
||||
{
|
||||
periods: [
|
||||
{
|
||||
metricTime: "2026-09-08T09:10:00Z",
|
||||
data: {
|
||||
wan: { avgLatency: 11, maxLatency: 12, packetLoss: 0, uptime: 100, ispName: "Example ISP" },
|
||||
},
|
||||
},
|
||||
{
|
||||
metricTime: "2026-09-08T08:00:00Z",
|
||||
data: { wan: { avgLatency: 99, maxLatency: 99, packetLoss: 5, uptime: 90, ispName: "Old" } },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
const api = new UnifiSmApi("cloud-key", fetchAsync as never);
|
||||
|
||||
const metrics = await api.getIspMetricsAsync(GATEWAY_MAC);
|
||||
|
||||
expect(metrics?.latencyMs).toBe(11);
|
||||
expect(metrics?.measuredAt).toEqual(new Date("2026-09-08T09:10:00Z"));
|
||||
});
|
||||
|
||||
test("returns null when no cloud site matches, never another account site", async () => {
|
||||
const { api } = createApi();
|
||||
|
||||
|
||||
@@ -115,7 +115,10 @@ export class UnifiSmApi {
|
||||
);
|
||||
|
||||
const periods = parsed.data.metrics[0]?.periods ?? [];
|
||||
const latest = periods.at(-1);
|
||||
const latest = periods.reduce<(typeof periods)[number] | undefined>((newest, period) => {
|
||||
if (newest === undefined) return period;
|
||||
return new Date(period.metricTime).getTime() > new Date(newest.metricTime).getTime() ? period : newest;
|
||||
}, undefined);
|
||||
const wan = latest?.data.wan;
|
||||
if (latest === undefined || wan === undefined) return null;
|
||||
|
||||
|
||||
Reference in new issue
Block a user