-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdatasource.go
More file actions
1379 lines (1215 loc) · 43 KB
/
datasource.go
File metadata and controls
1379 lines (1215 loc) · 43 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
package plugin
import (
"cmp"
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"slices"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/google/uuid"
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/backend/httpclient"
"github.com/grafana/grafana-plugin-sdk-go/backend/instancemgmt"
"github.com/grafana/grafana-plugin-sdk-go/backend/log"
"github.com/grafana/grafana-plugin-sdk-go/data"
"golang.org/x/sync/errgroup"
)
// Make sure Datasource implements required interfaces. This is important to do
// since otherwise we will only get a not implemented error response from plugin in
// runtime. In this example datasource instance implements backend.QueryDataHandler,
// backend.CheckHealthHandler interfaces. Plugin should not implement all these
// interfaces - only those which are required for a particular task.
var (
_ backend.QueryDataHandler = (*SiftDatasource)(nil)
_ backend.CheckHealthHandler = (*SiftDatasource)(nil)
_ instancemgmt.InstanceDisposer = (*SiftDatasource)(nil)
_ backend.CallResourceHandler = (*SiftDatasource)(nil)
)
const QueryVersion = "2.1"
const maxParallelDataQueries = 10
const (
EnumDisplayNone = ""
EnumDisplayBoth = "both"
EnumDisplayValue = "value"
EnumDisplayString = "string"
)
var ValidSiftGrafanaDataTypes = []string{
"CHANNEL_DATA_TYPE_STRING",
"CHANNEL_DATA_TYPE_BOOL",
"CHANNEL_DATA_TYPE_DOUBLE",
"CHANNEL_DATA_TYPE_FLOAT",
"CHANNEL_DATA_TYPE_INT_64",
"CHANNEL_DATA_TYPE_INT_32",
"CHANNEL_DATA_TYPE_UINT_32",
"CHANNEL_DATA_TYPE_UINT_64",
"CHANNEL_DATA_TYPE_ENUM",
"CHANNEL_DATA_TYPE_BIT_FIELD",
// Note: No bytes
}
const cacheTimeToLiveMax = time.Minute * 10
const cacheTimeToLiveMin = cacheTimeToLiveMax / 2
const cachePurgeTime = time.Minute * 5
func StringFromChannelSearchKey(c channelSearchKey) string {
return fmt.Sprintf("[%s] %s", c.assetId, c.searchTerm)
}
// NewSiftDatasource creates a new datasource instance.
func NewSiftDatasource(ctx context.Context, s backend.DataSourceInstanceSettings) (instancemgmt.Instance, error) {
// Initialize http client
opts, err := s.HTTPClientOptions(ctx)
if err != nil {
return nil, err
}
httpClient, err := httpclient.New(opts)
if err != nil {
return nil, err
}
// Cache logic - ID and Name caches can be long-lived since any misses will result in call to the API
// Regex caches are shorter since any newly added Assets/Runs/Channels won't be matched unless a new API call is made
assetsIdsCache := NewTypedCache[string, string](cacheTimeToLiveMax, cachePurgeTime)
assetsNameCache := NewTypedCacheWithRandomTtl[string, string](cacheTimeToLiveMax, cacheTimeToLiveMin, cachePurgeTime)
assetsRegexCache := NewTypedCacheWithRandomTtl[string, []string](cacheTimeToLiveMax, cacheTimeToLiveMin, cachePurgeTime)
runIdsCache := NewTypedCache[string, string](cacheTimeToLiveMax, cachePurgeTime)
runsNameCache := NewTypedCacheWithRandomTtl[string, []string](cacheTimeToLiveMax, cacheTimeToLiveMin, cachePurgeTime)
runsRegexCache := NewTypedCacheWithRandomTtl[string, []string](cacheTimeToLiveMax, cacheTimeToLiveMin, cachePurgeTime)
channelIdsCache := NewTypedCache[string, Channel](cacheTimeToLiveMax, cachePurgeTime)
channelNameCache := NewTypedCacheWithLoader[channelSearchKey, []Channel, string](
NewTypedCacheWithRandomTtl[string, []Channel](cacheTimeToLiveMax, cacheTimeToLiveMin, cachePurgeTime),
getChannelsByNameExact,
StringFromChannelSearchKey)
channelRegexCache := NewTypedCacheWithLoader[channelSearchKey, []Channel, string](
NewTypedCacheWithRandomTtl[string, []Channel](cacheTimeToLiveMax, cacheTimeToLiveMin, cachePurgeTime),
getChannelsByNameSearch,
StringFromChannelSearchKey)
return &SiftDatasource{
httpClient: httpClient,
assetsIdSearchCache: assetsIdsCache,
assetsRegexSearchCache: assetsRegexCache,
assetsNameSearchCache: assetsNameCache,
runsIdSearchCache: runIdsCache,
runsRegexSearchCache: runsRegexCache,
runsNameSearchCache: runsNameCache,
channelsIdSearchCache: channelIdsCache,
channelsNameSearchCache: channelNameCache,
channelsRegexSearchCache: channelRegexCache,
}, nil
}
// SiftDatasource is an example datasource which can respond to data queries, reports
// its health and has streaming skills.
type SiftDatasource struct {
httpClient *http.Client
assetsIdSearchCache *TypedCache[string, string]
assetsNameSearchCache *TypedCache[string, string] // assets are unique by name
assetsRegexSearchCache *TypedCache[string, []string]
runsIdSearchCache *TypedCache[string, string]
runsNameSearchCache *TypedCache[string, []string] // runs are not unique by name
runsRegexSearchCache *TypedCache[string, []string]
channelsIdSearchCache *TypedCache[string, Channel]
// channel caches use loader to avoid duplicate API calls at the same time
channelsNameSearchCache *TypedCacheWithLoader[channelSearchKey, []Channel, string]
channelsRegexSearchCache *TypedCacheWithLoader[channelSearchKey, []Channel, string]
}
// Dispose here tells plugin SDK that plugin wants to clean up resources when a new instance
// created. As soon as datasource settings change detected by SDK old datasource instance will
// be disposed and a new one will be created using NewSampleDatasource factory function.
func (d *SiftDatasource) Dispose() {
// Clean up datasource instance resources.
}
func (d *SiftDatasource) CallResource(ctx context.Context, req *backend.CallResourceRequest, sender backend.CallResourceResponseSender) error {
switch req.Path {
case "assets":
return d.callResourceAssets(ctx, req, sender)
case "channels":
return d.callResourceChannels(ctx, req, sender)
case "runs":
return d.callResourceRuns(ctx, req, sender)
case "migrate-query":
return d.callResourceMigrateQuery(ctx, req, sender)
case "purge-cache":
return d.callPurgeCache(ctx, req, sender)
case "resolve-query-to-sift-metadata":
return d.resolveQueryToSiftMetadata(ctx, req, sender)
default:
return sender.Send(&backend.CallResourceResponse{
Status: http.StatusNotFound,
})
}
}
// QueryData handles multiple queries and returns multiple responses.
// req contains the queries []DataQuery (where each query contains RefID as a unique identifier).
// The QueryDataResponse contains a map of RefID to the response for each query, and each response
// contains Frames ([]*Frame).
func (d *SiftDatasource) QueryData(ctx context.Context, req *backend.QueryDataRequest) (*backend.QueryDataResponse, error) {
response := backend.NewQueryDataResponse()
// loop over queries and execute them individually.
for _, q := range req.Queries {
// Unmarshal the JSON into our queryModel.
var fqm *queryModel
fqm, err := convertQueryIfNeeded(q.JSON)
if err != nil {
response.Responses[q.RefID] = backend.ErrDataResponse(backend.StatusBadRequest, fmt.Sprintf("json unmarshal: %v", err.Error()))
continue
}
if fqm.Hide {
continue
}
res := d.query(req.PluginContext, q, *fqm)
// save the response in a hashmap
// based on with RefID as identifier
response.Responses[q.RefID] = res
}
return response, nil
}
type jsonData struct {
Url string `json:"url"`
FrontendUrl string `json:"frontendUrl"`
}
type commonQueryProperties struct {
Key string `json:"key"`
Hide bool `json:"hide"`
QueryType string `json:"queryType"`
RefId string `json:"refId"`
}
type assetQuery struct {
AssetId string `json:"assetId"`
AssetName string `json:"assetName"`
NameAsRegex bool `json:"nameAsRegex"`
AsSelect bool `json:"asSelect"`
DashboardVariableName string `json:"dashboardVariableName"`
}
type runQuery struct {
RunId string `json:"runId"`
RunName string `json:"runName"`
NameAsRegex bool `json:"nameAsRegex"`
AsSelect bool `json:"asSelect"`
}
type channelQuery struct {
ChannelId string `json:"channelId"`
ChannelName string `json:"channelName"`
NameAsRegex bool `json:"nameAsRegex"`
AsSelect bool `json:"asSelect"`
}
type channelReferenceQuery struct {
channelQuery
ChannelReference string `json:"channelReference"`
}
type calculatedChannelQuery struct {
Name string `json:"name"`
ChannelReferences []channelReferenceQuery `json:"channelReferences"`
Expression string `json:"expression"`
}
type channelDataQuery struct {
AssetQueries []assetQuery `json:"assetQueries"`
RunQueries []runQuery `json:"runQueries"`
ChannelQueries []channelQuery `json:"channelQueries"`
CalculatedChannelQueries []calculatedChannelQuery `json:"calculatedChannelQueries"`
}
type queryModel struct {
commonQueryProperties
ChannelDataQueries []channelDataQuery `json:"channelDataQueries"`
CombineRuns bool `json:"combineRuns"`
EnumDisplay string `json:"enumDisplay"`
QueryVersion string `json:"queryVersion"`
}
type queryResponse struct {
Data []queryResponseData `json:"data"`
NextPageToken string `json:"nextPageToken"`
ErrorMessage string `json:"message"`
}
type queryResponseData struct {
Metadata queryResponseMetadata `json:"metadata"`
Values json.RawMessage `json:"values"`
}
type queryResponseChannelBitFieldElement struct {
Name string `json:"name"`
Index int32 `json:"index"`
BitCount uint32 `json:"bitCount"`
}
type queryResponseChannelEnumType struct {
Name string `json:"name"`
Key uint32 `json:"key"`
}
type queryResponseMetadata struct {
DataType string `json:"dataType"`
SampledMs int64 `json:"sampledMs"`
Asset struct {
AssetId string `json:"assetId"`
Name string `json:"name"`
} `json:"asset"`
Run struct {
RunId string `json:"runId"`
Name string `json:"name"`
} `json:"run"`
Channel struct {
ChannelId string `json:"channelId"`
Name string `json:"name"`
EnumTypes []queryResponseChannelEnumType `json:"enumTypes"`
BitFieldElements []queryResponseChannelBitFieldElement `json:"bitFieldElements"`
} `json:"channel"`
}
type stringValue struct {
Timestamp time.Time `json:"timestamp"`
Value string `json:"value"`
}
type boolValue struct {
Timestamp time.Time `json:"timestamp"`
Value bool `json:"value"`
}
type doubleValue struct {
Timestamp time.Time `json:"timestamp"`
Value float64 `json:"value"`
}
type floatValue struct {
Timestamp time.Time `json:"timestamp"`
Value float32 `json:"value"`
}
type int64Value struct { //nolint
Timestamp time.Time `json:"timestamp"`
Value int64 `json:"value"`
}
type int32Value struct {
Timestamp time.Time `json:"timestamp"`
Value int32 `json:"value"`
}
type uint32Value struct {
Timestamp time.Time `json:"timestamp"`
Value uint32 `json:"value"`
}
type uint64Value struct { //nolint
Timestamp time.Time `json:"timestamp"`
Value uint64 `json:"value"`
}
type enumValue struct {
Timestamp time.Time `json:"timestamp"`
Value uint32 `json:"value"`
}
type bitFieldValue struct {
Timestamp time.Time `json:"timestamp"`
Value uint32 `json:"value"`
}
type bitFieldElementValues struct {
Name string `json:"name"`
Values []bitFieldValue `json:"values"`
}
type frameKey struct {
channelId string
runId string
bitFieldElementName string
isEnumString bool
}
type expressionChannelReference struct {
ChannelReference string `json:"channel_reference"`
ChannelId string `json:"channel_id"`
ChannelName string
}
type calculatedChannelKey struct {
channelName string
channelReferences []expressionChannelReference
}
type channelSearchKey struct {
assetId string
searchTerm string
}
func getApiUrl(dataSourceInstanceSettings *backend.DataSourceInstanceSettings) (*url.URL, error) {
jsonData := jsonData{}
err := json.Unmarshal(dataSourceInstanceSettings.JSONData, &jsonData)
if err != nil {
return nil, fmt.Errorf("json unmarshal: %w", err)
}
u, err := url.Parse(jsonData.Url)
if err != nil {
return nil, fmt.Errorf("malformed api url: %w", err)
}
return u, nil
}
func (d *SiftDatasource) query(pCtx backend.PluginContext, query backend.DataQuery, fqm queryModel) backend.DataResponse {
defer func() {
if err := recover(); err != nil {
log.DefaultLogger.Error("recovered from panic", "error", err)
}
}()
var response backend.DataResponse
queryStart := time.Now()
queries, calculatedChannelKeys, err := generateQueries(pCtx, fqm, d)
if err != nil {
return backend.ErrDataResponse(backend.StatusBadRequest, fmt.Sprintf("error generating queries: %v", err.Error()))
}
afterLoadingQueries := time.Now()
responseData, err := runDataQueries(pCtx, queries, query, d)
if err != nil {
return backend.ErrDataResponse(backend.StatusBadRequest, fmt.Sprintf("error generating getting data: %v", err.Error()))
}
afterExecutingQueries := time.Now()
frame, err := generateDataFrame(responseData, calculatedChannelKeys, fqm.CombineRuns, fqm.EnumDisplay)
if err != nil {
return backend.ErrDataResponse(backend.StatusBadRequest, fmt.Sprintf("error generating data frame: %v", err.Error()))
}
afterTransformingData := time.Now()
// output timings
log.DefaultLogger.Debug("timings",
"loadingQueries", afterLoadingQueries.Sub(queryStart).Milliseconds(),
"gettingData", afterExecutingQueries.Sub(afterLoadingQueries).Milliseconds(),
"generatingDataFrame", afterTransformingData.Sub(afterExecutingQueries).Milliseconds(),
)
// add the frames to the response.
response.Frames = append(response.Frames, frame)
return response
}
// generateQueries creates query objects for both simple channel queries and calculated channel queries.
// For simple channel queries, it looks up asset IDs and channel IDs based on names/identifiers.
// For calculated channel queries, it generates the appropriate query structure with channel references.
// It returns:
// - A slice of query objects that can be sent to the backend API
// - A map of calculated channel keys to their metadata (for calculated channels only)
// - Any error that occurred during query generation
func generateQueries(pCtx backend.PluginContext, fqm queryModel, d *SiftDatasource) ([]siftApiGetDataSubQuery, map[string]calculatedChannelKey, error) {
queries := []siftApiGetDataSubQuery{}
calculatedChannelKeys := make(map[string]calculatedChannelKey)
for _, cdq := range fqm.ChannelDataQueries {
assetIds := []string{}
runIds := []string{}
// Get all asset IDs for the asset queries
assetIdQueries := []string{}
for _, assetQuery := range cdq.AssetQueries {
if assetQuery.AssetId != "" {
assetIdQueries = append(assetIdQueries, assetQuery.AssetId)
} else if assetQuery.AssetName != "" {
foundAssetIds, err := d.getAssetIdsByName(pCtx, assetQuery.AssetName, assetQuery.NameAsRegex)
if err != nil {
return nil, nil, fmt.Errorf("error looking up assets: %w", err)
}
assetIds = append(assetIds, foundAssetIds...)
}
}
validAssetIds, err := d.getValidAssetsById(pCtx, assetIdQueries)
if err != nil {
return nil, nil, fmt.Errorf("error looking up assets: %w", err)
}
assetIds = append(assetIds, validAssetIds...)
if len(assetIds) == 0 {
return nil, nil, fmt.Errorf("no assets found for query: %v", assetIdQueries)
}
// Get all run IDs for the run queries
runIdQueries := []string{}
for _, runQuery := range cdq.RunQueries {
// TODO: handle nil run
if runQuery.RunId != "" {
runIdQueries = append(runIdQueries, runQuery.RunId)
} else if runQuery.RunName != "" {
foundRunIds, err := d.getRunIdsByName(pCtx, assetIds, runQuery.RunName, runQuery.NameAsRegex)
if err != nil {
return nil, nil, fmt.Errorf("error looking up runs: %w", err)
}
runIds = append(runIds, foundRunIds...)
}
}
validRunIds, err := d.getValidRunsById(pCtx, runIdQueries)
if err != nil {
return nil, nil, fmt.Errorf("error looking up runs: %w", err)
}
runIds = append(runIds, validRunIds...)
// Process regular channel queries
channelQueries, err := getChannelQueries(pCtx, cdq, runIds, assetIds, d)
if err != nil {
return nil, nil, err
}
queries = append(queries, channelQueries...)
//Process calculated channel queries
calculationQueries, calculatedChanKeys, err := getCalculationQueries(pCtx, cdq, runIds, assetIds, fqm, d)
if err != nil {
return nil, nil, err
}
queries = append(queries, calculationQueries...)
for key, val := range calculatedChanKeys {
calculatedChannelKeys[key] = val
}
if len(queries) == 0 {
log.DefaultLogger.Debug("No channels found for query", "assetIds", assetIds, "runIds", runIds, "channelQueries", cdq.ChannelQueries)
}
}
return queries, calculatedChannelKeys, nil
}
func sortedKeys(set map[string]struct{}) []string {
if len(set) == 0 {
return []string{}
}
result := make([]string, 0, len(set))
for k := range set {
result = append(result, k)
}
slices.Sort(result)
return result
}
func splitQueries(queries []siftApiGetDataSubQuery, chunkSize int) [][]siftApiGetDataSubQuery {
var chunks [][]siftApiGetDataSubQuery
for i := 0; i < len(queries); i += chunkSize {
end := i + chunkSize
if end > len(queries) {
end = len(queries)
}
chunks = append(chunks, queries[i:end])
}
return chunks
}
func runDataQueries(pCtx backend.PluginContext, queries []siftApiGetDataSubQuery, query backend.DataQuery, d *SiftDatasource) ([]queryResponseData, error) {
chunks := splitQueries(queries, (len(queries)+maxParallelDataQueries-1)/maxParallelDataQueries)
var allData []queryResponseData
var mu sync.Mutex
g, _ := errgroup.WithContext(context.Background())
g.SetLimit(maxParallelDataQueries)
for _, chunk := range chunks {
chunk := chunk
g.Go(func() error {
dataResponse, err := d.getData(pCtx, chunk, query)
if err != nil {
return err
}
mu.Lock()
allData = append(allData, dataResponse...)
mu.Unlock()
return nil
})
}
if err := g.Wait(); err != nil {
return nil, err
}
return allData, nil
}
func generateDataFrame(responseData []queryResponseData, calculatedChannelKeys map[string]calculatedChannelKey, combineRuns bool, enumDisplay string) (*data.Frame, error) {
// create data frame response.
// For an overview on data frames and how grafana handles them:
// https://grafana.com/developers/plugin-tools/introduction/data-frames
dataMap := map[frameKey][]queryResponseData{}
md := map[frameKey]queryResponseMetadata{}
allData := map[frameKey]map[int64]any{}
for _, d := range responseData {
switch d.Metadata.DataType {
case "CHANNEL_DATA_TYPE_BIT_FIELD":
for _, bitFieldElement := range d.Metadata.Channel.BitFieldElements {
key := frameKey{
channelId: d.Metadata.Channel.ChannelId,
bitFieldElementName: bitFieldElement.Name,
}
if !combineRuns {
key.runId = d.Metadata.Run.RunId
}
dataMap[key] = append(dataMap[key], d)
if _, ok := md[key]; !ok {
md[key] = d.Metadata
}
}
case "CHANNEL_DATA_TYPE_ENUM":
for _, v := range []bool{true, false} {
key := frameKey{
channelId: d.Metadata.Channel.ChannelId,
isEnumString: v,
}
if !combineRuns {
key.runId = d.Metadata.Run.RunId
}
dataMap[key] = append(dataMap[key], d)
if _, ok := md[key]; !ok {
md[key] = d.Metadata
}
}
default:
key := frameKey{
channelId: d.Metadata.Channel.ChannelId,
}
if !combineRuns {
key.runId = d.Metadata.Run.RunId
}
dataMap[key] = append(dataMap[key], d)
if _, ok := md[key]; !ok {
md[key] = d.Metadata
}
}
}
allTimestamps := map[int64]bool{}
for key, dm := range dataMap {
values := map[int64]any{}
allData[key] = values
switch dm[0].Metadata.DataType {
default:
return nil, fmt.Errorf("unknown data type: %v", dm[0].Metadata.DataType)
case "CHANNEL_DATA_TYPE_STRING":
for _, d := range dm {
var v []stringValue
err := json.Unmarshal(d.Values, &v)
if err != nil {
return nil, fmt.Errorf("json unmarshal: %w", err)
}
for _, vv := range v {
values[vv.Timestamp.UnixNano()] = vv.Value
}
}
case "CHANNEL_DATA_TYPE_BOOL":
for _, d := range dm {
var v []boolValue
err := json.Unmarshal(d.Values, &v)
if err != nil {
return nil, fmt.Errorf("json unmarshal: %w", err)
}
for _, vv := range v {
values[vv.Timestamp.UnixNano()] = vv.Value
}
}
case "CHANNEL_DATA_TYPE_DOUBLE":
for _, d := range dm {
var v []doubleValue
err := json.Unmarshal(d.Values, &v)
if err != nil {
return nil, fmt.Errorf("json unmarshal: %w", err)
}
for _, vv := range v {
values[vv.Timestamp.UnixNano()] = vv.Value
}
}
case "CHANNEL_DATA_TYPE_FLOAT":
for _, d := range dm {
var v []floatValue
err := json.Unmarshal(d.Values, &v)
if err != nil {
return nil, fmt.Errorf("json unmarshal: %w", err)
}
for _, vv := range v {
values[vv.Timestamp.UnixNano()] = vv.Value
}
}
case "CHANNEL_DATA_TYPE_INT_64":
for _, d := range dm {
// note that these are returned as strings in the proto -> json mapping https://protobuf.dev/programming-guides/proto3/#json
var v []stringValue
err := json.Unmarshal(d.Values, &v)
if err != nil {
return nil, fmt.Errorf("json unmarshal: %w", err)
}
for _, vv := range v {
number, err := strconv.ParseInt(vv.Value, 10, 64)
if err != nil {
return nil, fmt.Errorf("failed to parse value: %w", err)
}
values[vv.Timestamp.UnixNano()] = number
}
}
case "CHANNEL_DATA_TYPE_INT_32":
for _, d := range dm {
var v []int32Value
err := json.Unmarshal(d.Values, &v)
if err != nil {
return nil, fmt.Errorf("json unmarshal: %w", err)
}
for _, vv := range v {
values[vv.Timestamp.UnixNano()] = vv.Value
}
}
case "CHANNEL_DATA_TYPE_UINT_32":
for _, d := range dm {
var v []uint32Value
err := json.Unmarshal(d.Values, &v)
if err != nil {
return nil, fmt.Errorf("json unmarshal: %w", err)
}
for _, vv := range v {
values[vv.Timestamp.UnixNano()] = vv.Value
}
}
case "CHANNEL_DATA_TYPE_UINT_64":
for _, d := range dm {
// note that these are returned as strings in the proto -> json mapping https://protobuf.dev/programming-guides/proto3/#json
var v []stringValue
err := json.Unmarshal(d.Values, &v)
if err != nil {
return nil, fmt.Errorf("json unmarshal: %w", err)
}
for _, vv := range v {
number, err := strconv.ParseUint(vv.Value, 10, 64)
if err != nil {
return nil, fmt.Errorf("failed to parse value: %w", err)
}
values[vv.Timestamp.UnixNano()] = number
}
}
case "CHANNEL_DATA_TYPE_ENUM":
for _, d := range dm {
var v []enumValue
err := json.Unmarshal(d.Values, &v)
if err != nil {
return nil, fmt.Errorf("json unmarshal: %w", err)
}
enumLookup := map[uint32]string{}
for _, e := range d.Metadata.Channel.EnumTypes {
enumLookup[e.Key] = e.Name
}
for _, vv := range v {
if key.isEnumString {
if enumName, ok := enumLookup[vv.Value]; ok {
values[vv.Timestamp.UnixNano()] = enumName
} else {
values[vv.Timestamp.UnixNano()] = fmt.Sprintf("%v", vv.Value)
}
} else {
values[vv.Timestamp.UnixNano()] = vv.Value
}
}
}
case "CHANNEL_DATA_TYPE_BIT_FIELD":
for _, d := range dm {
var v []bitFieldElementValues
err := json.Unmarshal(d.Values, &v)
if err != nil {
return nil, fmt.Errorf("json unmarshal: %w", err)
}
for _, bitfieldElementValues := range v {
if key.bitFieldElementName == bitfieldElementValues.Name {
for _, vv := range bitfieldElementValues.Values {
values[vv.Timestamp.UnixNano()] = vv.Value
}
}
}
}
}
for k := range values {
allTimestamps[k] = true
}
}
timestamps := []time.Time{}
for k := range allTimestamps {
timestamps = append(timestamps, time.Unix(0, k))
}
sort.Slice(timestamps, func(i, j int) bool {
return timestamps[i].Before(timestamps[j])
})
frame := data.NewFrame("response")
allDataKeys := []frameKey{}
for k := range allData {
allDataKeys = append(allDataKeys, k)
}
sort.SliceStable(allDataKeys, func(i, j int) bool {
return allDataKeys[i].runId < allDataKeys[j].runId && allDataKeys[i].channelId < allDataKeys[j].channelId
})
// Track enum field base names for filtering later
enumFieldBaseNames := map[string]bool{}
for _, key := range allDataKeys {
m := md[key]
name := m.Channel.Name
include_channel_id := false
var field *data.Field
labels := data.Labels{}
if v, ok := calculatedChannelKeys[m.Channel.ChannelId]; ok {
name = v.channelName
for _, cr := range v.channelReferences {
labels[cr.ChannelReference] = cr.ChannelName
labels[fmt.Sprintf("%s_id", cr.ChannelReference)] = cr.ChannelId
}
} else {
include_channel_id = true
}
if m.Run.Name != "" && !combineRuns {
labels["run"] = m.Run.Name
}
if m.Run.RunId != "" && !combineRuns {
labels["run_id"] = m.Run.RunId
}
if m.Asset.Name != "" {
labels["asset"] = m.Asset.Name
}
if m.Asset.AssetId != "" {
labels["asset_id"] = m.Asset.AssetId
}
if len(m.Channel.BitFieldElements) > 0 {
for _, bitFieldElement := range m.Channel.BitFieldElements {
if key.bitFieldElementName == bitFieldElement.Name {
labels["bitfield_element"] = bitFieldElement.Name
}
}
}
if include_channel_id {
labels["channel_id"] = m.Channel.ChannelId
}
switch m.DataType {
default:
return nil, fmt.Errorf("unknown data type: %v", m.DataType)
case "CHANNEL_DATA_TYPE_STRING":
field = data.NewField(name, labels, []*string{})
case "CHANNEL_DATA_TYPE_BOOL":
field = data.NewField(name, labels, []*bool{})
case "CHANNEL_DATA_TYPE_DOUBLE":
field = data.NewField(name, labels, []*float64{})
case "CHANNEL_DATA_TYPE_FLOAT":
field = data.NewField(name, labels, []*float32{})
case "CHANNEL_DATA_TYPE_INT_64":
field = data.NewField(name, labels, []*int64{})
case "CHANNEL_DATA_TYPE_INT_32":
field = data.NewField(name, labels, []*int32{})
case "CHANNEL_DATA_TYPE_UINT_32":
field = data.NewField(name, labels, []*uint32{})
case "CHANNEL_DATA_TYPE_UINT_64":
field = data.NewField(name, labels, []*uint64{})
case "CHANNEL_DATA_TYPE_ENUM":
// Track the base name for this enum field
enumFieldBaseNames[name] = true
if key.isEnumString {
name = name + "_string"
field = data.NewField(name, labels, []*string{})
} else {
name = name + "_value"
field = data.NewField(name, labels, []*uint32{})
}
case "CHANNEL_DATA_TYPE_BIT_FIELD":
field = data.NewField(name, labels, []*uint32{})
}
field.Extend(len(timestamps))
values := allData[key]
for i, t := range timestamps {
v := values[t.UnixNano()]
if v != nil {
field.SetConcrete(i, v)
}
}
frame.Fields = append(frame.Fields, field)
}
// Filter and rename enum fields based on enumDisplay setting
if enumDisplay == EnumDisplayString || enumDisplay == EnumDisplayValue {
filteredFields := []*data.Field{}
for _, field := range frame.Fields {
fieldName := field.Name
// Check if this is an enum field by looking for the suffix
isEnumField := false
baseName := ""
keepField := false
if strings.HasSuffix(fieldName, "_string") {
baseName = strings.TrimSuffix(fieldName, "_string")
if enumFieldBaseNames[baseName] {
isEnumField = true
keepField = enumDisplay == EnumDisplayString
}
} else if strings.HasSuffix(fieldName, "_value") {
baseName = strings.TrimSuffix(fieldName, "_value")
if enumFieldBaseNames[baseName] {
isEnumField = true
keepField = enumDisplay == EnumDisplayValue
}
}
if isEnumField {
if keepField {
// Rename the field to remove the suffix
field.Name = baseName
filteredFields = append(filteredFields, field)
}
// Skip fields we don't want to keep
} else {
// Keep non-enum fields as-is
filteredFields = append(filteredFields, field)
}
}
frame.Fields = filteredFields
}
// Sort fields by channel name first.
// Calculated channels will all have the
// same channel name, so we also sort by labels.
slices.SortFunc(frame.Fields, func(a, b *data.Field) int {
return cmp.Or(
strings.Compare(a.Name, b.Name),
strings.Compare(a.Labels.String(), b.Labels.String()),
)
})
// The time channel should always be first in the frame.
frame.Fields = append(
[]*data.Field{data.NewField("time", nil, timestamps)},
frame.Fields...,
)
// Add frame metadata
frame.Meta = &data.FrameMeta{
Type: data.FrameTypeTimeSeriesWide,
TypeVersion: data.FrameTypeVersion{0, 1},
Notices: []data.Notice{},
}
// Check for precision loss in INT64/UINT64 fields
checkInt64PrecisionLoss(frame)
return frame, nil
}
// checkInt64PrecisionLoss validates INT64/UINT64 fields for values outside JavaScript's safe integer range
// and attaches warnings to the frame if precision loss may occur in the frontend.
func checkInt64PrecisionLoss(frame *data.Frame) {
// JavaScript's safe integer range: ±2^53-1
const jsSafeIntMax int64 = 9007199254740991 // 2^53 - 1
const jsSafeIntMin int64 = -9007199254740991 // -(2^53 - 1)
const jsSafeUintMax uint64 = 9007199254740991
const warningFormat = "Field '%s' (asset: %s) contains %s values outside JavaScript's safe integer range (min: %d, max: %d). Values may not be displayed correctly."
for _, field := range frame.Fields {
var warning string
switch field.Type() {
case data.FieldTypeInt64, data.FieldTypeNullableInt64:
var minVal, maxVal int64
hasUnsafe := false
for i := 0; i < field.Len(); i++ {
var val int64
if v, ok := field.At(i).(*int64); ok && v != nil {
val = *v
} else if v, ok := field.At(i).(int64); ok {
val = v
} else {
continue
}
if i == 0 || val < minVal {
minVal = val
}
if i == 0 || val > maxVal {
maxVal = val
}
if val > jsSafeIntMax || val < jsSafeIntMin {
hasUnsafe = true
}
}
if hasUnsafe {
assetName := field.Labels["asset"]
if assetName == "" {
assetName = "unknown"
}
warning = fmt.Sprintf(warningFormat, field.Name, assetName, "INT64", minVal, maxVal)