-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathQueueMetricCards.tsx
More file actions
461 lines (432 loc) · 15.5 KB
/
Copy pathQueueMetricCards.tsx
File metadata and controls
461 lines (432 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
import { useEffect, useMemo, useState, type ReactNode } from "react";
import { buildActivityTimeAxis } from "~/components/primitives/charts/activityTimeAxis";
import {
Chart,
type ChartConfig,
type ChartState,
} from "~/components/primitives/charts/ChartCompound";
import { ChartCard } from "~/components/primitives/charts/ChartCard";
import { MiniLineChart } from "~/components/metrics/MiniLineChart";
import {
useMetricResourceQuery,
type MetricResourceTimeRange,
} from "~/hooks/useMetricResourceQuery";
import { Header3 } from "~/components/primitives/Headers";
import { Paragraph } from "~/components/primitives/Paragraph";
import { InfoIconTooltip } from "~/components/primitives/Tooltip";
import { useSearchParams } from "~/hooks/useSearchParam";
import { QUEUE_METRICS_DEFAULT_PERIOD } from "~/components/queues/queueMetricsPeriod";
import { cn } from "~/utils/cn";
import { formatNumberCompact } from "~/utils/numberFormatter";
// Shared building blocks for queue-metric UI (queue detail page, task detail page,
// run inspector). All CH-derived data is fetched client-side through useQueueMetric
// so pages render instantly; loaders only supply live counts and identifiers.
export const QUEUE_METRIC_COLORS = {
running: "var(--color-queues)",
limit: "#4D525B",
queued: "var(--color-queues)",
p50: "#22D3EE",
p95: "#F59E0B",
p99: "#EF4444",
throttled: "#F59E0B",
ckKeys: "#34D399",
ckWait: "#F59E0B",
};
export type QueueMetricIds = {
organizationId: string;
projectId: string;
environmentId: string;
};
export type QueueMetricTimeRange = MetricResourceTimeRange;
export function useQueueMetric(
query: string,
opts: {
ids: QueueMetricIds;
timeRange: QueueMetricTimeRange;
queueName: string;
fillGaps?: boolean;
/** Match the host page's TimeFilter default (e.g. "7d" on task detail). */
defaultPeriod?: string;
/** Poll ClickHouse on this cadence (ms). Omit to use the query's default interval. */
refreshIntervalMs?: number;
}
) {
return useMetricResourceQuery(query, {
...opts.ids,
timeRange: opts.timeRange,
defaultPeriod: opts.defaultPeriod ?? QUEUE_METRICS_DEFAULT_PERIOD,
queues: [opts.queueName],
fillGaps: opts.fillGaps,
refreshIntervalMs: opts.refreshIntervalMs,
});
}
export function toNumber(value: number | string | null | undefined): number {
const n = typeof value === "number" ? value : Number(value);
return Number.isFinite(n) ? n : 0;
}
export function clickhouseTimeToMs(value: unknown): number {
const s = String(value).replace(" ", "T");
return Date.parse(s.endsWith("Z") ? s : `${s}Z`);
}
export function formatWaitMs(ms: number): string {
if (ms < 1000) return `${Math.round(ms)}ms`;
if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`;
if (ms < 3_600_000) return `${(ms / 60_000).toFixed(1)}m`;
return `${(ms / 3_600_000).toFixed(1)}h`;
}
export type QueueMetricSeriesConfig = { key: string; label: string; color: string };
type QueueMetricChartProps = {
query: string;
series: QueueMetricSeriesConfig[];
ids: QueueMetricIds;
timeRange: QueueMetricTimeRange;
queueName: string;
valueFormat?: (value: number) => string;
fillGaps?: boolean;
defaultPeriod?: string;
/** Recolor a series warning where it drops below another (e.g. started below enqueued). */
warningOverlay?: { series: string; below: string } | { series: string; atOrAbove: string };
/**
* Series whose leading zeros should be back-filled with the first real value. Gauge series that
* are only emitted while the queue is active (e.g. the concurrency `limit`) read as 0 before the
* first emission — carry-forward has nothing to carry yet — which draws a false 0→N step. These
* are config values that existed all along, so carry the first value backward instead.
*/
carryBackfill?: string[];
/** Show the series legend below the chart (use for multi-series charts). */
showLegend?: boolean;
/**
* Recolour a series' stroke above a threshold with a gradient split (colour only above the
* line). `value` sets a constant threshold; `valueFromSeries` reads a (roughly constant)
* threshold off another series — e.g. the concurrency limit. `series` targets which line is
* recoloured; the others keep their own colour.
*/
thresholdStroke?: {
aboveColor: string;
series?: string;
value?: number;
valueFromSeries?: string;
};
/** Reports whether the chart has data to plot (false once it settles on the "no activity" state),
* so a wrapping card can hide the legend to match. */
onHasDataChange?: (hasData: boolean) => void;
};
// Bare chart (no card chrome) so it can live inside a shared card, e.g. a tabbed panel.
export function QueueMetricChart({
query,
series,
ids,
timeRange,
queueName,
valueFormat,
fillGaps,
defaultPeriod,
warningOverlay,
carryBackfill,
thresholdStroke,
onHasDataChange,
}: QueueMetricChartProps) {
const { rows, showLoading, failed } = useQueueMetric(query, {
ids,
timeRange,
queueName,
fillGaps,
defaultPeriod,
});
const data = useMemo(() => {
const points = rows
.map((r) => {
const point: { bucket: number } & Record<string, number> = {
bucket: clickhouseTimeToMs(r.t),
};
for (const s of series) point[s.key] = toNumber(r[s.key]);
return point;
})
.filter((p) => Number.isFinite(p.bucket));
// Back-fill leading zeros for config gauges (see `carryBackfill`): find the first positive
// value and carry it back over the earlier buckets so the line doesn't start at a false 0.
if (carryBackfill?.length) {
for (const key of carryBackfill) {
const first = points.findIndex((p) => p[key] > 0);
if (first > 0) {
const value = points[first]![key]!;
for (let i = 0; i < first; i++) points[i]![key] = value;
}
}
}
return points;
}, [rows, series, carryBackfill]);
const chartConfig = useMemo(() => {
const cfg: ChartConfig = {};
for (const s of series) cfg[s.key] = { label: s.label, color: s.color };
return cfg;
}, [series]);
const { tickFormatter, tooltipLabelFormatter } = useMemo(
() => buildActivityTimeAxis(data),
[data]
);
// Resolve the threshold value: a constant, or the max of another series (e.g. the limit line,
// which is effectively constant). A gradient split then colours the target series only above it.
// `valueFromSeries` targets integer-count series (concurrency limit), so split half a unit below
// the limit — that way the line renders warning *at or above* the limit (saturated), matching
// "turns yellow at the limit", rather than only when it strictly exceeds it.
const resolvedThresholdStroke = useMemo(() => {
if (!thresholdStroke) return undefined;
let value = thresholdStroke.value;
if (value == null && thresholdStroke.valueFromSeries) {
let max = -Infinity;
for (const p of data) {
const v = Number(p[thresholdStroke.valueFromSeries]);
if (Number.isFinite(v) && v > max) max = v;
}
value = max > 0 ? max - 0.5 : undefined;
}
if (value == null || !Number.isFinite(value)) return undefined;
return { value, aboveColor: thresholdStroke.aboveColor, series: thresholdStroke.series };
}, [thresholdStroke, data]);
const state: ChartState = showLoading ? "loading" : failed ? "invalid" : undefined;
// Report data presence so a wrapping card can hide its legend when the chart settles on the
// "no activity" state. Only report once loaded, so the legend stays put while loading.
useEffect(() => {
if (!showLoading) onHasDataChange?.(!failed && data.length > 0);
}, [showLoading, failed, data.length, onHasDataChange]);
return (
<Chart.Root
config={chartConfig}
data={data}
dataKey="bucket"
series={series.map((s) => s.key)}
state={state}
fillContainer
>
<Chart.Line
lineType="monotone"
xAxisProps={{ tickFormatter }}
yAxisProps={valueFormat ? { tickFormatter: (v: number) => valueFormat(v) } : undefined}
tooltipLabelFormatter={tooltipLabelFormatter}
tooltipValueFormatter={valueFormat}
warningOverlay={warningOverlay}
thresholdStroke={resolvedThresholdStroke}
/>
</Chart.Root>
);
}
export function QueueMetricChartCard({
title,
info,
titleAccessory,
className,
extraLegend,
...chart
}: QueueMetricChartProps & {
title: string;
info?: ReactNode;
/** Extra content rendered after the info icon inside the title row (e.g. a live readout). */
titleAccessory?: ReactNode;
className?: string;
/** Extra legend entries appended after the series — e.g. a warning state that isn't its own
* series (the orange "over threshold" colour). */
extraLegend?: Array<{ color: string; label: string }>;
}) {
// Hide the legend once the chart settles on the "no activity" state (reported by the chart).
const [hasData, setHasData] = useState(true);
return (
<div className={className ?? "h-64"}>
<ChartCard
title={
<span className="flex flex-col gap-1">
<span className="flex items-center gap-1">
{title}
{info ? (
<InfoIconTooltip
content={info}
contentClassName="max-w-[230px]"
disableHoverableContent
/>
) : null}
{titleAccessory}
</span>
{/* Inline legend below the title (swatch + label per series), matching the list-page
charts — instead of the Chart.Root legend with per-series totals. */}
{chart.showLegend &&
hasData &&
(chart.series.length > 0 || (extraLegend?.length ?? 0) > 0) ? (
<span className="flex flex-wrap items-center gap-2">
{chart.series.map((s) => (
<span
key={s.key}
className="flex items-center gap-1 text-xs font-normal text-text-dimmed"
>
<span className="size-2.5 rounded-[2px]" style={{ backgroundColor: s.color }} />
{s.label}
</span>
))}
{extraLegend?.map((e) => (
<span
key={e.label}
className="flex items-center gap-1 text-xs font-normal text-text-dimmed"
>
<span className="size-2.5 rounded-[2px]" style={{ backgroundColor: e.color }} />
{e.label}
</span>
))}
</span>
) : null}
</span>
}
>
<QueueMetricChart {...chart} onHasDataChange={setHasData} />
</ChartCard>
</div>
);
}
export type QueueLiveCounts = { queued: number; running: number };
// Compact two-line stat block for task detail sidebars: live counts from the loader,
// then delay p95 + peak backlog over the page's TimeFilter range.
export function QueueSidebarStats({
live,
ids,
queueName,
defaultPeriod,
}: {
live: QueueLiveCounts;
ids: QueueMetricIds;
queueName: string;
defaultPeriod?: string;
}) {
const { value } = useSearchParams();
const timeRange: QueueMetricTimeRange = {
period: value("period") ?? null,
from: value("from") ?? null,
to: value("to") ?? null,
};
const { rows, showLoading } = useQueueMetric(
`SELECT max(max_queued) AS peak_queued,\n round(quantilesMerge(0.5, 0.9, 0.95, 0.99)(wait_quantiles)[3]) AS worst_p95\nFROM queue_metrics`,
{ ids, timeRange, queueName, defaultPeriod }
);
const row = rows[0];
const worstP95 = row ? toNumber(row.worst_p95) : 0;
const peakQueued = row ? toNumber(row.peak_queued) : 0;
return (
<>
<Paragraph variant="extra-small" className="tabular-nums text-text-dimmed">
Queued now {live.queued.toLocaleString()} · Running now {live.running.toLocaleString()}
</Paragraph>
<Paragraph variant="extra-small" className="tabular-nums text-text-dimmed">
{showLoading || !row
? "…"
: `Delay p95 ${worstP95 > 0 ? formatWaitMs(worstP95) : "–"} · Peak backlog ${peakQueued.toLocaleString()}`}
</Paragraph>
</>
);
}
// A compact stat card with a recent trend sparkline underneath, for the run inspector.
// The headline is a live "now" value from the loader; the sparkline pulls its own series.
const SPARKLINE_PERIOD = "30m";
export function QueueSparklineStat({
title,
info,
query,
color,
ids,
queueName,
formatPeak,
unitLabel,
chartHeight,
}: {
title: string;
/** Tooltip text under the info icon next to the title (matches the queue page copy). */
info?: ReactNode;
query: string;
color: string;
ids: QueueMetricIds;
queueName: string;
formatPeak?: (peak: number) => string;
/** Unit shown in the per-bucket hover tooltip (e.g. queued, ms). */
unitLabel?: { singular: string; plural: string };
/** Plot height in px. Defaults to the shared mini-chart height. */
chartHeight?: number;
}) {
const timeRange: QueueMetricTimeRange = { period: SPARKLINE_PERIOD, from: null, to: null };
const { rows } = useQueueMetric(query, {
ids,
timeRange,
queueName,
fillGaps: true,
defaultPeriod: SPARKLINE_PERIOD,
});
const { data, throttled, bucketStartMs, bucketIntervalMs, peak } = useMemo(() => {
const points = rows
.map((r) => ({
bucket: clickhouseTimeToMs(r.t),
v: toNumber(r.v),
// Present only when the query selects it (Backlog); 0 elsewhere so no overlay draws.
throttled: toNumber(r.throttled),
}))
.filter((p) => Number.isFinite(p.bucket))
.sort((a, b) => a.bucket - b.bucket);
return {
data: points.map((p) => p.v),
throttled: points.map((p) => p.throttled),
bucketStartMs: points[0]?.bucket,
bucketIntervalMs: points.length > 1 ? points[1]!.bucket - points[0]!.bucket : undefined,
peak: points.reduce((m, p) => Math.max(m, p.v), 0),
};
}, [rows]);
return (
<div className="flex flex-col gap-2">
<div className="flex items-center gap-1">
<Header3 className="leading-6">{title}</Header3>
{info || (data.length > 0 && peak > 0) ? (
<InfoIconTooltip
content={
<div className="flex flex-col gap-1">
{info ? <span>{info}</span> : null}
{data.length > 0 && peak > 0 ? (
<span className="tabular-nums text-text-dimmed">
Peak {formatPeak ? formatPeak(peak) : formatNumberCompact(peak)}
</span>
) : null}
</div>
}
contentClassName="max-w-[230px]"
disableHoverableContent
/>
) : null}
</div>
<MiniLineChart
data={data}
throttled={throttled}
bucketStartMs={bucketStartMs}
bucketIntervalMs={bucketIntervalMs}
color={color}
unitLabel={unitLabel}
height={chartHeight}
fillWidth
showPeak={false}
/>
</div>
);
}
export function QueueMetricStat({
label,
value,
className,
loading,
}: {
label: string;
value: string;
className?: string;
loading?: boolean;
}) {
return (
<div className="rounded-sm border border-grid-dimmed bg-background-bright px-3 py-2">
<div className="text-xs text-text-dimmed">{label}</div>
{loading ? (
<div className="mt-1 h-6 w-12 animate-pulse rounded bg-grid-bright/50" />
) : (
<div className={cn("text-2xl tabular-nums text-text-bright", className)}>{value}</div>
)}
</div>
);
}