-
Notifications
You must be signed in to change notification settings - Fork 393
Expand file tree
/
Copy pathChartUtils.tsx
More file actions
1147 lines (1018 loc) · 30.9 KB
/
ChartUtils.tsx
File metadata and controls
1147 lines (1018 loc) · 30.9 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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { useMemo } from 'react';
import { add, differenceInSeconds } from 'date-fns';
import { omit } from 'lodash';
import SqlString from 'sqlstring';
import { z } from 'zod';
import {
ColumnMetaType,
filterColumnMetaByType,
inferTimestampColumn,
JSDataType,
ResponseJSON,
} from '@hyperdx/common-utils/dist/clickhouse';
import { isMetricChartConfig } from '@hyperdx/common-utils/dist/core/renderChartConfig';
import {
convertDateRangeToGranularityString,
convertGranularityToSeconds,
getAlignedDateRange,
Granularity,
} from '@hyperdx/common-utils/dist/core/utils';
import { isBuilderChartConfig } from '@hyperdx/common-utils/dist/guards';
import {
AggregateFunction as AggFnV2,
BuilderChartConfigWithDateRange,
BuilderChartConfigWithOptTimestamp,
BuilderSavedChartConfig,
ChartConfigWithDateRange,
ChartConfigWithOptDateRange,
DisplayType,
Filter,
MetricsDataType as MetricsDataTypeV2,
SourceKind,
SQLInterval,
TMetricSource,
TSource,
} from '@hyperdx/common-utils/dist/types';
import { notifications } from '@mantine/notifications';
import DateRangeIndicator from './components/charts/DateRangeIndicator';
import { MVOptimizationExplanationResult } from './hooks/useMVOptimizationExplanation';
import { getMetricNameSql } from './otelSemanticConventions';
import { AggFn, TableChartSeries, TimeChartSeries } from './types';
import { NumberFormat } from './types';
import { getColorProps, getLogLevelColorOrder, logLevelColor } from './utils';
const SORT_ORDER = [
{ value: 'asc' as const, label: 'Ascending' },
{ value: 'desc' as const, label: 'Descending' },
];
type SortOrder = (typeof SORT_ORDER)[number]['value'];
export const AGG_FNS = [
{ value: 'count' as const, label: 'Count of Events', isAttributable: false },
{ value: 'sum' as const, label: 'Sum', isAttributable: false },
{ value: 'p99' as const, label: '99th Percentile' },
{ value: 'p95' as const, label: '95th Percentile' },
{ value: 'p90' as const, label: '90th Percentile' },
{ value: 'p50' as const, label: 'Median' },
{ value: 'avg' as const, label: 'Average' },
{ value: 'max' as const, label: 'Maximum' },
{ value: 'min' as const, label: 'Minimum' },
{
value: 'count_distinct' as const,
label: 'Count Distinct',
isAttributable: false,
},
{ value: 'any' as const, label: 'Any' },
{ value: 'none' as const, label: 'Custom' },
];
export const DEFAULT_CHART_CONFIG: Omit<
BuilderSavedChartConfig,
'source' | 'connection'
> = {
name: '',
select: [
{
aggFn: 'count',
aggCondition: '',
aggConditionLanguage: 'lucene',
valueExpression: '',
},
],
where: '',
whereLanguage: 'lucene',
displayType: DisplayType.Line,
granularity: 'auto',
alignDateRangeToGranularity: true,
};
function getTimeChartGranularity(
granularity: string | undefined,
dateRange: [Date, Date],
) {
return granularity === 'auto' || granularity == null
? convertDateRangeToGranularityString(dateRange, 80)
: granularity;
}
function getTimeChartDateRange(
dateRange: [Date, Date],
alignDateRangeToGranularity: boolean | undefined,
granularity: string,
) {
return alignDateRangeToGranularity === false
? dateRange
: getAlignedDateRange(dateRange, granularity);
}
export function convertToTimeChartConfig(
config: ChartConfigWithDateRange,
): ChartConfigWithDateRange {
const granularity = getTimeChartGranularity(
config.granularity,
config.dateRange,
);
const dateRange = getTimeChartDateRange(
config.dateRange,
config.alignDateRangeToGranularity,
granularity,
);
return isBuilderChartConfig(config)
? {
...config,
dateRange,
dateRangeEndInclusive: false,
granularity,
limit: { limit: 100000 },
}
: {
...config,
dateRangeEndInclusive: false,
dateRange,
granularity,
};
}
export function useTimeChartSettings(
config: Pick<
ChartConfigWithDateRange,
| 'displayType'
| 'dateRange'
| 'fillNulls'
| 'granularity'
| 'alignDateRangeToGranularity'
>,
) {
return useMemo(() => {
const granularity = getTimeChartGranularity(
config.granularity,
config.dateRange,
);
const dateRange = getTimeChartDateRange(
config.dateRange,
config.alignDateRangeToGranularity,
granularity,
);
return {
displayType: config.displayType,
fillNulls: config.fillNulls,
dateRange,
granularity,
};
}, [config]);
}
export const ChartKeyJoiner = ' · ';
export const PreviousPeriodSuffix = ' (previous)';
// Note: roundToNearestMinutes is broken in date-fns currently
// additionally it doesn't support seconds or > 30min
// so we need to write our own :(
// see: https://github.com/date-fns/date-fns/pull/3267/files
export function toStartOfInterval(date: Date, granularity: SQLInterval): Date {
const [num, unit] = granularity.split(' ');
const numInt = Number.parseInt(num);
const roundFn = Math.floor;
switch (unit) {
case 'second':
return new Date(
Date.UTC(
date.getUTCFullYear(),
date.getUTCMonth(),
date.getUTCDate(),
date.getUTCHours(),
date.getUTCMinutes(),
roundFn(date.getUTCSeconds() / numInt) * numInt,
),
);
case 'minute':
return new Date(
Date.UTC(
date.getUTCFullYear(),
date.getUTCMonth(),
date.getUTCDate(),
date.getUTCHours(),
roundFn(date.getUTCMinutes() / numInt) * numInt,
),
);
case 'hour':
return new Date(
Date.UTC(
date.getUTCFullYear(),
date.getUTCMonth(),
date.getUTCDate(),
roundFn(date.getUTCHours() / numInt) * numInt,
),
);
case 'day': {
// Clickhouse uses the # of days since unix epoch to round dates
// see: https://github.com/ClickHouse/ClickHouse/blob/master/src/Common/DateLUTImpl.h#L1059
const daysSinceEpoch = date.getTime() / 1000 / 60 / 60 / 24;
const daysSinceEpochRounded = roundFn(daysSinceEpoch / numInt) * numInt;
return new Date(daysSinceEpochRounded * 1000 * 60 * 60 * 24);
}
default:
return date;
}
}
export function timeBucketByGranularity(
start: Date,
end: Date,
granularity: SQLInterval,
): Date[] {
const buckets: Date[] = [];
let current = toStartOfInterval(start, granularity);
const granularitySeconds = convertGranularityToSeconds(granularity);
while (current < end) {
buckets.push(current);
current = add(current, {
seconds: granularitySeconds,
});
}
return buckets;
}
export const isAggregateFunction = (value: string) => {
const fns = [
// Basic aggregates
'count',
'countIf',
'countDistinct',
'sum',
'sumIf',
'avg',
'avgIf',
'min',
'max',
'any',
'anyLast',
'groupArray',
'groupArrayInsertAt',
'groupArrayMovingAvg',
'groupArraySample',
'groupUniqArray',
'groupUniqArrayIf',
'groupArrayIntersect',
'groupArrayIntersectIf',
'groupArrayReduce',
'groupBitmap',
'groupBitmapIf',
'groupBitmapOr',
'groupBitmapXor',
// Quantiles
'quantile',
'quantileIf',
'quantileExact',
'quantileExactWeighted',
'quantileTiming',
'quantileTimingWeighted',
'quantileTDigest',
'quantileTDigestWeighted',
'quantileBFloat16',
'quantileBFloat16Weighted',
'quantiles',
'median',
'medianExact',
'medianTDigest',
'medianBFloat16',
// Statistical functions
'stddevPop',
'stddevPopIf',
'stddevSamp',
'stddevSampIf',
'varPop',
'varPopIf',
'varSamp',
'varSampIf',
'covarPop',
'covarSamp',
'corr',
// Combinators
'uniq',
'uniqExact',
'uniqCombined',
'uniqCombined64',
'uniqHLL12',
'uniqTheta',
// Bit operations
'groupBitAnd',
'groupBitOr',
'groupBitXor',
// Map and tuple
'groupArrayMap',
'groupArrayTuple',
'groupArraySorted',
'topK',
'topKIf',
'topKWeighted',
// Aggregate combinators
'argMin',
'argMax',
'minMap',
'maxMap',
// Specialized aggregates
'runningDifference',
'retention',
'sequenceCount',
'sequenceMatch',
'histogram',
'simpleLinearRegression',
'stochasticLinearRegression',
'categoricalInformationValue',
'sumMap',
'sumMapFiltered',
'sumWithOverflow',
'entropy',
'skewPop',
'skewSamp',
'kurtPop',
'kurtSamp',
];
// Make case-insensitive since ClickHouse function names are case-insensitive
const lowerValue = value.toLowerCase();
return fns.some(fn => lowerValue.includes(fn.toLowerCase() + '('));
};
export const INTEGER_NUMBER_FORMAT: NumberFormat = {
factor: 1,
output: 'number',
mantissa: 0,
thousandSeparated: true,
};
export const MS_NUMBER_FORMAT: NumberFormat = {
factor: 1,
output: 'number',
mantissa: 2,
thousandSeparated: true,
unit: 'ms',
};
export const ERROR_RATE_PERCENTAGE_NUMBER_FORMAT: NumberFormat = {
output: 'percent',
mantissa: 0,
};
export const K8S_CPU_PERCENTAGE_NUMBER_FORMAT: NumberFormat = {
output: 'percent',
mantissa: 0,
};
export const K8S_FILESYSTEM_NUMBER_FORMAT: NumberFormat = {
output: 'byte',
};
export const K8S_MEM_NUMBER_FORMAT: NumberFormat = {
output: 'byte',
};
function inferValueColumns(
meta: Array<{ name: string; type: string }>,
excluded: Set<string>,
) {
return filterColumnMetaByType(meta, [JSDataType.Number])?.filter(
c => !excluded.has(c.name),
);
}
function inferGroupColumns(meta: Array<{ name: string; type: string }>) {
return filterColumnMetaByType(meta, [
JSDataType.String,
JSDataType.Map,
JSDataType.Array,
]);
}
export function formatResponseForPieChart(
data: ResponseJSON<Record<string, unknown>>,
getColor: (index: number, label: string) => string,
): Array<{ label: string; value: number; color: string }> {
if (data.meta == null) {
throw new Error('No meta data found in response');
}
if (data.data.length === 0) return [];
const valueColumns = inferValueColumns(data.meta, new Set()) ?? [];
if (valueColumns.length === 0) {
throw new Error(
`No value columns found in result column metadata. Make sure a numeric column exists in the result set.\n\nResult column metadata: ${JSON.stringify(data.meta)}`,
);
}
const valueColumn = valueColumns[0].name;
const groupByColumns = inferGroupColumns(data.meta);
return (
data.data
.map(row => {
const label = groupByColumns?.length
? groupByColumns.map(({ name }) => row[name]).join(' - ')
: valueColumn;
const rawValue = row[valueColumn];
const value =
typeof rawValue === 'number'
? rawValue
: Number.parseFloat(`${rawValue}`);
return { label, value };
})
.filter(entry => !isNaN(entry.value) && isFinite(entry.value))
// Sort in descending order so the largest slice is always first and gets the first color in the palette
.sort((a, b) => b.value - a.value)
.map((entry, index) => ({
...entry,
color: getColor(index, entry.label),
}))
);
}
export function getPreviousDateRange(currentRange: [Date, Date]): [Date, Date] {
const [start, end] = currentRange;
const offsetSeconds = differenceInSeconds(end, start);
return [
new Date(start.getTime() - offsetSeconds * 1000),
new Date(end.getTime() - offsetSeconds * 1000),
];
}
export interface LineData {
dataKey: string;
currentPeriodKey: string;
previousPeriodKey: string;
displayName: string;
color: string;
isDashed?: boolean;
}
interface LineDataWithOptionalColor extends Omit<LineData, 'color'> {
color?: string;
}
function setLineColors(
sortedLineData: LineDataWithOptionalColor[],
): LineData[] {
// Ensure that the current and previous period lines are the same color
const lineColorByCurrentPeriodKey = new Map<string, string>();
let colorIndex = 0;
return sortedLineData.map(line => {
const currentPeriodKey = line.currentPeriodKey;
if (lineColorByCurrentPeriodKey.has(currentPeriodKey)) {
line.color = lineColorByCurrentPeriodKey.get(currentPeriodKey);
} else if (!line.color) {
line.color = getColorProps(
colorIndex++,
line.displayName ?? line.dataKey,
);
lineColorByCurrentPeriodKey.set(currentPeriodKey, line.color);
} else {
lineColorByCurrentPeriodKey.set(currentPeriodKey, line.color);
}
return line as LineData;
});
}
function firstGroupColumnIsLogLevel(
source: TSource | undefined,
groupColumns: ColumnMetaType[],
) {
if (!source || groupColumns.length !== 1) return false;
if (source.kind === SourceKind.Log) {
return groupColumns[0].name === source.severityTextExpression;
}
if (source.kind === SourceKind.Trace) {
return groupColumns[0].name === source.statusCodeExpression;
}
return false;
}
function addResponseToFormattedData({
response,
lineDataMap,
tsBucketMap,
source,
previousPeriodOffsetSeconds,
isPreviousPeriod,
hiddenSeries = [],
}: {
tsBucketMap: Map<number, Record<string, any>>;
lineDataMap: { [keyName: string]: LineDataWithOptionalColor };
response: ResponseJSON<Record<string, any>>;
source?: TSource;
isPreviousPeriod: boolean;
previousPeriodOffsetSeconds: number;
hiddenSeries?: string[];
}) {
const { meta, data } = response;
if (meta == null) {
throw new Error('No metadata found in response');
}
const timestampColumn = inferTimestampColumn(meta);
if (timestampColumn == null) {
throw new Error(
`No timestamp column found in result column metadata: ${JSON.stringify(meta)}`,
);
}
const valueColumns = inferValueColumns(meta, new Set(hiddenSeries)) ?? [];
const groupColumns = inferGroupColumns(meta) ?? [];
const isSingleValueColumn = valueColumns.length === 1;
const hasGroupColumns = groupColumns.length > 0;
for (const row of data) {
const date = new Date(row[timestampColumn.name]);
// Previous period data needs to be shifted forward to align with current period
const offsetSeconds = isPreviousPeriod ? previousPeriodOffsetSeconds : 0;
const ts = Math.round(date.getTime() / 1000 + offsetSeconds);
for (const valueColumn of valueColumns) {
let tsBucket = tsBucketMap.get(ts);
if (tsBucket == null) {
tsBucket = { [timestampColumn.name]: ts };
tsBucketMap.set(ts, tsBucket);
}
const currentPeriodKey = [
// Simplify the display name if there's only one series and a group by
...(isSingleValueColumn && hasGroupColumns ? [] : [valueColumn.name]),
...groupColumns.map(g => {
const v = row[g.name];
return typeof v === 'object' && v !== null ? JSON.stringify(v) : v;
}),
].join(ChartKeyJoiner);
const previousPeriodKey = `${currentPeriodKey}${PreviousPeriodSuffix}`;
const keyName = isPreviousPeriod ? previousPeriodKey : currentPeriodKey;
// UInt64 are returned as strings, we'll convert to number
// and accept a bit of floating point error
const rawValue = row[valueColumn.name];
const value =
typeof rawValue === 'number' ? rawValue : Number.parseFloat(rawValue);
// Mutate the existing bucket object to avoid repeated large object copies
tsBucket[keyName] = value;
// Special handling for log level / trace severity colors
let color: string | undefined = undefined;
if (firstGroupColumnIsLogLevel(source, groupColumns)) {
color = logLevelColor(row[groupColumns[0].name]);
}
lineDataMap[keyName] = {
dataKey: keyName,
currentPeriodKey,
previousPeriodKey,
displayName: keyName,
color,
isDashed: isPreviousPeriod,
};
}
}
}
// Input: { ts, value1, value2, groupBy1, groupBy2 },
// Output: { ts, [value1Name, groupBy1, groupBy2]: value1, [...]: value2 }
export function formatResponseForTimeChart({
currentPeriodResponse,
previousPeriodResponse,
dateRange,
granularity,
generateEmptyBuckets = true,
source,
hiddenSeries = [],
previousPeriodOffsetSeconds = 0,
}: {
dateRange: [Date, Date];
granularity?: SQLInterval;
currentPeriodResponse: ResponseJSON<Record<string, any>>;
previousPeriodResponse?: ResponseJSON<Record<string, any>>;
generateEmptyBuckets?: boolean;
source?: TSource;
hiddenSeries?: string[];
previousPeriodOffsetSeconds?: number;
}) {
const meta = currentPeriodResponse.meta;
if (meta == null) {
throw new Error('No meta data found in response');
}
const timestampColumn = inferTimestampColumn(meta);
const valueColumns = inferValueColumns(meta, new Set(hiddenSeries)) ?? [];
const groupColumns = inferGroupColumns(meta) ?? [];
const isSingleValueColumn = valueColumns.length === 1;
if (timestampColumn == null) {
throw new Error(
`No timestamp column found in result column metadata. Make sure a Date/DateTime column exists in the result set.\n\nResult column metadata: ${JSON.stringify(meta)}`,
);
}
if (valueColumns.length === 0) {
throw new Error(
`No value columns found in result column metadata. Make sure a numeric column exists in the result set.\n\nResult column metadata: ${JSON.stringify(meta)}`,
);
}
// Timestamp -> { tsCol, line1, line2, ...}
const tsBucketMap: Map<number, Record<string, any>> = new Map();
const lineDataMap: {
[keyName: string]: LineDataWithOptionalColor;
} = {};
addResponseToFormattedData({
response: currentPeriodResponse,
lineDataMap,
tsBucketMap,
source,
isPreviousPeriod: false,
previousPeriodOffsetSeconds,
hiddenSeries,
});
if (previousPeriodResponse != null) {
addResponseToFormattedData({
response: previousPeriodResponse,
lineDataMap,
tsBucketMap,
source,
isPreviousPeriod: true,
previousPeriodOffsetSeconds,
hiddenSeries,
});
}
const logLevelColorOrder = getLogLevelColorOrder();
const sortedLineData = Object.values(lineDataMap).sort((a, b) => {
return (
logLevelColorOrder.findIndex(color => color === a.color) -
logLevelColorOrder.findIndex(color => color === b.color)
);
});
if (generateEmptyBuckets && granularity != null) {
const generatedTsBuckets = timeBucketByGranularity(
dateRange[0],
dateRange[1],
granularity,
);
generatedTsBuckets.forEach(date => {
const ts = date.getTime() / 1000;
const tsBucket = tsBucketMap.get(ts);
if (tsBucket == null) {
const tsBucket: Record<string, any> = {
[timestampColumn.name]: ts,
};
for (const line of sortedLineData) {
tsBucket[line.dataKey] = 0;
}
tsBucketMap.set(ts, tsBucket);
} else {
for (const line of sortedLineData) {
if (tsBucket[line.dataKey] == null) {
tsBucket[line.dataKey] = 0;
}
}
tsBucketMap.set(ts, tsBucket);
}
});
}
// Sort results again by timestamp
const graphResults: {
[key: string]: number | undefined;
}[] = Array.from(tsBucketMap.values()).sort(
(a, b) => a[timestampColumn.name] - b[timestampColumn.name],
);
const sortedLineDataWithColors = setLineColors(sortedLineData);
return {
graphResults,
timestampColumn,
lineData: sortedLineDataWithColors,
groupColumns: groupColumns.map(g => g.name),
valueColumns: valueColumns.map(v => v.name),
isSingleValueColumn,
};
}
// Define a mapping from app AggFn to common-utils AggregateFunction
const mapV1AggFnToV2 = (aggFn?: AggFn): AggFnV2 | undefined => {
if (aggFn == null) {
return aggFn;
}
// Map rate-based aggregations to their base aggregation
if (aggFn.endsWith('_rate')) {
return mapV1AggFnToV2(aggFn.replace('_rate', '') as AggFn);
}
// Map percentiles to quantile
if (
aggFn === 'p50' ||
aggFn === 'p90' ||
aggFn === 'p95' ||
aggFn === 'p99'
) {
return 'quantile';
}
// Map per-time-unit counts to count
if (
aggFn === 'count_per_sec' ||
aggFn === 'count_per_min' ||
aggFn === 'count_per_hour'
) {
return 'count';
}
// For standard aggregations that exist in both, return as is
if (
[
'avg',
'count',
'count_distinct',
'last_value',
'max',
'min',
'sum',
].includes(aggFn)
) {
return aggFn as AggFnV2;
}
throw new Error(`Unsupported aggregation function in v2: ${aggFn}`);
};
const convertV1GroupByToV2 = (
metricSource: TMetricSource,
groupBy: string[],
): string => {
return groupBy
.map(g => {
if (g.startsWith('k8s')) {
return `${metricSource.resourceAttributesExpression}['${g}']`;
}
return g;
})
.join(',');
};
export const convertV1ChartConfigToV2 = (
chartConfig: {
// only support time or table series
series: (TimeChartSeries | TableChartSeries)[];
granularity?: Granularity;
dateRange: [Date, Date];
seriesReturnType: 'ratio' | 'column';
displayType?: 'stacked_bar' | 'line';
name?: string;
fillNulls?: number | false;
sortOrder?: SortOrder;
},
source: {
log?: TSource;
metric?: TMetricSource;
trace?: TSource;
},
): BuilderChartConfigWithDateRange => {
const {
series,
granularity,
dateRange,
displayType = 'line',
fillNulls,
} = chartConfig;
if (series.length < 1) {
throw new Error('series is required');
}
const firstSeries = series[0];
const convertedDisplayType =
displayType === 'stacked_bar' ? DisplayType.StackedBar : DisplayType.Line;
if (firstSeries.table === 'logs') {
// TODO: this might not work properly since logs + traces are mixed in v1
throw new Error('IMPLEMENT ME (logs)');
} else if (firstSeries.table === 'metrics') {
if (source.metric == null) {
throw new Error('source.metric is required for metrics');
}
return {
select: series.map(s => {
const field = s.field ?? '';
const [metricName, rawMetricDataType] = field
.split(' - ')
.map(s => s.trim());
// Check if this metric name needs version-based SQL transformation
const metricNameSql = getMetricNameSql(metricName);
const metricDataType = z
.nativeEnum(MetricsDataTypeV2)
.parse(rawMetricDataType?.toLowerCase());
return {
aggFn: mapV1AggFnToV2(s.aggFn),
metricType: metricDataType,
valueExpression: field,
metricName,
metricNameSql,
aggConditionLanguage: 'lucene',
aggCondition: s.where,
};
}),
from: source.metric?.from,
numberFormat: firstSeries.numberFormat,
groupBy: convertV1GroupByToV2(source.metric, firstSeries.groupBy),
dateRange,
connection: source.metric?.connection,
metricTables: source.metric?.metricTables,
timestampValueExpression: source.metric?.timestampValueExpression,
granularity,
where: '',
fillNulls,
displayType: convertedDisplayType,
};
}
throw new Error(`unsupported table in v2: ${firstSeries.table}`);
};
/**
* Build search URL for viewing events based on group-by values
* Used by both chart clicks and table row clicks
*/
export function buildEventsSearchUrl({
source,
config,
dateRange,
groupFilters,
valueRangeFilter,
}: {
source: TSource;
config: BuilderChartConfigWithDateRange;
dateRange: [Date, Date];
groupFilters?: Array<{ column: string; value: any }>;
valueRangeFilter?: { expression: string; value: number; threshold?: number };
}): string | null {
if (!source?.id) {
return null;
}
const isMetricChart = isMetricChartConfig(config);
if (isMetricChart) {
const logSourceId =
source.kind === SourceKind.Metric || source.kind === SourceKind.Trace
? source.logSourceId
: undefined;
if (logSourceId == null) {
notifications.show({
color: 'yellow',
message: 'No log source is associated with the selected metric source.',
});
return null;
}
}
let where = config.where;
let whereLanguage = config.whereLanguage || 'lucene';
if (
where.length === 0 &&
Array.isArray(config.select) &&
config.select.length === 1
) {
where = config.select[0].aggCondition ?? '';
whereLanguage = config.select[0].aggConditionLanguage ?? 'lucene';
}
const additionalFilters: Filter[] = [];
// Add group-by column filters
if (groupFilters && groupFilters.length > 0) {
groupFilters.forEach(({ column, value }) => {
if (column && value != null) {
// Can't use SQLString.escape here because the search endpoint relies on exist match for UI
const condition = `${column} IN (${SqlString.escape(value)})`;
additionalFilters.push({ type: 'sql', condition });
}
});
}
// Add Y-axis value range filter (±threshold) for charts
if (valueRangeFilter) {
const { expression, value, threshold = 0.05 } = valueRangeFilter;
const hasAggregateFunction = isAggregateFunction(expression);
if (!hasAggregateFunction) {
const lowerBound = value * (1 - threshold);
const upperBound = value * (1 + threshold);
// Can't use SQLString.escape here because the search endpoint relies on exist match for UI
const condition = `${expression} BETWEEN ${SqlString.escape(lowerBound)} AND ${SqlString.escape(upperBound)}`;
additionalFilters.push({
type: 'sql',
condition,
});
}
}
// Get the time range
const from = dateRange[0].getTime();
const to = dateRange[1].getTime();
const params: Record<string, string> = {
source: source?.id ?? '',
where: where,
whereLanguage: whereLanguage,
filters: JSON.stringify([...(config.filters ?? []), ...additionalFilters]),
isLive: 'false',
from: from.toString(),
to: to.toString(),
};
// If its a metric chart, we don't pass the where and filters
if (isMetricChart) {
params.where = '';
params.whereLanguage = 'lucene';
params.filters = JSON.stringify([]);
params.source =
(source.kind === SourceKind.Metric || source.kind === SourceKind.Trace
? source.logSourceId
: undefined) ?? '';
}
// Include the select parameter if provided to preserve custom columns
// eventTableSelect is used for charts that override select (like histograms with count)
// to preserve the original table's select expression
if (config.eventTableSelect) {
params.select = config.eventTableSelect;
}
return `/search?${new URLSearchParams(params).toString()}`;
}
/**
* Extract group column names from chart config's groupBy field
* Handles both string format ("col1, col2") and array format ([{ valueExpression: "col1" }, ...])
*/
function extractGroupColumns(
groupBy: BuilderChartConfigWithDateRange['groupBy'],
): string[] {
if (!groupBy) return [];
if (typeof groupBy === 'string') {
// String GROUP BY: "col1, col2"
return groupBy.split(',').map(v => v.trim());
}
// Array GROUP BY: [{ valueExpression: "col1" }, ...] or ["col1", ...]
return groupBy.map(g => (typeof g === 'string' ? g : g.valueExpression));
}
/**
* Build search URL from a table row click
* Extracts group filters and value range filter from the row data