EdgeFunctionOverview.utils.ts298 lines · main
| 1 | import dayjs from 'dayjs' |
| 2 | import maxBy from 'lodash/maxBy' |
| 3 | import meanBy from 'lodash/meanBy' |
| 4 | import sumBy from 'lodash/sumBy' |
| 5 | import type { ChartConfig } from 'ui' |
| 6 | |
| 7 | import type { ChartIntervals } from '@/types' |
| 8 | |
| 9 | export type EdgeFunctionChartRawDatum = { |
| 10 | timestamp: string | number |
| 11 | success_count?: string | number |
| 12 | redirect_count?: string | number |
| 13 | client_err_count?: string | number |
| 14 | server_err_count?: string | number |
| 15 | avg_execution_time?: string | number |
| 16 | max_execution_time?: string | number |
| 17 | avg_cpu_time_used?: string | number |
| 18 | max_cpu_time_used?: string | number |
| 19 | avg_memory_used?: string | number |
| 20 | avg_heap_memory_used?: string | number |
| 21 | avg_external_memory_used?: string | number |
| 22 | } |
| 23 | |
| 24 | export type EdgeFunctionChartDatum = { |
| 25 | timestamp: string |
| 26 | success_count: number |
| 27 | redirect_count: number |
| 28 | client_err_count: number |
| 29 | server_err_count: number |
| 30 | avg_execution_time: number |
| 31 | max_execution_time: number |
| 32 | avg_cpu_time_used: number |
| 33 | max_cpu_time_used: number |
| 34 | avg_memory_used: number |
| 35 | avg_heap_memory_used: number |
| 36 | avg_external_memory_used: number |
| 37 | } |
| 38 | |
| 39 | export type InvocationChartDatum = { |
| 40 | timestamp: string |
| 41 | ok_count: number |
| 42 | warning_count: number |
| 43 | error_count: number |
| 44 | } |
| 45 | |
| 46 | export type InvocationUpdateAnnotation = { |
| 47 | timestamp: string |
| 48 | position: number |
| 49 | updatedAt: Date |
| 50 | } |
| 51 | |
| 52 | export const EDGE_FUNCTION_CHART_INTERVALS: ChartIntervals[] = [ |
| 53 | { |
| 54 | key: '15min', |
| 55 | label: '15 min', |
| 56 | startValue: 15, |
| 57 | startUnit: 'minute', |
| 58 | format: 'MMM D, h:mm:ssa', |
| 59 | }, |
| 60 | { |
| 61 | key: '1hr', |
| 62 | label: '1 hour', |
| 63 | startValue: 1, |
| 64 | startUnit: 'hour', |
| 65 | format: 'MMM D, h:mma', |
| 66 | }, |
| 67 | { |
| 68 | key: '3hr', |
| 69 | label: '3 hours', |
| 70 | startValue: 3, |
| 71 | startUnit: 'hour', |
| 72 | format: 'MMM D, h:mma', |
| 73 | }, |
| 74 | { |
| 75 | key: '1day', |
| 76 | label: '1 day', |
| 77 | startValue: 1, |
| 78 | startUnit: 'day', |
| 79 | format: 'MMM D, h:mma', |
| 80 | }, |
| 81 | ] |
| 82 | |
| 83 | export const INVOCATION_CHART_CONFIG = { |
| 84 | ok_count: { |
| 85 | label: 'Ok', |
| 86 | color: 'hsl(var(--brand-default))', |
| 87 | }, |
| 88 | warning_count: { |
| 89 | label: 'Warnings', |
| 90 | color: 'hsl(var(--warning-default))', |
| 91 | }, |
| 92 | error_count: { |
| 93 | label: 'Errors', |
| 94 | color: 'hsl(var(--destructive-default))', |
| 95 | }, |
| 96 | } satisfies ChartConfig |
| 97 | |
| 98 | export const CPU_TIME_CHART_CONFIG = { |
| 99 | max_cpu_time_used: { |
| 100 | label: 'Max CPU Time', |
| 101 | color: 'hsl(var(--brand-default))', |
| 102 | }, |
| 103 | } satisfies ChartConfig |
| 104 | |
| 105 | export const EXECUTION_TIME_CHART_CONFIG = { |
| 106 | avg_execution_time: { |
| 107 | label: 'Average Execution Time', |
| 108 | color: 'hsl(var(--foreground-default))', |
| 109 | }, |
| 110 | max_execution_time: { |
| 111 | label: 'Max Execution Time', |
| 112 | color: 'hsl(var(--brand-default))', |
| 113 | }, |
| 114 | } satisfies ChartConfig |
| 115 | |
| 116 | export const MEMORY_CHART_CONFIG = { |
| 117 | avg_memory_used: { |
| 118 | label: 'Memory Usage', |
| 119 | color: 'hsl(var(--brand-default))', |
| 120 | }, |
| 121 | } satisfies ChartConfig |
| 122 | |
| 123 | const toManipulateUnit = (unit: ChartIntervals['startUnit']) => unit as dayjs.ManipulateType |
| 124 | const toNumber = (value: string | number | undefined) => Number(value ?? 0) |
| 125 | |
| 126 | export const getBucketedTimeRange = ( |
| 127 | interval: ChartIntervals, |
| 128 | now: Date = new Date() |
| 129 | ): [Date, Date] => { |
| 130 | const currentTime = dayjs(now) |
| 131 | const unit = toManipulateUnit(interval.startUnit) |
| 132 | const start = currentTime.subtract(interval.startValue, unit).startOf(unit) |
| 133 | const end = currentTime.startOf(unit) |
| 134 | |
| 135 | return [start.toDate(), end.toDate()] |
| 136 | } |
| 137 | |
| 138 | export const getRollingTimeRange = ( |
| 139 | interval: ChartIntervals, |
| 140 | now: Date = new Date() |
| 141 | ): [Date, Date] => { |
| 142 | const currentTime = dayjs(now) |
| 143 | const start = currentTime.subtract(interval.startValue, toManipulateUnit(interval.startUnit)) |
| 144 | |
| 145 | return [start.toDate(), currentTime.toDate()] |
| 146 | } |
| 147 | |
| 148 | export const formatChartTimestamp = (value: Date | string | number | undefined, format: string) => { |
| 149 | return dayjs(value === undefined ? '' : value).format(format) |
| 150 | } |
| 151 | |
| 152 | export const getChartTimeRangeLabels = ( |
| 153 | data: Array<{ timestamp: string }>, |
| 154 | format: string |
| 155 | ): { start: string; end: string } | undefined => { |
| 156 | if (data.length === 0) return undefined |
| 157 | |
| 158 | return { |
| 159 | start: formatChartTimestamp(data[0]?.timestamp, format), |
| 160 | end: formatChartTimestamp(data[data.length - 1]?.timestamp, format), |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | export const toEdgeFunctionChartData = ( |
| 165 | rows: EdgeFunctionChartRawDatum[] = [] |
| 166 | ): EdgeFunctionChartDatum[] => |
| 167 | rows.map((row) => ({ |
| 168 | timestamp: String(row.timestamp ?? ''), |
| 169 | success_count: toNumber(row.success_count), |
| 170 | redirect_count: toNumber(row.redirect_count), |
| 171 | client_err_count: toNumber(row.client_err_count), |
| 172 | server_err_count: toNumber(row.server_err_count), |
| 173 | avg_execution_time: toNumber(row.avg_execution_time), |
| 174 | max_execution_time: toNumber(row.max_execution_time), |
| 175 | avg_cpu_time_used: toNumber(row.avg_cpu_time_used), |
| 176 | max_cpu_time_used: toNumber(row.max_cpu_time_used), |
| 177 | avg_memory_used: toNumber(row.avg_memory_used), |
| 178 | avg_heap_memory_used: toNumber(row.avg_heap_memory_used), |
| 179 | avg_external_memory_used: toNumber(row.avg_external_memory_used), |
| 180 | })) |
| 181 | |
| 182 | export const getInvocationChartData = (data: EdgeFunctionChartDatum[]): InvocationChartDatum[] => |
| 183 | data.map((datum) => ({ |
| 184 | timestamp: datum.timestamp, |
| 185 | ok_count: datum.success_count, |
| 186 | warning_count: datum.redirect_count + datum.client_err_count, |
| 187 | error_count: datum.server_err_count, |
| 188 | })) |
| 189 | |
| 190 | export const getInvocationTotals = (data: InvocationChartDatum[]) => { |
| 191 | const totalInvocationCount = sumBy(data, (datum) => { |
| 192 | return datum.ok_count + datum.warning_count + datum.error_count |
| 193 | }) |
| 194 | |
| 195 | return { |
| 196 | totalInvocationCount, |
| 197 | totalWarningCount: sumBy(data, 'warning_count'), |
| 198 | totalErrorCount: sumBy(data, 'error_count'), |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | export const getExecutionMetrics = (data: EdgeFunctionChartDatum[]) => ({ |
| 203 | averageExecutionTime: meanBy(data, 'avg_execution_time') ?? 0, |
| 204 | maxExecutionTime: maxBy(data, 'max_execution_time')?.max_execution_time ?? 0, |
| 205 | }) |
| 206 | |
| 207 | export const getUsageMetrics = (data: EdgeFunctionChartDatum[]) => { |
| 208 | const totalHeapMemory = sumBy(data, 'avg_heap_memory_used') |
| 209 | const totalExternalMemory = sumBy(data, 'avg_external_memory_used') |
| 210 | |
| 211 | return { |
| 212 | averageCpuTime: meanBy(data, 'avg_cpu_time_used') ?? 0, |
| 213 | maxCpuTime: maxBy(data, 'max_cpu_time_used')?.max_cpu_time_used ?? 0, |
| 214 | averageMemoryUsage: meanBy(data, 'avg_memory_used') ?? 0, |
| 215 | totalHeapMemory, |
| 216 | totalExternalMemory, |
| 217 | totalMemoryByType: totalHeapMemory + totalExternalMemory, |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | export const getInvocationUpdateAnnotation = ({ |
| 222 | updatedAt, |
| 223 | invocationChartData, |
| 224 | windowStart, |
| 225 | windowEnd, |
| 226 | }: { |
| 227 | updatedAt?: string |
| 228 | invocationChartData: InvocationChartDatum[] |
| 229 | windowStart: Date |
| 230 | windowEnd: Date |
| 231 | }): InvocationUpdateAnnotation | undefined => { |
| 232 | if (!updatedAt || invocationChartData.length === 0) return undefined |
| 233 | |
| 234 | const updatedAtDate = new Date(updatedAt) |
| 235 | const updatedAtValue = updatedAtDate.valueOf() |
| 236 | |
| 237 | if (Number.isNaN(updatedAtValue)) return undefined |
| 238 | if (updatedAtValue < windowStart.valueOf() || updatedAtValue > windowEnd.valueOf()) { |
| 239 | return undefined |
| 240 | } |
| 241 | |
| 242 | const closestTimestamp = invocationChartData.reduce((closest, datum) => { |
| 243 | const datumDistance = Math.abs(new Date(datum.timestamp).valueOf() - updatedAtValue) |
| 244 | const closestDistance = Math.abs(new Date(closest.timestamp).valueOf() - updatedAtValue) |
| 245 | |
| 246 | return datumDistance < closestDistance ? datum : closest |
| 247 | }).timestamp |
| 248 | |
| 249 | const markerIndex = invocationChartData.findIndex((datum) => datum.timestamp === closestTimestamp) |
| 250 | if (markerIndex < 0) return undefined |
| 251 | |
| 252 | return { |
| 253 | timestamp: closestTimestamp, |
| 254 | position: ((markerIndex + 0.5) / invocationChartData.length) * 100, |
| 255 | updatedAt: updatedAtDate, |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | export const getSegmentedButtonClassName = (index: number, total: number) => { |
| 260 | if (index === 0) return 'rounded-tr-none rounded-br-none' |
| 261 | if (index === total - 1) return 'rounded-tl-none rounded-bl-none' |
| 262 | return 'rounded-none' |
| 263 | } |
| 264 | |
| 265 | export const getChartEmptyStateCopy = ( |
| 266 | subject: string, |
| 267 | isError: boolean, |
| 268 | errorMessage?: string |
| 269 | ) => ({ |
| 270 | title: isError ? `Unable to load ${subject}` : 'No data to show', |
| 271 | description: isError ? errorMessage : undefined, |
| 272 | }) |
| 273 | |
| 274 | export const formatMetric = (value?: number, unit?: string) => { |
| 275 | if (value === undefined || Number.isNaN(value)) return unit ? `0${unit}` : '0' |
| 276 | |
| 277 | const formatted = unit === 'MB' ? value.toFixed(1) : Math.round(value).toLocaleString('en-US') |
| 278 | return unit ? `${formatted}${unit}` : formatted |
| 279 | } |
| 280 | |
| 281 | export const formatRate = (count: number, total: number) => |
| 282 | new Intl.NumberFormat('en-US', { |
| 283 | style: 'percent', |
| 284 | maximumFractionDigits: 1, |
| 285 | }).format(total === 0 ? 0 : count / total) |
| 286 | |
| 287 | export const formatReferenceDelta = (value: number, reference: number, label = 'average') => { |
| 288 | const difference = value - reference |
| 289 | if (Math.abs(difference) < Number.EPSILON) return `At ${label}` |
| 290 | if (reference === 0) return `${difference > 0 ? 'Above' : 'Below'} ${label}` |
| 291 | |
| 292 | const percentDifference = Math.round(Math.abs((difference / reference) * 100)) |
| 293 | return `${percentDifference}% ${difference > 0 ? 'above' : 'below'} ${label}` |
| 294 | } |
| 295 | |
| 296 | export const getMemoryTooltipDetail = (heapMemory: number, externalMemory: number) => { |
| 297 | return `Heap ${formatMetric(heapMemory, 'MB')} • External ${formatMetric(externalMemory, 'MB')}` |
| 298 | } |