-
Notifications
You must be signed in to change notification settings - Fork 117
/
metrics_views.go
343 lines (291 loc) · 8.61 KB
/
metrics_views.go
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
package server
import (
"context"
"fmt"
"strings"
"github.com/rilldata/rill/runtime/api"
"github.com/rilldata/rill/runtime/drivers"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/structpb"
)
// MetricsViewMeta implements RuntimeService
func (s *Server) MetricsViewMeta(
ctx context.Context,
req *api.MetricsViewMetaRequest,
) (*api.MetricsViewMetaResponse, error) {
// NOTE: Mock implementation
dimensions := []*api.MetricsView_Dimension{
{Name: "time", Type: "TIMESTAMP", PrimaryTime: true},
{Name: "foo", Type: "VARCHAR"},
}
measures := []*api.MetricsView_Measure{
{Name: "bar", Type: "DOUBLE"},
{Name: "baz", Type: "INTEGER"},
}
resp := &api.MetricsViewMetaResponse{
MetricsViewName: req.MetricsViewName,
Dimensions: dimensions,
Measures: measures,
}
return resp, nil
}
// MetricsViewToplist implements RuntimeService
func (s *Server) MetricsViewToplist(
ctx context.Context,
req *api.MetricsViewToplistRequest,
) (*api.MetricsViewToplistResponse, error) {
// NOTE: Mock implementation
sql, args, err := buildMetricsTopListSql(req)
if err != nil {
return nil, status.Errorf(codes.Internal, "error building query: %s", err.Error())
}
meta, data, err := s.runQuery(ctx, req.InstanceId, sql, args)
if err != nil {
return nil, err
}
resp := &api.MetricsViewToplistResponse{
Meta: meta,
Data: data,
}
return resp, nil
}
// MetricsViewTimeSeries implements RuntimeService
func (s *Server) MetricsViewTimeSeries(
ctx context.Context,
req *api.MetricsViewTimeSeriesRequest,
) (*api.MetricsViewTimeSeriesResponse, error) {
// NOTE: Partially mocked - timestamp column is hardcoded
sql, args, err := buildMetricsTimeSeriesSQL(req)
if err != nil {
return nil, status.Errorf(codes.Internal, "error building query: %s", err.Error())
}
meta, data, err := s.runQuery(ctx, req.InstanceId, sql, args)
if err != nil {
return nil, err
}
resp := &api.MetricsViewTimeSeriesResponse{
Meta: meta,
Data: data,
}
return resp, nil
}
// MetricsViewTotals implements RuntimeService
func (s *Server) MetricsViewTotals(
ctx context.Context,
req *api.MetricsViewTotalsRequest,
) (*api.MetricsViewTotalsResponse, error) {
sql, args, err := buildMetricsTotalsSql(req)
if err != nil {
return nil, status.Errorf(codes.Internal, "error building query: %s", err.Error())
}
meta, data, err := s.runQuery(ctx, req.InstanceId, sql, args)
if err != nil {
return nil, err
}
if len(data) == 0 {
return nil, status.Errorf(codes.Internal, "no rows received from totals query")
}
resp := &api.MetricsViewTotalsResponse{
Meta: meta,
Data: data[0],
}
return resp, nil
}
func (s *Server) runQuery(
ctx context.Context,
instanceId string,
sql string,
args []any,
) ([]*api.SchemaColumn, []*structpb.Struct, error) {
rows, err := s.query(ctx, instanceId, &drivers.Statement{
Query: sql,
Args: args,
})
if err != nil {
return nil, nil, status.Error(codes.InvalidArgument, err.Error())
}
defer rows.Close()
meta, err := rowsToMeta(rows)
if err != nil {
return nil, nil, status.Error(codes.Internal, err.Error())
}
data, err := rowsToData(rows)
if err != nil {
return nil, nil, status.Error(codes.Internal, err.Error())
}
return meta, data, nil
}
func buildMetricsTimeSeriesSQL(req *api.MetricsViewTimeSeriesRequest) (string, []any, error) {
// TODO: get from Catalog
timeField := "timestamp"
timeCol := fmt.Sprintf("DATE_TRUNC('%s', %s) AS %s", req.TimeGranularity, timeField, timeField)
selectCols := append([]string{timeCol}, req.MeasureNames...)
whereClause := fmt.Sprintf("%s >= epoch_ms(?) AND %s < epoch_ms(?) ", timeField, timeField)
args := []any{req.TimeStart, req.TimeEnd}
if req.Filter != nil {
clause, clauseArgs, err := buildFilterClauseForMetricsViewFilter(req.Filter)
if err != nil {
return "", nil, err
}
whereClause += clause
args = append(args, clauseArgs...)
}
sql := fmt.Sprintf(
"SELECT %s FROM %s WHERE %s GROUP BY %s LIMIT 1000",
strings.Join(selectCols, ", "),
req.MetricsViewName,
whereClause,
timeField,
)
return sql, args, nil
}
func buildMetricsTopListSql(req *api.MetricsViewToplistRequest) (string, []any, error) {
// TODO: get from Catalog
timeField := "timestamp"
selectCols := append([]string{req.DimensionName}, req.MeasureNames...)
whereClause := fmt.Sprintf("%s >= epoch_ms(?) AND %s < epoch_ms(?) ", timeField, timeField)
args := []any{req.TimeStart, req.TimeEnd}
if req.Filter != nil {
clause, clauseArgs, err := buildFilterClauseForMetricsViewFilter(req.Filter)
if err != nil {
return "", nil, err
}
whereClause += clause
args = append(args, clauseArgs...)
}
if req.Sort != nil {
// TODO
}
sql := fmt.Sprintf("SELECT %s FROM %s WHERE %s GROUP BY %s LIMIT %d",
strings.Join(selectCols, ", "),
req.MetricsViewName, whereClause, req.DimensionName, req.Limit)
return sql, args, nil
}
func buildMetricsTotalsSql(req *api.MetricsViewTotalsRequest) (string, []any, error) {
// TODO: get from Catalog
timeField := "timestamp"
whereClause := fmt.Sprintf("%s >= epoch_ms(?) AND %s < epoch_ms(?) ", timeField, timeField)
args := []any{req.TimeStart, req.TimeEnd}
if req.Filter != nil {
clause, clauseArgs, err := buildFilterClauseForMetricsViewFilter(req.Filter)
if err != nil {
return "", nil, err
}
whereClause += clause
args = append(args, clauseArgs...)
}
sql := fmt.Sprintf("SELECT %s FROM %s WHERE %s",
strings.Join(req.MeasureNames, ", "), req.MetricsViewName, whereClause)
return sql, args, nil
}
// Builds clause and args for api.MetricsViewFilter
func buildFilterClauseForMetricsViewFilter(filter *api.MetricsViewFilter) (string, []any, error) {
whereClause := ""
var args []any
if filter != nil && filter.Include != nil {
clause, clauseArgs, err := buildFilterClauseForConditions(filter.Include, false)
if err != nil {
return "", nil, err
}
whereClause += clause
args = append(args, clauseArgs...)
}
if filter != nil && filter.Exclude != nil {
clause, clauseArgs, err := buildFilterClauseForConditions(filter.Exclude, true)
if err != nil {
return "", nil, err
}
whereClause += clause
args = append(args, clauseArgs...)
}
return whereClause, args, nil
}
func buildFilterClauseForConditions(conds []*api.MetricsViewFilter_Cond, exclude bool) (string, []any, error) {
clause := ""
var args []any
for _, cond := range conds {
condClause, condArgs, err := buildFilterClauseForCondition(cond, exclude)
if err != nil {
return "", nil, fmt.Errorf("filter error: %s", err.Error())
}
if condClause == "" {
continue
}
clause += condClause
args = append(args, condArgs...)
}
return clause, args, nil
}
func buildFilterClauseForCondition(cond *api.MetricsViewFilter_Cond, exclude bool) (string, []any, error) {
var clauses []string
var args []any
var operatorPrefix string
var conditionJoiner string
if exclude {
operatorPrefix = "NOT"
conditionJoiner = "AND"
} else {
operatorPrefix = ""
conditionJoiner = "OR"
}
if len(cond.In) > 0 {
// null values should be added with IS NULL / IS NOT NULL
nullCount := 0
for _, val := range cond.In {
if val == nil {
nullCount++
continue
}
arg, err := protobufValueToAny(val)
if err != nil {
return "", nil, fmt.Errorf("filter error: %s", err.Error())
}
args = append(args, arg)
}
questionMarks := strings.Join(repeatString("?", len(cond.In)-nullCount), ",")
// <dimension> (NOT) IN (?,?,...)
clauses = append(clauses, fmt.Sprintf("%s %s IN (%s)", cond.Name, operatorPrefix, questionMarks))
if nullCount > 0 {
// <dimension> IS (NOT) NULL
clauses = append(clauses, fmt.Sprintf("%s IS %s NULL", cond.Name, operatorPrefix))
}
}
if len(cond.Like) > 0 {
for _, val := range cond.Like {
arg, err := protobufValueToAny(val)
if err != nil {
return "", nil, fmt.Errorf("filter error: %s", err.Error())
}
args = append(args, arg)
// <dimension> (NOT) ILIKE ?
clauses = append(clauses, fmt.Sprintf("%s %s ILIKE ?", cond.Name, operatorPrefix))
}
}
clause := ""
if len(clauses) > 0 {
clause = fmt.Sprintf(" AND %s", strings.Join(clauses, conditionJoiner))
}
return clause, args, nil
}
func repeatString(val string, n int) []string {
res := make([]string, n)
for i := 0; i < n; i++ {
res[i] = val
}
return res
}
func protobufValueToAny(val *structpb.Value) (any, error) {
switch v := val.GetKind().(type) {
case *structpb.Value_StringValue:
return v.StringValue, nil
case *structpb.Value_BoolValue:
return v.BoolValue, nil
case *structpb.Value_NumberValue:
return v.NumberValue, nil
case *structpb.Value_NullValue:
return nil, nil
default:
return nil, fmt.Errorf("value not supported: %v", v)
}
}