-
Notifications
You must be signed in to change notification settings - Fork 100
/
template.go
340 lines (301 loc) · 9.76 KB
/
template.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
package rillv1
import (
"bytes"
"fmt"
"text/template"
"text/template/parse"
"github.com/Masterminds/sprig/v3"
runtimev1 "github.com/rilldata/rill/proto/gen/rill/runtime/v1"
"github.com/rilldata/rill/runtime/pkg/duckdbsql"
"golang.org/x/exp/maps"
"gopkg.in/yaml.v3"
)
// Template parsing serves a dual purpose of:
//
// a) extracting metadata at parse time (such as {{ config ...}} and {{ ref ... }})
// b) populating values at resolve time (such as {{ .vars ... }} and {{ ref ... }})
//
// The resolve time of a template varies. For models, the resolve time is when they are created in the database.
// But for dashboard expressions, the resolve time is when the dashboard is rendered.
//
// Note that no template resolution happens at parse time. This means templating can't be used to alter the structure of YAML files.
// Instead, templating can be used to alter values in certain YAML properties at resolve time.
// This is similar to the templating behavior you would see in Github Actions, but not in Helm.
//
// The supported template functions are (if not supported at parse time or resolve time, they are no-ops resolving to empty strings):
//
// configure `YAML`: set config from YAML blob (parse time)
// configure `key` `value`: set config key (parse time)
// dependency [`kind`] `name`: register a dependency (parse time)
// ref [`kind`] `name`: register a dependency at parse-time, resolve it to a name at resolve time (parse time and resolve time)
// lookup [`kind`] `name`: lookup another resource (resolve time)
// .vars.name: access a variable (resolve time)
// .user.attribute: access an attribute from auth claims (resolve time)
// .meta: access the current resource's metadata (resolve time)
// .spec: access the current resource's spec (resolve time)
// .state: access the current resource's state (resolve time)
// (All functions from Sprig except OS functions. See http://masterminds.github.io/sprig/ for details.)
//
// TemplateData contains data for resolving a template.
type TemplateData struct {
Environment string
User map[string]any
Variables map[string]string
ExtraProps map[string]any
Self TemplateResource
Resolve func(ref ResourceName) (string, error)
Lookup func(name ResourceName) (TemplateResource, error)
}
// TemplateResource contains data for a resource for injection into a template.
type TemplateResource struct {
Meta *runtimev1.ResourceMeta
Spec any
State any
}
// TemplateMetadata contains metadata extracted from a template.
type TemplateMetadata struct {
Refs []ResourceName
Config map[string]any
Variables []string
UsesTemplating bool
ResolvedWithPlaceholders string
}
// AnalyzeTemplate parses a template and extracts metadata.
func AnalyzeTemplate(tmpl string) (*TemplateMetadata, error) {
// Accumulate metadata
config := make(map[string]any)
refs := map[ResourceName]bool{}
// Build func map
funcMap := newFuncMap("")
funcMap["configure"] = func(parts ...any) (string, error) {
if len(parts) == 1 {
// Configure from YAML
yamlStr, ok := parts[0].(string)
if !ok {
return "", fmt.Errorf(`"configure" input must be a string`)
}
// Parse YAML into config
err := yaml.Unmarshal([]byte(yamlStr), &config)
if err != nil {
return "", fmt.Errorf(`"configure" failed to parse YAML: %w`, err)
}
return "", nil
} else if len(parts) == 2 {
// Configure from key-value pair
key, ok := parts[0].(string)
if !ok {
return "", fmt.Errorf(`"configure" key must be a string`)
}
config[key] = parts[1]
return "", nil
}
return "", fmt.Errorf(`"configure" takes one or two arguments`)
}
funcMap["dependency"] = func(parts ...string) (string, error) {
name, err := resourceNameFromArgs(parts...)
if err != nil {
return "", fmt.Errorf(`invalid "dependency" args: %w`, err)
}
refs[name] = true
return "", nil
}
funcMap["ref"] = func(parts ...string) (string, error) {
name, err := resourceNameFromArgs(parts...)
if err != nil {
return "", fmt.Errorf(`invalid "ref" args: %w`, err)
}
refs[name] = true
return "<no value>", nil
}
funcMap["lookup"] = func(parts ...string) (map[string]any, error) {
name, err := resourceNameFromArgs(parts...)
if err != nil {
return nil, fmt.Errorf(`invalid "lookup" args: %w`, err)
}
refs[name] = true
return map[string]any{}, nil
}
// Parse template (error on missing keys)
t, err := template.New("").Funcs(funcMap).Option("missingkey=default").Parse(tmpl)
if err != nil {
return nil, err
}
// Build template data
dataMap := map[string]interface{}{
"env": "",
"vars": map[string]any{},
"user": map[string]any{},
"meta": map[string]any{},
"spec": map[string]any{},
"state": map[string]any{},
}
// Resolve template
res := new(bytes.Buffer)
if err := t.Execute(res, dataMap); err != nil {
return nil, err
}
// Check if there is any templating
noTemplating := len(t.Root.Nodes) == 0 || len(t.Root.Nodes) == 1 && t.Root.Nodes[0].Type() == parse.NodeText
// Done
variables := extractVariablesFromTemplate(t.Tree)
return &TemplateMetadata{
Refs: maps.Keys(refs),
Config: config,
Variables: variables,
UsesTemplating: !noTemplating,
ResolvedWithPlaceholders: res.String(),
}, nil
}
// ResolveTemplate resolves a template to a string using the given data.
func ResolveTemplate(tmpl string, data TemplateData) (string, error) {
// Base func map
funcMap := newFuncMap(data.Environment)
// Add no-ops
funcMap["configure"] = func(parts ...string) error { return nil }
funcMap["dependency"] = func(parts ...string) error { return nil }
// Add func to resolve a "ref"
funcMap["ref"] = func(parts ...string) (string, error) {
// Parse the resource name
name, err := resourceNameFromArgs(parts...)
if err != nil {
return "", fmt.Errorf(`invalid "ref" input: %w`, err)
}
// Resolve the ref
ref, err := data.Resolve(name)
if err != nil {
return "", fmt.Errorf(`function "ref" failed: %w`, err)
}
// Return formatted as a map
return ref, nil
}
// Add func to lookup another resource
funcMap["lookup"] = func(parts ...string) (map[string]any, error) {
// Support is optional
if data.Lookup == nil {
return nil, fmt.Errorf(`function "lookup" is not supported in this context`)
}
// Parse the resource name
name, err := resourceNameFromArgs(parts...)
if err != nil {
return nil, fmt.Errorf(`invalid "lookup" input: %w`, err)
}
// Lookup the resource
resource, err := data.Lookup(name)
if err != nil {
return nil, fmt.Errorf(`function "lookup" failed: %w`, err)
}
// Return formatted as a map
return map[string]any{
"meta": resource.Meta,
"spec": resource.Spec,
"state": resource.State,
}, nil
}
// Parse template (error on missing keys)
// TODO: missingkey=error may be problematic for claims.
t, err := template.New("").Funcs(funcMap).Option("missingkey=error").Parse(tmpl)
if err != nil {
return "", err
}
// Build template data
dataMap := map[string]interface{}{
"env": data.Environment,
"vars": data.Variables,
"user": data.User,
"meta": data.Self.Meta,
"spec": data.Self.Spec,
"state": data.Self.State,
}
// Add extra props
for k, v := range data.ExtraProps {
dataMap[k] = v
}
// Resolve template
res := new(bytes.Buffer)
if err := t.Execute(res, dataMap); err != nil {
return "", err
}
return res.String(), nil
}
// newFuncMap creates a base func map for templates.
func newFuncMap(environment string) template.FuncMap {
// Add Sprig template functions (removing functions that leak host info)
// Derived from Helm: https://github.com/helm/helm/blob/main/pkg/engine/funcs.go
funcMap := sprig.TxtFuncMap()
delete(funcMap, "env")
delete(funcMap, "expandenv")
// Add helpers for checking for common environments
funcMap["dev"] = func() bool { return environment == "dev" }
funcMap["prod"] = func() bool { return environment == "prod" }
return funcMap
}
// resourceNameFromArgs builds a ResourceName from a list of args to a template function (currently "lookup" and "ref").
// It supports two forms: `fn "name"` or `fn "kind" "name"`
// In the first case, the Kind will be empty and upstream logic is expected to disambiguate.
func resourceNameFromArgs(parts ...string) (ResourceName, error) {
if len(parts) == 1 {
return ResourceName{Name: parts[0]}, nil
}
if len(parts) != 2 {
return ResourceName{}, fmt.Errorf("expected one or two args, but got %d", len(parts))
}
kind, err := ParseResourceKind(parts[0])
if err != nil {
return ResourceName{}, err
}
return ResourceName{
Kind: kind,
Name: parts[1],
}, nil
}
func EvaluateBoolExpression(expr string) (bool, error) {
if expr == "" {
return false, fmt.Errorf("cannot evaluate empty expression")
}
result, err := duckdbsql.EvaluateBool(expr)
if err != nil {
return false, fmt.Errorf("failed to evaluate expression: %w", err)
}
return result, nil
}
func extractVariablesFromTemplate(tree *parse.Tree) []string {
variablesMap := make(map[string]bool)
walkNodes(tree.Root, func(n parse.Node) {
if vn, ok := n.(*parse.FieldNode); ok {
v := joinIdentifiers(vn.Ident)
variablesMap[v] = true
}
})
return maps.Keys(variablesMap)
}
func walkNodes(node parse.Node, fn func(n parse.Node)) {
fn(node)
switch n := node.(type) {
case *parse.ListNode:
for _, ln := range n.Nodes {
walkNodes(ln, fn)
}
case *parse.ActionNode:
walkNodes(n.Pipe, fn)
case *parse.PipeNode:
for _, cmd := range n.Cmds {
walkNodes(cmd, fn)
}
case *parse.CommandNode:
for _, arg := range n.Args {
walkNodes(arg, fn)
}
default:
return
}
}
func joinIdentifiers(ident []string) string {
var result string
for _, id := range ident {
if result != "" {
result += "."
}
result += id
}
return result
}