-
Notifications
You must be signed in to change notification settings - Fork 423
Expand file tree
/
Copy pathdashboards.ts
More file actions
1402 lines (1316 loc) · 51.1 KB
/
Copy pathdashboards.ts
File metadata and controls
1402 lines (1316 loc) · 51.1 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 {
displayTypeSupportsBuilderAlerts,
displayTypeSupportsRawSqlAlerts,
} from '@hyperdx/common-utils/dist/core/utils';
import {
validateDashboardContainersStructure,
validateDashboardTileContainerRefs,
} from '@hyperdx/common-utils/dist/dashboardValidation';
import {
isBuilderSavedChartConfig,
isHeatmapCompatibleSource,
isPromqlSavedChartConfig,
isRawSqlSavedChartConfig,
} from '@hyperdx/common-utils/dist/guards';
import {
AggregateFunctionSchema,
BuilderSavedChartConfig,
ChartPaletteToken,
ColorCondition,
DASHBOARD_MAX_CONTAINERS,
DashboardContainer,
DashboardContainerSchema,
DisplayType,
isLogSource,
isOnClickDashboardById,
isOnClickSearchById,
isTraceSource,
NumberTileColorCondition,
NumberTileColorConditionSchema,
RawSqlSavedChartConfig,
resolveChartPaletteToken,
SavedChartConfig,
} from '@hyperdx/common-utils/dist/types';
import { SearchConditionLanguageSchema as whereLanguageSchema } from '@hyperdx/common-utils/dist/types';
import { pick } from 'lodash';
import _ from 'lodash';
import mongoose from 'mongoose';
import { z } from 'zod';
import { deleteDashboardAlerts } from '@/controllers/alerts';
import { getConnectionsByTeam } from '@/controllers/connection';
import { getSources } from '@/controllers/sources';
import Dashboard, { DashboardDocument } from '@/models/dashboard';
import {
translateExternalChartToTileConfig,
translateExternalFilterToFilter,
translateFilterToExternalFilter,
} from '@/utils/externalApi';
import logger from '@/utils/logger';
import {
ExternalDashboardFilter,
externalDashboardFilterSchema,
externalDashboardFilterSchemaWithId,
ExternalDashboardFilterWithId,
ExternalDashboardHeatmapSelectItem,
ExternalDashboardRawSqlTileConfig,
externalDashboardSavedFilterValueSchema,
ExternalDashboardSelectItem,
ExternalDashboardTileConfig,
externalDashboardTileListSchema,
ExternalDashboardTileWithId,
externalQuantileLevelSchema,
tagsSchema,
} from '@/utils/zod';
// --------------------------------------------------------------------------------
// Type Guards and Utility Types
// --------------------------------------------------------------------------------
export type SeriesTile = ExternalDashboardTileWithId & {
series: Exclude<ExternalDashboardTileWithId['series'], undefined>;
};
function isSeriesTile(tile: ExternalDashboardTileWithId): tile is SeriesTile {
return 'series' in tile && tile.series !== undefined;
}
export type ConfigTile = ExternalDashboardTileWithId & {
config: Exclude<ExternalDashboardTileWithId['config'], undefined>;
};
export function isRawSqlExternalTileConfig(
config: ExternalDashboardTileConfig,
): config is ExternalDashboardRawSqlTileConfig {
return 'configType' in config && config.configType === 'sql';
}
export function isConfigTile(
tile: ExternalDashboardTileWithId,
): tile is ConfigTile {
return 'config' in tile && tile.config != undefined;
}
export type ExternalDashboard = {
id: string;
name: string;
tiles: ExternalDashboardTileWithId[];
tags?: string[];
filters?: ExternalDashboardFilterWithId[];
savedQuery?: string | null;
savedQueryLanguage?: string | null;
savedFilterValues?: DashboardDocument['savedFilterValues'];
containers?: DashboardContainer[];
};
// --------------------------------------------------------------------------------
// Conversion functions from internal dashboard format to external dashboard format
// --------------------------------------------------------------------------------
const DEFAULT_SELECT_ITEM: ExternalDashboardSelectItem = {
aggFn: 'count',
where: '',
};
const convertToExternalHeatmapSelectItem = (
item: Exclude<BuilderSavedChartConfig['select'][number], string>,
): ExternalDashboardHeatmapSelectItem => ({
valueExpression: item.valueExpression,
// Use `!== undefined` (not truthy) to match the deserializer in
// convertToInternalTileConfig so empty-string round-trips do not
// silently drop fields.
...(item.countExpression !== undefined
? { countExpression: item.countExpression }
: {}),
...(item.heatmapScaleType !== undefined
? { heatmapScaleType: item.heatmapScaleType }
: {}),
});
const convertToExternalSelectItem = (
item: Exclude<BuilderSavedChartConfig['select'][number], string>,
): ExternalDashboardSelectItem => {
const parsedAggFn = AggregateFunctionSchema.safeParse(item.aggFn);
const aggFn = parsedAggFn.success ? parsedAggFn.data : 'none';
const parsedLevel =
'level' in item
? externalQuantileLevelSchema.safeParse(item.level)
: undefined;
const level = parsedLevel?.success ? parsedLevel.data : undefined;
return {
...pick(item, [
'valueExpression',
'alias',
'metricType',
'metricName',
'numberFormat',
]),
aggFn,
where: item.aggCondition ?? '',
whereLanguage: item.aggConditionLanguage ?? 'lucene',
periodAggFn: item.isDelta ? 'delta' : undefined,
...(level ? { level } : {}),
};
};
// Normalize the per-rule palette colors of a number tile's `colorRules`
// for the API response. `colorRules` shipped after the hue rename so
// stored rules already hold hue-named tokens; running each through
// `resolveChartPaletteToken` keeps the static `color` (which can hold a
// legacy `chart-1`..`chart-10` token from before the rename) and the rule
// colors on a single normalization path. A rule whose color cannot be
// resolved (reachable only via a direct DB write, since the input schema
// validates rule colors) is dropped, mirroring how the static `color`
// field omits an unresolvable token, so the response always stays within
// the palette-token enum instead of leaking an unknown string. When no
// rule survives (or the stored array is empty) the field is omitted
// entirely rather than emitted as `[]`, matching the static `color` omit.
const toExternalColorRules = (
colorRules: ColorCondition[] | undefined,
): NumberTileColorCondition[] | undefined => {
if (!colorRules) return undefined;
const resolved = colorRules.flatMap((rule): NumberTileColorCondition[] => {
const color = resolveChartPaletteToken(rule.color);
if (!color) return [];
// Re-validate against the number-tile subset so the response stays
// within the documented operator set: a string-match or regex rule
// (reachable only via a direct DB write, since neither the editor nor
// the input schema produces one on a number tile) is dropped, just
// like an unresolvable color token.
const parsed = NumberTileColorConditionSchema.safeParse({ ...rule, color });
return parsed.success ? [parsed.data] : [];
});
return resolved.length > 0 ? resolved : undefined;
};
const convertToExternalTileChartConfig = (
config: SavedChartConfig,
): ExternalDashboardTileConfig | undefined => {
if (isRawSqlSavedChartConfig(config)) {
switch (config.displayType) {
case DisplayType.Line:
return {
configType: 'sql',
displayType: DisplayType.Line,
connectionId: config.connection,
sqlTemplate: config.sqlTemplate,
sourceId: config.source,
alignDateRangeToGranularity: config.alignDateRangeToGranularity,
fillNulls: config.fillNulls !== false,
fitYAxisToData: config.fitYAxisToData,
numberFormat: config.numberFormat,
compareToPreviousPeriod: config.compareToPreviousPeriod,
};
case DisplayType.StackedBar:
return {
configType: 'sql',
displayType: config.displayType,
connectionId: config.connection,
sqlTemplate: config.sqlTemplate,
sourceId: config.source,
alignDateRangeToGranularity: config.alignDateRangeToGranularity,
fillNulls: config.fillNulls !== false,
numberFormat: config.numberFormat,
};
case DisplayType.Table:
return {
configType: 'sql',
displayType: DisplayType.Table,
connectionId: config.connection,
sqlTemplate: config.sqlTemplate,
sourceId: config.source,
numberFormat: config.numberFormat,
onClick: config.onClick,
};
case DisplayType.Number:
return {
configType: 'sql',
displayType: DisplayType.Number,
connectionId: config.connection,
sqlTemplate: config.sqlTemplate,
sourceId: config.source,
numberFormat: config.numberFormat,
// Raw SQL number tiles carry the static tile color too (no
// colorRules; see the schema). Normalize a legacy token saved
// before the hue rename to its hue name on output.
color: resolveChartPaletteToken(config.color),
};
case DisplayType.Pie:
return {
configType: 'sql',
displayType: DisplayType.Pie,
connectionId: config.connection,
sqlTemplate: config.sqlTemplate,
sourceId: config.source,
numberFormat: config.numberFormat,
};
case DisplayType.Search:
case DisplayType.Markdown:
case DisplayType.Heatmap:
case DisplayType.EventPatterns:
logger.error(
{ config },
'Error converting chart config to external chart - unsupported display type for raw SQL config',
);
return undefined;
}
config.displayType satisfies never | undefined;
return undefined;
}
// PromQL configs are not yet supported in the external API
if (isPromqlSavedChartConfig(config)) {
return undefined;
}
const sourceId = config.source?.toString() ?? '';
const stringValueOrDefault = <D>(
value: string | unknown,
defaultValue: D,
): string | D => {
return typeof value === 'string' ? value : defaultValue;
};
switch (config.displayType) {
case DisplayType.Line:
return {
displayType: DisplayType.Line,
sourceId,
asRatio:
config.seriesReturnType === 'ratio' &&
Array.isArray(config.select) &&
config.select.length == 2,
alignDateRangeToGranularity: config.alignDateRangeToGranularity,
fillNulls: config.fillNulls !== false,
fitYAxisToData: config.fitYAxisToData,
groupBy: stringValueOrDefault(config.groupBy, undefined),
select: Array.isArray(config.select)
? config.select.map(convertToExternalSelectItem)
: [DEFAULT_SELECT_ITEM],
compareToPreviousPeriod: config.compareToPreviousPeriod,
numberFormat: config.numberFormat,
};
case DisplayType.StackedBar:
return {
displayType: DisplayType.StackedBar,
sourceId,
asRatio:
config.seriesReturnType === 'ratio' &&
Array.isArray(config.select) &&
config.select.length == 2,
alignDateRangeToGranularity: config.alignDateRangeToGranularity,
fillNulls: config.fillNulls !== false,
groupBy: stringValueOrDefault(config.groupBy, undefined),
select: Array.isArray(config.select)
? config.select.map(convertToExternalSelectItem)
: [DEFAULT_SELECT_ITEM],
numberFormat: config.numberFormat,
};
case DisplayType.Number:
return {
displayType: config.displayType,
sourceId,
select: Array.isArray(config.select)
? [convertToExternalSelectItem(config.select[0])]
: [DEFAULT_SELECT_ITEM],
numberFormat: config.numberFormat,
// Normalize stored palette tokens on the way out. A static `color`
// saved before the hue rename holds a legacy `chart-1`..`chart-10`
// token in Mongo (the `tiles` field is `Mixed`), so map it to the
// hue name via `resolveChartPaletteToken`, matching the app's
// fetch-time `normalizeDashboardTileColors`. `colorRules` colors go
// through the same path (see `toExternalColorRules`). An absent or
// unrecognized token resolves to undefined and is omitted from the
// response, keeping it within the palette-token enum.
color: resolveChartPaletteToken(config.color),
colorRules: toExternalColorRules(config.colorRules),
// Pass `backgroundChart` through as-is: it shipped after the hue
// rename, so its optional `color` can only hold a hue-named token (no
// legacy normalization needed). Builder number tiles only; raw SQL
// number tiles never persist it (see the schema). Absent resolves to
// undefined and is omitted from the response.
backgroundChart: config.backgroundChart,
};
case DisplayType.Pie:
return {
displayType: config.displayType,
sourceId,
select: Array.isArray(config.select)
? [convertToExternalSelectItem(config.select[0])]
: [DEFAULT_SELECT_ITEM],
groupBy: stringValueOrDefault(config.groupBy, undefined),
numberFormat: config.numberFormat,
};
case DisplayType.Table:
return {
...pick(config, [
'having',
'numberFormat',
'groupByColumnsOnLeft',
'onClick',
]),
displayType: config.displayType,
sourceId,
asRatio:
config.seriesReturnType === 'ratio' &&
Array.isArray(config.select) &&
config.select.length == 2,
groupBy: stringValueOrDefault(config.groupBy, undefined),
select: Array.isArray(config.select)
? config.select.map(convertToExternalSelectItem)
: [DEFAULT_SELECT_ITEM],
orderBy: stringValueOrDefault(config.orderBy, undefined),
};
case DisplayType.Search:
return {
displayType: config.displayType,
sourceId,
select: stringValueOrDefault(config.select, ''),
where: config.where,
whereLanguage: config.whereLanguage ?? 'lucene',
};
case DisplayType.Markdown:
return {
displayType: config.displayType,
markdown: stringValueOrDefault(config.markdown, ''),
};
case DisplayType.Heatmap: {
// The internal heatmap schema requires `select[0]` to be a builder
// item with a non-empty `valueExpression`. Legacy/corrupted Mongo
// docs that lack one would otherwise produce a tile that violates
// the external schema's `min(1)` rule. Returning undefined here
// would let the caller fall through to `defaultTileConfig`, which
// emits `displayType: 'line'`. A subsequent GET -> PUT round-trip
// through the API would then silently overwrite the heatmap with
// a line chart in Mongo (data loss). Instead, emit a
// heatmap-shaped placeholder with an empty valueExpression so the
// response preserves displayType, and a re-PUT surfaces the
// breakage as a clear validation error from the input schema's
// `min(1)` rule on `valueExpression` rather than silently
// downgrading the tile.
const item = Array.isArray(config.select) ? config.select[0] : undefined;
if (
item === undefined ||
typeof item === 'string' ||
!item.valueExpression
) {
logger.warn(
{ tileId: sourceId, hasItem: item !== undefined },
'Heatmap tile is missing select[0].valueExpression; emitting placeholder so callers do not silently downgrade to line',
);
const placeholderItem: ExternalDashboardHeatmapSelectItem = {
valueExpression: '',
};
return {
displayType: DisplayType.Heatmap,
sourceId,
select: [placeholderItem],
where: stringValueOrDefault(config.where, ''),
whereLanguage: config.whereLanguage ?? 'lucene',
numberFormat: config.numberFormat,
};
}
return {
displayType: DisplayType.Heatmap,
sourceId,
select: [convertToExternalHeatmapSelectItem(item)],
where: stringValueOrDefault(config.where, ''),
whereLanguage: config.whereLanguage ?? 'lucene',
numberFormat: config.numberFormat,
};
}
case DisplayType.EventPatterns:
return {
displayType: config.displayType,
sourceId,
select: stringValueOrDefault(config.select, ''),
where: stringValueOrDefault(config.where, ''),
whereLanguage: config.whereLanguage ?? 'lucene',
};
case undefined:
logger.error(
{ config },
'Error converting chart config to external chart - unsupported display type',
);
return undefined;
default:
config.displayType satisfies never;
}
};
function convertTileToExternalChart(
tile: DashboardDocument['tiles'][number],
containerById: Map<string, DashboardContainer>,
dashboardId: string,
): ExternalDashboardTileWithId | undefined {
// PromQL tiles have no external schema representation yet. Dropping them on
// read (and letting the caller filter undefined) is safer than falling
// through to defaultTileConfig — that would silently overwrite the PromQL
// config with an empty Line tile on a GET → PUT round-trip.
if (isPromqlSavedChartConfig(tile.config)) {
logger.warn(
{ dashboardId, tileId: tile.id },
'Skipping PromQL tile in external API response (not yet supported)',
);
return undefined;
}
// Returned in case of a failure converting the saved chart config
const defaultTileConfig: ExternalDashboardTileConfig =
isRawSqlSavedChartConfig(tile.config)
? {
configType: 'sql',
displayType: 'line',
connectionId: tile.config.connection,
sqlTemplate: tile.config.sqlTemplate,
}
: {
displayType: 'line',
sourceId: tile.config.source?.toString() ?? '',
select: [DEFAULT_SELECT_ITEM],
};
// Treat empty-string container/tab refs as absent so legacy Mongo docs
// (the underlying `tiles` field is `Mixed`, so older entries may carry
// `containerId: ""`) round-trip through the external schema, which now
// enforces `min(1)`. Without this, a GET that hit a legacy doc would
// return a tile that the next PUT couldn't validate.
let containerId =
typeof tile.containerId === 'string' && tile.containerId.length > 0
? tile.containerId
: undefined;
let tabId =
typeof tile.tabId === 'string' && tile.tabId.length > 0
? tile.tabId
: undefined;
// Self-heal orphan refs on read. A doc may carry a containerId that
// points at a container that has since been removed (or never
// existed: legacy docs predating the containers feature can have any
// value in this `Mixed`-typed field). Round-trip these as if absent
// so a subsequent PUT validates instead of failing schema with
// "Tile references unknown containerId". Same idea for tabId.
if (containerId !== undefined) {
const container = containerById.get(containerId);
if (!container) {
logger.warn(
{ dashboardId, tileId: tile.id, containerId },
'Tile references unknown containerId; dropping ref on read',
);
containerId = undefined;
tabId = undefined;
} else if (
tabId !== undefined &&
!container.tabs?.some(t => t.id === tabId)
) {
logger.warn(
{ dashboardId, tileId: tile.id, containerId, tabId },
'Tile references unknown tabId; dropping tabId on read',
);
tabId = undefined;
}
} else if (tabId !== undefined) {
// tabId without containerId is invalid in the schema; the legacy
// doc would fail a subsequent PUT, so drop it on read.
logger.warn(
{ dashboardId, tileId: tile.id, tabId },
'Tile has tabId without containerId; dropping tabId on read',
);
tabId = undefined;
}
const { id, x, y, w, h } = tile;
return {
id,
x,
y,
w,
h,
name: tile.config.name ?? '',
config: convertToExternalTileChartConfig(tile.config) ?? defaultTileConfig,
...(containerId !== undefined ? { containerId } : {}),
...(tabId !== undefined ? { tabId } : {}),
};
}
export function convertToExternalDashboard(
dashboard: DashboardDocument,
): ExternalDashboard {
const containers = dashboard.containers ?? [];
// Dedupe by id when building the lookup map: a doc with duplicate
// container ids can only resolve tile refs against one of them, and
// last-write-wins is consistent with how Mongo would have persisted
// the array. Tile-resolution ambiguity in this case is logged when
// the tile ref turns out to point at a missing container.
const containerById = new Map<string, DashboardContainer>(
containers.map(c => [c.id, c]),
);
const dashboardId = dashboard._id.toString();
return {
id: dashboardId,
name: dashboard.name,
tiles: dashboard.tiles
.map(tile => convertTileToExternalChart(tile, containerById, dashboardId))
.filter(t => t !== undefined),
tags: dashboard.tags || [],
filters: dashboard.filters?.map(translateFilterToExternalFilter) || [],
savedQuery: dashboard.savedQuery ?? null,
savedQueryLanguage: dashboard.savedQueryLanguage ?? null,
savedFilterValues: dashboard.savedFilterValues ?? [],
// Mongoose persists missing arrays as []. Only emit containers when
// the user actually saved one or more, so dashboards without the
// organization layer round-trip with the field absent.
...(containers.length > 0 ? { containers } : {}),
};
}
// --------------------------------------------------------------------------------
// Conversion functions from external dashboard format to internal dashboard format
// --------------------------------------------------------------------------------
const convertToInternalSelectItem = (
item: ExternalDashboardSelectItem,
): Exclude<BuilderSavedChartConfig['select'][number], string> => {
return {
...pick(item, [
'alias',
'metricType',
'metricName',
'aggFn',
'level',
'numberFormat',
]),
aggCondition: item.where,
aggConditionLanguage: item.whereLanguage,
isDelta: item.periodAggFn === 'delta',
valueExpression: item.valueExpression ?? '',
};
};
export function convertToInternalTileConfig(
externalTile: ConfigTile,
): DashboardDocument['tiles'][number] {
const externalConfig = externalTile.config;
const name = externalTile.name || '';
let internalConfig: SavedChartConfig;
if (isRawSqlExternalTileConfig(externalConfig)) {
switch (externalConfig.displayType) {
case 'line':
case 'stacked_bar':
internalConfig = {
configType: 'sql',
...pick(externalConfig, [
'numberFormat',
'alignDateRangeToGranularity',
'compareToPreviousPeriod',
'fitYAxisToData',
]),
displayType:
externalConfig.displayType === 'stacked_bar'
? DisplayType.StackedBar
: DisplayType.Line,
fillNulls: externalConfig.fillNulls === false ? false : undefined,
name,
connection: externalConfig.connectionId,
sqlTemplate: externalConfig.sqlTemplate,
source: externalConfig.sourceId,
} satisfies RawSqlSavedChartConfig;
break;
case 'table':
case 'number':
case 'pie':
internalConfig = {
configType: 'sql',
displayType:
externalConfig.displayType === 'table'
? DisplayType.Table
: externalConfig.displayType === 'number'
? DisplayType.Number
: DisplayType.Pie,
name,
connection: externalConfig.connectionId,
sqlTemplate: externalConfig.sqlTemplate,
source: externalConfig.sourceId,
numberFormat: externalConfig.numberFormat,
onClick:
externalConfig.displayType === 'table'
? externalConfig.onClick
: undefined,
// Only the raw SQL number variant carries `color`; table and pie
// do not expose it. `_.omitBy(_.isNil)` below drops it when absent.
color:
externalConfig.displayType === 'number'
? externalConfig.color
: undefined,
} satisfies RawSqlSavedChartConfig;
break;
default:
// Typecheck to ensure all display types are handled
externalConfig satisfies never;
// We should never hit this due to the typecheck above.
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
internalConfig = {} as SavedChartConfig;
}
} else {
switch (externalConfig.displayType) {
case 'line':
case 'stacked_bar':
internalConfig = {
...pick(externalConfig, [
'groupBy',
'numberFormat',
'alignDateRangeToGranularity',
'compareToPreviousPeriod',
'fitYAxisToData',
]),
displayType:
externalConfig.displayType === 'stacked_bar'
? DisplayType.StackedBar
: DisplayType.Line,
select: externalConfig.select.map(convertToInternalSelectItem),
source: externalConfig.sourceId,
where: '',
fillNulls: externalConfig.fillNulls === false ? false : undefined,
seriesReturnType: externalConfig.asRatio ? 'ratio' : undefined,
name,
} satisfies BuilderSavedChartConfig;
break;
case 'table':
internalConfig = {
...pick(externalConfig, [
'groupBy',
'numberFormat',
'having',
'orderBy',
'groupByColumnsOnLeft',
'onClick',
]),
displayType: DisplayType.Table,
select: externalConfig.select.map(convertToInternalSelectItem),
source: externalConfig.sourceId,
where: '',
seriesReturnType: externalConfig.asRatio ? 'ratio' : undefined,
name,
} satisfies BuilderSavedChartConfig;
break;
case 'number':
internalConfig = {
displayType: DisplayType.Number,
select: [convertToInternalSelectItem(externalConfig.select[0])],
source: externalConfig.sourceId,
where: '',
numberFormat: externalConfig.numberFormat,
// The input schema validates these as hue-only palette tokens,
// so pass them through directly; `_.omitBy(_.isNil)` below drops
// them when absent.
color: externalConfig.color,
colorRules: externalConfig.colorRules,
// Builder number tiles only; `_.omitBy(_.isNil)` below drops it when
// absent. The input schema validates the nested color as a hue-only
// palette token, so it passes through directly.
backgroundChart: externalConfig.backgroundChart,
name,
} satisfies BuilderSavedChartConfig;
break;
case 'pie':
internalConfig = {
...pick(externalConfig, ['groupBy', 'numberFormat']),
displayType: DisplayType.Pie,
select: [convertToInternalSelectItem(externalConfig.select[0])],
source: externalConfig.sourceId,
where: '',
name,
} satisfies BuilderSavedChartConfig;
break;
case 'heatmap': {
// Heatmap is builder-only and uses a single select item with
// its own shape: aggFn is the literal 'heatmap' on the external
// surface, mapped to the internal 'count' aggFn that the editor
// form persists, with the heatmap-specific countExpression /
// heatmapScaleType fields preserved on the select item. The
// row-level filter lives at the chart-config level (matching
// HeatmapSeriesEditor in the UI), not on the select item.
const item = externalConfig.select[0];
internalConfig = {
...pick(externalConfig, ['numberFormat']),
displayType: DisplayType.Heatmap,
// Match the editor's `applyHeatmapDefaults` (in
// `packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx`,
// search for `aggFn: 'count'`) for the two fields the editor
// always writes on the select item: `aggFn: 'count'` and
// `aggCondition: ''`.
//
// Where this path intentionally diverges from the editor:
//
// - `aggConditionLanguage` is hardcoded `'lucene'`; the
// editor uses `getStoredLanguage() ?? 'lucene'` (a user
// session preference). For a UI-saved heatmap whose
// author had `'sql'` selected, a GET -> PUT round-trip
// through this converter will downgrade the persisted
// value to `'lucene'`. The chart renderer does not read
// `aggConditionLanguage` for heatmap tiles (heatmap has
// no per-select where), so the change is invisible at
// render time.
//
// - The editor unconditionally writes
// `numberFormat: { output: 'duration', factor: 0.001 }`
// and `series.0.countExpression: 'count()'`. Both are
// passed through verbatim from the external payload here
// and left absent otherwise, so an API-built tile
// renders without duration formatting unless the caller
// asks for it.
select: [
{
aggFn: 'count',
aggCondition: '',
aggConditionLanguage: 'lucene',
valueExpression: item.valueExpression,
...(item.countExpression !== undefined
? { countExpression: item.countExpression }
: {}),
...(item.heatmapScaleType !== undefined
? { heatmapScaleType: item.heatmapScaleType }
: {}),
},
],
source: externalConfig.sourceId,
// `where` is `z.string().max(10000).optional().default('')` so
// it is always a string post-parse; sibling pie/number/table
// arms write the unconditional value too.
where: externalConfig.where,
whereLanguage: externalConfig.whereLanguage ?? 'lucene',
name,
} satisfies BuilderSavedChartConfig;
break;
}
case 'search':
internalConfig = {
...pick(externalConfig, ['select', 'where']),
displayType: DisplayType.Search,
source: externalConfig.sourceId,
name,
whereLanguage: externalConfig.whereLanguage ?? 'lucene',
} satisfies BuilderSavedChartConfig;
break;
case 'event_patterns':
internalConfig = {
...pick(externalConfig, ['select', 'where']),
displayType: DisplayType.EventPatterns,
source: externalConfig.sourceId,
name,
whereLanguage: externalConfig.whereLanguage ?? 'lucene',
} satisfies BuilderSavedChartConfig;
break;
case 'markdown':
internalConfig = {
displayType: DisplayType.Markdown,
markdown: externalConfig.markdown,
source: '',
where: '',
select: [],
name,
} satisfies BuilderSavedChartConfig;
break;
default:
// Typecheck to ensure all display types are handled
externalConfig satisfies never;
// We should never hit this due to the typecheck above.
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
internalConfig = {} as SavedChartConfig;
}
}
// Omit keys that are null/undefined, so that they're not saved as null in Mongo.
// We know that the resulting object will conform to SavedChartConfig since we're just
// removing null properties and anything that is null will just be undefined instead.
const strippedConfig = _.omitBy(internalConfig, _.isNil) as SavedChartConfig;
// Mirror the spread-conditional pattern used in `convertTileToExternalChart`:
// destructure statically (compile-time narrowing) and include the optional
// refs only when set, so a tile without a containerId never persists
// `containerId: undefined` to Mongo. The previous `pick(...)` over the
// external tile included `name`, but the internal `Tile` type stores the
// name on `config`, not at the top level (`strippedConfig` carries it).
// Stripping the top-level `name` brings the runtime shape back in line
// with `DashboardDocument['tiles'][number]`.
const { id, x, y, w, h, containerId, tabId } = externalTile;
return {
id,
x,
y,
w,
h,
...(containerId !== undefined ? { containerId } : {}),
...(tabId !== undefined ? { tabId } : {}),
config: strippedConfig,
};
}
// --------------------------------------------------------------------------------
// Shared dashboard validation helpers (used by both the REST router and MCP tools)
// --------------------------------------------------------------------------------
/**
* The shape of a source as returned from `getSources(team)` (and reused
* by every dashboard validation helper below). Re-exported so the
* router can pass a single fetched array into multiple helpers without
* pulling in `controllers/sources` for the type alone.
*/
type SourceForValidation = Awaited<ReturnType<typeof getSources>>[number];
/** Fetches sources for a team. Re-exports the controller call so callers
* outside `controllers/sources` don't need a second import for the
* validation flow. The return type is the awaited shape of `getSources`
* (an array of Source documents) so callers can `await` it directly. */
async function fetchSourcesForValidation(
team: string | mongoose.Types.ObjectId,
): Promise<SourceForValidation[]> {
return getSources(team.toString());
}
/**
* Extract the tile's onClick config, if the tile uses the new "config" format
* and the display type supports onClick (currently only table).
*/
function getTileOnClick(tile: ExternalDashboardTileWithId) {
if (!isConfigTile(tile)) return undefined;
if (!('onClick' in tile.config)) return undefined;
return tile.config.onClick;
}
/** Returns source IDs referenced in tiles/filters that do not exist for the team */
function getMissingSources(
sources: SourceForValidation[],
tiles: ExternalDashboardTileWithId[],
filters?: (ExternalDashboardFilter | ExternalDashboardFilterWithId)[],
): string[] {
const sourceIds = new Set<string>();
for (const tile of tiles) {
if (isSeriesTile(tile)) {
for (const series of tile.series) {
if ('sourceId' in series) {
sourceIds.add(series.sourceId);
}
}
} else if (isConfigTile(tile)) {
if ('sourceId' in tile.config && tile.config.sourceId) {
sourceIds.add(tile.config.sourceId);
}
}
// Include source IDs referenced by OnClick link-outs (mode=id, type=search)
const onClick = getTileOnClick(tile);
if (isOnClickSearchById(onClick)) {
sourceIds.add(onClick.target.id);
}
}
if (filters?.length) {
for (const filter of filters) {
if ('sourceId' in filter) {
sourceIds.add(filter.sourceId);
}
}
}
const existingSourceIds = new Set(
sources.map(source => source._id.toString()),
);
return [...sourceIds].filter(sourceId => !existingSourceIds.has(sourceId));
}
/**
* Returns source IDs referenced by heatmap tiles that exist but are not
* compatible with heatmap rendering. The heatmap UI gates the source picker
* via the same `HEATMAP_ALLOWED_SOURCE_KINDS` set used here (see
* `packages/common-utils/src/guards.ts` and `ChartEditorControls.tsx`), so
* UI and API gates move together.
*/
function getHeatmapTilesWithIncompatibleSources(
sources: SourceForValidation[],
tiles: ExternalDashboardTileWithId[],
): string[] {
const heatmapSourceIds = new Set<string>();
for (const tile of tiles) {
if (
isConfigTile(tile) &&
!isRawSqlExternalTileConfig(tile.config) &&
tile.config.displayType === 'heatmap' &&
tile.config.sourceId
) {
heatmapSourceIds.add(tile.config.sourceId);
}
}
if (heatmapSourceIds.size === 0) return [];
const sourceById = new Map(sources.map(s => [s._id.toString(), s]));
return [...heatmapSourceIds].filter(id => {
const source = sourceById.get(id);
return source !== undefined && !isHeatmapCompatibleSource(source);
});
}
/**
* For a PUT (update) request, return only the heatmap tiles that need
* to be re-validated against the source-kind gate. A heatmap tile that
* was already on the same source in the existing dashboard is kept as
* "unchanged" so the user can edit other parts of the dashboard
* without being blocked when the underlying source's `kind` was
* changed after the heatmap was originally accepted. New heatmap
* tiles, tiles whose displayType just changed to heatmap, and tiles
* whose `sourceId` changed all flow through the check.
*/
function filterChangedHeatmapTiles(
requestTiles: ExternalDashboardTileWithId[],
existingTiles: DashboardDocument['tiles'],
): ExternalDashboardTileWithId[] {
const existingTilesById = new Map<string, DashboardDocument['tiles'][number]>(
existingTiles.map(t => [t.id, t]),
);
return requestTiles.filter(tile => {
if (
!isConfigTile(tile) ||
isRawSqlExternalTileConfig(tile.config) ||
tile.config.displayType !== 'heatmap'
) {
return false;
}
const existing = tile.id ? existingTilesById.get(tile.id) : undefined;
if (existing === undefined) {
// New heatmap tile: validate.
return true;
}
const existingConfig = existing.config;
if (isRawSqlSavedChartConfig(existingConfig)) {
// Existing tile was raw-SQL; user is converting to a heatmap.
return true;
}
if (existingConfig.displayType !== DisplayType.Heatmap) {
// displayType changed to heatmap.
return true;
}
// Existing tile was already a heatmap. Re-check only when the