-
Notifications
You must be signed in to change notification settings - Fork 104
/
parse_node.go
479 lines (433 loc) · 14.2 KB
/
parse_node.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
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
package rillv1
import (
"errors"
"fmt"
"path/filepath"
"strings"
"github.com/mitchellh/mapstructure"
"github.com/rilldata/rill/runtime/pkg/sqlparse"
"gopkg.in/yaml.v3"
)
// Node represents one path stem in the project. It contains data derived from a YAML and/or SQL file (e.g. "/path/to/file.yaml" for "/path/to/file.sql").
type Node struct {
Kind ResourceKind
Name string
Refs []ResourceName
Paths []string
YAML *yaml.Node
YAMLOverride *yaml.Node
YAMLRaw string
YAMLPath string
Connector string
ConnectorInferred bool
SQL string
SQLPath string
SQLAnnotations map[string]any
SQLUsesTemplating bool
}
// parseNode multiplexes to the appropriate parse function based on the node kind.
func (p *Parser) parseNode(node *Node) error {
switch node.Kind {
case ResourceKindSource:
return p.parseSource(node)
case ResourceKindModel:
return p.parseModel(node)
case ResourceKindMetricsView:
return p.parseMetricsView(node)
case ResourceKindMigration:
return p.parseMigration(node)
case ResourceKindReport:
return p.parseReport(node)
case ResourceKindAlert:
return p.parseAlert(node)
case ResourceKindTheme:
return p.parseTheme(node)
case ResourceKindComponent:
return p.parseComponent(node)
case ResourceKindDashboard:
return p.parseDashboard(node)
case ResourceKindAPI:
return p.parseAPI(node)
default:
panic(fmt.Errorf("unexpected resource type: %s", node.Kind.String()))
}
}
// commonYAML parses YAML fields common to all YAML files.
type commonYAML struct {
// Type can be inferred from the directory name in certain cases, but otherwise must be specified manually.
Type *string `yaml:"type"`
// Deprecated: Changed to Type. "Kind" is still used internally to refer to resource types.
Kind *string `yaml:"kind"`
// Name is usually inferred from the filename, but can be specified manually.
Name string `yaml:"name"`
// Refs are a list of other resources that this resource depends on. They are usually inferred from other fields, but can also be specified manually.
Refs []yaml.Node `yaml:"refs"`
// ParserConfig enables setting file-level parser config.
ParserConfig struct {
Templating *bool `yaml:"templating"`
} `yaml:"parser"`
// Connector names the connector to use for this resource. It may not be used in all resources, but is included here since it provides context for the SQL field.
Connector string `yaml:"connector"`
// SQL contains the SQL string for this resource. It may be specified inline, or will be loaded from a file at the same stem. It may not be supported in all resources.
SQL string `yaml:"sql"`
// Environment-specific overrides
Env map[string]yaml.Node `yaml:"env"`
// Shorthand for setting "env:dev:"
Dev yaml.Node `yaml:"dev"`
// Shorthand for setting "env:prod:"
Prod yaml.Node `yaml:"prod"`
}
// parseStem parses a pair of YAML and SQL files with the same path stem (e.g. "/path/to/file.yaml" for "/path/to/file.sql").
// Note that either of the YAML or SQL files may be empty (the paths arg will only contain non-nil paths).
func (p *Parser) parseStem(paths []string, ymlPath, yml, sqlPath, sql string) (*Node, error) {
// The rest of the function builds a Node from YAML and SQL info
res := &Node{Paths: paths}
// Parse YAML into commonYAML
var cfg *commonYAML
if ymlPath != "" {
var node yaml.Node
err := yaml.Unmarshal([]byte(yml), &node)
if err != nil {
return nil, pathError{path: ymlPath, err: newYAMLError(err)}
}
res.YAML = &node
res.YAMLRaw = yml
res.YAMLPath = ymlPath
err = node.Decode(&cfg)
if err != nil {
return nil, pathError{path: ymlPath, err: newYAMLError(err)}
}
}
// Handle YAML config
templatingEnabled := true
if cfg != nil {
// Copy basic properties
res.Name = cfg.Name
res.Connector = cfg.Connector
res.SQL = cfg.SQL
res.SQLPath = ymlPath
// Handle "dev:" and "prod:" shorthands (copy to to cfg.Env)
if !cfg.Dev.IsZero() {
if cfg.Env == nil {
cfg.Env = make(map[string]yaml.Node)
}
cfg.Env["dev"] = cfg.Dev
}
if !cfg.Prod.IsZero() {
if cfg.Env == nil {
cfg.Env = make(map[string]yaml.Node)
}
cfg.Env["prod"] = cfg.Prod
}
// Set environment-specific override
if envOverride := cfg.Env[p.Environment]; !envOverride.IsZero() {
res.YAMLOverride = &envOverride
}
// Handle templating config
if cfg.ParserConfig.Templating != nil {
templatingEnabled = *cfg.ParserConfig.Templating
}
// Parse refs provided in YAML
var err error
res.Refs, err = parseYAMLRefs(cfg.Refs)
if err != nil {
return nil, pathError{path: ymlPath, err: newYAMLError(err)}
}
// Parse resource kind if set in YAML. If not set, we try to infer it from path later.
// NOTE: We use "kind" internally, but "type:" is the preferred user-facing field.
// However, we still need to support "kind:" for backwards compatibility.
if cfg.Kind != nil {
res.Kind, err = ParseResourceKind(*cfg.Kind)
if err != nil {
return nil, pathError{path: ymlPath, err: err}
}
}
if cfg.Type != nil {
kind, err := ParseResourceKind(*cfg.Type)
if err == nil {
res.Kind = kind
} else if !strings.HasPrefix(paths[0], "/sources") {
// Backwards compatibility: "type:" was previously used in sources instead of "connector:". This was when sources were always created in the "sources" directory.
// So for backwards compatibility, we ignore parse errors for the "type:" field when the file is in the "sources" directory.
// (The source parser handles the backwards compatibility around mapping "type:" to "connector:".)
return nil, pathError{path: ymlPath, err: err}
}
}
}
// Set SQL
if sql != "" {
// Check SQL was not already provided in YAML
if res.SQL != "" {
return nil, pathError{path: ymlPath, err: errors.New("SQL provided using both a YAML key and a companion file")}
}
res.SQL = sql
res.SQLPath = sqlPath
}
// Parse SQL templating
if templatingEnabled && res.SQL != "" {
meta, err := AnalyzeTemplate(res.SQL)
if err != nil {
if sqlPath != "" {
return nil, pathError{path: sqlPath, err: err}
}
return nil, pathError{path: ymlPath, err: err}
}
res.SQLUsesTemplating = meta.UsesTemplating
res.SQLAnnotations = meta.Config
res.Refs = append(res.Refs, meta.Refs...) // If needed, deduplication happens in insertResource
// Additionally parse annotations provided in comments (e.g. "-- @materialize: true")
commentAnnotations := sqlparse.ExtractAnnotations(res.SQL)
if len(commentAnnotations) > 0 && res.SQLAnnotations == nil {
res.SQLAnnotations = make(map[string]any)
}
for k, v := range commentAnnotations {
res.SQLAnnotations[k] = v
}
// Expand dots in annotations. E.g. turn annotations["foo.bar"] into annotations["foo"]["bar"].
res.SQLAnnotations, err = expandAnnotations(res.SQLAnnotations)
if err != nil {
if sqlPath != "" {
return nil, pathError{path: sqlPath, err: err}
}
return nil, pathError{path: ymlPath, err: err}
}
}
// Some annotations in the SQL file can override the base config: kind, name, connector
var err error
for k, v := range res.SQLAnnotations {
switch strings.ToLower(k) {
case "type", "kind": // "kind" is for backwards compatibility
v, ok := v.(string)
if !ok {
err = fmt.Errorf("invalid type %T for property 'type'", v)
break
}
res.Kind, err = ParseResourceKind(v)
if err != nil {
break
}
case "name":
v, ok := v.(string)
if !ok {
err = fmt.Errorf("invalid type %T for property 'name'", v)
break
}
res.Name = v
case "connector":
v, ok := v.(string)
if !ok {
err = fmt.Errorf("invalid type %T for property 'connector'", v)
break
}
res.Connector = v
}
}
if err != nil {
if sqlPath != "" {
return nil, pathError{path: sqlPath, err: err}
}
return nil, pathError{path: ymlPath, err: err}
}
// If name is not set in YAML or SQL, infer it from path
if res.Name == "" {
if ymlPath != "" {
res.Name = filepath.Base(pathStem(ymlPath))
} else if sqlPath != "" {
res.Name = filepath.Base(pathStem(sqlPath))
}
}
// If resource kind is not set in YAML or SQL, try to infer it from the context
if res.Kind == ResourceKindUnspecified {
if strings.HasPrefix(paths[0], "/sources") {
res.Kind = ResourceKindSource
} else if strings.HasPrefix(paths[0], "/models") {
res.Kind = ResourceKindModel
} else if strings.HasPrefix(paths[0], "/dashboards") {
res.Kind = ResourceKindMetricsView
} else if strings.HasPrefix(paths[0], "/init.sql") {
res.Kind = ResourceKindMigration
} else if sqlPath != "" {
// SQL files without an explicit kind are assumed to be models
res.Kind = ResourceKindModel
} else {
path := ymlPath
if path == "" {
path = sqlPath
}
return nil, pathError{path: path, err: errors.New("resource type not specified and could not be inferred from context")}
}
}
// If connector wasn't set explicitly, use the default OLAP connector
if res.Connector == "" {
res.Connector = p.defaultOLAPConnector()
res.ConnectorInferred = true
}
return res, nil
}
// decodeNodeYAML decodes a Node into a YAML struct.
// If knownFields is true, it will return an error if the YAML contains unknown fields.
// It applies defaults from rill.yaml, then the YAML, then the YAML's environment-specific overrides, and finally the SQL annotations.
// If an error is returned, it will be a pathError associated with the node.
func (p *Parser) decodeNodeYAML(node *Node, knownFields bool, dst any) error {
// Apply defaults from rill.yaml
if p.RillYAML != nil {
defaults := p.RillYAML.Defaults[node.Kind]
if !defaults.IsZero() {
if err := defaults.Decode(dst); err != nil {
return pathError{path: node.YAMLPath, err: fmt.Errorf("failed applying defaults from rill.yaml: %w", err)}
}
}
}
// Apply YAML
if node.YAML != nil {
var err error
if knownFields {
// Using node.YAMLRaw instead of node.YAML because we need to set KnownFields for metrics views
dec := yaml.NewDecoder(strings.NewReader(node.YAMLRaw))
dec.KnownFields(true)
err = dec.Decode(dst)
} else {
err = node.YAML.Decode(dst)
}
if err != nil {
return pathError{path: node.YAMLPath, err: newYAMLError(err)}
}
}
// Override YAML config with SQL annotations
if len(node.SQLAnnotations) > 0 {
err := mapstructureUnmarshal(node.SQLAnnotations, dst)
if err != nil {
return pathError{path: node.SQLPath, err: fmt.Errorf("invalid SQL annotations: %w", err)}
}
}
// Apply environment-specific overrides
if node.YAMLOverride != nil {
err := node.YAMLOverride.Decode(dst)
if err != nil {
return pathError{path: node.YAMLPath, err: newYAMLError(err)}
}
}
return nil
}
// parseYAMLRefs parses a list of YAML nodes into a list of ResourceNames.
// It's used to parse the "refs" field in baseConfig.
func parseYAMLRefs(refs []yaml.Node) ([]ResourceName, error) {
var res []ResourceName
for i := range refs {
ref := refs[i]
// We support string refs of the form "my-resource" and "Kind/my-resource"
if ref.Kind == yaml.ScalarNode {
var identifier string
err := ref.Decode(&identifier)
if err != nil {
return nil, fmt.Errorf("invalid refs: %v", ref)
}
// Parse name and kind from identifier
parts := strings.Split(identifier, "/")
if len(parts) != 1 && len(parts) != 2 {
return nil, fmt.Errorf("invalid refs: invalid identifier %q", identifier)
}
var name ResourceName
if len(parts) == 1 {
name.Name = parts[0]
} else {
// Kind and name specified
kind, err := ParseResourceKind(parts[0])
if err != nil {
return nil, fmt.Errorf("invalid refs: %w", err)
}
name.Kind = kind
name.Name = parts[1]
}
res = append(res, name)
continue
}
// We support map refs of the form { type: "kind", name: "my-resource" }
if ref.Kind == yaml.MappingNode {
m := make(map[string]string)
err := ref.Decode(m)
if err != nil {
return nil, fmt.Errorf("invalid refs: %w", err)
}
if m["name"] == "" {
return nil, errors.New(`an object ref must provide the properties "type" and "name" properties`)
}
var name ResourceName
name.Name = m["name"]
if m["type"] != "" {
kind, err := ParseResourceKind(m["type"])
if err != nil {
return nil, fmt.Errorf("invalid refs: %w", err)
}
name.Kind = kind
}
// Backwards compatibility for "kind:" changed to "type:"
if m["kind"] != "" {
kind, err := ParseResourceKind(m["kind"])
if err != nil {
return nil, fmt.Errorf("invalid refs: %w", err)
}
name.Kind = kind
}
res = append(res, name)
continue
}
// ref was neither a string nor a map
return nil, fmt.Errorf("invalid refs: %v", ref)
}
return res, nil
}
// mapstructureUnmarshal is used to unmarshal SQL annotations into a struct (overriding YAML config).
func mapstructureUnmarshal(annotations map[string]any, dst any) error {
if len(annotations) == 0 {
return nil
}
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
Result: dst,
WeaklyTypedInput: true,
})
if err != nil {
panic(err)
}
return decoder.Decode(annotations)
}
// expandAnnotations turns annotations with dots in their key into nested maps.
// For example, annotations["foo.bar"] becomes annotations["foo"]["bar"].
func expandAnnotations(annotations map[string]any) (map[string]any, error) {
if len(annotations) == 0 {
return nil, nil
}
res := make(map[string]any)
for k, v := range annotations {
parts := strings.Split(k, ".")
if len(parts) < 2 {
res[k] = v
continue
}
m := res
for i := 0; i < len(parts)-1; i++ {
part := parts[i]
// Check if a map already exists for this part; if yes, assign to m
x, ok := m[part]
if ok {
m, ok = x.(map[string]any)
if !ok {
return nil, fmt.Errorf("invalid annotation %q: nesting incompatible with other keys", k)
}
continue
}
// Create a map for this part, then update m
tmp := make(map[string]any)
m[part] = tmp
m = tmp
}
// Check the last part of this key isn't an intermediate part of a previously expanded key
k2 := parts[len(parts)-1]
if _, ok := m[k2]; ok {
return nil, fmt.Errorf("invalid annotation2 %q: nesting incompatible with other keys", k)
}
// Assign the value to the last part
m[k2] = v
}
return res, nil
}