mirror of https://github.com/jetkvm/kvm.git
feat: add someIterable utility function and update Metric components for consistent metric handling
- Introduced `someIterable` function to check for the presence of a metric in an iterable. - Updated `CustomTooltip` and `Metric` components to use `metric` instead of `stat` for improved clarity. - Refactored `StatChart` to align with the new metric naming convention.
This commit is contained in:
parent
5acfb67d29
commit
3bd9f841e0
|
@ -1,25 +1,25 @@
|
||||||
import Card from "@components/Card";
|
import Card from "@components/Card";
|
||||||
|
|
||||||
export interface CustomTooltipProps {
|
export interface CustomTooltipProps {
|
||||||
payload: { payload: { date: number; stat: number }; unit: string }[];
|
payload: { payload: { date: number; metric: number }; unit: string }[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function CustomTooltip({ payload }: CustomTooltipProps) {
|
export default function CustomTooltip({ payload }: CustomTooltipProps) {
|
||||||
if (payload?.length) {
|
if (payload?.length) {
|
||||||
const toolTipData = payload[0];
|
const toolTipData = payload[0];
|
||||||
const { date, stat } = toolTipData.payload;
|
const { date, metric } = toolTipData.payload;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card>
|
<Card>
|
||||||
<div className="p-2 text-black dark:text-white">
|
<div className="px-2 py-1.5 text-black dark:text-white">
|
||||||
<div className="font-semibold">
|
<div className="text-[13px] font-semibold">
|
||||||
{new Date(date * 1000).toLocaleTimeString()}
|
{new Date(date * 1000).toLocaleTimeString()}
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
<div className="flex items-center gap-x-1">
|
<div className="flex items-center gap-x-1">
|
||||||
<div className="h-[2px] w-2 bg-blue-700" />
|
<div className="h-[2px] w-2 bg-blue-700" />
|
||||||
<span >
|
<span className="text-[13px]">
|
||||||
{stat} {toolTipData?.unit}
|
{metric} {toolTipData?.unit}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
@ -1,12 +1,14 @@
|
||||||
import { ComponentProps } from "react";
|
import { ComponentProps } from "react";
|
||||||
import { cva, cx } from "cva";
|
import { cva, cx } from "cva";
|
||||||
|
|
||||||
|
import { someIterable } from "../utils";
|
||||||
|
|
||||||
import { GridCard } from "./Card";
|
import { GridCard } from "./Card";
|
||||||
import StatChart from "./StatChart";
|
import MetricsChart from "./MetricsChart";
|
||||||
|
|
||||||
interface ChartPoint {
|
interface ChartPoint {
|
||||||
date: number;
|
date: number;
|
||||||
stat: number | null;
|
metric: number | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface MetricProps<T, K extends keyof T> {
|
interface MetricProps<T, K extends keyof T> {
|
||||||
|
@ -17,45 +19,42 @@ interface MetricProps<T, K extends keyof T> {
|
||||||
data?: ChartPoint[];
|
data?: ChartPoint[];
|
||||||
gate?: Map<number, unknown>;
|
gate?: Map<number, unknown>;
|
||||||
supported?: boolean;
|
supported?: boolean;
|
||||||
map?: (p: { date: number; stat: T[K] | null }) => ChartPoint;
|
map?: (p: { date: number; metric: number | null }) => ChartPoint;
|
||||||
domain?: [number, number];
|
domain?: [number, number];
|
||||||
unit?: string;
|
unit: string;
|
||||||
heightClassName?: string;
|
heightClassName?: string;
|
||||||
referenceValue?: number;
|
referenceValue?: number;
|
||||||
badge?: ComponentProps<typeof MetricHeader>["badge"];
|
badge?: ComponentProps<typeof MetricHeader>["badge"];
|
||||||
badgeTheme?: ComponentProps<typeof MetricHeader>["badgeTheme"];
|
badgeTheme?: ComponentProps<typeof MetricHeader>["badgeTheme"];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* eslint-disable-next-line */
|
||||||
export function createChartArray<T, K extends keyof T>(
|
export function createChartArray<T, K extends keyof T>(
|
||||||
stream: Map<number, T>,
|
metrics: Map<number, T>,
|
||||||
metric: K,
|
metricName: K,
|
||||||
): { date: number; stat: T[K] | null }[] {
|
) {
|
||||||
const stat = Array.from(stream).map(([key, stats]) => {
|
const result: { date: number; metric: number | null }[] = [];
|
||||||
return { date: key, stat: stats[metric] };
|
const iter = metrics.entries();
|
||||||
});
|
let next = iter.next() as IteratorResult<[number, T]>;
|
||||||
|
|
||||||
// Sort the dates to ensure they are in chronological order
|
|
||||||
const sortedStat = stat.map(x => x.date).sort((a, b) => a - b);
|
|
||||||
|
|
||||||
// Determine the earliest statistic date
|
|
||||||
const earliestStat = sortedStat[0];
|
|
||||||
|
|
||||||
// Current time in seconds since the Unix epoch
|
|
||||||
const now = Math.floor(Date.now() / 1000);
|
const now = Math.floor(Date.now() / 1000);
|
||||||
|
|
||||||
// Determine the starting point for the chart data
|
// We want 120 data points, in the chart.
|
||||||
const firstChartDate = earliestStat ? Math.min(earliestStat, now - 120) : now - 120;
|
const firstDate = Math.min(next.value?.[0] ?? now, now - 120);
|
||||||
|
|
||||||
// Generate the chart array for the range between 'firstChartDate' and 'now'
|
for (let t = firstDate; t < now; t++) {
|
||||||
return Array.from({ length: now - firstChartDate }, (_, i) => {
|
while (!next.done && next.value[0] < t) next = iter.next();
|
||||||
const currentDate = firstChartDate + i;
|
const has = !next.done && next.value[0] === t;
|
||||||
return {
|
|
||||||
date: currentDate,
|
let metric = null;
|
||||||
// Find the statistic for 'currentDate', or use the last known statistic if none exists for that date
|
if (has) metric = next.value[1][metricName] as number;
|
||||||
stat: stat.find(x => x.date === currentDate)?.stat ?? null,
|
result.push({ date: t, metric });
|
||||||
};
|
|
||||||
});
|
if (has) next = iter.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
const theme = {
|
const theme = {
|
||||||
light:
|
light:
|
||||||
"bg-white text-black border border-slate-800/20 dark:border dark:border-slate-700 dark:bg-slate-800 dark:text-slate-300",
|
"bg-white text-black border border-slate-800/20 dark:border dark:border-slate-700 dark:bg-slate-800 dark:text-slate-300",
|
||||||
|
@ -110,26 +109,30 @@ export function Metric<T, K extends keyof T>({
|
||||||
domain = [0, 600],
|
domain = [0, 600],
|
||||||
unit = "",
|
unit = "",
|
||||||
heightClassName = "h-[127px]",
|
heightClassName = "h-[127px]",
|
||||||
referenceValue,
|
|
||||||
badge,
|
badge,
|
||||||
badgeTheme,
|
badgeTheme,
|
||||||
}: MetricProps<T, K>) {
|
}: MetricProps<T, K>) {
|
||||||
const ready = gate ? gate.size > 0 : stream ? stream.size > 0 : true;
|
const ready = gate ? gate.size > 0 : stream ? stream.size > 0 : true;
|
||||||
const supportedFinal =
|
const supportedFinal =
|
||||||
supported ??
|
supported ??
|
||||||
(stream && metric
|
(stream && metric ? someIterable(stream, ([, s]) => s[metric] !== undefined) : true);
|
||||||
? Array.from(stream).some(([, s]) => s[metric] !== undefined)
|
|
||||||
: true);
|
|
||||||
|
|
||||||
const raw = stream && metric ? createChartArray(stream, metric) : [];
|
// Either we let the consumer provide their own chartArray, or we create one from the stream and metric.
|
||||||
const dataFinal: ChartPoint[] =
|
const raw = data ?? ((stream && metric && createChartArray(stream, metric)) || []);
|
||||||
data ??
|
|
||||||
(map
|
// If the consumer provides a map function, we apply it to the raw data.
|
||||||
? raw.map(map)
|
const dataFinal: ChartPoint[] = map ? raw.map(map) : raw;
|
||||||
: raw.map(x => ({
|
const recent = dataFinal
|
||||||
date: x.date,
|
.slice(-(raw.length - 1))
|
||||||
stat: typeof x.stat === "number" ? (x.stat as unknown as number) : null,
|
.filter(x => x.metric != null) as ChartPoint[];
|
||||||
})));
|
|
||||||
|
// Average the recent values
|
||||||
|
const computedReferenceValue =
|
||||||
|
recent.length > 0
|
||||||
|
? Math.round(
|
||||||
|
recent.reduce((sum, x) => sum + (x.metric as number), 0) / recent.length,
|
||||||
|
)
|
||||||
|
: undefined;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
|
@ -149,11 +152,11 @@ export function Metric<T, K extends keyof T>({
|
||||||
<p className="text-slate-700">Waiting for data...</p>
|
<p className="text-slate-700">Waiting for data...</p>
|
||||||
</div>
|
</div>
|
||||||
) : supportedFinal ? (
|
) : supportedFinal ? (
|
||||||
<StatChart
|
<MetricsChart
|
||||||
data={dataFinal}
|
data={dataFinal}
|
||||||
domain={domain}
|
domain={domain}
|
||||||
unit={unit}
|
unit={unit}
|
||||||
referenceValue={referenceValue}
|
referenceValue={computedReferenceValue}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<div className="flex flex-col items-center space-y-1">
|
<div className="flex flex-col items-center space-y-1">
|
||||||
|
|
|
@ -12,13 +12,13 @@ import {
|
||||||
|
|
||||||
import CustomTooltip, { CustomTooltipProps } from "@components/CustomTooltip";
|
import CustomTooltip, { CustomTooltipProps } from "@components/CustomTooltip";
|
||||||
|
|
||||||
export default function StatChart({
|
export default function MetricsChart({
|
||||||
data,
|
data,
|
||||||
domain,
|
domain,
|
||||||
unit,
|
unit,
|
||||||
referenceValue,
|
referenceValue,
|
||||||
}: {
|
}: {
|
||||||
data: { date: number; stat: number | null | undefined }[];
|
data: { date: number; metric: number | null | undefined }[];
|
||||||
domain?: [string | number, string | number];
|
domain?: [string | number, string | number];
|
||||||
unit?: string;
|
unit?: string;
|
||||||
referenceValue?: number;
|
referenceValue?: number;
|
||||||
|
@ -33,7 +33,7 @@ export default function StatChart({
|
||||||
strokeLinecap="butt"
|
strokeLinecap="butt"
|
||||||
stroke="rgba(30, 41, 59, 0.1)"
|
stroke="rgba(30, 41, 59, 0.1)"
|
||||||
/>
|
/>
|
||||||
{referenceValue && (
|
{referenceValue !== undefined && (
|
||||||
<ReferenceLine
|
<ReferenceLine
|
||||||
y={referenceValue}
|
y={referenceValue}
|
||||||
strokeDasharray="3 3"
|
strokeDasharray="3 3"
|
||||||
|
@ -64,7 +64,7 @@ export default function StatChart({
|
||||||
.map(x => x.date)}
|
.map(x => x.date)}
|
||||||
/>
|
/>
|
||||||
<YAxis
|
<YAxis
|
||||||
dataKey="stat"
|
dataKey="metric"
|
||||||
axisLine={false}
|
axisLine={false}
|
||||||
orientation="right"
|
orientation="right"
|
||||||
tick={{
|
tick={{
|
||||||
|
@ -73,6 +73,7 @@ export default function StatChart({
|
||||||
fill: "rgba(107, 114, 128, 1)",
|
fill: "rgba(107, 114, 128, 1)",
|
||||||
}}
|
}}
|
||||||
padding={{ top: 0, bottom: 0 }}
|
padding={{ top: 0, bottom: 0 }}
|
||||||
|
allowDecimals
|
||||||
tickLine={false}
|
tickLine={false}
|
||||||
unit={unit}
|
unit={unit}
|
||||||
domain={domain || ["auto", "auto"]}
|
domain={domain || ["auto", "auto"]}
|
||||||
|
@ -87,7 +88,7 @@ export default function StatChart({
|
||||||
<Line
|
<Line
|
||||||
type="monotone"
|
type="monotone"
|
||||||
isAnimationActive={false}
|
isAnimationActive={false}
|
||||||
dataKey="stat"
|
dataKey="metric"
|
||||||
stroke="rgb(29 78 216)"
|
stroke="rgb(29 78 216)"
|
||||||
strokeLinecap="round"
|
strokeLinecap="round"
|
||||||
strokeWidth={2}
|
strokeWidth={2}
|
|
@ -5,19 +5,13 @@ import { useRTCStore, useUiStore } from "@/hooks/stores";
|
||||||
|
|
||||||
import { createChartArray, Metric } from "../Metric";
|
import { createChartArray, Metric } from "../Metric";
|
||||||
import { SettingsSectionHeader } from "../SettingsSectionHeader";
|
import { SettingsSectionHeader } from "../SettingsSectionHeader";
|
||||||
|
import { someIterable } from "../../utils";
|
||||||
|
|
||||||
export default function ConnectionStatsSidebar() {
|
export default function ConnectionStatsSidebar() {
|
||||||
const inboundVideoRtpStats = useRTCStore(state => state.inboundRtpStats);
|
const inboundVideoRtpStats = useRTCStore(state => state.inboundRtpStats);
|
||||||
const iceCandidatePairStats = useRTCStore(state => state.candidatePairStats);
|
const iceCandidatePairStats = useRTCStore(state => state.candidatePairStats);
|
||||||
const setSidebarView = useUiStore(state => state.setSidebarView);
|
const setSidebarView = useUiStore(state => state.setSidebarView);
|
||||||
|
|
||||||
function isMetricSupported<T, K extends keyof T>(
|
|
||||||
stream: Map<number, T>,
|
|
||||||
metric: K,
|
|
||||||
): boolean {
|
|
||||||
return Array.from(stream).some(([, stat]) => stat[metric] !== undefined);
|
|
||||||
}
|
|
||||||
|
|
||||||
const appendInboundVideoRtpStats = useRTCStore(state => state.appendInboundRtpStats);
|
const appendInboundVideoRtpStats = useRTCStore(state => state.appendInboundRtpStats);
|
||||||
const appendIceCandidatePair = useRTCStore(state => state.appendCandidatePairStats);
|
const appendIceCandidatePair = useRTCStore(state => state.appendCandidatePairStats);
|
||||||
const appendDiskDataChannelStats = useRTCStore(
|
const appendDiskDataChannelStats = useRTCStore(
|
||||||
|
@ -72,13 +66,13 @@ export default function ConnectionStatsSidebar() {
|
||||||
);
|
);
|
||||||
|
|
||||||
const jitterBufferAvgDelayData = jitterBufferDelay.map((d, idx) => {
|
const jitterBufferAvgDelayData = jitterBufferDelay.map((d, idx) => {
|
||||||
if (idx === 0) return { date: d.date, stat: null };
|
if (idx === 0) return { date: d.date, metric: null };
|
||||||
const prevDelay = jitterBufferDelay[idx - 1]?.stat as number | null | undefined;
|
const prevDelay = jitterBufferDelay[idx - 1]?.metric as number | null | undefined;
|
||||||
const currDelay = d.stat as number | null | undefined;
|
const currDelay = d.metric as number | null | undefined;
|
||||||
const prevEmitted =
|
const prevEmitted =
|
||||||
(jitterBufferEmittedCount[idx - 1]?.stat as number | null | undefined) ?? null;
|
(jitterBufferEmittedCount[idx - 1]?.metric as number | null | undefined) ?? null;
|
||||||
const currEmitted =
|
const currEmitted =
|
||||||
(jitterBufferEmittedCount[idx]?.stat as number | null | undefined) ?? null;
|
(jitterBufferEmittedCount[idx]?.metric as number | null | undefined) ?? null;
|
||||||
|
|
||||||
if (
|
if (
|
||||||
prevDelay == null ||
|
prevDelay == null ||
|
||||||
|
@ -86,7 +80,7 @@ export default function ConnectionStatsSidebar() {
|
||||||
prevEmitted == null ||
|
prevEmitted == null ||
|
||||||
currEmitted == null
|
currEmitted == null
|
||||||
) {
|
) {
|
||||||
return { date: d.date, stat: null };
|
return { date: d.date, metric: null };
|
||||||
}
|
}
|
||||||
|
|
||||||
const deltaDelay = currDelay - prevDelay;
|
const deltaDelay = currDelay - prevDelay;
|
||||||
|
@ -94,23 +88,13 @@ export default function ConnectionStatsSidebar() {
|
||||||
|
|
||||||
// Guard counter resets or no emitted frames
|
// Guard counter resets or no emitted frames
|
||||||
if (deltaDelay < 0 || deltaEmitted <= 0) {
|
if (deltaDelay < 0 || deltaEmitted <= 0) {
|
||||||
return { date: d.date, stat: null };
|
return { date: d.date, metric: null };
|
||||||
}
|
}
|
||||||
|
|
||||||
const valueMs = Math.round((deltaDelay / deltaEmitted) * 1000);
|
const valueMs = Math.round((deltaDelay / deltaEmitted) * 1000);
|
||||||
return { date: d.date, stat: valueMs };
|
return { date: d.date, metric: valueMs };
|
||||||
});
|
});
|
||||||
|
|
||||||
// Rolling average over the last N seconds for the reference line
|
|
||||||
const rollingWindowSeconds = 20;
|
|
||||||
const recent = jitterBufferAvgDelayData
|
|
||||||
.slice(-rollingWindowSeconds)
|
|
||||||
.filter(x => x.stat != null) as { date: number; stat: number }[];
|
|
||||||
const referenceValue =
|
|
||||||
recent.length > 0
|
|
||||||
? Math.round(recent.reduce((sum, x) => sum + (x.stat as number), 0) / recent.length)
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="grid h-full grid-rows-(--grid-headerBody) shadow-xs">
|
<div className="grid h-full grid-rows-(--grid-headerBody) shadow-xs">
|
||||||
<SidebarHeader title="Connection Stats" setSidebarView={setSidebarView} />
|
<SidebarHeader title="Connection Stats" setSidebarView={setSidebarView} />
|
||||||
|
@ -128,11 +112,10 @@ export default function ConnectionStatsSidebar() {
|
||||||
title="Round-Trip Time"
|
title="Round-Trip Time"
|
||||||
description="Round-trip time for the active ICE candidate pair between peers."
|
description="Round-trip time for the active ICE candidate pair between peers."
|
||||||
stream={iceCandidatePairStats}
|
stream={iceCandidatePairStats}
|
||||||
gate={inboundVideoRtpStats}
|
|
||||||
metric="currentRoundTripTime"
|
metric="currentRoundTripTime"
|
||||||
map={x => ({
|
map={x => ({
|
||||||
date: x.date,
|
date: x.date,
|
||||||
stat: x.stat ? Math.round((x.stat as number) * 1000) : null,
|
metric: x.metric != null ? Math.round(x.metric * 1000) : null,
|
||||||
})}
|
})}
|
||||||
domain={[0, 600]}
|
domain={[0, 600]}
|
||||||
unit=" ms"
|
unit=" ms"
|
||||||
|
@ -156,7 +139,7 @@ export default function ConnectionStatsSidebar() {
|
||||||
metric="jitter"
|
metric="jitter"
|
||||||
map={x => ({
|
map={x => ({
|
||||||
date: x.date,
|
date: x.date,
|
||||||
stat: x.stat ? Math.round((x.stat as number) * 1000) : null,
|
metric: x.metric != null ? Math.round(x.metric * 1000) : null,
|
||||||
})}
|
})}
|
||||||
domain={[0, 10]}
|
domain={[0, 10]}
|
||||||
unit=" ms"
|
unit=" ms"
|
||||||
|
@ -171,12 +154,17 @@ export default function ConnectionStatsSidebar() {
|
||||||
data={jitterBufferAvgDelayData}
|
data={jitterBufferAvgDelayData}
|
||||||
gate={inboundVideoRtpStats}
|
gate={inboundVideoRtpStats}
|
||||||
supported={
|
supported={
|
||||||
isMetricSupported(inboundVideoRtpStats, "jitterBufferDelay") &&
|
someIterable(
|
||||||
isMetricSupported(inboundVideoRtpStats, "jitterBufferEmittedCount")
|
inboundVideoRtpStats,
|
||||||
|
([, x]) => x.jitterBufferDelay != null,
|
||||||
|
) &&
|
||||||
|
someIterable(
|
||||||
|
inboundVideoRtpStats,
|
||||||
|
([, x]) => x.jitterBufferEmittedCount != null,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
domain={[0, 30]}
|
domain={[0, 30]}
|
||||||
unit=" ms"
|
unit=" ms"
|
||||||
referenceValue={referenceValue}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Packets Lost */}
|
{/* Packets Lost */}
|
||||||
|
|
|
@ -738,7 +738,7 @@ export default function KvmIdRoute() {
|
||||||
send("getUpdateStatus", {}, async (resp: JsonRpcResponse) => {
|
send("getUpdateStatus", {}, async (resp: JsonRpcResponse) => {
|
||||||
if ("error" in resp) {
|
if ("error" in resp) {
|
||||||
notifications.error(`Failed to get device version: ${resp.error}`);
|
notifications.error(`Failed to get device version: ${resp.error}`);
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = resp.result as SystemVersionInfo;
|
const result = resp.result as SystemVersionInfo;
|
||||||
|
|
|
@ -94,6 +94,17 @@ export const formatters = {
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export function someIterable<T>(
|
||||||
|
iterable: Iterable<T>,
|
||||||
|
predicate: (item: T) => boolean,
|
||||||
|
): boolean {
|
||||||
|
for (const item of iterable) {
|
||||||
|
if (predicate(item)) return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
export const VIDEO = new Blob(
|
export const VIDEO = new Blob(
|
||||||
[
|
[
|
||||||
new Uint8Array([
|
new Uint8Array([
|
||||||
|
|
Loading…
Reference in New Issue