Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/pkg/river/internal/stdlib/stdlib.go
4096 views
1
// Package stdlib contains standard library functions exposed to River configs.
2
package stdlib
3
4
import (
5
"encoding/json"
6
"os"
7
8
"github.com/grafana/agent/pkg/river/internal/value"
9
"github.com/grafana/agent/pkg/river/rivertypes"
10
)
11
12
// Identifiers holds a list of stdlib identifiers by name. All interface{}
13
// values are River-compatible values.
14
//
15
// Function identifiers are Go functions with exactly one non-error return
16
// value, with an optionally supported error return value as the second return
17
// value.
18
var Identifiers = map[string]interface{}{
19
// See constants.go for the definition.
20
"constants": constants,
21
22
"env": os.Getenv,
23
24
"nonsensitive": func(secret rivertypes.Secret) string {
25
return string(secret)
26
},
27
28
// concat is implemented as a raw function so it can bypass allocations
29
// converting arguments into []interface{}. concat is optimized to allow it
30
// to perform well when it is in the hot path for combining targets from many
31
// other blocks.
32
"concat": value.RawFunction(func(funcValue value.Value, args ...value.Value) (value.Value, error) {
33
if len(args) == 0 {
34
return value.Array(), nil
35
}
36
37
// finalSize is the final size of the resulting concatenated array. We type
38
// check our arguments while computing what finalSize will be.
39
var finalSize int
40
for i, arg := range args {
41
if arg.Type() != value.TypeArray {
42
return value.Null, value.ArgError{
43
Function: funcValue,
44
Argument: arg,
45
Index: i,
46
Inner: value.TypeError{
47
Value: arg,
48
Expected: value.TypeArray,
49
},
50
}
51
}
52
53
finalSize += arg.Len()
54
}
55
56
// Optimization: if there's only one array, we can just return it directly.
57
// This is done *after* the previous loop to ensure that args[0] is a River
58
// array.
59
if len(args) == 1 {
60
return args[0], nil
61
}
62
63
raw := make([]value.Value, 0, finalSize)
64
for _, arg := range args {
65
for i := 0; i < arg.Len(); i++ {
66
raw = append(raw, arg.Index(i))
67
}
68
}
69
70
return value.Array(raw...), nil
71
}),
72
73
"json_decode": func(in string) (interface{}, error) {
74
var res interface{}
75
err := json.Unmarshal([]byte(in), &res)
76
if err != nil {
77
return nil, err
78
}
79
return res, nil
80
},
81
82
"coalesce": value.RawFunction(func(funcValue value.Value, args ...value.Value) (value.Value, error) {
83
if len(args) == 0 {
84
return value.Null, nil
85
}
86
87
for _, arg := range args {
88
if arg.Type() == value.TypeNull {
89
continue
90
}
91
92
if !arg.Reflect().IsZero() {
93
if argType := value.RiverType(arg.Reflect().Type()); (argType == value.TypeArray || argType == value.TypeObject) && arg.Len() == 0 {
94
continue
95
}
96
97
return arg, nil
98
}
99
}
100
101
return args[len(args)-1], nil
102
}),
103
}
104
105